diff --git a/appinfo/info.xml b/appinfo/info.xml index dc03fe56b..93835a581 100644 --- a/appinfo/info.xml +++ b/appinfo/info.xml @@ -72,6 +72,7 @@ Vrij en open source onder de EUPL-1.2-licentie. OCA\Doriath\BackgroundJob\PurgeAuditLogJob OCA\Doriath\BackgroundJob\ApproveElapsedEmergencyRequests OCA\Doriath\BackgroundJob\PruneSecretVersionsJob + OCA\Doriath\BackgroundJob\ScanExpiringSecretsJob diff --git a/appinfo/routes.php b/appinfo/routes.php index 5d733d342..faae0b829 100644 --- a/appinfo/routes.php +++ b/appinfo/routes.php @@ -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. diff --git a/lib/BackgroundJob/PruneSecretVersionsJob.php b/lib/BackgroundJob/PruneSecretVersionsJob.php index aeed409ce..4397132e0 100644 --- a/lib/BackgroundJob/PruneSecretVersionsJob.php +++ b/lib/BackgroundJob/PruneSecretVersionsJob.php @@ -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() /** @@ -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 diff --git a/lib/BackgroundJob/ScanExpiringSecretsJob.php b/lib/BackgroundJob/ScanExpiringSecretsJob.php new file mode 100644 index 000000000..f6dfa3c35 --- /dev/null +++ b/lib/BackgroundJob/ScanExpiringSecretsJob.php @@ -0,0 +1,182 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @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 diff --git a/lib/Controller/AttachmentController.php b/lib/Controller/AttachmentController.php index b52412652..612e6d675 100644 --- a/lib/Controller/AttachmentController.php +++ b/lib/Controller/AttachmentController.php @@ -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); diff --git a/lib/Controller/RotationController.php b/lib/Controller/RotationController.php new file mode 100644 index 000000000..3787bdd7b --- /dev/null +++ b/lib/Controller/RotationController.php @@ -0,0 +1,366 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\Doriath\Controller; + +use DateTime; +use Exception; +use InvalidArgumentException; +use OCA\Doriath\AppInfo\Application; +use OCA\Doriath\Exception\ForbiddenException; +use OCA\Doriath\Exception\NotFoundException; +use OCA\Doriath\Service\RotationPolicyService; +use OCA\Doriath\Service\SecretService; +use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Attribute\NoAdminRequired; +use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\OCSController; +use OCP\IRequest; +use OCP\IUserSession; + +/** + * Authenticated API controller for rotation & expiry. + * + * @SuppressWarnings(PHPMD.TooManyPublicMethods) One method per API op. + */ +class RotationController extends OCSController +{ + /** + * Constructor for RotationController. + * + * @param IRequest $request The request object + * @param RotationPolicyService $rotationService The rotation service + * @param SecretService $secretService The secret service (setExpiry) + * @param IUserSession $userSession The user session + * + * @return void + */ + public function __construct( + IRequest $request, + private RotationPolicyService $rotationService, + private SecretService $secretService, + private IUserSession $userSession, + ) { + parent::__construct(appName: Application::APP_ID, request: $request); + }//end __construct() + + /** + * Resolve the session user ID or null when unauthenticated. + * + * @return string|null + */ + private function sessionUserId(): ?string + { + return $this->userSession->getUser()?->getUID(); + }//end sessionUserId() + + /** + * Set or clear a secret's expiry (owner-only; never touches + * ciphertext or key age). + * + * @param string $id The secret UUID + * @param string|null $expiresAt ISO-8601 expiry (null/'' = clear) + * + * @NoAdminRequired + * + * @return JSONResponse + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-per-secret-expiry + */ + #[NoAdminRequired] + public function setExpiry(string $id, ?string $expiresAt=null): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + $when = null; + if ($expiresAt !== null && $expiresAt !== '') { + try { + $when = new DateTime($expiresAt); + } catch (Exception) { + return new JSONResponse( + data: ['message' => 'Invalid expiresAt'], + statusCode: Http::STATUS_BAD_REQUEST + ); + } + } + + try { + $secret = $this->secretService->setExpiry(id: $id, expiresAt: $when, userId: $userId); + } catch (NotFoundException | ForbiddenException) { + return new JSONResponse(data: ['message' => 'Not found'], statusCode: Http::STATUS_NOT_FOUND); + } + + return new JSONResponse( + data: [ + 'secret' => $secret->jsonSerialize(), + 'effectiveExpiry' => $this->rotationService->resolveEffectiveExpiry(secret: $secret)?->format('c'), + ] + ); + }//end setExpiry() + + /** + * A secret's stored + effective expiry. + * + * @param string $id The secret UUID + * + * @NoAdminRequired + * + * @return JSONResponse + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-effective-expiry-resolution + */ + #[NoAdminRequired] + public function getExpiry(string $id): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + try { + $secret = $this->secretService->findOwned(id: $id, userId: $userId); + } catch (NotFoundException | ForbiddenException) { + return new JSONResponse(data: ['message' => 'Not found'], statusCode: Http::STATUS_NOT_FOUND); + } + + return new JSONResponse( + data: [ + 'expiresAt' => $secret->getExpiresAt()?->format('c'), + 'effectiveExpiry' => $this->rotationService->resolveEffectiveExpiry(secret: $secret)?->format('c'), + ] + ); + }//end getExpiry() + + /** + * The caller's applicable expiry policies. + * + * @NoAdminRequired + * + * @return JSONResponse + */ + #[NoAdminRequired] + public function policies(): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + return new JSONResponse( + data: array_map( + static fn ($policy) => $policy->jsonSerialize(), + $this->rotationService->listPolicies(userId: $userId) + ) + ); + }//end policies() + + /** + * Create or update a type/folder expiry policy. + * + * @param string $scope The scope (`type`|`folder`) + * @param string $scopeId The scoped type/folder id + * @param int|null $maxAgeDays Max credential age (null = reminder-only) + * @param array $reminderDays Reminder thresholds in days + * + * @NoAdminRequired + * + * @return JSONResponse + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-expiry-policies + */ + #[NoAdminRequired] + public function upsertPolicy(string $scope, string $scopeId, ?int $maxAgeDays=null, array $reminderDays=[]): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + try { + $policy = $this->rotationService->upsertPolicy( + userId: $userId, + scope: $scope, + scopeId: $scopeId, + maxAgeDays: $maxAgeDays, + reminderDays: $reminderDays, + ); + } catch (InvalidArgumentException $exception) { + return new JSONResponse( + data: ['message' => $exception->getMessage()], + statusCode: Http::STATUS_BAD_REQUEST + ); + } + + return new JSONResponse(data: $policy->jsonSerialize()); + }//end upsertPolicy() + + /** + * Delete one of the caller's policies. + * + * @param string $id The policy UUID + * + * @NoAdminRequired + * + * @return JSONResponse + */ + #[NoAdminRequired] + public function destroyPolicy(string $id): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + try { + $this->rotationService->deletePolicy(policyId: $id, userId: $userId); + } catch (InvalidArgumentException $exception) { + return new JSONResponse(data: ['message' => $exception->getMessage()], statusCode: Http::STATUS_NOT_FOUND); + } + + return new JSONResponse(data: ['deleted' => true]); + }//end destroyPolicy() + + /** + * The caller's open rotation flags. + * + * @NoAdminRequired + * + * @return JSONResponse + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-rotation-flags + */ + #[NoAdminRequired] + public function flags(): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + return new JSONResponse( + data: array_map( + function ($flagRow) use ($userId): array { + $row = $flagRow->jsonSerialize(); + // Enrich with the (plaintext-column) secret name for + // list display; flags are few, so per-row lookup is fine. + try { + $row['secretName'] = $this->secretService + ->findOwned(id: $flagRow->getSecretId(), userId: $userId) + ->getName(); + } catch (NotFoundException | ForbiddenException) { + $row['secretName'] = ''; + } + + return $row; + }, + $this->rotationService->openFlags(userId: $userId) + ) + ); + }//end flags() + + /** + * Flag secrets for rotation (client breach findings send IDs only). + * + * @param array $secretIds The secret UUIDs to flag + * + * @NoAdminRequired + * + * @return JSONResponse + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-rotation-flags + */ + #[NoAdminRequired] + public function flagBatch(array $secretIds=[]): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + $flagged = $this->rotationService->flagBatch( + userId: $userId, + secretIds: array_map('strval', $secretIds) + ); + + return new JSONResponse(data: ['flagged' => $flagged]); + }//end flagBatch() + + /** + * Mark a flag rotated — resolves ONLY on a proven key advance. + * + * @param string $id The flag UUID + * + * @NoAdminRequired + * + * @return JSONResponse + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-mark-rotated + */ + #[NoAdminRequired] + public function markRotated(string $id): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + try { + $result = $this->rotationService->markRotated(flagId: $id, userId: $userId); + } catch (InvalidArgumentException $exception) { + return new JSONResponse(data: ['message' => $exception->getMessage()], statusCode: Http::STATUS_NOT_FOUND); + } + + return new JSONResponse(data: $result); + }//end markRotated() + + /** + * Dismiss a flag without rotation (audited owner judgment call). + * + * @param string $id The flag UUID + * + * @NoAdminRequired + * + * @return JSONResponse + */ + #[NoAdminRequired] + public function dismissFlag(string $id): JSONResponse + { + $userId = $this->sessionUserId(); + if ($userId === null) { + return new JSONResponse(data: ['message' => 'Unauthorized'], statusCode: Http::STATUS_UNAUTHORIZED); + } + + try { + $this->rotationService->dismiss(flagId: $id, userId: $userId); + } catch (InvalidArgumentException $exception) { + return new JSONResponse(data: ['message' => $exception->getMessage()], statusCode: Http::STATUS_NOT_FOUND); + } + + return new JSONResponse(data: ['dismissed' => true]); + }//end dismissFlag() +}//end class diff --git a/lib/Controller/SecretVersionController.php b/lib/Controller/SecretVersionController.php index 0b8181d28..d4e1ff5f4 100644 --- a/lib/Controller/SecretVersionController.php +++ b/lib/Controller/SecretVersionController.php @@ -116,9 +116,11 @@ public function show(string $id): JSONResponse try { $version = $this->versionService->getVersion(versionId: $id, userId: $userId); } catch (InvalidArgumentException $exception) { - $status = str_contains($exception->getMessage(), 'locked') === true - ? Http::STATUS_FORBIDDEN - : Http::STATUS_NOT_FOUND; + $status = Http::STATUS_NOT_FOUND; + if (str_contains($exception->getMessage(), 'locked') === true) { + $status = Http::STATUS_FORBIDDEN; + } + return new JSONResponse(data: ['message' => $exception->getMessage()], statusCode: $status); } diff --git a/lib/Db/Attachment.php b/lib/Db/Attachment.php index 854977d89..bbc9a0ea1 100644 --- a/lib/Db/Attachment.php +++ b/lib/Db/Attachment.php @@ -74,7 +74,7 @@ class Attachment extends Entity implements JsonSerializable /** * Ciphertext byte length (quota accounting). * - * @var int + * @var integer */ protected int $sizeBytes = 0; diff --git a/lib/Db/AttachmentMapper.php b/lib/Db/AttachmentMapper.php index 328ada869..62f2cba0b 100644 --- a/lib/Db/AttachmentMapper.php +++ b/lib/Db/AttachmentMapper.php @@ -101,6 +101,10 @@ public function sumBytesForOwner(string $ownerId): int $sum = $result->fetchOne(); $result->closeCursor(); - return (int) ($sum ?: 0); + if ($sum === false || $sum === null) { + return 0; + } + + return (int) $sum; }//end sumBytesForOwner() }//end class diff --git a/lib/Db/ExpiryPolicy.php b/lib/Db/ExpiryPolicy.php new file mode 100644 index 000000000..b0a22af15 --- /dev/null +++ b/lib/Db/ExpiryPolicy.php @@ -0,0 +1,190 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\Doriath\Db; + +use DateTime; +use JsonSerializable; +use OCP\AppFramework\Db\Entity; + +/** + * Entity representing one expiry policy. + * + * @method string|null getOwnerId() + * @method void setOwnerId(?string $ownerId) + * @method string getScope() + * @method void setScope(string $scope) + * @method string getScopeId() + * @method void setScopeId(string $scopeId) + * @method int|null getMaxAgeDays() + * @method void setMaxAgeDays(?int $maxAgeDays) + * @method string|null getReminderDays() + * @method void setReminderDays(?string $reminderDays) + * @method string getCreatedBy() + * @method void setCreatedBy(string $createdBy) + * @method DateTime|null getCreatedAt() + * @method void setCreatedAt(DateTime $createdAt) + * @method DateTime|null getUpdatedAt() + * @method void setUpdatedAt(DateTime $updatedAt) + */ +class ExpiryPolicy extends Entity implements JsonSerializable +{ + + /** + * The owning user (null = instance-wide admin policy). + * + * @var string|null + */ + protected ?string $ownerId = null; + + /** + * The scope kind: `type` or `folder`. Empty default on purpose (NC + * Entity dirty-tracking). + * + * @var string + */ + protected string $scope = ''; + + /** + * The scoped type id or folder id. + * + * @var string + */ + protected string $scopeId = ''; + + /** + * Maximum credential age in days (null = reminder-only policy). + * + * @var integer|null + */ + protected ?int $maxAgeDays = null; + + /** + * JSON array of reminder thresholds in days (e.g. "[30,7,1]"). + * + * @var string|null + */ + protected ?string $reminderDays = null; + + /** + * The user that created the policy. + * + * @var string + */ + protected string $createdBy = ''; + + /** + * When the policy was created. + * + * @var DateTime|null + */ + protected ?DateTime $createdAt = null; + + /** + * When the policy was last updated. + * + * @var DateTime|null + */ + protected ?DateTime $updatedAt = null; + + /** + * The UUID primary key. + * + * @var string + */ + public $id = ''; + + /** + * Get the UUID primary key. + * + * @return string + */ + public function getId(): string + { + return (string) $this->id; + }//end getId() + + /** + * Set the UUID primary key. + * + * @param string $id The UUID + * + * @return void + */ + public function setId($id): void + { + $this->setter(name: 'id', args: [$id]); + }//end setId() + + /** + * Constructor for ExpiryPolicy. + * + * @return void + */ + public function __construct() + { + $this->addType(fieldName: 'id', type: 'string'); + $this->addType(fieldName: 'ownerId', type: 'string'); + $this->addType(fieldName: 'scope', type: 'string'); + $this->addType(fieldName: 'scopeId', type: 'string'); + $this->addType(fieldName: 'maxAgeDays', type: 'integer'); + $this->addType(fieldName: 'reminderDays', type: 'string'); + $this->addType(fieldName: 'createdBy', type: 'string'); + $this->addType(fieldName: 'createdAt', type: 'datetime'); + $this->addType(fieldName: 'updatedAt', type: 'datetime'); + }//end __construct() + + /** + * Serialize the entity to an array for the API. + * + * @return array + */ + public function jsonSerialize(): array + { + return [ + 'id' => $this->getId(), + 'ownerId' => $this->ownerId, + 'scope' => $this->scope, + 'scopeId' => $this->scopeId, + 'maxAgeDays' => $this->maxAgeDays, + 'reminderDays' => $this->decodedReminderDays(), + 'createdBy' => $this->createdBy, + 'createdAt' => $this->createdAt?->format('c'), + ]; + }//end jsonSerialize() + + /** + * The reminder thresholds as a decoded array (null when unset). + * + * @return int[]|null + */ + private function decodedReminderDays(): ?array + { + if ($this->reminderDays === null) { + return null; + } + + return json_decode($this->reminderDays, true); + }//end decodedReminderDays() +}//end class diff --git a/lib/Db/ExpiryPolicyMapper.php b/lib/Db/ExpiryPolicyMapper.php new file mode 100644 index 000000000..79cace572 --- /dev/null +++ b/lib/Db/ExpiryPolicyMapper.php @@ -0,0 +1,109 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\Doriath\Db; + +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Db\QBMapper; +use OCP\IDBConnection; + +/** + * Mapper for the doriath_expiry_policies table. + * + * @template-extends QBMapper + */ +class ExpiryPolicyMapper extends QBMapper +{ + /** + * Constructor for ExpiryPolicyMapper. + * + * @param IDBConnection $db The database connection + * + * @return void + */ + public function __construct(IDBConnection $db) + { + parent::__construct(db: $db, tableName: 'doriath_expiry_policies', entityClass: ExpiryPolicy::class); + }//end __construct() + + /** + * Find a policy by its UUID. + * + * @param string $id The policy UUID + * + * @return ExpiryPolicy + * + * @throws DoesNotExistException When no row matches + */ + public function findById(string $id): ExpiryPolicy + { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + + return $this->findEntity(query: $qb); + }//end findById() + + /** + * All policies of one owner (null owner = instance-wide policies). + * + * @param string|null $ownerId The owner (null = admin default rows) + * + * @return ExpiryPolicy[] + */ + public function findByOwner(?string $ownerId): array + { + $qb = $this->db->getQueryBuilder(); + $qb->select('*')->from($this->getTableName()); + + if ($ownerId === null) { + $qb->where($qb->expr()->isNull('owner_id')); + } else { + $qb->where($qb->expr()->eq('owner_id', $qb->createNamedParameter($ownerId))); + } + + return $this->findEntities(query: $qb); + }//end findByOwner() + + /** + * The policies applicable to a secret: the owner's rows plus the + * instance-wide rows, filtered by scope match in the service. + * + * @param string $ownerId The secret owner's user ID + * + * @return ExpiryPolicy[] + */ + public function findApplicable(string $ownerId): array + { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where( + $qb->expr()->orX( + $qb->expr()->eq('owner_id', $qb->createNamedParameter($ownerId)), + $qb->expr()->isNull('owner_id') + ) + ); + + return $this->findEntities(query: $qb); + }//end findApplicable() +}//end class diff --git a/lib/Db/RotationFlag.php b/lib/Db/RotationFlag.php new file mode 100644 index 000000000..4d9264243 --- /dev/null +++ b/lib/Db/RotationFlag.php @@ -0,0 +1,168 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\Doriath\Db; + +use DateTime; +use JsonSerializable; +use OCP\AppFramework\Db\Entity; + +/** + * Entity representing one rotation flag. + * + * @method string getSecretId() + * @method void setSecretId(string $secretId) + * @method string getReason() + * @method void setReason(string $reason) + * @method string getStatus() + * @method void setStatus(string $status) + * @method DateTime|null getFlaggedAt() + * @method void setFlaggedAt(DateTime $flaggedAt) + * @method string|null getFlaggedBy() + * @method void setFlaggedBy(?string $flaggedBy) + * @method DateTime|null getResolvedAt() + * @method void setResolvedAt(?DateTime $resolvedAt) + * @method DateTime|null getKeyUpdatedAtAtFlag() + * @method void setKeyUpdatedAtAtFlag(?DateTime $keyUpdatedAtAtFlag) + * + * @SuppressWarnings(PHPMD.LongVariable) Property names mirror DB columns. + */ +class RotationFlag extends Entity implements JsonSerializable +{ + + /** + * The flagged secret. + * + * @var string + */ + protected string $secretId = ''; + + /** + * The flag reason: `user_flagged`, `policy_expiry`, or + * `suite_compromise`. Empty default (NC Entity dirty-tracking). + * + * @var string + */ + protected string $reason = ''; + + /** + * The flag status: `open`, `rotated`, or `dismissed`. + * + * @var string + */ + protected string $status = ''; + + /** + * When the flag was raised. + * + * @var DateTime|null + */ + protected ?DateTime $flaggedAt = null; + + /** + * The user that raised the flag (null = system). + * + * @var string|null + */ + protected ?string $flaggedBy = null; + + /** + * When the flag was resolved. + * + * @var DateTime|null + */ + protected ?DateTime $resolvedAt = null; + + /** + * The head's key_updated_at frozen at flag time (rotation proof). + * + * @var DateTime|null + */ + protected ?DateTime $keyUpdatedAtAtFlag = null; + + /** + * The UUID primary key. + * + * @var string + */ + public $id = ''; + + /** + * Get the UUID primary key. + * + * @return string + */ + public function getId(): string + { + return (string) $this->id; + }//end getId() + + /** + * Set the UUID primary key. + * + * @param string $id The UUID + * + * @return void + */ + public function setId($id): void + { + $this->setter(name: 'id', args: [$id]); + }//end setId() + + /** + * Constructor for RotationFlag. + * + * @return void + */ + public function __construct() + { + $this->addType(fieldName: 'id', type: 'string'); + $this->addType(fieldName: 'secretId', type: 'string'); + $this->addType(fieldName: 'reason', type: 'string'); + $this->addType(fieldName: 'status', type: 'string'); + $this->addType(fieldName: 'flaggedAt', type: 'datetime'); + $this->addType(fieldName: 'flaggedBy', type: 'string'); + $this->addType(fieldName: 'resolvedAt', type: 'datetime'); + $this->addType(fieldName: 'keyUpdatedAtAtFlag', type: 'datetime'); + }//end __construct() + + /** + * Serialize the entity to an array for the API. + * + * @return array + */ + public function jsonSerialize(): array + { + return [ + 'id' => $this->getId(), + 'secretId' => $this->secretId, + 'reason' => $this->reason, + 'status' => $this->status, + 'flaggedAt' => $this->flaggedAt?->format('c'), + 'flaggedBy' => $this->flaggedBy, + 'resolvedAt' => $this->resolvedAt?->format('c'), + ]; + }//end jsonSerialize() +}//end class diff --git a/lib/Db/RotationFlagMapper.php b/lib/Db/RotationFlagMapper.php new file mode 100644 index 000000000..7906d6dec --- /dev/null +++ b/lib/Db/RotationFlagMapper.php @@ -0,0 +1,119 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\Doriath\Db; + +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Db\QBMapper; +use OCP\IDBConnection; + +/** + * Mapper for the doriath_rotation_flags table. + * + * @template-extends QBMapper + */ +class RotationFlagMapper extends QBMapper +{ + /** + * Constructor for RotationFlagMapper. + * + * @param IDBConnection $db The database connection + * + * @return void + */ + public function __construct(IDBConnection $db) + { + parent::__construct(db: $db, tableName: 'doriath_rotation_flags', entityClass: RotationFlag::class); + }//end __construct() + + /** + * Find a flag by its UUID. + * + * @param string $id The flag UUID + * + * @return RotationFlag + * + * @throws DoesNotExistException When no row matches + */ + public function findById(string $id): RotationFlag + { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); + + return $this->findEntity(query: $qb); + }//end findById() + + /** + * The flag row of a secret (open or resolved; unique per secret). + * + * @param string $secretId The secret UUID + * + * @return RotationFlag + * + * @throws DoesNotExistException When the secret carries no flag + */ + public function findBySecret(string $secretId): RotationFlag + { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('secret_id', $qb->createNamedParameter($secretId))); + + return $this->findEntity(query: $qb); + }//end findBySecret() + + /** + * All open flags whose secrets belong to a user. + * + * @param string $ownerId The owner user ID + * + * @return RotationFlag[] + */ + public function findOpenForOwner(string $ownerId): array + { + $qb = $this->db->getQueryBuilder(); + $qb->select('f.*') + ->from($this->getTableName(), 'f') + ->innerJoin('f', 'doriath_secrets', 's', $qb->expr()->eq('f.secret_id', 's.id')) + ->where($qb->expr()->eq('f.status', $qb->createNamedParameter('open'))) + ->andWhere($qb->expr()->eq('s.owner_type', $qb->createNamedParameter('user'))) + ->andWhere($qb->expr()->eq('s.owner_id', $qb->createNamedParameter($ownerId))); + + return $this->findEntities(query: $qb); + }//end findOpenForOwner() + + /** + * Delete a secret's flag row (delete cascade; idempotent). + * + * @param string $secretId The secret UUID + * + * @return void + */ + public function deleteBySecret(string $secretId): void + { + $qb = $this->db->getQueryBuilder(); + $qb->delete($this->getTableName()) + ->where($qb->expr()->eq('secret_id', $qb->createNamedParameter($secretId))); + $qb->executeStatement(); + }//end deleteBySecret() +}//end class diff --git a/lib/Db/Secret.php b/lib/Db/Secret.php index 098ee63c0..31d3c91e1 100644 --- a/lib/Db/Secret.php +++ b/lib/Db/Secret.php @@ -55,6 +55,8 @@ * @method void setPossiblyCompromisedAt(?DateTime $possiblyCompromisedAt) * @method DateTime|null getKeyUpdatedAt() * @method void setKeyUpdatedAt(?DateTime $keyUpdatedAt) + * @method DateTime|null getExpiresAt() + * @method void setExpiresAt(?DateTime $expiresAt) * @method string|null getMigrationError() * @method void setMigrationError(?string $migrationError) * @method DateTime|null getTombstonedAt() @@ -164,6 +166,13 @@ class Secret extends Entity implements JsonSerializable */ protected ?DateTime $keyUpdatedAt = null; + /** + * Optional per-secret expiry instant (rotation-expiry-policies §2.3). + * + * @var DateTime|null + */ + protected ?DateTime $expiresAt = null; + /** * A migration error message, if re-encryption failed (nullable). * @@ -255,6 +264,7 @@ public function __construct() $this->addType(fieldName: 'ownerId', type: 'string'); $this->addType(fieldName: 'possiblyCompromisedAt', type: 'datetime'); $this->addType(fieldName: 'keyUpdatedAt', type: 'datetime'); + $this->addType(fieldName: 'expiresAt', type: 'datetime'); $this->addType(fieldName: 'migrationError', type: 'string'); $this->addType(fieldName: 'tombstonedAt', type: 'datetime'); $this->addType(fieldName: 'tombstoneReason', type: 'string'); @@ -285,6 +295,7 @@ public function jsonSerialize(): array 'createdAt' => $this->createdAt?->format('c'), 'updatedAt' => $this->updatedAt?->format('c'), 'keyUpdatedAt' => $this->keyUpdatedAt?->format('c'), + 'expiresAt' => $this->expiresAt?->format('c'), 'possiblyCompromisedAt' => $this->possiblyCompromisedAt?->format('c'), 'tombstonedAt' => $this->tombstonedAt?->format('c'), 'tombstoneReason' => $this->tombstoneReason, diff --git a/lib/Db/SecretMapper.php b/lib/Db/SecretMapper.php index 7bd66e0ed..5b03a20a5 100644 --- a/lib/Db/SecretMapper.php +++ b/lib/Db/SecretMapper.php @@ -152,6 +152,28 @@ public function findByOwner( return $this->findEntities(query: $qb); }//end findByOwner() + /** + * Page through ALL user-owned secrets (rotation-expiry-policies §4.1 + * scan job). Ordered by id for stable pagination across runs. + * + * @param int $limit Maximum rows + * @param int $offset Row offset + * + * @return Secret[] + */ + public function findAllUserOwnedPaged(int $limit, int $offset): array + { + $qb = $this->db->getQueryBuilder(); + $qb->select('*') + ->from($this->getTableName()) + ->where($qb->expr()->eq('owner_type', $qb->createNamedParameter('user'))) + ->orderBy('id', 'ASC') + ->setMaxResults($limit) + ->setFirstResult($offset); + + return $this->findEntities(query: $qb); + }//end findAllUserOwnedPaged() + /** * Find an owner's secrets by exact (case-sensitive) plaintext name, * optionally constrained to a single folder. diff --git a/lib/Db/SecretVersion.php b/lib/Db/SecretVersion.php index 542881a48..1bad6aedf 100644 --- a/lib/Db/SecretVersion.php +++ b/lib/Db/SecretVersion.php @@ -69,7 +69,7 @@ class SecretVersion extends Entity implements JsonSerializable /** * The monotonically increasing version number per secret. * - * @var int + * @var integer */ protected int $versionNumber = 0; @@ -217,8 +217,8 @@ public function jsonSerializeWithBlobs(): array { $data = $this->jsonSerialize(); - $data['key'] = $this->key; - $data['login'] = $this->login; + $data['key'] = $this->key; + $data['login'] = $this->login; $data['additionalFields'] = $this->additionalFields; return $data; diff --git a/lib/Db/SecretVersionMapper.php b/lib/Db/SecretVersionMapper.php index 51ff7c9a0..3ff4fb223 100644 --- a/lib/Db/SecretVersionMapper.php +++ b/lib/Db/SecretVersionMapper.php @@ -103,7 +103,11 @@ public function nextVersionNumber(string $secretId): int $max = $result->fetchOne(); $result->closeCursor(); - return ((int) ($max ?: 0)) + 1; + if ($max === false || $max === null) { + return 1; + } + + return ((int) $max) + 1; }//end nextVersionNumber() /** @@ -125,7 +129,7 @@ public function pruneByCount(string $secretId, int $keep): int } foreach ($victims as $version) { - $this->delete($version); + $this->delete(entity: $version); } return count($victims); @@ -150,7 +154,7 @@ public function pruneOlderThan(DateTime $cutoff, int $limit=500): int $pruned = 0; foreach ($this->findEntities(query: $qb) as $version) { - $this->delete($version); + $this->delete(entity: $version); ++$pruned; } diff --git a/lib/Event/Audit/AuditEventTypes.php b/lib/Event/Audit/AuditEventTypes.php index 019ebdc08..d950cb93a 100644 --- a/lib/Event/Audit/AuditEventTypes.php +++ b/lib/Event/Audit/AuditEventTypes.php @@ -91,6 +91,13 @@ final class AuditEventTypes // number only, never ciphertext or values. public const SECRET_VERSION_RESTORED = 'secret.version_restored'; + // Rotation & expiry (rotation-expiry-policies §5.2) — ids/reasons only. + public const SECRET_EXPIRY_SET = 'secret.expiry_set'; + public const SECRET_ROTATION_FLAGGED = 'secret.rotation_flagged'; + public const SECRET_ROTATED = 'secret.rotated'; + public const SECRET_ROTATION_DISMISSED = 'secret.rotation_dismissed'; + public const POLICY_EXPIRY_CHANGED = 'policy.expiry_changed'; + // Encrypted attachments (encrypted-attachments §5.1) — id/size only, // never filename, file key, or content. public const ATTACHMENT_UPLOADED = 'attachment.uploaded'; @@ -171,6 +178,12 @@ public static function whitelist(): array self::EMERGENCY_ACCESS_REVOKED => ['grantorUserId', 'granteeUserId'], self::EMERGENCY_ACCESS_INVALIDATED => ['grantorUserId', 'granteeUserId', 'reason'], self::SECRET_VERSION_RESTORED => ['versionNumber'], + // Rotation & expiry — ids/reasons only (§5.2). + self::SECRET_EXPIRY_SET => ['expiresAt'], + self::SECRET_ROTATION_FLAGGED => ['reason'], + self::SECRET_ROTATED => ['reason'], + self::SECRET_ROTATION_DISMISSED => ['reason'], + self::POLICY_EXPIRY_CHANGED => ['scope', 'scopeId'], // Encrypted attachments — id/size only (§5.1). self::ATTACHMENT_UPLOADED => ['secretId', 'sizeBytes'], self::ATTACHMENT_DOWNLOADED => ['secretId', 'sizeBytes'], diff --git a/lib/Listener/SuiteCompromiseListener.php b/lib/Listener/SuiteCompromiseListener.php index f61f4414e..6312d241c 100644 --- a/lib/Listener/SuiteCompromiseListener.php +++ b/lib/Listener/SuiteCompromiseListener.php @@ -27,6 +27,7 @@ use OCA\Doriath\Db\ShareTargetMapper; use OCA\Doriath\Event\SuiteMigrationCompletedEvent; use OCA\Doriath\Service\NotificationService; +use OCA\Doriath\Service\RotationPolicyService; use OCP\AppFramework\Db\DoesNotExistException; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; @@ -45,10 +46,11 @@ class SuiteCompromiseListener implements IEventListener /** * Constructor. * - * @param SecretMapper $secretMapper The Secret mapper (lookup recipient copies) - * @param ShareTargetMapper $shareTargetMapper The share-target mapper (resolve owners) - * @param NotificationService $notificationService The notification dispatcher - * @param LoggerInterface $logger The logger + * @param SecretMapper $secretMapper The Secret mapper (lookup recipient copies) + * @param ShareTargetMapper $shareTargetMapper The share-target mapper (resolve owners) + * @param NotificationService $notificationService The notification dispatcher + * @param LoggerInterface $logger The logger + * @param RotationPolicyService|null $rotationPolicyService The rotation service (auto-flag) * * @return void */ @@ -57,6 +59,7 @@ public function __construct( private ShareTargetMapper $shareTargetMapper, private NotificationService $notificationService, private LoggerInterface $logger, + private ?RotationPolicyService $rotationPolicyService=null, ) { }//end __construct() @@ -84,6 +87,13 @@ public function handle(Event $event): void continue; } + // Auto-raise a rotation flag per compromised secret + // (rotation-expiry-policies §3.2; idempotent). + $this->rotationPolicyService?->flag( + secretId: $secret->getId(), + reason: 'suite_compromise' + ); + $ownerId = $this->resolveSourceOwner( recipientSecretId: $secret->getId(), fallbackOwnerId: $secret->getOwnerId() diff --git a/lib/Migration/Version000022Date20260718110000.php b/lib/Migration/Version000022Date20260718110000.php new file mode 100644 index 000000000..a7edcd02b --- /dev/null +++ b/lib/Migration/Version000022Date20260718110000.php @@ -0,0 +1,108 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\Doriath\Migration; + +use Closure; +use OCP\DB\ISchemaWrapper; +use OCP\DB\Types; +use OCP\Migration\IOutput; +use OCP\Migration\SimpleMigrationStep; + +/** + * Create expiry-policy + rotation-flag tables and the expires_at column. + */ +class Version000022Date20260718110000 extends SimpleMigrationStep +{ + /** + * Apply the schema changes. + * + * @param IOutput $output The output interface + * @param Closure $schemaClosure The schema closure + * @param array $options Migration options + * + * @return null|ISchemaWrapper + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper + { + // @var ISchemaWrapper $schema + $schema = $schemaClosure(); + $changed = false; + + if ($schema->hasTable('doriath_secrets') === true) { + $table = $schema->getTable('doriath_secrets'); + if ($table->hasColumn('expires_at') === false) { + $table->addColumn('expires_at', Types::DATETIME, ['notnull' => false]); + $table->addIndex(['expires_at'], 'doriath_sec_expires_idx'); + $changed = true; + } + } + + if ($schema->hasTable('doriath_expiry_policies') === false) { + $table = $schema->createTable('doriath_expiry_policies'); + + $table->addColumn('id', Types::STRING, ['notnull' => true, 'length' => 36]); + $table->addColumn('owner_id', Types::STRING, ['notnull' => false, 'length' => 64]); + $table->addColumn('scope', Types::STRING, ['notnull' => true, 'length' => 16]); + $table->addColumn('scope_id', Types::STRING, ['notnull' => true, 'length' => 64]); + $table->addColumn('max_age_days', Types::INTEGER, ['notnull' => false]); + $table->addColumn('reminder_days', Types::TEXT, ['notnull' => false]); + $table->addColumn('created_by', Types::STRING, ['notnull' => true, 'length' => 64]); + $table->addColumn('created_at', Types::DATETIME, ['notnull' => false]); + $table->addColumn('updated_at', Types::DATETIME, ['notnull' => false]); + + $table->setPrimaryKey(['id']); + $table->addIndex(['owner_id'], 'doriath_ep_owner_idx'); + $table->addUniqueIndex(['owner_id', 'scope', 'scope_id'], 'doriath_ep_scope_uniq'); + $changed = true; + } + + if ($schema->hasTable('doriath_rotation_flags') === false) { + $table = $schema->createTable('doriath_rotation_flags'); + + $table->addColumn('id', Types::STRING, ['notnull' => true, 'length' => 36]); + $table->addColumn('secret_id', Types::STRING, ['notnull' => true, 'length' => 36]); + $table->addColumn('reason', Types::STRING, ['notnull' => true, 'length' => 32]); + $table->addColumn('status', Types::STRING, ['notnull' => true, 'length' => 16]); + $table->addColumn('flagged_at', Types::DATETIME, ['notnull' => false]); + $table->addColumn('flagged_by', Types::STRING, ['notnull' => false, 'length' => 64]); + $table->addColumn('resolved_at', Types::DATETIME, ['notnull' => false]); + $table->addColumn('key_updated_at_at_flag', Types::DATETIME, ['notnull' => false]); + + $table->setPrimaryKey(['id']); + $table->addUniqueIndex(['secret_id'], 'doriath_rf_secret_uniq'); + $table->addIndex(['status'], 'doriath_rf_status_idx'); + $changed = true; + } + + if ($changed === false) { + return null; + } + + return $schema; + }//end changeSchema() +}//end class diff --git a/lib/Notification/DoriathNotifier.php b/lib/Notification/DoriathNotifier.php index 846899580..8543ef12b 100644 --- a/lib/Notification/DoriathNotifier.php +++ b/lib/Notification/DoriathNotifier.php @@ -206,6 +206,25 @@ public function prepare(INotification $notification, string $languageCode): INot ); break; + case 'secret_expiring': + $secretName = (string) ($p['secret_name'] ?? $l->t('a secret')); + $daysLeft = (int) ($p['days_left'] ?? 0); + $notification->setParsedSubject((string) $l->t('Secret expiring soon')); + $notification->setParsedMessage( + (string) $l->t('Your secret "%1$s" expires in %2$d day(s). Rotate it before then.', [$secretName, $daysLeft]) + ); + $this->withSecretLink(notification: $notification, params: $p); + break; + + case 'secret_rotation_due': + $secretName = (string) ($p['secret_name'] ?? $l->t('a secret')); + $notification->setParsedSubject((string) $l->t('Secret rotation due')); + $notification->setParsedMessage( + (string) $l->t('Your secret "%s" is past its expiry and has been flagged for rotation.', [$secretName]) + ); + $this->withSecretLink(notification: $notification, params: $p); + break; + case 'emergency_access_accessed': $granteeName = (string) ($p['grantee_name'] ?? $p['granteeUserId'] ?? $l->t('a trusted contact')); $notification->setParsedSubject((string) $l->t('Emergency access used')); diff --git a/lib/Service/AccountDeletionService.php b/lib/Service/AccountDeletionService.php index f69e40117..99aa70bfe 100644 --- a/lib/Service/AccountDeletionService.php +++ b/lib/Service/AccountDeletionService.php @@ -70,17 +70,19 @@ class AccountDeletionService /** * Constructor for AccountDeletionService. * - * @param SecretMapper $secretMapper The secret mapper - * @param FolderMapper $folderMapper The folder mapper - * @param ShareTargetMapper $shareMapper The share-target mapper - * @param GroupShareMapper $groupShareMapper The group-share mapper - * @param SecretDelegationMapper $delegationMapper The delegation mapper - * @param LinkShareMapper $linkShareMapper The link-share mapper - * @param SecretRequestMapper $requestMapper The secret-request mapper - * @param EncryptionSuiteMapper $suiteMapper The encryption-suite mapper - * @param SuiteMigrationMapper $migrationMapper The suite-migration mapper - * @param DashboardSettingMapper $settingMapper The settings mapper - * @param IEventDispatcher $dispatcher The event dispatcher + * @param SecretMapper $secretMapper The secret mapper + * @param FolderMapper $folderMapper The folder mapper + * @param ShareTargetMapper $shareMapper The share-target mapper + * @param GroupShareMapper $groupShareMapper The group-share mapper + * @param SecretDelegationMapper $delegationMapper The delegation mapper + * @param LinkShareMapper $linkShareMapper The link-share mapper + * @param SecretRequestMapper $requestMapper The secret-request mapper + * @param EncryptionSuiteMapper $suiteMapper The encryption-suite mapper + * @param SuiteMigrationMapper $migrationMapper The suite-migration mapper + * @param DashboardSettingMapper $settingMapper The settings mapper + * @param IEventDispatcher $dispatcher The event dispatcher + * @param AttachmentService|null $attachmentService The attachment service (delete cascade) + * @param SecretVersionService|null $versionService The version-history service (delete cascade) * * @return void */ diff --git a/lib/Service/AttachmentService.php b/lib/Service/AttachmentService.php index d732e8fcc..78fc8c438 100644 --- a/lib/Service/AttachmentService.php +++ b/lib/Service/AttachmentService.php @@ -55,7 +55,9 @@ */ class AttachmentService { - /** The IAppData folder holding attachment ciphertext blobs. */ + /** + * The IAppData folder holding attachment ciphertext blobs. + */ private const BLOB_FOLDER = 'attachments'; /** @@ -119,11 +121,11 @@ private function blobFolder(): \OCP\Files\SimpleFS\ISimpleFolder * owner's RSA-wrapped file key. Size limit and per-user quota are * enforced server-side in ciphertext bytes BEFORE persisting. * - * @param string $secretId The owning secret UUID - * @param string $userId The caller (must own the secret) - * @param string $blob The ciphertext bytes + * @param string $secretId The owning secret UUID + * @param string $userId The caller (must own the secret) + * @param string $blob The ciphertext bytes * @param string $encryptedMetadata The AES-GCM metadata ciphertext - * @param string $wrappedFileKey The owner's RSA-wrapped file key + * @param string $wrappedFileKey The owner's RSA-wrapped file key * * @return array{attachment: Attachment, grant: AttachmentGrant} * @@ -234,9 +236,9 @@ public function listForSecret(string $secretId, string $userId): array continue; } - $row = $attachment->jsonSerialize(); + $row = $attachment->jsonSerialize(); $row['wrappedFileKey'] = $grant->getWrappedFileKey(); - $out[] = $row; + $out[] = $row; } return $out; diff --git a/lib/Service/CertificateAuthorityService.php b/lib/Service/CertificateAuthorityService.php index 1fe20bfe7..ff535fe92 100644 --- a/lib/Service/CertificateAuthorityService.php +++ b/lib/Service/CertificateAuthorityService.php @@ -219,11 +219,11 @@ public function signPublicKey( string $commonName='Doriath User', ?string $privateKeyPem=null, ): string { - $intermediate = $this->caCertificateMapper->findActiveIntermediate(); - $intermediatePriv = $this->crypto->decrypt($intermediate->getPrivateKey()); - $intermediateKey = openssl_pkey_get_private(private_key: $intermediatePriv); - $intermediateCert = $intermediate->getCertificate(); - $submittedPub = openssl_pkey_get_public(public_key: $publicKeyPem); + $intermediate = $this->caCertificateMapper->findActiveIntermediate(); + $intermediatePriv = $this->crypto->decrypt($intermediate->getPrivateKey()); + $intermediateKey = openssl_pkey_get_private(private_key: $intermediatePriv); + $intermediateCert = $intermediate->getCertificate(); + $submittedPub = openssl_pkey_get_public(public_key: $publicKeyPem); if ($submittedPub === false) { throw new InvalidArgumentException('Invalid public key PEM'); diff --git a/lib/Service/DashboardService.php b/lib/Service/DashboardService.php index 5d1fa7ee6..2998f51b6 100644 --- a/lib/Service/DashboardService.php +++ b/lib/Service/DashboardService.php @@ -31,6 +31,7 @@ use OCA\Doriath\Db\DashboardSetting; use OCA\Doriath\Db\DashboardSettingMapper; use OCA\Doriath\Db\FolderMapper; +use OCA\Doriath\Db\RotationFlagMapper; use OCA\Doriath\Db\SecretMapper; use OCA\Doriath\Db\ShareTargetMapper; use OCP\AppFramework\Db\DoesNotExistException; @@ -74,12 +75,13 @@ class DashboardService * preference path keep their original two-argument signature. The * Nextcloud DI container injects them in production. * - * @param DashboardSettingMapper $mapper The dashboard-setting mapper - * @param LoggerInterface $logger The logger - * @param SecretMapper|null $secretMapper Secret counter (summary aggregator) - * @param FolderMapper|null $folderMapper Folder counter (summary aggregator) - * @param ShareTargetMapper|null $shareTargetMapper Shared-with-me counter (summary aggregator) - * @param ApplicationMapper|null $applicationMapper Pending-application counter (summary aggregator) + * @param DashboardSettingMapper $mapper The dashboard-setting mapper + * @param LoggerInterface $logger The logger + * @param SecretMapper|null $secretMapper Secret counter (summary aggregator) + * @param FolderMapper|null $folderMapper Folder counter (summary aggregator) + * @param ShareTargetMapper|null $shareTargetMapper Shared-with-me counter (summary aggregator) + * @param ApplicationMapper|null $applicationMapper Pending-application counter (summary aggregator) + * @param RotationFlagMapper|null $rotationFlagMapper Rotation-due counter (rotation-expiry-policies §7.2) * * @return void */ @@ -90,6 +92,7 @@ public function __construct( private ?FolderMapper $folderMapper=null, private ?ShareTargetMapper $shareTargetMapper=null, private ?ApplicationMapper $applicationMapper=null, + private ?RotationFlagMapper $rotationFlagMapper=null, ) { }//end __construct() @@ -146,6 +149,10 @@ public function fetchSummary(string $userId, bool $isAdmin): array fn: $foldersCount, metricId: 'folders_count', ), + 'rotation_due_count' => $this->safeCount( + fn: fn () => count($this->rotationFlagMapper?->findOpenForOwner($userId) ?? []), + metricId: 'rotation_due_count', + ), 'pending_apps_count' => null, 'is_admin' => $isAdmin, 'last_updated' => (new DateTime())->format('c'), diff --git a/lib/Service/FolderService.php b/lib/Service/FolderService.php index a436b3730..72cbfc7b0 100644 --- a/lib/Service/FolderService.php +++ b/lib/Service/FolderService.php @@ -49,11 +49,12 @@ class FolderService /** * Constructor for FolderService. * - * @param FolderMapper $mapper The folder mapper - * @param SecretMapper $secretMapper The secret mapper (for cascade operations) - * @param LoggerInterface $logger The logger interface - * @param IEventDispatcher|null $eventDispatcher The event dispatcher - * @param AttachmentService|null $attachmentService The attachment service (delete cascade) + * @param FolderMapper $mapper The folder mapper + * @param SecretMapper $secretMapper The secret mapper (for cascade operations) + * @param LoggerInterface $logger The logger interface + * @param IEventDispatcher|null $eventDispatcher The event dispatcher + * @param AttachmentService|null $attachmentService The attachment service (delete cascade) + * @param SecretVersionService|null $versionService The version-history service (delete cascade) * * @return void */ diff --git a/lib/Service/GdprService.php b/lib/Service/GdprService.php index 67dbdeedb..a6c1f0214 100644 --- a/lib/Service/GdprService.php +++ b/lib/Service/GdprService.php @@ -59,13 +59,15 @@ class GdprService /** * Constructor for GdprService. * - * @param SecretMapper $secretMapper The secret mapper - * @param ShareTargetMapper $shareMapper The share-target mapper - * @param SecretDelegationMapper $delegationMapper The delegation mapper - * @param LinkShareMapper $linkShareMapper The link-share mapper - * @param SecretRequestMapper $requestMapper The secret-request mapper - * @param EncryptionSuiteMapper $suiteMapper The encryption-suite mapper - * @param SettingsService $settingsService The settings service + * @param SecretMapper $secretMapper The secret mapper + * @param ShareTargetMapper $shareMapper The share-target mapper + * @param SecretDelegationMapper $delegationMapper The delegation mapper + * @param LinkShareMapper $linkShareMapper The link-share mapper + * @param SecretRequestMapper $requestMapper The secret-request mapper + * @param EncryptionSuiteMapper $suiteMapper The encryption-suite mapper + * @param SettingsService $settingsService The settings service + * @param \OCA\Doriath\Db\AttachmentMapper|null $attachmentMapper The attachment mapper (export metadata) + * @param \OCA\Doriath\Db\AttachmentGrantMapper|null $attachmentGrantMapper The attachment-grant mapper (export metadata) * * @return void */ @@ -152,7 +154,7 @@ private function collectAttachments(array $ownedSecrets, string $userId): array foreach ($this->attachmentMapper->findBySourceSecret(sourceSecretId: $secret->getId()) as $attachment) { $row = $attachment->jsonSerialize(); try { - $grant = $this->attachmentGrantMapper->findForRecipient( + $grant = $this->attachmentGrantMapper->findForRecipient( attachmentId: $attachment->getId(), recipientId: $userId ); diff --git a/lib/Service/NotificationService.php b/lib/Service/NotificationService.php index 9961f1cdd..144773171 100644 --- a/lib/Service/NotificationService.php +++ b/lib/Service/NotificationService.php @@ -64,6 +64,10 @@ class NotificationService // to a recipient; group-join approval request to the owner. 'team_folder_shared' => 'notify_shares', 'team_folder_join_request' => 'notify_group_shares', + // Rotation & expiry (rotation-expiry-policies §4): approaching + // expiry reminders and the overdue/rotation-due flag. + 'secret_expiring' => 'notify_security', + 'secret_rotation_due' => 'notify_security', ]; /** diff --git a/lib/Service/RotationPolicyService.php b/lib/Service/RotationPolicyService.php new file mode 100644 index 000000000..9fbed298d --- /dev/null +++ b/lib/Service/RotationPolicyService.php @@ -0,0 +1,548 @@ + + * @copyright 2024 Conduction B.V. + * @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12 + * + * @version GIT: + * + * @link https://conduction.nl + */ + +declare(strict_types=1); + +namespace OCA\Doriath\Service; + +use DateInterval; +use DateTime; +use InvalidArgumentException; +use OCA\Doriath\AppInfo\Application; +use OCA\Doriath\Db\ExpiryPolicy; +use OCA\Doriath\Db\ExpiryPolicyMapper; +use OCA\Doriath\Db\RotationFlag; +use OCA\Doriath\Db\RotationFlagMapper; +use OCA\Doriath\Db\Secret; +use OCA\Doriath\Db\SecretMapper; +use OCA\Doriath\Event\Audit\AuditEvent; +use OCA\Doriath\Event\Audit\AuditEventTypes; +use OCP\AppFramework\Db\DoesNotExistException; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IAppConfig; +use OCP\IConfig; +use Ramsey\Uuid\Uuid; + +/** + * Business logic for the rotation/expiry lifecycle. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) The resolution + + * flag invariants live in one place across policy/flag/secret mappers. + * @SuppressWarnings(PHPMD.TooManyPublicMethods) One method per API op. + */ +class RotationPolicyService +{ + /** + * Constructor for RotationPolicyService. + * + * @param ExpiryPolicyMapper $policyMapper The policy mapper + * @param RotationFlagMapper $flagMapper The flag mapper + * @param SecretMapper $secretMapper The secret mapper + * @param IAppConfig $appConfig The app config (admin defaults) + * @param IEventDispatcher|null $eventDispatcher The audit event dispatcher + * @param IConfig|null $config The NC config (user max-age override) + * + * @return void + */ + public function __construct( + private ExpiryPolicyMapper $policyMapper, + private RotationFlagMapper $flagMapper, + private SecretMapper $secretMapper, + private IAppConfig $appConfig, + private ?IEventDispatcher $eventDispatcher=null, + private ?IConfig $config=null, + ) { + }//end __construct() + + /** + * Resolve a secret's effective expiry: the EARLIEST of the per-secret + * `expires_at` and each applicable policy's `key_updated_at + + * max_age_days` (falling back to `created_at` when key age is null), + * including the admin default max age. Server-visible fields only. + * + * @param Secret $secret The secret row + * + * @return DateTime|null The effective expiry (null = never expires) + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-effective-expiry-resolution + */ + public function resolveEffectiveExpiry(Secret $secret): ?DateTime + { + $candidates = []; + + if ($secret->getExpiresAt() !== null) { + $candidates[] = $secret->getExpiresAt(); + } + + $base = $secret->getKeyUpdatedAt() ?? $secret->getCreatedAt(); + if ($base !== null) { + foreach ($this->policyMapper->findApplicable(ownerId: $secret->getOwnerId()) as $policy) { + if ($this->policyApplies(policy: $policy, secret: $secret) === false) { + continue; + } + + $maxAge = $policy->getMaxAgeDays(); + if ($maxAge !== null && $maxAge > 0) { + $candidates[] = (clone $base)->add(new DateInterval('P'.$maxAge.'D')); + } + } + + // Per-user override (0 = off), then instance-wide admin + // default (0 = off) — precedence is moot under min(). + $userMax = (int) ($this->config?->getUserValue( + $secret->getOwnerId(), + Application::APP_ID, + 'expiry_max_age_days', + '0' + ) ?? 0); + if ($userMax > 0) { + $candidates[] = (clone $base)->add(new DateInterval('P'.$userMax.'D')); + } + + $adminMax = $this->appConfig->getValueInt(Application::APP_ID, 'expiry_default_max_age_days', 0); + if ($adminMax > 0) { + $candidates[] = (clone $base)->add(new DateInterval('P'.$adminMax.'D')); + } + }//end if + + if ($candidates === []) { + return null; + } + + return min($candidates); + }//end resolveEffectiveExpiry() + + /** + * Whether a policy's scope matches a secret. + * + * @param ExpiryPolicy $policy The policy + * @param Secret $secret The secret + * + * @return bool + */ + private function policyApplies(ExpiryPolicy $policy, Secret $secret): bool + { + if ($policy->getScope() === 'type') { + return $policy->getScopeId() === (string) $secret->getTypeId(); + } + + if ($policy->getScope() === 'folder') { + return $policy->getScopeId() === (string) $secret->getFolderId(); + } + + return false; + }//end policyApplies() + + /** + * List the caller's policies plus the instance-wide rows. + * + * @param string $userId The caller + * + * @return ExpiryPolicy[] + */ + public function listPolicies(string $userId): array + { + return $this->policyMapper->findApplicable(ownerId: $userId); + }//end listPolicies() + + /** + * Create or update a type/folder policy for the caller. + * + * @param string $userId The caller + * @param string $scope The scope (`type`|`folder`) + * @param string $scopeId The scoped type/folder id + * @param int|null $maxAgeDays Max credential age in days (null = reminder-only) + * @param int[] $reminderDays Reminder thresholds in days + * + * @return ExpiryPolicy + * + * @throws InvalidArgumentException On invalid input + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-expiry-policies + */ + public function upsertPolicy( + string $userId, + string $scope, + string $scopeId, + ?int $maxAgeDays, + array $reminderDays=[], + ): ExpiryPolicy { + if (in_array($scope, ['type', 'folder'], true) === false) { + throw new InvalidArgumentException('scope must be type or folder'); + } + + if ($scopeId === '') { + throw new InvalidArgumentException('scopeId is required'); + } + + if ($maxAgeDays !== null && $maxAgeDays < 1) { + throw new InvalidArgumentException('maxAgeDays must be positive or null'); + } + + $reminderDays = array_values(array_filter(array_map('intval', $reminderDays), static fn ($d) => $d > 0)); + + $encodedReminders = null; + if ($reminderDays !== []) { + $encodedReminders = (string) json_encode($reminderDays); + } + + $policy = null; + foreach ($this->policyMapper->findByOwner(ownerId: $userId) as $existing) { + if ($existing->getScope() === $scope && $existing->getScopeId() === $scopeId) { + $policy = $existing; + break; + } + } + + if ($policy === null) { + $policy = new ExpiryPolicy(); + $policy->setId(Uuid::uuid4()->toString()); + $policy->setOwnerId($userId); + $policy->setScope($scope); + $policy->setScopeId($scopeId); + $policy->setCreatedBy($userId); + $policy->setCreatedAt(new DateTime()); + $policy->setMaxAgeDays($maxAgeDays); + $policy->setReminderDays($encodedReminders); + $policy->setUpdatedAt(new DateTime()); + $policy = $this->policyMapper->insert($policy); + } else { + $policy->setMaxAgeDays($maxAgeDays); + $policy->setReminderDays($encodedReminders); + $policy->setUpdatedAt(new DateTime()); + $policy = $this->policyMapper->update($policy); + } + + $this->dispatchAudit( + actorId: $userId, + eventType: AuditEventTypes::POLICY_EXPIRY_CHANGED, + objectId: $policy->getId(), + metadata: [ + 'scope' => $scope, + 'scopeId' => $scopeId, + ], + ); + + return $policy; + }//end upsertPolicy() + + /** + * Delete one of the caller's policies. + * + * @param string $policyId The policy UUID + * @param string $userId The caller + * + * @return void + * + * @throws InvalidArgumentException On not found / foreign owner + */ + public function deletePolicy(string $policyId, string $userId): void + { + try { + $policy = $this->policyMapper->findById($policyId); + } catch (DoesNotExistException) { + throw new InvalidArgumentException('Policy not found'); + } + + if ($policy->getOwnerId() !== $userId) { + throw new InvalidArgumentException('Policy not found'); + } + + $this->policyMapper->delete($policy); + }//end deletePolicy() + + /** + * Raise (or return the existing open) rotation flag for a secret — + * idempotent one-open-flag-per-secret. + * + * @param string $secretId The secret UUID + * @param string $reason The reason (`user_flagged`|`policy_expiry`|`suite_compromise`) + * @param string|null $flaggedBy The raising user (null = system) + * + * @return RotationFlag + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-rotation-flags + */ + public function flag(string $secretId, string $reason, ?string $flaggedBy=null): RotationFlag + { + try { + $existing = $this->flagMapper->findBySecret(secretId: $secretId); + if ($existing->getStatus() === 'open') { + return $existing; + } + + // A resolved flag is re-opened (fresh reason + proof point). + $existing->setReason($reason); + $existing->setStatus('open'); + $existing->setFlaggedAt(new DateTime()); + $existing->setFlaggedBy($flaggedBy); + $existing->setResolvedAt(null); + $existing->setKeyUpdatedAtAtFlag($this->headKeyUpdatedAt(secretId: $secretId)); + return $this->flagMapper->update($existing); + } catch (DoesNotExistException) { + // No flag yet — create below. + } + + $flagRow = new RotationFlag(); + $flagRow->setId(Uuid::uuid4()->toString()); + $flagRow->setSecretId($secretId); + $flagRow->setReason($reason); + $flagRow->setStatus('open'); + $flagRow->setFlaggedAt(new DateTime()); + $flagRow->setFlaggedBy($flaggedBy); + $flagRow->setKeyUpdatedAtAtFlag($this->headKeyUpdatedAt(secretId: $secretId)); + $flagRow = $this->flagMapper->insert($flagRow); + + $this->dispatchAudit( + actorId: ($flaggedBy ?? 'system'), + eventType: AuditEventTypes::SECRET_ROTATION_FLAGGED, + objectId: $secretId, + metadata: ['reason' => $reason], + ); + + return $flagRow; + }//end flag() + + /** + * Batch-flag secrets the caller owns (client breach findings send IDs + * ONLY — no verdicts, scores, or digests are persisted). + * + * @param string $userId The caller + * @param string[] $secretIds The secret UUIDs + * + * @return int Flags now open + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-rotation-flags + */ + public function flagBatch(string $userId, array $secretIds): int + { + $flagged = 0; + foreach ($secretIds as $secretId) { + try { + $secret = $this->secretMapper->findById((string) $secretId); + } catch (DoesNotExistException) { + continue; + } + + if ($secret->getOwnerType() !== 'user' || $secret->getOwnerId() !== $userId) { + continue; + } + + $this->flag(secretId: (string) $secretId, reason: 'user_flagged', flaggedBy: $userId); + ++$flagged; + } + + return $flagged; + }//end flagBatch() + + /** + * Open flags for the caller's secrets. + * + * @param string $userId The caller + * + * @return RotationFlag[] + */ + public function openFlags(string $userId): array + { + return $this->flagMapper->findOpenForOwner(ownerId: $userId); + }//end openFlags() + + /** + * Mark a flag rotated — ONLY when the head's `key_updated_at` has + * advanced past the value frozen at flag time (a proven rotation). + * Otherwise the caller is told to rotate first (re-request path). + * + * @param string $flagId The flag UUID + * @param string $userId The caller (must own the secret) + * + * @return array{resolved:bool,requiresRotation:bool} + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-mark-rotated + */ + public function markRotated(string $flagId, string $userId): array + { + $flagRow = $this->loadOwnedFlag(flagId: $flagId, userId: $userId); + + $head = $this->secretMapper->findById($flagRow->getSecretId()); + $frozen = $flagRow->getKeyUpdatedAtAtFlag(); + $current = $head->getKeyUpdatedAt(); + + $advanced = $current !== null && ($frozen === null || $current > $frozen); + if ($advanced === false) { + return [ + 'resolved' => false, + 'requiresRotation' => true, + ]; + } + + $flagRow->setStatus('rotated'); + $flagRow->setResolvedAt(new DateTime()); + $this->flagMapper->update($flagRow); + + $this->dispatchAudit( + actorId: $userId, + eventType: AuditEventTypes::SECRET_ROTATED, + objectId: $flagRow->getSecretId(), + metadata: ['reason' => $flagRow->getReason()], + ); + + return [ + 'resolved' => true, + 'requiresRotation' => false, + ]; + }//end markRotated() + + /** + * Dismiss a flag without rotation (owner judgment call; audited). + * + * @param string $flagId The flag UUID + * @param string $userId The caller (must own the secret) + * + * @return void + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-mark-rotated + */ + public function dismiss(string $flagId, string $userId): void + { + $flagRow = $this->loadOwnedFlag(flagId: $flagId, userId: $userId); + + $flagRow->setStatus('dismissed'); + $flagRow->setResolvedAt(new DateTime()); + $this->flagMapper->update($flagRow); + + $this->dispatchAudit( + actorId: $userId, + eventType: AuditEventTypes::SECRET_ROTATION_DISMISSED, + objectId: $flagRow->getSecretId(), + metadata: ['reason' => $flagRow->getReason()], + ); + }//end dismiss() + + /** + * Auto-raise `suite_compromise` flags for every possibly-compromised + * secret of a user (called from the compromise sweep). Idempotent. + * + * @param string $ownerId The affected owner + * + * @return int Flags raised or already open + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-rotation-flags + */ + public function flagCompromisedSecrets(string $ownerId): int + { + $count = 0; + foreach ($this->secretMapper->findByOwner('user', $ownerId, null, null, 'asc', 100000, 0) as $secret) { + if ($secret->getPossiblyCompromisedAt() === null) { + continue; + } + + $this->flag(secretId: $secret->getId(), reason: 'suite_compromise'); + ++$count; + } + + return $count; + }//end flagCompromisedSecrets() + + /** + * Delete a secret's flag row (delete cascade; idempotent). + * + * @param string $secretId The secret UUID + * + * @return void + */ + public function deleteForSecret(string $secretId): void + { + $this->flagMapper->deleteBySecret(secretId: $secretId); + }//end deleteForSecret() + + /** + * The head's current key_updated_at (null-tolerant). + * + * @param string $secretId The secret UUID + * + * @return DateTime|null + */ + private function headKeyUpdatedAt(string $secretId): ?DateTime + { + try { + return $this->secretMapper->findById($secretId)->getKeyUpdatedAt(); + } catch (DoesNotExistException) { + return null; + } + }//end headKeyUpdatedAt() + + /** + * Load a flag and assert the caller owns its secret. + * + * @param string $flagId The flag UUID + * @param string $userId The caller + * + * @return RotationFlag + * + * @throws InvalidArgumentException On not found / foreign owner + */ + private function loadOwnedFlag(string $flagId, string $userId): RotationFlag + { + try { + $flagRow = $this->flagMapper->findById($flagId); + } catch (DoesNotExistException) { + throw new InvalidArgumentException('Flag not found'); + } + + try { + $secret = $this->secretMapper->findById($flagRow->getSecretId()); + } catch (DoesNotExistException) { + throw new InvalidArgumentException('Flag not found'); + } + + if ($secret->getOwnerType() !== 'user' || $secret->getOwnerId() !== $userId) { + throw new InvalidArgumentException('Flag not found'); + } + + return $flagRow; + }//end loadOwnedFlag() + + /** + * Dispatch an audit event (identifiers only). + * + * @param string $actorId The actor + * @param string $eventType The event type + * @param string $objectId The object id + * @param array $metadata The whitelisted metadata + * + * @return void + */ + private function dispatchAudit(string $actorId, string $eventType, string $objectId, array $metadata): void + { + $this->eventDispatcher?->dispatchTyped( + AuditEvent::forUser( + actorId: $actorId, + eventType: $eventType, + objectType: 'secret', + objectId: $objectId, + objectName: '', + metadata: $metadata, + ) + ); + }//end dispatchAudit() +}//end class diff --git a/lib/Service/SecretService.php b/lib/Service/SecretService.php index 5f3135622..1cbea234f 100644 --- a/lib/Service/SecretService.php +++ b/lib/Service/SecretService.php @@ -136,6 +136,7 @@ class SecretService * @param AuditService|null $auditService The audit recorder (single write path) * @param AttachmentService|null $attachmentService The attachment service (delete cascade) * @param SecretVersionService|null $versionService The version-history service (pre-update snapshots) + * @param RotationPolicyService|null $rotationPolicyService The rotation service (flag cascade) * * @return void */ @@ -154,6 +155,7 @@ public function __construct( private ?AuditService $auditService=null, private ?AttachmentService $attachmentService=null, private ?SecretVersionService $versionService=null, + private ?RotationPolicyService $rotationPolicyService=null, ) { }//end __construct() @@ -903,6 +905,9 @@ public function delete(string $id, string $userId): void // Version-history cascade (secret-version-history §5.2). $this->versionService?->deleteForSecret($id); + // Rotation-flag cascade (rotation-expiry-policies). + $this->rotationPolicyService?->deleteForSecret($id); + $this->mapper->delete($secret); $this->logger->info("Doriath: secret {$id} deleted by {$userId}"); @@ -1254,6 +1259,61 @@ private function clampLimit(int $limit): int return min($limit, self::MAX_LIMIT); }//end clampLimit() + /** + * Load an owned secret WITHOUT dispatching a secret.read audit event + * (rotation-expiry-policies §5.1) — for metadata-only lookups such as + * effective-expiry resolution; no encrypted blob leaves this path. + * + * @param string $id The secret UUID + * @param string $userId The caller (must own the secret) + * + * @return Secret + * + * @throws NotFoundException When the secret does not exist + * @throws ForbiddenException When the secret belongs to another user + */ + public function findOwned(string $id, string $userId): Secret + { + return $this->loadOwned(id: $id, userId: $userId); + }//end findOwned() + + /** + * Set or clear a secret's per-secret expiry (rotation-expiry-policies + * §2.3) — owner-only; NEVER touches ciphertext or `key_updated_at`. + * + * @param string $id The secret UUID + * @param DateTime|null $expiresAt The expiry instant (null = clear) + * @param string $userId The caller (must own the secret) + * + * @return Secret + * + * @throws NotFoundException When the secret does not exist + * @throws ForbiddenException When the secret belongs to another user + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-per-secret-expiry + */ + public function setExpiry(string $id, ?DateTime $expiresAt, string $userId): Secret + { + $secret = $this->loadOwned(id: $id, userId: $userId); + + $secret->setExpiresAt($expiresAt); + $secret->setUpdatedAt(new DateTime()); + $this->mapper->update($secret); + + $this->dispatchAudit( + event: AuditEvent::forUser( + actorId: $userId, + eventType: AuditEventTypes::SECRET_EXPIRY_SET, + objectType: 'secret', + objectId: $id, + objectName: $secret->getName(), + metadata: ['expiresAt' => $expiresAt?->format('c')], + ) + ); + + return $secret; + }//end setExpiry() + /** * Whether any versionable field differs between two states of a * secret row (secret-version-history §2.2). Pure string comparison — diff --git a/lib/Service/SettingsService.php b/lib/Service/SettingsService.php index 127403199..7c223965f 100644 --- a/lib/Service/SettingsService.php +++ b/lib/Service/SettingsService.php @@ -79,6 +79,9 @@ class SettingsService // checking; UI is shown only when the admin gate is also on. 'health_staleness_days' => '365', 'breach_check_opt_in' => '0', + // Per-user max credential age in days (rotation-expiry-policies + // §2.2); '0' = off. Feeds effective-expiry resolution. + 'expiry_max_age_days' => '0', ]; /** @@ -146,19 +149,25 @@ public function getAdminSettings(): array { $appId = Application::APP_ID; $settings = [ - 'min_password_length' => $this->appConfig->getValueInt($appId, 'min_password_length', 12), - 'min_password_score' => $this->appConfig->getValueInt($appId, 'min_password_score', 3), - 'default_session_timeout' => $this->appConfig->getValueString($appId, 'default_session_timeout', 'session'), - 'ca_auto_renew_enabled' => $this->appConfig->getValueBool($appId, 'ca_auto_renew_enabled', true), - 'audit_retention_days' => $this->appConfig->getValueInt( + 'min_password_length' => $this->appConfig->getValueInt($appId, 'min_password_length', 12), + 'min_password_score' => $this->appConfig->getValueInt($appId, 'min_password_score', 3), + 'default_session_timeout' => $this->appConfig->getValueString($appId, 'default_session_timeout', 'session'), + 'ca_auto_renew_enabled' => $this->appConfig->getValueBool($appId, 'ca_auto_renew_enabled', true), + 'audit_retention_days' => $this->appConfig->getValueInt( $appId, 'audit_retention_days', self::AUDIT_RETENTION_DEFAULT ), - 'breach_check_enabled' => $this->appConfig->getValueBool($appId, 'breach_check_enabled', false), - 'version_retention_count' => $this->appConfig->getValueInt($appId, 'version_retention_count', 20), - 'version_retention_days' => $this->appConfig->getValueInt($appId, 'version_retention_days', 365), - 'attachment_max_bytes' => $this->appConfig->getValueInt($appId, 'attachment_max_bytes', 26214400), + 'breach_check_enabled' => $this->appConfig->getValueBool($appId, 'breach_check_enabled', false), + 'expiry_default_max_age_days' => $this->appConfig->getValueInt($appId, 'expiry_default_max_age_days', 0), + 'expiry_reminder_days' => json_decode( + $this->appConfig->getValueString($appId, 'expiry_reminder_days', '[30,7,1]'), + true + ), + 'expiry_policy_enforced' => $this->appConfig->getValueBool($appId, 'expiry_policy_enforced', false), + 'version_retention_count' => $this->appConfig->getValueInt($appId, 'version_retention_count', 20), + 'version_retention_days' => $this->appConfig->getValueInt($appId, 'version_retention_days', 365), + 'attachment_max_bytes' => $this->appConfig->getValueInt($appId, 'attachment_max_bytes', 26214400), 'attachment_user_quota_bytes' => $this->appConfig->getValueInt( $appId, 'attachment_user_quota_bytes', @@ -247,6 +256,35 @@ public function updateAdminSettings(array $data): array $this->appConfig->setValueBool($appId, 'breach_check_enabled', (bool) $data['breach_check_enabled']); } + // Expiry defaults (rotation-expiry-policies §2.2): admin max age + // ships OFF (0); reminder thresholds validated as positive ints. + if (isset($data['expiry_default_max_age_days']) === true) { + $maxAge = (int) $data['expiry_default_max_age_days']; + if ($maxAge < 0) { + throw new InvalidArgumentException('expiry_default_max_age_days must be 0 (off) or positive'); + } + + $this->appConfig->setValueInt($appId, 'expiry_default_max_age_days', $maxAge); + } + + if (isset($data['expiry_reminder_days']) === true) { + $thresholds = array_values( + array_filter( + array_map('intval', (array) $data['expiry_reminder_days']), + static fn (int $d): bool => $d > 0 + ) + ); + if ($thresholds === []) { + throw new InvalidArgumentException('expiry_reminder_days needs at least one positive threshold'); + } + + $this->appConfig->setValueString($appId, 'expiry_reminder_days', (string) json_encode($thresholds)); + } + + if (isset($data['expiry_policy_enforced']) === true) { + $this->appConfig->setValueBool($appId, 'expiry_policy_enforced', (bool) $data['expiry_policy_enforced']); + } + // Version retention (secret-version-history §4.1): a floor of 1 // kept version preserves restorability; days 0 = unlimited age. if (isset($data['version_retention_count']) === true) { diff --git a/lib/Service/ShareService.php b/lib/Service/ShareService.php index 4a23ecd07..f3f80bbf5 100644 --- a/lib/Service/ShareService.php +++ b/lib/Service/ShareService.php @@ -72,6 +72,7 @@ class ShareService * @param IDBConnection $db The DB connection (for syncUpdate transaction) * @param LoggerInterface $logger The logger interface * @param IEventDispatcher|null $eventDispatcher The event dispatcher + * @param AttachmentService|null $attachmentService The attachment service (revoke cascade) * * @return void */ @@ -342,7 +343,7 @@ public function revokeShare(string $shareId, string $userId): void } catch (Throwable $exception) { $this->db->rollBack(); throw $exception; - } + }//end try $this->logger->info( 'Revoked share '.$shareId.' for source '.$entity->getSourceSecretId(), diff --git a/lib/Service/TeamFolderService.php b/lib/Service/TeamFolderService.php index d7c392c2e..0298975a6 100644 --- a/lib/Service/TeamFolderService.php +++ b/lib/Service/TeamFolderService.php @@ -561,7 +561,7 @@ public function reconcile(string $teamFolderId, string $userId): array public function registerFanOutShares(string $teamFolderId, array $shares, string $userId): array { $createdRows = []; - $teamFolder = $this->loadOwnedTeamFolder(teamFolderId: $teamFolderId, userId: $userId); + $teamFolder = $this->loadOwnedTeamFolder(teamFolderId: $teamFolderId, userId: $userId); $subtreeSecretIds = []; foreach ($this->subtreeSecretRefs(teamFolder: $teamFolder) as $secretRef) { @@ -622,7 +622,7 @@ public function registerFanOutShares(string $teamFolderId, array $shares, string $this->shareTargetMapper->insert($entity); ++$created; $newRecipients[$targetUserId] = true; - $createdRows[] = [ + $createdRows[] = [ 'sourceSecretId' => $sourceSecretId, 'targetUserId' => $targetUserId, 'recipientSecretId' => $copy->getId(), diff --git a/openspec/changes/rotation-expiry-policies/tasks.md b/openspec/changes/rotation-expiry-policies/tasks.md index 578bcdd52..1720d52fb 100644 --- a/openspec/changes/rotation-expiry-policies/tasks.md +++ b/openspec/changes/rotation-expiry-policies/tasks.md @@ -2,47 +2,50 @@ ## 1. Data layer -- [ ] 1.1 Migration: add nullable `expires_at` to `doriath_secrets`; new tables `doriath_expiry_policies` (`id`, `owner_id` nullable, `scope` enum `type|folder`, `scope_id`, `max_age_days` nullable, `reminder_days` JSON nullable, `created_by`, `created_at`, `updated_at`; unique `(owner_id, scope, scope_id)`) and `doriath_rotation_flags` (`id`, `secret_id`, `reason` enum, `status` enum, `flagged_at`, `flagged_by` nullable, `resolved_at` nullable, `key_updated_at_at_flag` nullable; unique `(secret_id)`) -- [ ] 1.2 `ExpiryPolicy` + `RotationFlag` entities and `ExpiryPolicyMapper` + `RotationFlagMapper` (standard `QBMapper` pattern matching `SecretMapper`); add `expiresAt` accessor to `Secret` +- [x] 1.1 Migration: add nullable `expires_at` to `doriath_secrets`; new tables `doriath_expiry_policies` (`id`, `owner_id` nullable, `scope` enum `type|folder`, `scope_id`, `max_age_days` nullable, `reminder_days` JSON nullable, `created_by`, `created_at`, `updated_at`; unique `(owner_id, scope, scope_id)`) and `doriath_rotation_flags` (`id`, `secret_id`, `reason` enum, `status` enum, `flagged_at`, `flagged_by` nullable, `resolved_at` nullable, `key_updated_at_at_flag` nullable; unique `(secret_id)`) +- [x] 1.2 `ExpiryPolicy` + `RotationFlag` entities and `ExpiryPolicyMapper` + `RotationFlagMapper` (standard `QBMapper` pattern matching `SecretMapper`); add `expiresAt` accessor to `Secret` ## 2. Policy + resolution service -- [ ] 2.1 `RotationPolicyService::resolveEffectiveExpiry(secret)` — earliest of per-secret `expires_at` and each applicable policy's `key_updated_at + max_age_days` (fallback `created_at` when `key_updated_at` null); server-visible fields only, no decryption -- [ ] 2.2 `RotationPolicyService` CRUD for type/folder policies; extend `SettingsService` with admin keys `expiry_default_max_age_days` (default 0), `expiry_reminder_days` (default `[30,7,1]`), `expiry_policy_enforced` (default false) and user override `expiry_max_age_days` -- [ ] 2.3 `SecretService`: set/clear per-secret `expires_at` without touching ciphertext or `key_updated_at`; owner-only guard +- [x] 2.1 `RotationPolicyService::resolveEffectiveExpiry(secret)` — earliest of per-secret `expires_at` and each applicable policy's `key_updated_at + max_age_days` (fallback `created_at` when `key_updated_at` null); server-visible fields only, no decryption +- [x] 2.2 `RotationPolicyService` CRUD for type/folder policies; extend `SettingsService` with admin keys `expiry_default_max_age_days` (default 0), `expiry_reminder_days` (default `[30,7,1]`), `expiry_policy_enforced` (default false) and user override `expiry_max_age_days` +- [x] 2.3 `SecretService`: set/clear per-secret `expires_at` without touching ciphertext or `key_updated_at`; owner-only guard ## 3. Rotation flags + mark-rotated -- [ ] 3.1 `RotationPolicyService::flagBatch(userId, secretIds)` (reason `user_flagged`, IDs only) and `flag(secretId, reason)` idempotent one-open-flag-per-secret -- [ ] 3.2 `markRotated(flagId, ownerId)` — transition to `rotated` only when `key_updated_at` advanced past `key_updated_at_at_flag`; else return the re-request path; `dismiss(flagId, ownerId)` -- [ ] 3.3 Suite-compromise handling auto-raises `suite_compromise` flags for every `possibly_compromised_at` secret (reuse `SuiteCompromiseListener` sweep) +- [x] 3.1 `RotationPolicyService::flagBatch(userId, secretIds)` (reason `user_flagged`, IDs only) and `flag(secretId, reason)` idempotent one-open-flag-per-secret +- [x] 3.2 `markRotated(flagId, ownerId)` — transition to `rotated` only when `key_updated_at` advanced past `key_updated_at_at_flag`; else return the re-request path; `dismiss(flagId, ownerId)` +- [x] 3.3 Suite-compromise handling auto-raises `suite_compromise` flags for every `possibly_compromised_at` secret (reuse `SuiteCompromiseListener` sweep) ## 4. Background job -- [ ] 4.1 `ScanExpiringSecretsJob` (`TimedJob`, daily `setInterval(86400)`, mirrors `CheckRootCertificateExpiry`): notify on approaching-threshold + overdue via `NotificationService`, one notification per secret+threshold, gated by `notify_security`; auto-raise `policy_expiry` flags for overdue; register the job in `appinfo/info.xml` `` alongside the CA/audit/emergency jobs +- [x] 4.1 `ScanExpiringSecretsJob` (`TimedJob`, daily `setInterval(86400)`, mirrors `CheckRootCertificateExpiry`): notify on approaching-threshold + overdue via `NotificationService`, one notification per secret+threshold, gated by `notify_security`; auto-raise `policy_expiry` flags for overdue; register the job in `appinfo/info.xml` `` alongside the CA/audit/emergency jobs ## 5. Notifications + audit -- [ ] 5.1 `DoriathNotifier` case + `NotificationService` method for expiry reminders (deep-link to secret, approaching vs overdue subjects) -- [ ] 5.2 Add `secret.expiry_set`, `secret.rotation_flagged`, `secret.rotated`, `secret.rotation_dismissed`, `policy.expiry_changed` to `AuditEventTypes` with non-sensitive-only whitelists; dispatch from the service +- [x] 5.1 `DoriathNotifier` case + `NotificationService` method for expiry reminders (deep-link to secret, approaching vs overdue subjects) +- [x] 5.2 Add `secret.expiry_set`, `secret.rotation_flagged`, `secret.rotated`, `secret.rotation_dismissed`, `policy.expiry_changed` to `AuditEventTypes` with non-sensitive-only whitelists; dispatch from the service ## 6. Controllers + routes -- [ ] 6.1 `ExpiryPolicyController` (index/create/update/destroy) and per-secret `secret#setExpiry` (`PUT /api/v1/secrets/{id}/expiry`) — `#[NoAdminRequired]`, per-object owner guard -- [ ] 6.2 `RotationFlagController` (`index`, `batch`, `markRotated`, `dismiss`); admin instance-default policy managed via the settings surface; register all routes under a commented "Rotation & expiry" section in `appinfo/routes.php` +- [x] 6.1 `ExpiryPolicyController` (index/create/update/destroy) and per-secret `secret#setExpiry` (`PUT /api/v1/secrets/{id}/expiry`) — `#[NoAdminRequired]`, per-object owner guard + > Note: consolidated with 6.2 into a single `RotationController` (policies + flags + expiry share the service and auth pattern); routes and behavior are as specced. +- [x] 6.2 `RotationFlagController` (`index`, `batch`, `markRotated`, `dismiss`); admin instance-default policy managed via the settings surface; register all routes under a commented "Rotation & expiry" section in `appinfo/routes.php` ## 7. Frontend -- [ ] 7.1 Expiry field + status chip on the secret detail view; policy admin panel (type/folder rules, admin default) via `CnSettingsSection` -- [ ] 7.2 Dashboard rotation-due card + rotation category in the password-health report, each finding deep-linking to the secret -- [ ] 7.3 Per-secret "mark rotated" / "re-request rotation" actions and a client batch-flag action wired from the health breach findings (IDs only) +- [x] 7.1 Expiry field + status chip on the secret detail view; policy admin panel (type/folder rules, admin default) via `CnSettingsSection` + > Note: the admin `CnSettingsSection` covers the instance default max age + reminder thresholds; per-user type/folder rules are fully served by the API + Pinia store (`upsertPolicy`/`deletePolicy`), a dedicated rule-editor UI is deferred (tracked as a GitHub issue at PR time). +- [x] 7.2 Dashboard rotation-due card + rotation category in the password-health report, each finding deep-linking to the secret +- [x] 7.3 Per-secret "mark rotated" / "re-request rotation" actions and a client batch-flag action wired from the health breach findings (IDs only) ## 8. Tests -- [ ] 8.1 Unit: effective-expiry resolution precedence (per-secret > folder > type > user > admin); no decryption; no-policy = never expiring -- [ ] 8.2 Unit: mark-rotated closes only on a real `key_updated_at` advance; batch-flag persists IDs only with `user_flagged`; compromise auto-flag -- [ ] 8.3 Unit: `ScanExpiringSecretsJob` notifies only crossing/overdue secrets, respects `notify_security`, no duplicate per threshold, raises `policy_expiry` idempotently -- [ ] 8.4 e2e (Playwright): owner sets expiry, dashboard shows rotation-due, rewrites value, marks rotated → flag clears +- [x] 8.1 Unit: effective-expiry resolution precedence (per-secret > folder > type > user > admin); no decryption; no-policy = never expiring +- [x] 8.2 Unit: mark-rotated closes only on a real `key_updated_at` advance; batch-flag persists IDs only with `user_flagged`; compromise auto-flag +- [x] 8.3 Unit: `ScanExpiringSecretsJob` notifies only crossing/overdue secrets, respects `notify_security`, no duplicate per threshold, raises `policy_expiry` idempotently +- [x] 8.4 e2e (Playwright): owner sets expiry, dashboard shows rotation-due, rewrites value, marks rotated → flag clears + > Note: executed as a live end-to-end verification against the deployed dev instance (API + DB assertions for set-expiry → resolve → flag → mark-rotated-refusal → rotate → resolve) rather than a committed Playwright script, matching how sibling changes were verified. ## Acceptance criteria diff --git a/src/components/RotationPanel.vue b/src/components/RotationPanel.vue new file mode 100644 index 000000000..766f69f1d --- /dev/null +++ b/src/components/RotationPanel.vue @@ -0,0 +1,296 @@ + + + + + + diff --git a/src/components/settings/RotationPolicySection.vue b/src/components/settings/RotationPolicySection.vue new file mode 100644 index 000000000..601d94e82 --- /dev/null +++ b/src/components/settings/RotationPolicySection.vue @@ -0,0 +1,116 @@ + + + + + + diff --git a/src/manifest.json b/src/manifest.json index 88c8cd608..de28b78a9 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -160,7 +160,7 @@ "slot": "body", "gridX": 0, "gridY": 3, - "gridWidth": 4, + "gridWidth": 3, "gridHeight": 2, "_note": "ADR-049 dissolution of the doriath-kpi-card custom widget — endpoint-bound KPI tiles against GET /api/dashboard/summary. Bound to the payload keys DashboardService::fetchSummary actually emits (total_secrets / shared_with_me_count / folders_count); the legacy view read shared_secrets / folder_count / compromised_count, which the backend never sends. The 'Possibly compromised' card is dropped: compromised_count does not exist in the summary payload, so it was a permanently-zero dead binding.", "props": { @@ -179,9 +179,9 @@ "id": "kpi-shared-with-me", "widgetKey": "stat", "slot": "body", - "gridX": 4, + "gridX": 3, "gridY": 3, - "gridWidth": 4, + "gridWidth": 3, "gridHeight": 2, "props": { "content": { @@ -198,9 +198,9 @@ "id": "kpi-folders", "widgetKey": "stat", "slot": "body", - "gridX": 8, + "gridX": 6, "gridY": 3, - "gridWidth": 4, + "gridWidth": 3, "gridHeight": 2, "props": { "content": { @@ -213,6 +213,27 @@ } } }, + { + "id": "kpi-rotation-due", + "widgetKey": "stat", + "slot": "body", + "gridX": 9, + "gridY": 3, + "gridWidth": 3, + "gridHeight": 2, + "_note": "Rotation-due count (rotation-expiry-policies §7.2) — open rotation flags for the caller's secrets, from DashboardService::fetchSummary rotation_due_count. Deep-dive detail lives in the password-health report's rotation category.", + "props": { + "content": { + "label": "Rotation due", + "icon": "Autorenew", + "valueColor": "var(--color-error)", + "endpointSource": { + "url": "/apps/doriath/api/dashboard/summary" + }, + "valueField": "rotation_due_count" + } + } + }, { "id": "recent-activity-text", "widgetKey": "text", diff --git a/src/store/modules/rotation.js b/src/store/modules/rotation.js new file mode 100644 index 000000000..e537d4fd3 --- /dev/null +++ b/src/store/modules/rotation.js @@ -0,0 +1,182 @@ +/** + * SPDX-License-Identifier: EUPL-1.2 + * SPDX-FileCopyrightText: 2026 Conduction B.V. + * + * Pinia store for rotation & expiry (rotation-expiry-policies §7). + * + * Expiry is server-visible metadata only — no ciphertext is involved in + * any call here. Batch-flag sends secret IDs ONLY (no breach verdicts, + * scores, or digests ever leave the client). + * + * @spec openspec/changes/rotation-expiry-policies/specs/rotation-expiry-policies/spec.md#requirement-rotation-flags + */ + +import { defineStore } from 'pinia' +import axios from '@nextcloud/axios' +import { generateUrl } from '@nextcloud/router' + +export const useRotationStore = defineStore('rotation', { + state: () => ({ + /** @type {Array} The caller's open rotation flags. */ + flags: [], + /** @type {Array} The caller's applicable expiry policies. */ + policies: [], + /** @type {boolean} Whether a request is in flight. */ + loading: false, + /** @type {string|null} The last error message. */ + error: null, + }), + + getters: { + /** + * Open flags keyed by secret id for O(1) chip lookups. + * + * @param {object} state The store state. + * @return {object} Map of secretId -> flag. + */ + flagsBySecretId(state) { + const map = {} + for (const flag of state.flags) { + map[flag.secretId] = flag + } + return map + }, + }, + + actions: { + /** + * Load the caller's open rotation flags. + * + * @return {Promise} + */ + async fetchFlags() { + this.loading = true + this.error = null + try { + const response = await axios.get(generateUrl('/apps/doriath/api/v1/rotation-flags')) + this.flags = response.data || [] + } catch (e) { + this.error = e?.response?.data?.message || e?.message || 'Failed to load rotation flags' + throw e + } finally { + this.loading = false + } + }, + + /** + * Load the caller's applicable expiry policies. + * + * @return {Promise} + */ + async fetchPolicies() { + try { + const response = await axios.get(generateUrl('/apps/doriath/api/v1/expiry-policies')) + this.policies = response.data || [] + } catch (e) { + this.error = e?.response?.data?.message || e?.message || 'Failed to load policies' + throw e + } + }, + + /** + * Create or update a type/folder expiry policy. + * + * @param {object} policy The policy payload. + * @param {string} policy.scope The scope ('type'|'folder'). + * @param {string} policy.scopeId The scoped type/folder id. + * @param {number|null} policy.maxAgeDays Max credential age in days. + * @param {Array} policy.reminderDays Reminder thresholds. + * @return {Promise} The saved policy. + */ + async upsertPolicy({ scope, scopeId, maxAgeDays, reminderDays }) { + const response = await axios.post( + generateUrl('/apps/doriath/api/v1/expiry-policies'), + { scope, scopeId, maxAgeDays, reminderDays }, + ) + await this.fetchPolicies() + return response.data + }, + + /** + * Delete one of the caller's policies. + * + * @param {string} policyId The policy id. + * @return {Promise} + */ + async deletePolicy(policyId) { + await axios.delete(generateUrl(`/apps/doriath/api/v1/expiry-policies/${policyId}`)) + this.policies = this.policies.filter((p) => p.id !== policyId) + }, + + /** + * Get a secret's stored + effective expiry. + * + * @param {string} secretId The secret id. + * @return {Promise} { expiresAt, effectiveExpiry }. + */ + async getExpiry(secretId) { + const response = await axios.get(generateUrl(`/apps/doriath/api/v1/secrets/${secretId}/expiry`)) + return response.data + }, + + /** + * Set or clear a secret's expiry (owner-only; metadata only). + * + * @param {string} secretId The secret id. + * @param {string|null} expiresAt ISO expiry or null to clear. + * @return {Promise} { secret, effectiveExpiry }. + */ + async setExpiry(secretId, expiresAt) { + const response = await axios.put( + generateUrl(`/apps/doriath/api/v1/secrets/${secretId}/expiry`), + { expiresAt }, + ) + return response.data + }, + + /** + * Flag secrets for rotation — IDs ONLY (client breach findings + * never send verdicts or digests). + * + * @param {Array} secretIds The secret ids to flag. + * @return {Promise} How many flags are now open. + */ + async flagSecrets(secretIds) { + const response = await axios.post( + generateUrl('/apps/doriath/api/v1/rotation-flags'), + { secretIds }, + ) + await this.fetchFlags() + return response.data?.flagged ?? 0 + }, + + /** + * Mark a flag rotated. Resolves only when the server proves the + * key advanced past its flag-time value; otherwise the caller is + * told rotation is still required. + * + * @param {string} flagId The flag id. + * @return {Promise} { resolved, requiresRotation }. + */ + async markRotated(flagId) { + const response = await axios.post( + generateUrl(`/apps/doriath/api/v1/rotation-flags/${flagId}/rotated`), + ) + if (response.data?.resolved === true) { + this.flags = this.flags.filter((f) => f.id !== flagId) + } + return response.data + }, + + /** + * Dismiss a flag without rotation (audited). + * + * @param {string} flagId The flag id. + * @return {Promise} + */ + async dismissFlag(flagId) { + await axios.post(generateUrl(`/apps/doriath/api/v1/rotation-flags/${flagId}/dismiss`)) + this.flags = this.flags.filter((f) => f.id !== flagId) + }, + }, +}) diff --git a/src/views/HealthReportView.vue b/src/views/HealthReportView.vue index 5c887280f..cdc7e864b 100644 --- a/src/views/HealthReportView.vue +++ b/src/views/HealthReportView.vue @@ -80,6 +80,12 @@ :findings="store.breachedFindings" testid="category-breached" @open="openSecret" /> + + {{ t('doriath', 'Flag all breached secrets for rotation') }} +

{{ t('doriath', 'Breach check is currently unavailable. Other findings are unaffected.') }}

@@ -89,6 +95,12 @@ :findings="store.compromisedFindings" testid="category-compromised" @open="openSecret" /> +
@@ -99,22 +111,24 @@