Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Vrij en open source onder de EUPL-1.2-licentie.
<job>OCA\Doriath\BackgroundJob\PurgeAuditLogJob</job>
<job>OCA\Doriath\BackgroundJob\ApproveElapsedEmergencyRequests</job>
<job>OCA\Doriath\BackgroundJob\PruneSecretVersionsJob</job>
<job>OCA\Doriath\BackgroundJob\ScanExpiringSecretsJob</job>
</background-jobs>

<repair-steps>
Expand Down
11 changes: 11 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,17 @@
['name' => 'secretVersion#show', 'url' => '/api/v1/versions/{id}', 'verb' => 'GET'],
['name' => 'secretVersion#restore', 'url' => '/api/v1/versions/{id}/restore', 'verb' => 'POST'],

// Rotation & expiry (rotation-expiry-policies §5.1).
['name' => 'rotation#getExpiry', 'url' => '/api/v1/secrets/{id}/expiry', 'verb' => 'GET'],
['name' => 'rotation#setExpiry', 'url' => '/api/v1/secrets/{id}/expiry', 'verb' => 'PUT'],
['name' => 'rotation#policies', 'url' => '/api/v1/expiry-policies', 'verb' => 'GET'],
['name' => 'rotation#upsertPolicy', 'url' => '/api/v1/expiry-policies', 'verb' => 'POST'],
['name' => 'rotation#destroyPolicy', 'url' => '/api/v1/expiry-policies/{id}', 'verb' => 'DELETE'],
['name' => 'rotation#flags', 'url' => '/api/v1/rotation-flags', 'verb' => 'GET'],
['name' => 'rotation#flagBatch', 'url' => '/api/v1/rotation-flags', 'verb' => 'POST'],
['name' => 'rotation#markRotated', 'url' => '/api/v1/rotation-flags/{id}/rotated', 'verb' => 'POST'],
['name' => 'rotation#dismissFlag', 'url' => '/api/v1/rotation-flags/{id}/dismiss', 'verb' => 'POST'],

// Attachments (encrypted-attachments §4.2). Upload/list ride under the
// owning secret; download/grants/delete address the attachment id.
// Per-object authorization lives in AttachmentService method bodies.
Expand Down
6 changes: 3 additions & 3 deletions lib/BackgroundJob/PruneSecretVersionsJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public function __construct(
private IAppConfig $appConfig,
private LoggerInterface $logger,
) {
parent::__construct($time);
$this->setInterval(86400);
parent::__construct(time: $time);
$this->setInterval(seconds: 86400);
}//end __construct()

/**
Expand Down Expand Up @@ -95,6 +95,6 @@ protected function run($argument): void
'Doriath: version prune failed: '.$exception->getMessage(),
['app' => Application::APP_ID]
);
}
}//end try
}//end run()
}//end class
182 changes: 182 additions & 0 deletions lib/BackgroundJob/ScanExpiringSecretsJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
<?php

/**
* Doriath Scan Expiring Secrets Job
*
* Daily scan of all user-owned secrets against their effective expiry
* (rotation-expiry-policies §4.1): reminder notifications when days-left
* exactly hits a configured threshold (the daily cadence makes each
* threshold fire once, no dedupe storage needed), and an auto-raised
* `policy_expiry` rotation flag + one-time notification once overdue.
* Server-visible metadata only — no ciphertext is ever touched.
*
* @category BackgroundJob
* @package OCA\Doriath\BackgroundJob
*
* @author Conduction Development Team <dev@conductio.nl>
* @copyright 2024 Conduction B.V.
* @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*
* @version GIT: <git-id>
*
* @link https://conduction.nl
*/

declare(strict_types=1);

namespace OCA\Doriath\BackgroundJob;

use OCA\Doriath\AppInfo\Application;
use OCA\Doriath\Db\RotationFlagMapper;
use OCA\Doriath\Db\Secret;
use OCA\Doriath\Db\SecretMapper;
use OCA\Doriath\Service\NotificationService;
use OCA\Doriath\Service\RotationPolicyService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\IAppConfig;
use Psr\Log\LoggerInterface;
use Throwable;

/**
* Daily expiry scan: reminders at thresholds, flags once overdue.
*/
class ScanExpiringSecretsJob extends TimedJob
{
/**
* Rows fetched per page during the full-vault scan.
*
* @var int
*/
private const PAGE_SIZE = 500;

/**
* Constructor for ScanExpiringSecretsJob.
*
* @param ITimeFactory $time The time factory
* @param SecretMapper $secretMapper The secret mapper
* @param RotationFlagMapper $flagMapper The flag mapper (open-flag check)
* @param RotationPolicyService $rotationService The rotation service
* @param NotificationService $notificationService The notification dispatcher
* @param IAppConfig $appConfig The app config
* @param LoggerInterface $logger The logger
*
* @return void
*/
public function __construct(
ITimeFactory $time,
private SecretMapper $secretMapper,
private RotationFlagMapper $flagMapper,
private RotationPolicyService $rotationService,
private NotificationService $notificationService,
private IAppConfig $appConfig,
private LoggerInterface $logger,
) {
parent::__construct(time: $time);
$this->setInterval(seconds: 86400);
}//end __construct()

/**
* Run the expiry scan (fail-soft, per-secret isolation).
*
* @param mixed $argument Unused job argument
*
* @return void
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
* @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-expiry-scanning-and-reminders
*/
protected function run($argument): void
{
$thresholds = json_decode(
$this->appConfig->getValueString(Application::APP_ID, 'expiry_reminder_days', '[30,7,1]'),
true
);
if (is_array($thresholds) === false || $thresholds === []) {
$thresholds = [30, 7, 1];
}

$now = $this->time->getDateTime();
$offset = 0;
do {
$page = $this->secretMapper->findAllUserOwnedPaged(limit: self::PAGE_SIZE, offset: $offset);
foreach ($page as $secret) {
try {
$this->scanOne(secret: $secret, thresholds: $thresholds, now: $now);
} catch (Throwable $exception) {
$this->logger->warning(
'Doriath: expiry scan failed for secret '.$secret->getId().': '.$exception->getMessage(),
['app' => Application::APP_ID]
);
}
}

$offset += self::PAGE_SIZE;
} while (count($page) === self::PAGE_SIZE);
}//end run()

/**
* Scan a single secret: threshold reminder or overdue flag.
*
* @param Secret $secret The secret row
* @param int[] $thresholds Reminder thresholds (days before expiry)
* @param \DateTimeInterface $now The scan instant
*
* @return void
*/
private function scanOne(Secret $secret, array $thresholds, \DateTimeInterface $now): void
{
$expiry = $this->rotationService->resolveEffectiveExpiry(secret: $secret);
if ($expiry === null) {
return;
}

$daysLeft = (int) floor(($expiry->getTimestamp() - $now->getTimestamp()) / 86400);

if ($daysLeft < 0) {
// Overdue: raise the policy_expiry flag; notify ONLY when the
// flag was not already open (one notification per episode).
$alreadyOpen = false;
try {
$alreadyOpen = $this->flagMapper->findBySecret(secretId: $secret->getId())->getStatus() === 'open';
} catch (DoesNotExistException) {
// No flag yet.
}

if ($alreadyOpen === true) {
return;
}

$this->rotationService->flag(secretId: $secret->getId(), reason: 'policy_expiry');
$this->notificationService->notify(
subject: 'secret_rotation_due',
recipientId: $secret->getOwnerId(),
params: [
'secret_name' => $secret->getName(),
'secret_id' => $secret->getId(),
],
objectType: 'secret',
objectId: $secret->getId(),
);
return;
}//end if

// Approaching: the daily cadence means daysLeft passes each integer
// exactly once, so an exact threshold match is naturally deduped.
if (in_array($daysLeft, array_map('intval', $thresholds), true) === true) {
$this->notificationService->notify(
subject: 'secret_expiring',
recipientId: $secret->getOwnerId(),
params: [
'secret_name' => $secret->getName(),
'secret_id' => $secret->getId(),
'days_left' => $daysLeft,
],
objectType: 'secret',
objectId: $secret->getId(),
);
}
}//end scanOne()
}//end class
2 changes: 1 addition & 1 deletion lib/Controller/AttachmentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public function create(
);
}

$row = $result['attachment']->jsonSerialize();
$row = $result['attachment']->jsonSerialize();
$row['wrappedFileKey'] = $result['grant']->getWrappedFileKey();

return new JSONResponse(data: $row, statusCode: Http::STATUS_CREATED);
Expand Down
Loading