@abgov/adsp-sdk-mcp-server 1.15.0 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,6 +15,7 @@ communicate over APIs and RabbitMQ, and so deployment into other hosting environ
15
15
  ## Prerequisites
16
16
 
17
17
  <!-- tags: [keycloak] -->
18
+
18
19
  A few prerequisites are needed to set up an ADSP deployment:
19
20
 
20
21
  1. [Keycloak](https://www.keycloak.org/) is used as an IAM solution. Realms provide tenants with user access management under their own administrative control.
@@ -37,28 +38,29 @@ The tenant service creates realms for new tenants using a service account.
37
38
  Platform micro-services make requests under a non-tenant 'core' context. This is handled with a 'core' realm in Keycloak.
38
39
 
39
40
  1. Create a 'core' realm in Keycloak.
40
- 2. Create public *client* with *Standard Flow* enabled for tenant administration application: `urn:ads:platform:tenant-admin-app`.
41
- 3. Create confidential *clients* with service accounts for `urn:ads:platform:subscriber-gateway` and `urn:ads:platform:api-docs-app`.
42
- 4. Create confidential *clients* with service accounts for backend micro-services including:
41
+ 2. Create public _client_ with _Standard Flow_ enabled for tenant administration application: `urn:ads:platform:tenant-admin-app`.
42
+ 3. Create confidential _clients_ with service accounts for `urn:ads:platform:subscriber-gateway` and `urn:ads:platform:api-docs-app`.
43
+ 4. Create confidential _clients_ with service accounts for backend micro-services including:
43
44
  - `urn:ads:platform:tenant-service`
44
45
  - `urn:ads:platform:event-service`
45
46
  - `urn:ads:platform:value-service`
46
47
  - ...
47
- 5. Create service *client roles*:
48
+ 5. Create service _client roles_:
48
49
  - In `urn:ads:platform:value-service`, create `value-reader` and `value-writer` roles.
49
50
  - In `urn:ads:platform:event-service`, create `event-sender` role.
50
- - In `urn:ads:platform:configuration-service`, create `configured-service` role.
51
+ - In `urn:ads:platform:configuration-service`, create `configured-service` role.
51
52
  - In `urn:ads:platform:notification-service`, create `subscription-app` role.
52
53
  - In `urn:ads:platform:verify-service`, create `code-generator` and `code-verifier` roles.
53
- - In `urn:ads:platform:tenant-service`, create `platform-service` role, enable *composite roles*, and add `event-sender` and `configured-service` client roles from above.
54
- 6. Assign roles to *clients*
54
+ - In `urn:ads:platform:tenant-service`, create `platform-service` role, enable _composite roles_, and add `event-sender` and `configured-service` client roles from above.
55
+ 6. Assign roles to _clients_
55
56
  - Grant the service accounts the `platform-service` role.
56
- - Grant `urn:ads:platform:event-service` the `value-writer` role.
57
+ - Grant `urn:ads:platform:event-service` the `value-writer` role, so it can log events, and the `value-reader`
58
+ role, so it can count events on behalf of event log API consumers.
57
59
  - Grant `urn:ads:platform:notification-service` the `code-generator` and `code-verifier` roles.
58
60
  - Grant `urn:ads:platform:subscriber-gateway` and `urn:ads:platform:form-service` the `subscription-app` role.
59
61
 
60
-
61
62
  ## RabbitMQ configuration
63
+
62
64
  Some platform services communicate over RabbitMQ. The exchange and queue configuration required is contained in the code, but manual configuration is necessary to create the accounts. All accounts should access a common vhost in RabbitMQ.
63
65
 
64
66
  1. Create accounts for platform services including:
@@ -77,4 +79,3 @@ References for configuration in the form of ConfigMaps and Secrets are included
77
79
  2. Set appropriate values in the ConfigMaps and Secrets and apply to environments.
78
80
  3. Create a service account in 'build' with edit permission to other projects for the pipeline.
79
81
  4. Process and apply managed templates, and/or set service account token in GitHub for the pipeline.
80
-
@@ -0,0 +1,83 @@
1
+ ---
2
+ layout: page
3
+ title: Access service backup and disaster recovery
4
+ nav_order: 3
5
+ parent: Services
6
+ ---
7
+
8
+ # Access service backup and disaster recovery
9
+
10
+ ## Introduction
11
+
12
+ The ADSP Access Service provides authentication and identity management for the platform. It is deployed as Keycloak on the Government of Alberta's Azure Red Hat OpenShift (ARO) cluster, in the `adsp-prod` namespace.
13
+
14
+ This document describes recovery responsibilities and validation for the Access Service. Keycloak deployment configuration, secrets, themes, and other artifacts outside the database must also be recoverable.
15
+
16
+ ## Access Service Cluster in ARO
17
+
18
+ The Keycloak service is configured in high-availability (HA) mode, running three instances in the `adsp-prod` ARO environment behind a traffic proxy. A health-check monitor tracks Keycloak, and Azure alerts are configured to notify administrators of CPU or traffic issues. This application-level HA setup provides instance redundancy so authentication can continue if an instance becomes unavailable. End-to-end availability depends on traffic reaching healthy instances and the database and ARO platform remaining available. Failover testing and distribution across separate failure zones still need confirmation.
19
+
20
+ End-to-end availability also depends on the GoA-managed database and the ARO platform. Confirm the database failover arrangements and the behavior of the service during an instance or platform failure with the responsible teams.
21
+
22
+ This is a high-level view of the intended strategy. Instance failover, failure-zone coverage, and database recovery still need confirmation.
23
+
24
+ ### Recovery coverage
25
+
26
+ The supplied information references an ARO backup and restore, but does not confirm whether the database and all required Access Service data were included or whether end-to-end recovery was tested. Confirm backup coverage and the results of the latest recovery test.
27
+
28
+ ## Database
29
+
30
+ Keycloak stores realm and identity data, including users, clients, and roles, in its database. The database is managed by the Government of Alberta Dev/Ops team, which owns its backup and recovery. The database technology, availability design, failover process, backup schedule, and recovery objectives have not been confirmed. Confirm these details with GoA Dev/Ops. ARO application backups do not necessarily include the separately managed database.
31
+
32
+ ## Responsibilities
33
+
34
+ | Responsibility | Owner |
35
+ | ------------------------------------------------------------------- | ------------------------------------------------ |
36
+ | Database backup, retention, protection, and restore | GoA Dev/Ops team |
37
+ | Provide database recovery objectives and restore procedure | GoA Dev/Ops team |
38
+ | Coordinate the Keycloak incident and recovery validation | ADSP team |
39
+ | Restore or redeploy Keycloak configuration and supporting artifacts | To be confirmed with the ADSP service owner |
40
+ | Confirm tenant and application access after recovery | ADSP team with affected tenant/application teams |
41
+
42
+ Confirm these ownership boundaries and the applicable operational contacts with both teams.
43
+
44
+ ## Recovery information to confirm
45
+
46
+ The following information is not currently documented and must be confirmed with GoA Dev/Ops, the ADSP service owner, or the OpenShift team as applicable before this document can be treated as an approved recovery runbook.
47
+
48
+ | Item | Confirmed value |
49
+ | ------------------------------------------------------------------------ | --------------- |
50
+ | Database availability and failover arrangements | To be confirmed |
51
+ | Database backup schedule, retention, and recovery objectives | To be confirmed |
52
+ | Database restore process and escalation contact | To be confirmed |
53
+ | Whether backups cover all required Access Service data and configuration | To be confirmed |
54
+ | How traffic moves to healthy instances during a failure | To be confirmed |
55
+ | Whether instances are distributed across separate failure zones | To be confirmed |
56
+ | Frequency and results of end-to-end failover and recovery tests | To be confirmed |
57
+
58
+ ## Recovery procedure
59
+
60
+ 1. **Declare and coordinate the incident.** The ADSP incident lead records the impact, affected environments, and time detected, then contacts GoA Dev/Ops through the agreed incident channel. Do not attempt an independent database restore or modify the managed database outside the approved process.
61
+ 2. **Confirm the recovery point.** GoA Dev/Ops confirms the available restore points, expected data-loss window, and estimated recovery time with the ADSP incident lead before proceeding.
62
+ 3. **Restore the database.** GoA Dev/Ops performs the database recovery using its approved process and confirms when the database is ready for Keycloak.
63
+ 4. **Recover the Access Service.** The service owner restores the application and its required configuration using the approved ARO recovery process, reconnects it to the recovered database, and confirms that healthy instances can serve authentication requests.
64
+ 5. **Validate service behavior.** Complete the checks below before declaring the Access Service recovered. Coordinate tenant-specific checks with affected tenant/application teams.
65
+ 6. **Communicate and document.** Report service status and any known data-loss window to stakeholders. Record the incident timeline, restore point, validation results, and follow-up actions.
66
+
67
+ ## Post-recovery validation
68
+
69
+ - Keycloak starts successfully and its administrative interface is available to authorized operators.
70
+ - All three intended Keycloak instances are healthy, and authentication continues if one instance becomes unavailable.
71
+ - OpenID Connect discovery and token endpoints respond as expected for the affected realms.
72
+ - A controlled test account can authenticate, and a test service account can obtain a token where applicable.
73
+ - Test tokens contain the expected issuer, audience, and roles, and a representative ADSP service accepts the token.
74
+ - A sample of affected tenant realms, clients, users, and roles is present and usable. Coordinate tenant-specific verification with tenant administrators.
75
+ - Tenant administration and dependent application workflows are confirmed with their owners.
76
+ - The health-check monitor reports the Keycloak service as healthy after recovery.
77
+ - Azure CPU and traffic metrics are available, and alert notifications are working.
78
+
79
+ Use non-production test accounts where possible. Do not use real user credentials as recovery test data.
80
+
81
+ ## Review
82
+
83
+ Review this document with GoA Dev/Ops and the ADSP service owner, fill in the recovery information above, and update it after a restore test or a material change to the Keycloak deployment or database service.
@@ -0,0 +1,468 @@
1
+ ---
2
+ layout: page
3
+ title: Audit service
4
+ parent: Services
5
+ ---
6
+
7
+ # Audit service
8
+
9
+ The action catalog registers the classification of audit actions. Registering an action does not
10
+ generate audit records. The write endpoint validates and enriches events, then submits them through
11
+ the write buffer to PostgreSQL. History endpoints read committed rows from the same database.
12
+ Action catalogs and retention settings remain in Configuration Service, not the audit database.
13
+ SIEM forwarding is a separate capability. Scheduled retention is enabled by default.
14
+
15
+ ## Source layout
16
+
17
+ The `apps/audit-service/src/audit` module follows the Calendar Service layout:
18
+
19
+ - `model/`: catalog loading and retention configuration resolution.
20
+ - `buffer/`: write scheduling, durability handling and the database adapter contract.
21
+ - `jobs/`: scheduled retention and its tenant-scoped run audit.
22
+ - `router/`: HTTP routes, write handlers, and OpenAPI definitions.
23
+ - `types/`: event payloads and the submission contract.
24
+ - `utils/`: event/request validation and write authorization.
25
+
26
+ `app.ts` initializes the application and registers configuration and roles; `main.ts` starts the
27
+ HTTP listener and handles shutdown. `src/postgres/` connects history, the write buffer and failed-event administration
28
+ to the migrated `audit_events` and `audit_failed_events` tables. Tests are colocated with their implementations.
29
+
30
+ ## Authorization
31
+
32
+ `initializePlatform` registers three roles on `urn:ads:platform:audit-service`:
33
+
34
+ - `audit-reader`: read access; included in `tenant-admin` via `inTenantAdmin: true`.
35
+ - `audit-writer`: event writes; explicitly assigned to application service accounts.
36
+ - `audit-admin`: failed-event administration and protected actor identity access;
37
+ does not replace reader/writer permissions.
38
+
39
+ Every audit route uses `requireAuditRole` to check both the role and resolved tenant.
40
+ Core callers may cross tenants but still need the role. Missing/invalid tokens return 401;
41
+ insufficient permissions return 403. Discovery, health and Swagger remain public.
42
+
43
+ New tenants receive the registered roles during provisioning. Existing tenants and Core still
44
+ require role provisioning; redeploying this service alone does not synchronize their Keycloak roles.
45
+
46
+ ## Configuration contract
47
+
48
+ Audit Service registers a namespace-level schema at startup through `initializePlatform` with
49
+ `configuration.useNamespace: true`. The definition is the `audit-service` entry in Core
50
+ `platform:configuration-service`. It appears under **Configuration service > Definitions > Core definitions**.
51
+ Registration follows the SDK's asynchronous startup behavior: inspect registration logs and the stored
52
+ definition before onboarding applications; a listening HTTP server alone does not prove registration succeeded.
53
+
54
+ Each application stores a complete catalog in `audit-service:actions-<application>`, in its tenant
55
+ or in Core for shared actions:
56
+
57
+ ```json
58
+ {
59
+ "kind": "actionCatalog",
60
+ "application": "case-service",
61
+ "actions": {
62
+ "case.update": {
63
+ "version": 1,
64
+ "category": "administrative",
65
+ "severity": "info",
66
+ "retentionClass": "compliance",
67
+ "resourceType": "case",
68
+ "captureChangeSet": true,
69
+ "forwardToSiem": false,
70
+ "metadataSchema": {
71
+ "type": "object",
72
+ "properties": { "reason": { "type": "string" } }
73
+ }
74
+ }
75
+ }
76
+ }
77
+ ```
78
+
79
+ `application` is a lowercase kebab-case identifier, at most 40 characters. The API's `namespace`
80
+ is this same identifier, **not** the Configuration Service namespace `audit-service`. For an SDK
81
+ client it should equal `serviceId.service`. Applications are trusted to register only their own
82
+ catalog; Configuration Service roles do not provide application-level write isolation.
83
+
84
+ Actions require a positive integer `version`, `category` (`administrative`, `runtime`, `security`,
85
+ `data-access`), `severity` (`info`, `warning`, `critical`), and a kebab-case `retentionClass`.
86
+ Optional fields are `description`, `resourceType`, `captureChangeSet`, `forwardToSiem`, and
87
+ `metadataSchema`. The two flags resolve to `false` when omitted. An omitted metadata schema imposes
88
+ no action-specific metadata constraint. The listing returns any supplied schema intact.
89
+ Unknown document and definition fields are rejected. Action keys omit the event outcome suffix.
90
+
91
+ The namespace schema also preserves `retentionSettings` and `applicationRetentionSettings` document
92
+ shapes, with positive integer `classes.<class>.days`. Catalog registration creates no retention periods.
93
+ At write time the service resolves configured periods over the design defaults: standard 90 days,
94
+ security and compliance 365 days. Application settings in `audit-service:retention-<application>`
95
+ override `audit-service:retention`, which overrides those defaults. Expiry is calculated from
96
+ `occurred_at` in UTC days. Missing custom classes fail writes with a retryable 503.
97
+
98
+ ### Retention periods and forward-only changes
99
+
100
+ `RETENTION_MIN_DAYS` and `RETENTION_MAX_DAYS` configure platform-wide, inclusive bounds
101
+ (defaults **1** and **3650** days, pending PO confirmation). Both must be positive integers,
102
+ with minimum no greater than maximum. These bounds apply to tenant and Core retention settings,
103
+ application overrides, and custom classes. The fixed default periods remain 90/365/365 days.
104
+ If narrower bounds exclude a default, configure an in-range replacement for that class.
105
+
106
+ The service registers these bounds in the Configuration Service namespace schema, so out-of-range
107
+ period updates are rejected there. Restart the service after changing the platform environment
108
+ settings and verify that the updated namespace definition has registered. All replicas must use
109
+ the same bounds. The write path also validates resolved periods, refusing old positive periods
110
+ outside new bounds with 503 rather than silently substituting defaults. Existing SDK handling of
111
+ configuration transport/structural conversion failures remains as documented below.
112
+
113
+ Changes are **forward only**: after the active configuration/cache refreshes, newly enriched
114
+ events use the new period, but stored `retention_until` values are never recalculated. Buffered
115
+ events already enriched keep their original expiry too. Cleanup uses only stored expiry, not the
116
+ current period or a TimescaleDB chunk boundary.
117
+
118
+ ### Registering through the SDK
119
+
120
+ `auditDefinitions()` turns application constants into a map keyed by action name and rejects
121
+ duplicate names at startup. Category and severity types and configuration validation use the
122
+ SDK's shared constants; custom retention class names remain supported.
123
+
124
+ ```typescript
125
+ import {
126
+ adspId,
127
+ AuditAction,
128
+ AuditCategories,
129
+ AuditSeverities,
130
+ BuiltInRetentionClasses,
131
+ auditDefinitions,
132
+ } from '@abgov/adsp-service-sdk';
133
+
134
+ const serviceId = adspId`urn:ads:case-team:case-service`;
135
+ const ACTIONS = {
136
+ UPDATE_CASE: {
137
+ name: 'case.update',
138
+ version: 1,
139
+ category: AuditCategories.Administrative,
140
+ severity: AuditSeverities.Info,
141
+ retentionClass: BuiltInRetentionClasses.Compliance,
142
+ },
143
+ } satisfies Record<string, AuditAction>;
144
+
145
+ // Include this entry in initializeService's serviceConfigurations.
146
+ const serviceConfigurations = [
147
+ {
148
+ serviceId: adspId`urn:ads:platform:audit-service`,
149
+ configuration: [
150
+ {
151
+ name: `actions-${serviceId.service}`,
152
+ operation: 'REPLACE' as const,
153
+ configuration: {
154
+ kind: 'actionCatalog',
155
+ application: serviceId.service,
156
+ actions: auditDefinitions(ACTIONS),
157
+ },
158
+ },
159
+ ],
160
+ },
161
+ ];
162
+ ```
163
+
164
+ Use `initializePlatform` for a Core platform service. The same registration entry then creates a
165
+ shared Core catalog. Existing SDK registrations continue to use `UPDATE` unless a named document
166
+ explicitly selects `REPLACE`. For direct Configuration Service calls, PATCH the named catalog with
167
+ `{ "operation": "REPLACE", "configuration": <complete catalog> }`.
168
+
169
+ Replacing one application's document cannot delete another application's catalog, including during
170
+ concurrent registration. Replacing its action map removes obsolete definitions, unlike a shallow
171
+ `UPDATE` merge. Concurrent writers to the _same_ application remain last-writer-wins; coordinate
172
+ those deployments. Only trusted administrators/deployment accounts should have write access.
173
+
174
+ If an active revision is set, changing latest alone may not publish the change. Create and activate
175
+ revisions through the normal Configuration Service workflow, with a configuration-admin account.
176
+
177
+ ## Loading and cache behavior
178
+
179
+ The service reads active revisions with fallback to latest, through the existing SDK configuration
180
+ service. It merges tenant and Core maps **by action name**, with the entire Core definition winning
181
+ on conflicts. Tenant-only actions remain. An empty tenant catalog does not hide shared Core actions.
182
+ The stored `application` must match the requested configuration name.
183
+
184
+ The SDK caches converted documents by tenant, configuration namespace, and document name. Core
185
+ documents are shared deliberately. The combine function uses the SDK's existing memoization.
186
+ Tenant `configuration-updated` and `active-revision-set` notifications invalidate the affected
187
+ entry; the next request reloads it. Core changes also have the TTL backstop; do not assume a Core
188
+ write emits a tenant notification.
189
+
190
+ `useLongConfigurationCacheTTL` is **false**, retaining the SDK's 900-second (15-minute) TTL.
191
+ With Configuration Service available, a missed notification is picked up on the first request
192
+ after expiry, plus fetch latency. An update notice normally refreshes on the next request; there is
193
+ no measured end-to-end notification latency guarantee yet. Register actions before deploying code
194
+ that emits them.
195
+
196
+ Audit Service uses the SDK's existing error handling. Configuration HTTP or converter failures are
197
+ logged and returned as `null`, so the catalog API cannot reliably distinguish these failures from
198
+ missing configuration. If neither scope supplies a catalog, listing returns 404; if only one scope
199
+ succeeds, it can return a partial catalog. A registered empty catalog retains its `actions: {}`.
200
+ Errors that still propagate, such as token acquisition failures, and application-name consistency
201
+ failures return 503. On writes, SDK-handled failures can produce unknown-action rejections or
202
+ fallback retention periods; reliable failure-versus-absence distinction is not provided.
203
+
204
+ **Deferred by the MVP scope decision:** stale-on-error after invalidation/expiry, explicit cache
205
+ capacity limits, and stronger invalidation/in-flight refresh guarantees. Existing unexpired
206
+ configuration cache entries avoid configuration HTTP reads, but token retrieval remains an SDK
207
+ dependency. Once an entry expires or is invalidated, a configuration HTTP failure resolves to null;
208
+ the SDK does not retain the old value for fallback. These remaining OSP-730 cache guarantees
209
+ are not claimed complete.
210
+
211
+ ## Listing definitions
212
+
213
+ ```http
214
+ GET /audit/v1/case-service/actions
215
+ Authorization: Bearer <token with audit-reader>
216
+ ```
217
+
218
+ Returns a JSON array, with each action's `name` plus its definition fields. Optional absent
219
+ `resourceType`, `description`, and `metadataSchema` remain omitted.
220
+
221
+ | Status | Meaning |
222
+ | ------ | -------------------------------------------------------------------------------------- |
223
+ | 200 | Resolved definitions; `[]` means registered but empty. |
224
+ | 400 | Invalid application/namespace or tenant ID format. |
225
+ | 401 | Not authenticated. |
226
+ | 403 | No `audit-reader`, or a tenant caller attempted to select a different tenant. |
227
+ | 404 | Neither scope supplied a catalog; SDK-handled failures can also produce this response. |
228
+ | 503 | A propagated SDK error or application-name consistency failure; retry. |
229
+
230
+ `audit-reader` is tenant-wide: callers can read any namespace in their tenant, not only their own.
231
+ A Core caller with the role can select a tenant via
232
+ `?tenantId=urn:ads:platform:tenant-service:v2:/tenants/<id>`. A Core request without tenant context
233
+ reads Core catalogs only. The service registers this role for tenant provisioning; existing tenants
234
+ still need their normal role provisioning/assignment process.
235
+
236
+ The catalog governs future write classification, not history access. Removing a definition performs
237
+ no audit-record deletion. History endpoints query PostgreSQL independently of the catalog, so
238
+ removing an action does not prevent reading its existing records.
239
+
240
+ ## Writing events
241
+
242
+ ```http
243
+ POST /audit/v1/case-service/events
244
+ Content-Type: application/json
245
+ ```
246
+
247
+ Supply an authenticated bearer token with `audit-writer` and a body
248
+ `{ "events": [ ... ] }` containing 1 to 500 events. Configure the Audit Service
249
+ audience on the application client and explicitly grant the role to its service
250
+ account; `audit-writer` is not automatically assigned to tenant administrators.
251
+
252
+ The verified token's `azp` must be a service URN. Tenant writers may write only
253
+ its service component's namespace. Core writers with the role follow the existing
254
+ platform exemption and can select another namespace and tenant through `?tenantId=...`.
255
+ Core must supply a tenant. Role provisioning, not an additional claim check,
256
+ limits this permission to service accounts.
257
+
258
+ Events require a UUID `eventId`, `occurredAt`, `action`, `status`, and `actor.id/type`.
259
+ Occurrence time must be within the past seven days or next five minutes. Actions
260
+ may have a terminal `.succeeded` or `.failed` suffix. An omitted `actionVersion`
261
+ uses the current catalog version; an explicit mismatch is rejected.
262
+ Resource type and metadata are validated against the resolved action.
263
+ Metadata and change sets each have a 16 KiB UTF-8 JSON limit; the whole body has a
264
+ 20 MiB limit. A non-capturing action drops change sets from the trusted row.
265
+
266
+ Malformed batch envelopes return 400, oversized bodies return 413, and malformed
267
+ individual events produce individual rejections. Classification, identity and
268
+ retention columns are server-set, never copied from caller-supplied row fields.
269
+
270
+ A 202 response accounts for all inputs after storage outcomes are confirmed:
271
+
272
+ ```json
273
+ { "accepted": 1, "duplicates": 0, "rejected": [] }
274
+ ```
275
+
276
+ Each rejection includes a zero-based input `index`, `code`, `reason`, and an
277
+ `eventId` when available. Counts and rejection length account for every input.
278
+ Duplicates are determined by PostgreSQL, not an in-memory router check.
279
+ If durable storage is unavailable, valid submissions return **503 with Retry-After**.
280
+
281
+ ## Reading events
282
+
283
+ `GET /audit/v1/events` lists events across the resolved tenant's namespaces;
284
+ `GET /audit/v1/{namespace}/events` restricts that list to one namespace.
285
+ `GET /audit/v1/{namespace}/events/{id}` retrieves a record by its service-generated UUID,
286
+ returning 404 when it does not exist in that tenant and namespace.
287
+ All three require `audit-reader` and tenant context. Core readers can select a tenant with `tenantId`.
288
+
289
+ Lists accept `actor`, `resourceType`, `resourceId`, `action`, `status`, `category`, `scope`,
290
+ `occurredFrom` and `occurredTo`. Filters combine with AND; time bounds are inclusive, and `scope`
291
+ matches an element of `scopeIds`. Results are ordered by `occurred_at DESC, id DESC`, with `top`
292
+ and an opaque `after` keyset cursor (the last event's `occurred_at` and `id`, returned as `page.next`)
293
+ controlling pagination. Paging is stable while new events arrive, including the events recorded by
294
+ the reads themselves.
295
+
296
+ Responses retain the existing camelCase event shape and never expose `tenant_id`.
297
+ Database read failures return 503 rather than an empty result or a false 404.
298
+
299
+ See the [submission contract](https://github.com/GovAlta/adsp-monorepo/blob/main/apps/audit-service/README.md#submission-contract-osp-707--osp-708)
300
+ for the boundary with OSP-708.
301
+
302
+ ## Write buffer
303
+
304
+ The router submits enriched events through
305
+ `submit(events: EnrichedEvent[]): Promise<Map<string, EventOutcome>>`.
306
+ Results use the service-generated `id`, never client `event_id`, to keep concurrent requests
307
+ and tenants separate. Inputs must remain unchanged until the promise settles.
308
+
309
+ The buffer batches at 200 events or 200 ms, with default limits of 5,000 retained events and
310
+ 32 MiB of serialized payload per pod. Capacity is reserved for the whole request before enqueueing;
311
+ over-capacity requests return 503 without storing any of their events. The byte limit is not a
312
+ measurement of process memory.
313
+
314
+ Transient failures retry after 200 ms, 1 s and 3 s; constraint failures are retried individually.
315
+ `accepted` requires a committed audit row. `storage_failed` requires the original event to be
316
+ committed to failed-event storage and is counted as rejected, not accepted. If neither write
317
+ succeeds, the request returns 503. The PostgreSQL adapter uses
318
+ `ON CONFLICT (tenant_id, namespace, event_id) DO NOTHING RETURNING id`, resolves only after commit,
319
+ and returns only inserted service IDs. It does not update existing events on conflict.
320
+ Failed-event writes preserve the original payload and map the buffer's `attempt_count` to
321
+ the database's `attempts` column.
322
+
323
+ Writes use transactions with a four-second server-side statement timeout, including lock waits.
324
+ Cancellation is checked before database work and before commit; cancelled operations roll back
325
+ after the current bounded statement settles. Connection acquisition retains the database pool's
326
+ 30-second bound; a cancellation during that wait prevents a late insert. Until an outstanding
327
+ operation settles, the buffer refuses additional writes rather than accumulating abandoned work.
328
+
329
+ `close()` refuses new submissions and drains within a configurable 25-second default budget,
330
+ reserving the final 5 seconds for failed-event storage. SIGTERM and SIGINT stop new connections,
331
+ drain queued writes and in-flight HTTP requests, then close the database pool and telemetry.
332
+ A 29-second process deadline exits with failure if shutdown cannot finish.
333
+ `GET /health` includes `db` and `ready`; it returns 503 when the database or buffer is unavailable
334
+ or the buffer is draining.
335
+
336
+ ## Failed-event administration
337
+
338
+ Both endpoints require `audit-admin` and use the caller's tenant. Core administrators must
339
+ provide `tenantId`. Reader or writer permissions alone are not enough.
340
+
341
+ | Endpoint | Purpose |
342
+ | ---------------------------------------- | ------------------------------------------------------------------- |
343
+ | `GET /audit/v1/failed-events` | List the tenant's open, replayed and discarded events, newest first. |
344
+ | `POST /audit/v1/failed-events/{id}/replay` | Retry an open event using its stored data. No request body is needed. |
345
+
346
+ Listing accepts `top` (default 20, maximum 100) and the previous response's `page.next` as
347
+ `after`, an opaque keyset cursor (the last row's `failed_at` and `id`), so pages stay stable while
348
+ new failures are parked. It returns `{ results, page: { after?, size, next? } }`.
349
+
350
+ Both endpoints use the same PostgreSQL connection as normal event writes and history reads.
351
+ Replay saves the recovered event, failed-row update and replay audit record in one transaction:
352
+ either all succeed or none do. Concurrent replay attempts cannot recover the same failed row twice.
353
+
354
+ The recovered event keeps its original actor; `written_by` identifies Audit Service.
355
+ `replayed_as` links to its database row ID. If that event already exists, replay links to it
356
+ without changing it. The `audit-service` action `failed-event.replay.succeeded` records the
357
+ requesting administrator. Startup registers its definition through the SDK into the Core
358
+ `audit-service:actions-audit-service` catalog using `REPLACE`; replay reads the effective catalog
359
+ like other event writes. Registration is asynchronous: a missing or incompatible replay action
360
+ returns 503 and rolls back the replay, rather than using a hardcoded fallback.
361
+
362
+ Replay checks the stored input against the current action catalog and retention settings, but
363
+ allows events older than seven days. Invalid input returns 400 and leaves the failed row open.
364
+ A missing tenant row returns 404; replayed or discarded rows return 409. Unavailable storage
365
+ or configuration returns 503 with `Retry-After: 1`.
366
+
367
+ The replay migration grants `audit_app` permission to update only `status` and `replayed_as`
368
+ on failed rows. Audit history remains append-only. As with existing migrations, the role must
369
+ already exist; if absent, the DBA must apply this grant when creating it.
370
+
371
+ For real database tests, point `AUDIT_TEST_DATABASE_URL` at a **disposable localhost** PostgreSQL
372
+ database named `audit_replay_test`, then run `npx nx test audit-service --runInBand --skipNxCache`.
373
+ The integration suite runs migrations and deletes test rows; never use a shared database.
374
+
375
+ ### Monitoring
376
+
377
+ `OTEL_EXPORTER_OTLP_ENDPOINT` sets where metrics are sent, for example
378
+ `http://otel-collector:4318`. Leaving it empty disables metric export.
379
+
380
+ The rules in `.openshift/observability/observability-stack.yml` alert when **at least one
381
+ failed event is still open**, or when the count cannot be read. An unavailable count is
382
+ unknown, not zero. Detection follows the monitoring update cycle; email or message delivery
383
+ needs separate configuration.
384
+
385
+ Open-event counts come from PostgreSQL. The write buffer counts confirmed parked events and
386
+ unconfirmed saves; failed replay saves use the same failure counter with `operation=replay`.
387
+
388
+ ## Scheduled retention
389
+
390
+ Retention is enabled by default and runs daily at 02:00 UTC. Set `RETENTION_ENABLED=false` to
391
+ disable it. Configure these environment variables (or the `audit-service` ConfigMap in OpenShift)
392
+ and restart the service to apply changes:
393
+
394
+ | Variable | Default | Meaning |
395
+ | ----------------------- | ----------- | ----------------------------------------------- |
396
+ | `RETENTION_ENABLED` | `true` | Set to `false` to disable scheduled deletion. |
397
+ | `RETENTION_SCHEDULE` | `0 2 * * *` | Cron schedule, at 02:00 UTC by default. |
398
+ | `RETENTION_BATCH_SIZE` | `1000` | Maximum audit rows deleted in one statement. |
399
+ | `RETENTION_MAX_BATCHES` | `10` | Maximum batches per tenant per scheduled sweep. |
400
+ | `RETENTION_MIN_DAYS` | `1` | Minimum configured retention period. |
401
+ | `RETENTION_MAX_DAYS` | `3650` | Maximum configured retention period. |
402
+
403
+ Each tick enumerates tenants with records in `audit_events` (including tenants no longer listed
404
+ by Tenant Service) and performs a separate bounded run for each. Every delete filters by that
405
+ tenant and `retention_until < cutoff`, where cutoff is captured at the start of the sweep.
406
+ Rows at exactly the cutoff and future rows are retained. No table-wide delete or `drop_chunks`
407
+ is used. A `(tenant_id, retention_until, id)` index supports the bounded ordered selection.
408
+ The per-tenant cap leaves remaining expired rows for the next sweep.
409
+
410
+ A database-wide PostgreSQL transaction advisory lock excludes concurrent cleanup across all
411
+ tenants and replicas. A lock loser skips rather than queues; a local running guard also prevents
412
+ overlapping timer invocations. The lock is held on the same connection as deletion and released
413
+ on commit, rollback or disconnect. No distributed guarantee is attributed to SDK `LimitToOne`.
414
+ Shutdown cancels future ticks, stops between tenants, and awaits the active run before closing storage.
415
+
416
+ Each executed tenant run, including a zero-deletion run, inserts `retention.run.succeeded` or
417
+ `retention.run.failed` in that tenant's `audit-service` namespace. The system actor and writer are
418
+ the service ID. The registered action uses the compliance class; metadata contains `deletedCount`,
419
+ completed `batches`, `cutoff`, and a sanitized `error` on failure. Tenants without any audit records
420
+ and ticks skipped for a busy lock do not create synthetic audit records.
421
+
422
+ The job resolves its registered action and retention before deleting. Deletion batches use savepoints
423
+ within one bounded tenant transaction. A failed batch rolls back to its savepoint, and earlier
424
+ successful batches commit **with a failure audit containing their count**. If that audit cannot be
425
+ inserted, or the process/connection dies before commit, the entire tenant transaction rolls back.
426
+ Database/configuration failures that prevent a run from starting, or prevent a failure record from
427
+ being committed, are reported through logs and `instrumentJob` telemetry; no durable failure event
428
+ can be guaranteed while the database itself is unavailable.
429
+
430
+ **Single-account MVP:** migrations, normal requests and retention reuse the existing `DB_USER` /
431
+ `DB_PASSWORD`. That account needs SELECT, INSERT and DELETE on `audit_events`; migration ownership
432
+ already supplies them. No new role or credential is created. Separate `audit_retention` credentials
433
+ and the acceptance criterion preventing business-role UPDATE/DELETE are explicitly deferred;
434
+ the service does not claim database-enforced append-only isolation in this mode.
435
+
436
+ The existing `ON DELETE CASCADE` on `audit_failed_events.replayed_as` is intentionally preserved.
437
+ Deleting an expired event also deletes any linked replayed failure rows; unreplayed failures are
438
+ untouched. `deletedCount` counts audit events, not cascaded failure rows.
439
+
440
+ For local integration verification only, set `AUDIT_RETENTION_TEST_DATABASE_URL` to a disposable
441
+ PostgreSQL database on `localhost` or `127.0.0.1` named `audit_retention_test`, then run the audit-service
442
+ tests. The suite refuses other hosts/database names and deletes its fixture rows. Never point it at Dev/UAT.
443
+
444
+ ## Self-auditing
445
+
446
+ Reading the audit trail is itself recorded. Each successful read writes one event to the
447
+ `audit-service` namespace of the tenant that was queried. The namespace's action catalog is
448
+ registered by the service at startup in core configuration, alongside `failed-event.replay`, and
449
+ applies to every tenant. If registration has not propagated yet, reads still succeed but recording
450
+ fails and is counted.
451
+
452
+ | Action | Category | Recorded when |
453
+ | --- | --- | --- |
454
+ | `events.list` | `data-access` | A namespace listing succeeds. |
455
+ | `events.list-all` | `data-access` | A cross-namespace listing succeeds. |
456
+ | `events.read` | `data-access` | A single event read succeeds. |
457
+ | `failed-events.list` | `data-access` | A failed-events listing succeeds. |
458
+
459
+ Reads use the `security` retention class (365 days by default). Replay is recorded
460
+ transactionally by the replay itself (see above), not by this mechanism.
461
+
462
+ The event's actor is the caller, `written_by` is the Audit Service's own client, and `metadata`
463
+ holds the `endpoint`, the `filters` supplied and the `resultCount`. `correlationId` is taken from the
464
+ `x-correlation-id` request header when present. A paged read records one event per request.
465
+
466
+ Events go through the normal validation, enrichment and buffer. A failure to record is logged and
467
+ counted and never fails the read. The count is exposed as `selfAuditFailures` in `GET /health`.
468
+ Failed or unauthorized reads are not recorded.