@abgov/adsp-sdk-mcp-server 1.17.0 → 1.19.0

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.
@@ -6,141 +6,85 @@ parent: Services
6
6
 
7
7
  # Audit service
8
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 runs in a separate job Deployment,
14
- not in the serving API replicas.
9
+ Audit Service stores tenant-scoped audit records: who did what, when, to which resource, and with
10
+ what outcome. Applications register **action definitions**, then explicitly submit **events**.
11
+ Registering an action does not create an audit record.
15
12
 
16
- ## Source layout
13
+ Use the `auditService` capability in `@abgov/adsp-service-sdk`, or call the REST API directly.
14
+ There is no separate Audit SDK package. Action catalogs and retention settings live in
15
+ Configuration Service; committed events live in PostgreSQL.
17
16
 
18
- The `apps/audit-service/src/audit` module follows the Calendar Service layout:
17
+ ## Prepare access
19
18
 
20
- - `model/`: catalog loading and retention configuration resolution.
21
- - `buffer/`: write scheduling, durability handling and the database adapter contract.
22
- - `jobs/`: scheduled retention and its tenant-scoped run audit.
23
- - `router/`: HTTP routes, write handlers, and OpenAPI definitions.
24
- - `types/`: event payloads and the submission contract.
25
- - `utils/`: event/request validation and write authorization.
19
+ Start with the [Node.js SDK service-account setup](../platform/platform-node-sdk.md#setting-up-a-service-account).
20
+ Use an SDK release that includes `auditActions`, `auditService.record()` and `auditService.query()`.
21
+ Keep client secrets in approved secret storage, never in source code.
26
22
 
27
- `app.ts` initializes the application and registers configuration and roles; `main.ts` starts the
28
- HTTP listener and handles shutdown. `src/postgres/` connects history, the write buffer and failed-event administration
29
- to the migrated `audit_events` and `audit_failed_events` tables. Tests are colocated with their implementations.
23
+ | Identifier | Example | Purpose |
24
+ | --- | --- | --- |
25
+ | Application client ID | `urn:ads:case-team:case-service` | Keycloak client and SDK `serviceId`. |
26
+ | Audit namespace | `case-service` | The service component of the client ID: `serviceId.service`. |
27
+ | Audit Service client | `urn:ads:platform:audit-service` | Owns the Audit roles and required token audience. |
28
+ | API discovery ID | `urn:ads:platform:audit-service:v1` | Resolves the environment's Audit API URL. |
29
+ | Action catalog | `audit-service:actions-case-service` | Configuration namespace and document name. |
30
30
 
31
- ## Authorization
31
+ Audit namespaces must be lowercase kebab-case, at most 40 characters. A tenant writer can write
32
+ only to the namespace derived from its verified client identity (`azp`). Readers can read all
33
+ namespaces within their tenant. Core callers need the appropriate role and an explicit target
34
+ tenant for event writes and history reads.
32
35
 
33
- `initializePlatform` registers three roles on `urn:ads:platform:audit-service`:
36
+ ### Roles and audience
34
37
 
35
- - `audit-reader`: read access; included in `tenant-admin` via `inTenantAdmin: true`.
36
- - `audit-writer`: event writes; explicitly assigned to application service accounts.
37
- - `audit-admin`: failed-event administration and protected actor identity access;
38
- does not replace reader/writer permissions.
38
+ These client roles belong to `urn:ads:platform:audit-service`:
39
39
 
40
- Every audit route uses `requireAuditRole` to check both the role and resolved tenant.
41
- Core callers may cross tenants but still need the role. Missing/invalid tokens return 401;
42
- insufficient permissions return 403. Discovery, health and Swagger remain public.
40
+ | Role | Permission | Included in `tenant-admin` |
41
+ | --- | --- | --- |
42
+ | `audit-reader` | Read action definitions and audit history. | Yes, after provisioning. |
43
+ | `audit-writer` | Submit audit events. | No; assign explicitly. |
44
+ | `audit-admin` | Administer failed events and access protected actor identity. | No; assign only when needed. |
43
45
 
44
- New tenants receive the registered roles during provisioning. Existing tenants and Core still
45
- require role provisioning; redeploying this service alone does not synchronize their Keycloak roles.
46
+ `audit-admin` does not replace reader or writer permissions.
46
47
 
47
- ## Configuration contract
48
+ 1. In **Tenant Management App > Access > Service roles**, find Audit Service, including under
49
+ **Core service roles**. Use **Action > +** to provision missing roles in the tenant realm.
50
+ 2. In Keycloak, open the **calling application's client**. Under **Client scopes**, open its
51
+ dedicated scope and add an **Audience** mapper with **Included Client Audience** set to
52
+ `urn:ads:platform:audit-service`. Include it in the access token.
53
+ 3. Under **Service account roles**, assign `audit-writer` from the Audit Service client.
54
+ Also assign `audit-reader` if the application needs to query records.
55
+ 4. Obtain a fresh client-credentials token. Verify its audience, roles and `azp` locally;
56
+ never paste tokens into public decoding services.
48
57
 
49
- Audit Service registers a namespace-level schema at startup through `initializePlatform` with
50
- `configuration.useNamespace: true`. The definition is the `audit-service` entry in Core
51
- `platform:configuration-service`. It appears under **Configuration service > Definitions > Core definitions**.
52
- Registration follows the SDK's asynchronous startup behavior: inspect registration logs and the stored
53
- definition before onboarding applications; a listening HTTP server alone does not prove registration succeeded.
58
+ **Provisioning a role is not the same as assigning it to an application.** Redeploying Audit
59
+ Service alone does not provision missing roles in existing realms. If the service is absent,
60
+ ask an administrator to check the environment and tenant/Core registration views.
54
61
 
55
- Each application stores a complete catalog in `audit-service:actions-<application>`, in its tenant
56
- or in Core for shared actions:
62
+ Action registration separately requires Configuration Service access and audience. The standard
63
+ SDK registration path uses `configured-service`; creating and activating revisions requires an
64
+ authorized `configuration-admin`. `audit-writer` alone cannot publish action definitions.
57
65
 
58
- ```json
59
- {
60
- "kind": "actionCatalog",
61
- "application": "case-service",
62
- "actions": {
63
- "case.update": {
64
- "version": 1,
65
- "category": "administrative",
66
- "severity": "info",
67
- "retentionClass": "compliance",
68
- "resourceType": "case",
69
- "captureChangeSet": true,
70
- "forwardToSiem": false,
71
- "metadataSchema": {
72
- "type": "object",
73
- "properties": { "reason": { "type": "string" } }
74
- }
75
- }
76
- }
77
- }
78
- ```
66
+ ## Integrate with the Node.js SDK
67
+
68
+ The examples run in asynchronous application code. `config` is validated deployment configuration
69
+ and `logger` is a Winston logger. Replace the illustrative client, actor and resource identifiers
70
+ with your application's values.
79
71
 
80
- `application` is a lowercase kebab-case identifier, at most 40 characters. The API's `namespace`
81
- is this same identifier, **not** the Configuration Service namespace `audit-service`. For an SDK
82
- client it should equal `serviceId.service`. Applications are trusted to register only their own
83
- catalog; Configuration Service roles do not provide application-level write isolation.
84
-
85
- Actions require a positive integer `version`, `category` (`administrative`, `runtime`, `security`,
86
- `data-access`), `severity` (`info`, `warning`, `critical`), and a kebab-case `retentionClass`.
87
- Optional fields are `description`, `resourceType`, `captureChangeSet`, `forwardToSiem`, and
88
- `metadataSchema`. The two flags resolve to `false` when omitted. An omitted metadata schema imposes
89
- no action-specific metadata constraint. The listing returns any supplied schema intact.
90
- Unknown document and definition fields are rejected. Action keys omit the event outcome suffix.
91
-
92
- The namespace schema also preserves `retentionSettings` and `applicationRetentionSettings` document
93
- shapes, with positive integer `classes.<class>.days`. Catalog registration creates no retention periods.
94
- At write time the service resolves configured periods over the design defaults: standard 90 days,
95
- security and compliance 365 days. Application settings in `audit-service:retention-<application>`
96
- override `audit-service:retention`, which overrides those defaults. Expiry is calculated from
97
- `occurred_at` in UTC days. Missing custom classes fail writes with a retryable 503.
98
-
99
- The schema also accepts the Core-only `rateLimitSettings` document described in
100
- [Write rate limiting](#write-rate-limiting).
101
-
102
- ### Retention periods and forward-only changes
103
-
104
- `RETENTION_MIN_DAYS` and `RETENTION_MAX_DAYS` configure platform-wide, inclusive bounds
105
- (defaults **1** and **3650** days, pending PO confirmation). Both must be positive integers,
106
- with minimum no greater than maximum. These bounds apply to tenant and Core retention settings,
107
- application overrides, and custom classes. The fixed default periods remain 90/365/365 days.
108
- If narrower bounds exclude a default, configure an in-range replacement for that class.
109
-
110
- The service registers these bounds in the Configuration Service namespace schema, so out-of-range
111
- period updates are rejected there. Restart the service after changing the platform environment
112
- settings and verify that the updated namespace definition has registered. All replicas must use
113
- the same bounds. The write path also validates resolved periods, refusing old positive periods
114
- outside new bounds with 503 rather than silently substituting defaults. Existing SDK handling of
115
- configuration transport/structural conversion failures remains as documented below.
116
-
117
- Changes are **forward only**: after the active configuration/cache refreshes, newly enriched
118
- events use the new period, but stored `retention_until` values are never recalculated. Buffered
119
- events already enriched keep their original expiry too. Cleanup uses only stored expiry, not the
120
- current period or a TimescaleDB chunk boundary.
121
-
122
- ### Registering through the SDK
123
-
124
- `auditDefinitions()` turns application constants (a map or an array) into a map keyed by action
125
- name and rejects duplicate names at startup. Category and severity types and configuration
126
- validation use the SDK's shared constants; custom retention class names remain supported.
127
-
128
- The simplest option is `auditActions` on `initializeService` or `initializePlatform`. The SDK
129
- replaces the `actions-<serviceId.service>` catalog with these actions. Duplicate or invalid names
130
- fail initialization. Registration itself is asynchronous; `auditService` holds writes until it has
131
- settled, so the first events are not rejected as unknown actions.
72
+ ### Define the actions
73
+
74
+ Use base action names without a terminal `.succeeded` or `.failed` suffix.
132
75
 
133
76
  ```typescript
134
77
  import {
78
+ AdspId,
135
79
  adspId,
136
- AuditAction,
137
80
  AuditCategories,
138
81
  AuditSeverities,
139
82
  BuiltInRetentionClasses,
83
+ initializePlatform,
140
84
  initializeService,
141
85
  } from '@abgov/adsp-service-sdk';
86
+ import type { AuditAction } from '@abgov/adsp-service-sdk';
142
87
 
143
- const serviceId = adspId`urn:ads:case-team:case-service`;
144
88
  const ACTIONS = {
145
89
  UPDATE_CASE: {
146
90
  name: 'case.update',
@@ -148,576 +92,355 @@ const ACTIONS = {
148
92
  category: AuditCategories.Administrative,
149
93
  severity: AuditSeverities.Info,
150
94
  retentionClass: BuiltInRetentionClasses.Compliance,
95
+ resourceType: 'case',
96
+ captureChangeSet: true,
97
+ metadataSchema: {
98
+ type: 'object',
99
+ properties: { reason: { type: 'string' } },
100
+ required: ['reason'],
101
+ additionalProperties: false,
102
+ },
151
103
  },
152
104
  } satisfies Record<string, AuditAction>;
153
-
154
- const { auditService } = await initializeService(
155
- { serviceId, displayName: 'Case service', description: 'Case management', auditActions: ACTIONS },
156
- { logger },
157
- );
158
105
  ```
159
106
 
160
- Alternatively, register the catalog explicitly as a named configuration document:
107
+ ### Tenant application: `initializeService`
161
108
 
162
- ```typescript
163
- import { auditDefinitions } from '@abgov/adsp-service-sdk';
109
+ A tenant application supplies its realm. Its service-account token determines the tenant.
164
110
 
165
- // Include this entry in initializeService's serviceConfigurations.
166
- const serviceConfigurations = [
111
+ ```typescript
112
+ const { auditService } = await initializeService(
167
113
  {
168
- serviceId: adspId`urn:ads:platform:audit-service`,
169
- configuration: [
170
- {
171
- name: `actions-${serviceId.service}`,
172
- operation: 'REPLACE' as const,
173
- configuration: {
174
- kind: 'actionCatalog',
175
- application: serviceId.service,
176
- actions: auditDefinitions(ACTIONS),
177
- },
178
- },
179
- ],
114
+ serviceId: adspId`urn:ads:case-team:case-service`,
115
+ displayName: 'Case service',
116
+ description: 'Case management',
117
+ realm: config.realm,
118
+ clientSecret: config.clientSecret,
119
+ accessServiceUrl: new URL(config.accessServiceUrl),
120
+ directoryUrl: new URL(config.directoryUrl),
121
+ auditActions: ACTIONS,
180
122
  },
181
- ];
123
+ { logger },
124
+ );
182
125
  ```
183
126
 
184
- Use `initializePlatform` for a Core platform service. The same registration entry then creates a
185
- shared Core catalog. Existing SDK registrations continue to use `UPDATE` unless a named document
186
- explicitly selects `REPLACE`. For direct Configuration Service calls, PATCH the named catalog with
187
- `{ "operation": "REPLACE", "configuration": <complete catalog> }`.
127
+ ### Core platform service: `initializePlatform`
188
128
 
189
- Replacing one application's document cannot delete another application's catalog, including during
190
- concurrent registration. Replacing its action map removes obsolete definitions, unlike a shallow
191
- `UPDATE` merge. Concurrent writers to the _same_ application remain last-writer-wins; coordinate
192
- those deployments. Only trusted administrators/deployment accounts should have write access.
129
+ Use this **instead of** the tenant initialization above for a Core service. It automatically
130
+ uses the `core` realm and registers a shared Core catalog; do not pass a `realm` option.
131
+ Use credentials for the Core client, not the tenant application's client.
193
132
 
194
- If an active revision is set, changing latest alone may not publish the change. Create and activate
195
- revisions through the normal Configuration Service workflow, with a configuration-admin account.
196
-
197
- ### Recording and querying through the SDK
133
+ ```typescript
134
+ const { auditService } = await initializePlatform(
135
+ {
136
+ serviceId: adspId`urn:ads:platform:case-service`,
137
+ displayName: 'Case service',
138
+ description: 'Multi-tenant case management',
139
+ clientSecret: config.clientSecret,
140
+ accessServiceUrl: new URL(config.accessServiceUrl),
141
+ directoryUrl: new URL(config.directoryUrl),
142
+ auditActions: ACTIONS,
143
+ },
144
+ { logger },
145
+ );
198
146
 
199
- `initializeService` and `initializePlatform` return `auditService`, which writes to the calling
200
- service's namespace (`serviceId.service`):
147
+ const tenantId = AdspId.parse(config.tenantId);
201
148
 
202
- ```typescript
203
149
  const outcome = await auditService.record(ACTIONS.UPDATE_CASE, {
204
- actor: { id: user.id, type: 'user' },
205
- resource: { type: 'case', id: caseId },
206
- metadata: { reason },
207
- changeSet: { before, after }, // Dropped unless the action sets captureChangeSet.
150
+ tenantId,
151
+ actor: { id: 'onboarding-test-user', type: 'user' },
152
+ resource: { type: 'case', id: 'onboarding-case-001' },
153
+ metadata: { reason: 'Onboarding verification' },
208
154
  });
209
155
 
210
156
  if (outcome.status !== 'recorded') {
211
- logger.warn(`Audit event ${outcome.eventId} was not recorded: ${outcome.reason}`);
157
+ logger.error('Audit event was not confirmed recorded', { outcome });
158
+ throw new Error(`Audit write failed: ${outcome.status}`);
212
159
  }
213
160
 
214
- const { results, page } = await auditService.query({ resourceType: 'case', resourceId: caseId }, { top: 50 });
161
+ const history = await auditService.query(
162
+ { resourceType: 'case', resourceId: 'onboarding-case-001' },
163
+ { tenantId, top: 20 },
164
+ );
215
165
  ```
216
166
 
217
- - **Default delivery**: each event is sent immediately in its own HTTP request, without a
218
- client-side batch timer. Sending still waits for action registration to settle. Core services
219
- must pass `tenantId`.
220
- - **Outcomes**: `record()` never rejects. It resolves `recorded` (accepted or an idempotent
221
- duplicate), `rejected` (the service rejected the event, with its `code` and `reason`), or
222
- `failed` (delivery failed or could not be confirmed, with a `reason`). Await it and check the
223
- outcome; `recorded` confirms a committed audit row, not just queue admission. A timeout or lost
224
- response can leave the result uncertain; resend with the same `eventId` to avoid duplicates.
225
- - **Retries**: network errors, timeouts, 429, 502, 503 and 504 are retried with the same `eventId`
226
- after 200 ms, 1 s, 3 s and 5 s, honouring `Retry-After` up to 30 s. Other errors are not retried.
227
- - **Capacity**: up to 1,000 events or 8 MB (serialized) can be in flight, retrying or queued for
228
- optional batching. New events beyond either limit fail immediately with `buffer_full`. These
229
- limits still apply to immediate delivery; pending work is in memory and is lost if the process exits.
230
- - **Dropped events**: every `rejected` or `failed` outcome increments the
231
- `audit.client.dropped_events` OpenTelemetry counter (`audit_client_dropped_events_total` in
232
- Prometheus) with a `reason` attribute, and `auditService.droppedEventCount`.
233
- - **Shutdown**: no separate audit `flush()` is needed once all `record()` calls have settled.
234
- Normal graceful shutdown must still wait for in-flight application requests and tasks. If
235
- records remain unawaited or batches are pending, call `await auditService.flush()` before exiting;
236
- it sends buffered events and waits for in-flight requests, including retries. Immediate delivery
237
- does not guarantee completion of fire-and-forget calls or survive forced process termination.
238
- - **Queries**: `query()` reads the service's namespace with the service token by default. Pass
239
- `namespace`, `tenantId` (Core) or a user `token` in options; failures reject.
240
-
241
- #### Optional client batching
242
-
243
- Set `audit.batchSize` greater than 1 on `initializeService` or `initializePlatform` to opt into
244
- client-side batching. A full batch is sent immediately; a partial batch waits up to
245
- `audit.batchIntervalMs` (500 ms by default). Core events are batched separately per tenant.
246
- The same options are available on the SDK's internal `createAuditService` factory.
167
+ `config.tenantId` must be a tenant URN such as
168
+ `urn:ads:platform:tenant-service:v2:/tenants/<tenant-id>`, taken from trusted tenant context.
169
+ Core callers must pass this `AdspId` in **record details** and **query options**, as shown above.
170
+ Tenant applications use the same calls but omit `tenantId`.
247
171
 
248
- ```typescript
249
- const { auditService } = await initializeService(
250
- {
251
- ...serviceOptions,
252
- auditActions: ACTIONS,
253
- audit: { batchSize: 100, batchIntervalMs: 500 },
254
- },
255
- { logger },
256
- );
257
- ```
172
+ ### Event content and delivery
258
173
 
259
- This explicitly preserves the previous default of 100 events / 500 ms. Without it, upgrading
260
- increases HTTP request volume but removes the client-side batch wait. Both modes use the same
261
- outcome, retry and idempotency contracts. `AuditClientOptions` is exported from the SDK for typed
262
- configuration, including capacity limits, `requestTimeoutMs` and `retryDelaysMs`.
263
-
264
- Client batching reduces HTTP overhead. The service independently combines concurrent submissions
265
- into database batches of 200 events or 200 ms; a single-event HTTP request does not necessarily
266
- cause an individual database write. Sequentially awaiting records in one loop does not itself
267
- provide concurrent events to batch. Immediate delivery still waits for service-side batching,
268
- database work and possible retries. The request timeout applies per HTTP attempt, not to the total
269
- call including registration, discovery, token acquisition and retries.
270
-
271
- ## Loading and cache behavior
272
-
273
- The service reads active revisions with fallback to latest, through the existing SDK configuration
274
- service. It merges tenant and Core maps **by action name**, with the entire Core definition winning
275
- on conflicts. Tenant-only actions remain. An empty tenant catalog does not hide shared Core actions.
276
- The stored `application` must match the requested configuration name.
277
-
278
- The SDK caches converted documents by tenant, configuration namespace, and document name. Core
279
- documents are shared deliberately. The combine function uses the SDK's existing memoization.
280
- Tenant `configuration-updated` and `active-revision-set` notifications invalidate the affected
281
- entry; the next request reloads it. Core changes also have the TTL backstop; do not assume a Core
282
- write emits a tenant notification.
283
-
284
- `useLongConfigurationCacheTTL` is **false**, retaining the SDK's 900-second (15-minute) TTL.
285
- With Configuration Service available, a missed notification is picked up on the first request
286
- after expiry, plus fetch latency. An update notice normally refreshes on the next request; there is
287
- no measured end-to-end notification latency guarantee yet. Register actions before deploying code
288
- that emits them.
289
-
290
- Audit Service uses the SDK's existing error handling. Configuration HTTP or converter failures are
291
- logged and returned as `null`, so the catalog API cannot reliably distinguish these failures from
292
- missing configuration. If neither scope supplies a catalog, listing returns 404; if only one scope
293
- succeeds, it can return a partial catalog. A registered empty catalog retains its `actions: {}`.
294
- Errors that still propagate, such as token acquisition failures, and application-name consistency
295
- failures return 503. On writes, SDK-handled failures can produce unknown-action rejections or
296
- fallback retention periods; reliable failure-versus-absence distinction is not provided.
297
-
298
- **Deferred by the MVP scope decision:** stale-on-error after invalidation/expiry, explicit cache
299
- capacity limits, and stronger invalidation/in-flight refresh guarantees. Existing unexpired
300
- configuration cache entries avoid configuration HTTP reads, but token retrieval remains an SDK
301
- dependency. Once an entry expires or is invalidated, a configuration HTTP failure resolves to null;
302
- the SDK does not retain the old value for fallback. These remaining OSP-730 cache guarantees
303
- are not claimed complete.
304
-
305
- ## Listing definitions
174
+ `record()` supplies a UUID `eventId`, the current `occurredAt`, and business `status: 'success'`
175
+ when omitted. Supply these explicitly when preserving an event for later delivery. Business
176
+ status can be `success`, `failure`, `blocked` or `error`; it is separate from the delivery outcome.
306
177
 
307
- ```http
308
- GET /audit/v1/case-service/actions
309
- Authorization: Bearer <token with audit-reader>
178
+ To capture changes, set `captureChangeSet: true` on the action and add
179
+ `changeSet: { before: { state: 'draft' }, after: { state: 'submitted' } }` to the record details.
180
+ Otherwise the SDK drops the change set before sending. Record only necessary data; never include
181
+ credentials or unnecessary personal information.
182
+
183
+ **Always await `record()` and inspect its outcome.** It does not reject to report write failures.
184
+
185
+ | Outcome | Meaning | Response |
186
+ | --- | --- | --- |
187
+ | `recorded` | A committed audit row or an existing idempotent duplicate was confirmed. | Continue. |
188
+ | `rejected` | The service returned a per-event `code` and `reason`. | Investigate; the SDK does not resubmit it automatically. |
189
+ | `failed` | Delivery failed or could not be confirmed; includes `reason` and `error`. | Apply an explicit recovery policy; the event may already be stored. |
190
+
191
+ The SDK sends events immediately by default. It retries network errors, timeouts and HTTP
192
+ 429/502/503/504 with the same IDs. For application-level retries, preserve the original event,
193
+ including its `eventId` and `occurredAt`; a new ID can create a duplicate after a lost response.
194
+
195
+ Optional client batching is enabled with `audit: { batchSize: 100, batchIntervalMs: 500 }` in
196
+ either initializer. Pending, in-flight and retrying work defaults to a maximum of 1,000 events
197
+ or 8 MiB of serialized data; excess events fail with `buffer_full`. This buffer is in memory,
198
+ not durable recovery storage.
199
+
200
+ Monitor `auditService.droppedEventCount` and the `audit.client.dropped_events` metric.
201
+ Before shutdown, stop accepting new work and call `await auditService.flush()` if unawaited
202
+ records or batches remain. No separate flush is needed once all `record()` calls have settled.
203
+ Forced termination can lose pending work.
204
+
205
+ ## Register and publish actions
206
+
207
+ `auditActions` replaces the complete `audit-service:actions-<serviceId.service>` catalog.
208
+ Include every action that must remain registered and coordinate deployments of the same
209
+ application: concurrent replacements are last-writer-wins. Other applications' catalogs are
210
+ separate. Only trusted deployment identities should publish catalogs; Configuration Service
211
+ permissions do not enforce application-level write isolation.
212
+
213
+ Each definition requires a positive integer `version`, `category` (`administrative`, `runtime`,
214
+ `security`, `data-access`, `diagnostic`), `severity` (`info`, `warning`, `critical`) and a kebab-case
215
+ `retentionClass`. Optional fields include `description`, `resourceType`, `metadataSchema`,
216
+ `captureChangeSet` and `forwardToSiem`. Both flags default to false; SIEM forwarding is a separate
217
+ capability. Shared Core definitions win over tenant definitions with the same action name.
218
+
219
+ The `diagnostic` category is for debugging-oriented records (as opposed to audit records of who did
220
+ what). Applications register diagnostic actions in their own catalog like any other category, and
221
+ the events are filterable with `category=diagnostic` when reading or exporting.
222
+
223
+ ### Register without the SDK
224
+
225
+ Through [Configuration Service](configuration-service.md), PATCH the document in namespace
226
+ `audit-service`, name `actions-case-service`, using this complete-document replacement:
227
+
228
+ ```json
229
+ {
230
+ "operation": "REPLACE",
231
+ "configuration": {
232
+ "kind": "actionCatalog",
233
+ "application": "case-service",
234
+ "actions": {
235
+ "case.update": {
236
+ "version": 1,
237
+ "category": "administrative",
238
+ "severity": "info",
239
+ "retentionClass": "compliance",
240
+ "resourceType": "case",
241
+ "captureChangeSet": true,
242
+ "metadataSchema": {
243
+ "type": "object",
244
+ "properties": { "reason": { "type": "string" } },
245
+ "required": ["reason"],
246
+ "additionalProperties": false
247
+ }
248
+ }
249
+ }
250
+ }
251
+ }
310
252
  ```
311
253
 
312
- Returns a JSON array, with each action's `name` plus its definition fields. Optional absent
313
- `resourceType`, `description`, and `metadataSchema` remain omitted.
254
+ ### Confirm publication
255
+
256
+ If an active revision exists, updating latest alone does not publish the change. Create and
257
+ activate the intended revision through Configuration Service.
258
+
259
+ Registration is asynchronous. SDK writes wait for registration to settle, **not** for proof
260
+ that it succeeded or every Audit Service instance has refreshed. The current cache TTL is
261
+ 900 seconds (15 minutes), with invalidation notifications allowing earlier refresh. This setting
262
+ is provisional, not a propagation guarantee.
314
263
 
315
- | Status | Meaning |
316
- | ------ | -------------------------------------------------------------------------------------- |
317
- | 200 | Resolved definitions; `[]` means registered but empty. |
318
- | 400 | Invalid application/namespace or tenant ID format. |
319
- | 401 | Not authenticated. |
320
- | 403 | No `audit-reader`, or a tenant caller attempted to select a different tenant. |
321
- | 404 | Neither scope supplied a catalog; SDK-handled failures can also produce this response. |
322
- | 503 | A propagated SDK error or application-name consistency failure; retry. |
264
+ Before emitting a new action, check registration logs and use an `audit-reader` token to call
265
+ `GET /audit/v1/case-service/actions`. Confirm the expected name and version, then submit and
266
+ query a controlled event. Do not use a fixed sleep as a readiness check. Configuration-read
267
+ failures can appear as missing catalogs or unknown actions; a 404 alone does not prove that
268
+ registration is absent.
323
269
 
324
- `audit-reader` is tenant-wide: callers can read any namespace in their tenant, not only their own.
325
- A Core caller with the role can select a tenant via
326
- `?tenantId=urn:ads:platform:tenant-service:v2:/tenants/<id>`. A Core request without tenant context
327
- reads Core catalogs only. The service registers this role for tenant provisioning; existing tenants
328
- still need their normal role provisioning/assignment process.
270
+ ## Use the REST API
329
271
 
330
- The catalog governs future write classification, not history access. Removing a definition performs
331
- no audit-record deletion. History endpoints query PostgreSQL independently of the catalog, so
332
- removing an action does not prevent reading its existing records.
272
+ Resolve `urn:ads:platform:audit-service:v1` through the target environment's Directory Service.
273
+ The SDK handles discovery automatically. For full schemas, follow the service root's
274
+ `_links.docs.href` to its OpenAPI document (`/swagger/docs/v1`).
333
275
 
334
- ## Writing events
276
+ ### Adding an action
335
277
 
336
278
  ```http
337
- POST /audit/v1/case-service/events
279
+ POST /audit/v1/{namespace}/actions
280
+ Authorization: Bearer <token with audit-admin>
338
281
  Content-Type: application/json
282
+
283
+ { "name": "case.update", "version": 1, "category": "runtime", "severity": "info", "retentionClass": "standard" }
339
284
  ```
340
285
 
341
- Supply an authenticated bearer token with `audit-writer` and a body
342
- `{ "events": [ ... ] }` containing 1 to 500 events. Configure the Audit Service
343
- audience on the application client and explicitly grant the role to its service
344
- account; `audit-writer` is not automatically assigned to tenant administrators.
286
+ Adds the action to the caller's tenant catalog (`actions-<namespace>`, created if missing). The caller's token is
287
+ forwarded to the configuration service, so configuration write permission is required as well. The name is compared
288
+ in full and case-insensitively with the namespace's own catalog and every Core catalog, read directly from the
289
+ configuration service rather than the cache. `409` is returned when the name already exists in either, or when the
290
+ namespace is itself a Core namespace; `503` when the check cannot be made, in which case nothing is written.
345
291
 
346
- The verified token's `azp` must be a service URN. Tenant writers may write only
347
- its service component's namespace. Core writers with the role follow the existing
348
- platform exemption and can select another namespace and tenant through `?tenantId=...`.
349
- Core must supply a tenant. Role provisioning, not an additional claim check,
350
- limits this permission to service accounts.
292
+ ### Write an event
351
293
 
352
- Events require a UUID `eventId`, `occurredAt`, `action`, `status`, and `actor.id/type`.
353
- Occurrence time must be within the past seven days or next five minutes. Actions
354
- may have a terminal `.succeeded` or `.failed` suffix. An omitted `actionVersion`
355
- uses the current catalog version; an explicit mismatch is rejected.
356
- Resource type and metadata are validated against the resolved action.
357
- Metadata and change sets each have a 16 KiB UTF-8 JSON limit; the whole body has a
358
- 20 MiB limit. A non-capturing action drops change sets from the trusted row.
294
+ Use a bearer token with the Audit audience and `audit-writer`. Replace the placeholders with
295
+ a UUID and the current ISO 8601 UTC timestamp; preserve both when retrying.
296
+ Core callers must also supply the URL-encoded tenant URN as the `tenantId` query parameter.
359
297
 
360
- Malformed batch envelopes return 400, oversized bodies or enriched batches return 413, and malformed
361
- individual events produce individual rejections. Classification, identity and
362
- retention columns are server-set, never copied from caller-supplied row fields.
298
+ ```http
299
+ POST /audit/v1/case-service/events
300
+ Authorization: Bearer {{ACCESS_TOKEN}}
301
+ Content-Type: application/json
302
+
303
+ {
304
+ "events": [
305
+ {
306
+ "eventId": "{{EVENT_UUID}}",
307
+ "occurredAt": "{{CURRENT_UTC_TIMESTAMP}}",
308
+ "action": "case.update",
309
+ "actionVersion": 1,
310
+ "status": "success",
311
+ "actor": { "id": "onboarding-test-user", "type": "user" },
312
+ "resource": { "type": "case", "id": "onboarding-case-001" },
313
+ "metadata": { "reason": "Onboarding verification" }
314
+ }
315
+ ]
316
+ }
317
+ ```
363
318
 
364
- A 202 response accounts for all inputs after storage outcomes are confirmed:
319
+ A confirmed single-event write returns HTTP 202:
365
320
 
366
321
  ```json
367
322
  { "accepted": 1, "duplicates": 0, "rejected": [] }
368
323
  ```
369
324
 
370
- Each rejection includes a zero-based input `index`, `code`, `reason`, and an
371
- `eventId` when available. Counts and rejection length account for every input.
372
- Duplicates are determined by PostgreSQL, not an in-memory router check.
373
- If durable storage is unavailable, valid submissions return **503 with Retry-After**.
374
- A writer over its rate limit receives **429 with Retry-After**; see [Write rate limiting](#write-rate-limiting).
375
-
376
- ## Write rate limiting
377
-
378
- Writes are rate limited per **tenant and namespace** to constrain retry loops.
379
- One namespace exhausting its allowance does not consume another namespace's allowance in the same
380
- tenant, or any other tenant's allowance. The buffer remains shared: rate limiting does not reserve
381
- buffer space or guarantee capacity for other writers. Reads are not rate limited.
382
-
383
- The limit counts **events, not requests**: a request of 500 events uses 500 units of allowance,
384
- the same as 500 requests of one event. Each tenant and namespace has a token bucket that holds at
385
- most `burst` events and refills at `eventsPerSecond`. A request that does not fit in the current
386
- allowance is refused whole with **429** and `Retry-After` (seconds until enough allowance has
387
- accumulated, assuming no competing writes for the same key). None of its events are stored and it
388
- consumes no allowance, so the caller resends the complete request. The check runs after envelope
389
- validation and before event enrichment. All admitted events consume allowance, including duplicates,
390
- individual rejections and requests that later return 413 or 503. Failed requests are not refunded:
391
- otherwise an application retrying during a storage outage could bypass the limiter. A corrected or
392
- retried request can receive 429 until its allowance refills.
393
-
394
- 429 and 503 stay distinct: 429 means _this writer is sending too much_; 503 means _the service
395
- cannot keep up with everyone_ (for example the buffer is full or storage is unavailable).
396
-
397
- | Setting | Default | Bounds |
398
- | ----------------- | ------- | ------------------------ |
399
- | `eventsPerSecond` | `500` | 1 to 500 (inclusive) |
400
- | `burst` | `500` | 500 to 1,000 (inclusive) |
401
-
402
- The burst must accept the largest request (500 events) and must not exceed the per-pod buffer
403
- (1,000 events). The deployment default comes from `RATE_LIMIT_EVENTS_PER_SECOND` and
404
- `RATE_LIMIT_BURST`; the service refuses to start with out-of-range values.
405
- The 500 events/s ceiling applies to both environment settings and Core configuration, including
406
- tenant overrides. It is an operational guardrail, not a measured database throughput guarantee.
407
-
408
- To change limits **without a redeploy**, a platform administrator saves the **Core**
409
- `audit-service:rate-limit` configuration:
325
+ **202 alone does not mean every event succeeded.** Check all fields:
326
+ `accepted + duplicates + rejected.length` accounts for the submitted events. Rejections include
327
+ the zero-based input `index`, `code`, `reason`, and `eventId` when available.
410
328
 
411
- ```json
412
- {
413
- "kind": "rateLimitSettings",
414
- "default": { "eventsPerSecond": 500, "burst": 500 },
415
- "tenants": {
416
- "urn:ads:platform:tenant-service:v2:/tenants/<tenant-id>": { "eventsPerSecond": 250, "burst": 500 }
417
- }
418
- }
329
+ | Constraint | Limit |
330
+ | --- | --- |
331
+ | Events per request | 1-500 |
332
+ | Occurrence time | Previous 7 days through 5 minutes into the future |
333
+ | Metadata and change set | 16 KiB UTF-8 JSON each |
334
+ | HTTP request body | 20 MiB; enriched batches must also fit the smaller service buffer |
335
+ | Action version | Omit to use the current catalog version; an explicit mismatch is rejected |
336
+
337
+ ### Read and export
338
+
339
+ History reads require `audit-reader` and tenant context. The writer role alone is insufficient.
340
+
341
+ ```http
342
+ GET /audit/v1/case-service/events?resourceType=case&resourceId=onboarding-case-001&top=20
343
+ Authorization: Bearer {{ACCESS_TOKEN}}
419
344
  ```
420
345
 
421
- A tenant entry applies to every namespace in that tenant; `default` applies to tenants without an
422
- entry; the environment default applies when neither is set. Only the Core document is read, so a
423
- tenant cannot raise its own ceiling with a tenant-scoped document. Changes apply after the
424
- configuration cache refreshes. Errors that propagate from the SDK, wrong document kinds and
425
- out-of-range resolved limits are logged and return 503 with Retry-After rather than silently
426
- relaxing a tenant's ceiling. The SDK can still convert HTTP or structural conversion failures to
427
- null, indistinguishable from a missing document; those cases use the environment default, as
428
- described in [Loading and cache behavior](#loading-and-cache-behavior).
429
-
430
- Limits are held **in memory per pod**. With the three API replicas, the effective limit for a
431
- tenant and namespace is up to three times the configured value, and depends on how the route
432
- distributes requests. Restarting a pod resets its buckets. A limit shared across replicas would
433
- need an external store (for example Redis) and an ADR; it is intentionally not used.
434
-
435
- Refusals are counted by `audit.write.rate_limited.requests` and `audit.write.rate_limited.events`
436
- (exported to Prometheus as `audit_write_rate_limited_requests_total` and
437
- `audit_write_rate_limited_events_total`), labelled with `tenant` and `namespace`. Sustained
438
- refusals warrant checking retry behaviour and expected volume before changing a limit.
439
-
440
- ## Reading events
441
-
442
- `GET /audit/v1/events` lists events across the resolved tenant's namespaces;
443
- `GET /audit/v1/{namespace}/events` restricts that list to one namespace.
444
- `GET /audit/v1/{namespace}/events/{id}` retrieves a record by its service-generated UUID,
445
- returning 404 when it does not exist in that tenant and namespace.
446
- All three require `audit-reader` and tenant context. Core readers can select a tenant with `tenantId`.
447
-
448
- Lists accept `actor`, `resourceType`, `resourceId`, `action`, `status`, `category`, `severity`, `scope`,
449
- `correlationId`, `sessionId`, `occurredFrom` and `occurredTo`. Filters combine with AND; time bounds are
450
- inclusive, and `scope` matches an element of `scopeIds`. `severity` and `sessionId` have no dedicated
451
- index; combine them with other filters on large tenants. Free-text search is not supported. Results are ordered by `occurred_at DESC, id DESC`, with `top`
452
- and an opaque `after` keyset cursor (the last event's `occurred_at` and `id`, returned as `page.next`)
453
- controlling pagination. Paging is stable while new events arrive, including the events recorded by
454
- the reads themselves.
455
-
456
- Responses retain the existing camelCase event shape and never expose `tenant_id`.
457
- Database read failures return 503 rather than an empty result or a false 404.
458
-
459
- See the [submission contract](https://github.com/GovAlta/adsp-monorepo/blob/main/apps/audit-service/README.md#submission-contract-osp-707--osp-708)
460
- for the boundary with OSP-708.
461
-
462
- ## Write buffer
463
-
464
- The router submits enriched events through
465
- `submit(events: EnrichedEvent[]): Promise<Map<string, EventOutcome>>`.
466
- Results use the service-generated `id`, never client `event_id`, to keep concurrent requests
467
- and tenants separate. Inputs must remain unchanged until the promise settles.
468
-
469
- The buffer batches at 200 events or 200 ms, with limits of 1,000 retained events and
470
- 8 MiB of serialized enriched payload (including original input) per pod. Capacity is reserved
471
- for the whole request before enqueueing. A batch that cannot fit even in an empty buffer returns
472
- 413 without storing any of its events; split it into smaller requests rather than retrying unchanged.
473
- A batch that fits on its own but exceeds the currently available capacity returns 503 with
474
- `Retry-After: 1`. The HTTP envelope still accepts up to 500 events and 20 MiB of input, but
475
- enrichment/original-input retention can make a valid request too large for the smaller buffer.
476
- The byte limit is not a measurement of process memory.
477
-
478
- Transient failures retry after 200 ms, 1 s and 3 s; constraint failures are retried individually.
479
- `accepted` requires a committed audit row. `storage_failed` requires the original event to be
480
- committed to failed-event storage and is counted as rejected, not accepted. If neither write
481
- succeeds, the request returns 503. The PostgreSQL adapter uses
482
- `ON CONFLICT (tenant_id, namespace, event_id) DO NOTHING RETURNING id`, resolves only after commit,
483
- and returns only inserted service IDs. It does not update existing events on conflict.
484
- Failed-event writes preserve the original payload and map the buffer's `attempt_count` to
485
- the database's `attempts` column.
486
-
487
- Writes use transactions with a four-second server-side statement timeout, including lock waits.
488
- Cancellation is checked before database work and before commit; cancelled operations roll back
489
- after the current bounded statement settles. Connection acquisition retains the database pool's
490
- 30-second bound; a cancellation during that wait prevents a late insert. Until an outstanding
491
- operation settles, the buffer refuses additional writes rather than accumulating abandoned work.
492
-
493
- `close()` refuses new submissions and drains within a configurable 25-second default budget,
494
- reserving the final 5 seconds for failed-event storage. SIGTERM and SIGINT first mark readiness
495
- unavailable, leaving the listener and write buffer open for a 10-second traffic-withdrawal window.
496
- The service then closes the listener and idle connections, drains queued writes and in-flight
497
- HTTP requests, and closes the database pools and telemetry. A 45-second process deadline exits
498
- with failure if shutdown cannot finish. OpenShift allows 60 seconds before forced termination.
499
- `GET /health` includes `db` and `ready`; it returns 503 when the database or buffer is unavailable
500
- or shutdown has started. This legacy diagnostic endpoint is not used by platform probes.
501
-
502
- ## Operational readiness
503
-
504
- The deployment intentionally differs from platform templates that use `/` for both probes:
505
-
506
- | Endpoint | Meaning |
507
- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
508
- | `/health/live` | Returns 200 while the HTTP process is responsive. Never checks PostgreSQL or platform dependencies. |
509
- | `/health/ready` | Returns 200 when PostgreSQL is reachable and the buffer can accept writes; otherwise 503. Shutdown immediately makes it return 503. |
510
-
511
- Both endpoints are unauthenticated and return empty bodies, with no connection, tenant or error
512
- details. Readiness uses a separate pool with at most one connection, 250 ms acquisition/query
513
- timeouts and a 750 ms overall deadline. Concurrent probes share one check; timed-out and failed
514
- connections are discarded. This avoids queuing probes behind 60-second history reads in the
515
- application pool. Each API/job pod may therefore use **DB_POOL_MAX + 1** connections.
516
-
517
- A successful database check can restore readiness without a new write or a restart; historical
518
- write failures do not permanently remove a recovered pod from service. An outstanding cancelled
519
- storage operation still prevents readiness. A full buffer uses per-request backpressure rather
520
- than removing the entire pod and shifting its load to other replicas.
521
-
522
- Readiness is checked every 5 seconds with a 1-second timeout and one failure to withdraw the pod.
523
- Liveness runs every 60 seconds with a 2-second timeout and three failures before restart.
524
- A startup probe allows up to five minutes for initialization/migrations before liveness starts.
525
- The 10-second shutdown withdrawal window covers two readiness intervals before refusing new work;
526
- actual ingress propagation remains an environment-dependent deployment concern.
527
-
528
- ### Resource and shutdown budgets
529
-
530
- Both workloads keep the original per-pod resources: requests of 20m CPU / 50Mi memory and
531
- limits of 100m CPU / 200Mi memory. The buffer is reduced instead of increasing these resources,
532
- with simultaneous caps of 1,000 events and 8 MiB serialized payload. Smaller buffers absorb
533
- shorter bursts and apply backpressure earlier; the 200-event / 200-ms write batching is unchanged.
534
-
535
- Allowing four times the serialized cap for retained objects/strings reserves 32 MiB for the
536
- buffer, leaving 168 MiB of the 200 MiB limit for the runtime, request parsing and transient/GC
537
- allocations. This is a planning envelope, not a measurement that the runtime fits in 168 MiB.
538
-
539
- These are sizing allowances, **not measured peak RSS or a guarantee for arbitrary concurrent
540
- requests**. Request parsing/enrichment happens before buffer admission, and the unchanged 20 MiB
541
- HTTP body limit is separate from the buffer cap. Observe actual memory usage with representative
542
- payloads before treating sizing as production capacity evidence. The job uses the same per-pod
543
- limits, but the additional job pod still increases the total workload resource allocation.
544
-
545
- The shutdown budget is `10s withdrawal + 25s flush + 10s cleanup = 45s process deadline`,
546
- with an additional 15 seconds in `terminationGracePeriodSeconds: 60`. Flush configuration must
547
- remain below 30 seconds so withdrawal and cleanup retain time. Long-running reads can be
548
- interrupted by this shutdown deadline; only durably committed events are acknowledged.
549
-
550
- ### History query and route timeouts
551
-
552
- Audit history list/detail queries have a separate 60-second database query timeout, with
553
- cancellation on timeout. Writes, failed-event administration and retention keep their existing
554
- 4-second statement limits. Pool acquisition remains bounded at 30 seconds. The Route sets
555
- `haproxy.router.openshift.io/timeout: 120s` to allow acquisition, history reads and response overhead
556
- without inheriting the router's 30-second default. Client-side deadlines must also allow the
557
- intended read duration; the route annotation alone cannot override client or database limits.
558
-
559
- ### Verification boundary
560
-
561
- Automated checks cover probe behavior, bounded database checks, readiness recovery, shutdown
562
- ordering, distinct query budgets and the deployment configuration. Live database-outage/recovery
563
- and rolling-deployment-under-write-load exercises are deferred for this delivery. They are not
564
- claimed as completed acceptance evidence. Platform metric visibility and a real long query
565
- through the deployed Route also require verification in the target environment.
566
-
567
- ## Failed-event administration
568
-
569
- Both endpoints require `audit-admin` and use the caller's tenant. Core administrators must
570
- provide `tenantId`. Reader or writer permissions alone are not enough.
571
-
572
- | Endpoint | Purpose |
573
- | ------------------------------------------ | --------------------------------------------------------------------- |
574
- | `GET /audit/v1/failed-events` | List the tenant's open, replayed and discarded events, newest first. |
575
- | `POST /audit/v1/failed-events/{id}/replay` | Retry an open event using its stored data. No request body is needed. |
576
-
577
- Listing accepts `top` (default 20, maximum 100) and the previous response's `page.next` as
578
- `after`, an opaque keyset cursor (the last row's `failed_at` and `id`), so pages stay stable while
579
- new failures are parked. It returns `{ results, page: { after?, size, next? } }`.
580
-
581
- Both endpoints use the same PostgreSQL connection as normal event writes and history reads.
582
- Replay saves the recovered event, failed-row update and replay audit record in one transaction:
583
- either all succeed or none do. Concurrent replay attempts cannot recover the same failed row twice.
584
-
585
- The recovered event keeps its original actor; `written_by` identifies Audit Service.
586
- `replayed_as` links to its database row ID. If that event already exists, replay links to it
587
- without changing it. The `audit-service` action `failed-event.replay.succeeded` records the
588
- requesting administrator. Startup registers its definition through the SDK into the Core
589
- `audit-service:actions-audit-service` catalog using `REPLACE`; replay reads the effective catalog
590
- like other event writes. Registration is asynchronous: a missing or incompatible replay action
591
- returns 503 and rolls back the replay, rather than using a hardcoded fallback.
592
-
593
- Replay checks the stored input against the current action catalog and retention settings, but
594
- allows events older than seven days. Invalid input returns 400 and leaves the failed row open.
595
- A missing tenant row returns 404; replayed or discarded rows return 409. Unavailable storage
596
- or configuration returns 503 with `Retry-After: 1`.
597
-
598
- The replay migration grants `audit_app` permission to update only `status` and `replayed_as`
599
- on failed rows. Audit history remains append-only. As with existing migrations, the role must
600
- already exist; if absent, the DBA must apply this grant when creating it.
601
-
602
- For real database tests, point `AUDIT_TEST_DATABASE_URL` at a **disposable localhost** PostgreSQL
603
- database named `audit_replay_test`, then run `npx nx test audit-service --runInBand --skipNxCache`.
604
- The integration suite runs migrations and deletes test rows; never use a shared database.
605
-
606
- ### Monitoring
607
-
608
- `OTEL_EXPORTER_OTLP_ENDPOINT` sets where metrics are sent, for example
609
- `http://otel-collector:4318`. Leaving it empty disables metric export.
610
-
611
- Both API and job pods inherit this setting from the Audit Service ConfigMap. Metrics use the
612
- existing platform pipeline: service OTLP export -> Collector -> Prometheus scrape of the
613
- Collector's `:8889` endpoint. A separate unauthenticated `/metrics` route on Audit Service is
614
- not required by this platform integration. The SDK exports every 60 seconds and Prometheus
615
- scrapes every 30 seconds; allow at least two minutes after startup/activity before checking.
616
- In the target environment, verify `audit_failed_events_available` is present and equals 1,
617
- and query `audit_failed_events_open`. An absent series is not a successful zero result.
618
- Check the Collector target is up and inspect exporter/Collector errors if metrics are missing.
619
-
620
- The rules in `.openshift/observability/observability-stack.yml` alert when **at least one
621
- failed event is still open**, or when the count cannot be read. An unavailable count is
622
- unknown, not zero. Detection follows the monitoring update cycle; email or message delivery
623
- needs separate configuration.
624
-
625
- Open-event counts come from PostgreSQL. The write buffer counts confirmed parked events and
626
- unconfirmed saves; failed replay saves use the same failure counter with `operation=replay`.
627
-
628
- ## Scheduled retention
629
-
630
- Retention runs daily at 02:00 UTC in the separate `audit-service-job` Deployment. It has one
631
- replica and a `Recreate` update strategy to avoid overlapping schedulers during updates.
632
- It uses the same image, platform identity and database Secret as the API, but has `component: job`
633
- and is excluded from the API Service/Route. Do not autoscale this workload. API scaling does not
634
- change the number of schedulers.
635
-
636
- `RETENTION_ENABLED` defaults to false. The API Deployment explicitly sets it to false even if
637
- an older ConfigMap still enables it; the job Deployment explicitly sets it to true.
638
- To suspend retention in OpenShift, scale the job Deployment to zero or change its explicit
639
- environment setting; changing only the shared ConfigMap will not override that setting.
640
- Configure schedule/batch settings in the shared ConfigMap and restart the job to apply them:
641
-
642
- | Variable | Default | Meaning |
643
- | ----------------------- | ----------- | ----------------------------------------------- |
644
- | `RETENTION_ENABLED` | `false` | Explicitly enabled only on the job Deployment. |
645
- | `RETENTION_SCHEDULE` | `0 2 * * *` | Cron schedule, at 02:00 UTC by default. |
646
- | `RETENTION_BATCH_SIZE` | `1000` | Maximum audit rows deleted in one statement. |
647
- | `RETENTION_MAX_BATCHES` | `10` | Maximum batches per tenant per scheduled sweep. |
648
- | `RETENTION_MIN_DAYS` | `1` | Minimum configured retention period. |
649
- | `RETENTION_MAX_DAYS` | `3650` | Maximum configured retention period. |
650
-
651
- Each tick enumerates tenants with records in `audit_events` (including tenants no longer listed
652
- by Tenant Service) and performs a separate bounded run for each. Every delete filters by that
653
- tenant and `retention_until < cutoff`, where cutoff is captured at the start of the sweep.
654
- Rows at exactly the cutoff and future rows are retained. No table-wide delete or `drop_chunks`
655
- is used. A `(tenant_id, retention_until, id)` index supports the bounded ordered selection.
656
- The per-tenant cap leaves remaining expired rows for the next sweep.
657
-
658
- A database-wide PostgreSQL transaction advisory lock excludes concurrent cleanup across all
659
- tenants and replicas. A lock loser skips rather than queues; a local running guard also prevents
660
- overlapping timer invocations. The lock is held on the same connection as deletion and released
661
- on commit, rollback or disconnect. No distributed guarantee is attributed to SDK `LimitToOne`.
662
- Shutdown cancels future ticks, stops between tenants, and awaits the active run before closing storage.
663
- The lock is a concurrency safeguard, not a once-per-schedule execution ledger. The separate
664
- single-replica scheduler prevents API replicas from independently starting scheduled sweeps.
665
- During the first rollout of this separation, disable retention on all old API replicas and
666
- wait for them to drain **before starting the job Deployment**. The existing `deploy-app` action
667
- promotes the API and then the `-job` Deployment. Keep that ordering for manual deployments too;
668
- updating only the API image leaves the retention image unchanged.
669
- The in-process schedule does not catch up a tick missed while the job is stopped or updating.
670
-
671
- Each executed tenant run, including a zero-deletion run, inserts `retention.run.succeeded` or
672
- `retention.run.failed` in that tenant's `audit-service` namespace. The system actor and writer are
673
- the service ID. The registered action uses the compliance class; metadata contains `deletedCount`,
674
- completed `batches`, `cutoff`, and a sanitized `error` on failure. Tenants without any audit records
675
- and ticks skipped for a busy lock do not create synthetic audit records.
676
-
677
- The job resolves its registered action and retention before deleting. Deletion batches use savepoints
678
- within one bounded tenant transaction. A failed batch rolls back to its savepoint, and earlier
679
- successful batches commit **with a failure audit containing their count**. If that audit cannot be
680
- inserted, or the process/connection dies before commit, the entire tenant transaction rolls back.
681
- Database/configuration failures that prevent a run from starting, or prevent a failure record from
682
- being committed, are reported through logs and `instrumentJob` telemetry; no durable failure event
683
- can be guaranteed while the database itself is unavailable.
684
-
685
- **Single-account MVP:** migrations, normal requests and retention reuse the existing `DB_USER` /
686
- `DB_PASSWORD`. That account needs SELECT, INSERT and DELETE on `audit_events`; migration ownership
687
- already supplies them. No new role or credential is created. Separate `audit_retention` credentials
688
- and the acceptance criterion preventing business-role UPDATE/DELETE are explicitly deferred;
689
- the service does not claim database-enforced append-only isolation in this mode.
690
-
691
- The existing `ON DELETE CASCADE` on `audit_failed_events.replayed_as` is intentionally preserved.
692
- Deleting an expired event also deletes any linked replayed failure rows; unreplayed failures are
693
- untouched. `deletedCount` counts audit events, not cascaded failure rows.
694
-
695
- For local integration verification only, set `AUDIT_RETENTION_TEST_DATABASE_URL` to a disposable
696
- PostgreSQL database on `localhost` or `127.0.0.1` named `audit_retention_test`, then run the audit-service
697
- tests. The suite refuses other hosts/database names and deletes its fixture rows. Never point it at Dev/UAT.
698
-
699
- ## Self-auditing
700
-
701
- Reading the audit trail is itself recorded. Each successful read writes one event to the
702
- `audit-service` namespace of the tenant that was queried. The namespace's action catalog is
703
- registered by the service at startup in core configuration, alongside `failed-event.replay`, and
704
- applies to every tenant. If registration has not propagated yet, reads still succeed but recording
705
- fails and is counted.
706
-
707
- | Action | Category | Recorded when |
708
- | -------------------- | ------------- | ----------------------------------- |
709
- | `events.list` | `data-access` | A namespace listing succeeds. |
710
- | `events.list-all` | `data-access` | A cross-namespace listing succeeds. |
711
- | `events.read` | `data-access` | A single event read succeeds. |
712
- | `failed-events.list` | `data-access` | A failed-events listing succeeds. |
713
-
714
- Reads use the `security` retention class (365 days by default). Replay is recorded
715
- transactionally by the replay itself (see above), not by this mechanism.
716
-
717
- The event's actor is the caller, `written_by` is the Audit Service's own client, and `metadata`
718
- holds the `endpoint`, the `filters` supplied and the `resultCount`. `correlationId` is taken from the
719
- `x-correlation-id` request header when present. A paged read records one event per request.
720
-
721
- Events go through the normal validation, enrichment and buffer. A failure to record is logged and
722
- counted and never fails the read. The count is exposed as `selfAuditFailures` in `GET /health`.
723
- Failed or unauthorized reads are not recorded.
346
+ Both REST lists and SDK `query()` return `{ results, page }`. Pass `page.next` as `after` for the
347
+ next page, keeping the same filters; URL-encode it for REST. Results are newest first.
348
+ The detail endpoint uses the returned record's **`id`**, not the caller's `eventId`.
349
+ Unlike `record()`, SDK query failures reject the promise.
350
+
351
+ REST filters include `actor`, `resourceType`, `resourceId`, `action`, `status`, `category`,
352
+ `severity`, `scope`, `correlationId`, `sessionId`, `occurredFrom` and `occurredTo`. Filters combine
353
+ with AND; time bounds are inclusive. Free-text search is not supported. The SDK's typed criteria
354
+ cover a subset; see [SDK types](https://github.com/GovAlta/adsp-monorepo/blob/main/libs/adsp-service-sdk/src/audit/types.ts).
355
+ SDK query options also accept another readable `namespace` or an authorized user `token`.
356
+
357
+ All paths below are relative to `/audit/v1`.
358
+
359
+ | Method and path | Role | Purpose |
360
+ | --- | --- | --- |
361
+ | `GET /{namespace}/actions` | `audit-reader` | Effective action definitions. |
362
+ | `GET /actions` | `audit-reader` | All effective application catalogs. |
363
+ | `GET /retention` | `audit-reader` | Configured retention settings, excluding implicit defaults. |
364
+ | `POST /{namespace}/events` | `audit-writer` | Submit a batch of events. |
365
+ | `GET /events` | `audit-reader` | History across the tenant's namespaces. |
366
+ | `GET /{namespace}/events` | `audit-reader` | History in one namespace. |
367
+ | `GET /{namespace}/events/{id}` | `audit-reader` | One stored record. |
368
+ | `GET /namespaces` | `audit-reader` | Namespaces with stored events. |
369
+ | `GET /events/export` | `audit-reader` | Stream matching events as CSV. |
370
+ | `GET /{namespace}/events/export` | `audit-reader` | Stream one namespace's events as CSV. |
371
+ | `GET /failed-events` | `audit-admin` | List failed events. |
372
+ | `POST /failed-events/{id}/replay` | `audit-admin` | Replay an open failed event; no body required. |
373
+
374
+ CSV exports use the same filters but ignore `top` and `after`; they are not capped to a page.
375
+ Actor name/email columns require `audit-admin` in addition to reader access. An interrupted
376
+ export may be incomplete. Removing an action definition does not delete or hide its stored history.
377
+
378
+ ## Retention and administration
379
+
380
+ Actions reference a retention class, not a number of days. Built-in defaults are **90 days**
381
+ for `standard` and **365 days** for `security` and `compliance`; confirm the appropriate policy
382
+ for your application.
383
+
384
+ Settings in `audit-service:retention-<application>` override resolved shared settings in
385
+ `audit-service:retention`, which override built-in defaults. Custom classes require a configured
386
+ period before use. `RETENTION_MIN_DAYS` and `RETENTION_MAX_DAYS` bound configured periods
387
+ (currently 1-3650 days, pending policy confirmation). Missing custom periods or resolved periods
388
+ outside the bounds fail writes with 503.
389
+
390
+ Expiry is calculated from `occurredAt`. Changes apply only to newly enriched events after
391
+ configuration refresh; existing stored expiry values are not recalculated.
392
+
393
+ The **Tenant Management App > Services > Audit** (`audit` feature flag) provides Overview, Logs,
394
+ Catalogs and Retention tabs. The Sandbox Audit page also supports controlled writes and failed-event
395
+ inspection. Successful history reads are themselves audited; a self-audit failure is logged and
396
+ counted but does not fail the read.
397
+
398
+ Failed-event replay validates the stored event against current configuration, while allowing
399
+ events older than seven days. It atomically saves the recovered record, replay status and replay
400
+ audit. Invalid data returns 400, an absent row 404, and a non-open row 409. Investigate before replaying.
401
+
402
+ ## Troubleshooting
403
+
404
+ | Result | What to check or do |
405
+ | --- | --- |
406
+ | 401 | Token expiry, issuer, environment and Audit audience. Obtain a fresh token after access changes. |
407
+ | 403 | Actual caller's role assignment, namespace ownership and target tenant. Provisioning alone does not grant access. |
408
+ | 400 / validation rejection | Correct the envelope, action version, timestamp, actor, resource or metadata. |
409
+ | Unknown action / catalog 404 | Check catalog publication, active revision, tenant/Core scope, cache visibility and configuration errors. |
410
+ | 413 | Reduce the payload or split the batch; enriched events must fit the service buffer too. |
411
+ | 429 | Respect `Retry-After`, reduce load and resend the same events with unchanged IDs. |
412
+ | 503 / timeout | Check configuration and storage dependencies. Use bounded retries and preserve IDs; delivery may be uncertain. |
413
+ | Rejection `storage_failed` | The event was parked in failed-event storage, not normal history. Use the authorized investigation/replay process. |
414
+ | SDK `failed` / `buffer_full` | Apply backpressure and durable recovery where required; do not silently discard events. |
415
+
416
+ Configuration fetch/conversion failures can be indistinguishable from missing configuration and
417
+ may cause partial catalogs or fallback settings. An empty role/schema listing from a development
418
+ tool is also not proof of missing registration; compare the tenant and Core configuration views.
419
+
420
+ ## Operational notes
421
+
422
+ - **Rate limits:** per tenant and namespace, counting events rather than requests. Defaults are
423
+ 500 events/second and a burst of 500; Core `audit-service:rate-limit` configuration can override
424
+ them within bounds (1-500 events/second, burst 500-1,000). Limits are per pod, not cluster-wide.
425
+ A 429 refuses the whole request; admitted events consume allowance even if later rejected.
426
+ - **Storage:** the service batches independently of the SDK (200 events or 200 ms), with a
427
+ per-pod buffer of 1,000 events / 8 MiB. A committed row is required for acceptance.
428
+ Neither buffer provides durable storage during a forced process exit.
429
+ - **Health:** `/health/live` checks process responsiveness; `/health/ready` checks database and
430
+ write availability and returns 503 during shutdown. History database queries allow 60 seconds;
431
+ the deployed Route allows 120 seconds. Client deadlines must also allow the intended duration.
432
+ - **Retention job:** a separate, single-replica `audit-service-job` runs daily at 02:00 UTC.
433
+ Keep retention disabled in API replicas; drain old API schedulers before starting the job.
434
+ Configure `RETENTION_SCHEDULE`, `RETENTION_BATCH_SIZE` and `RETENTION_MAX_BATCHES` on the job.
435
+ To suspend it, scale the job to zero or change its explicit `RETENTION_ENABLED` setting.
436
+ Cleanup uses stored expiry; missed schedules are not replayed.
437
+ - **Database permissions:** the current deployment shares a database account across migrations,
438
+ requests and retention. It does not provide database-enforced append-only isolation.
439
+ - **Monitoring:** configure `OTEL_EXPORTER_OTLP_ENDPOINT`. Check
440
+ `audit_failed_events_available = 1`, `audit_failed_events_open`, rate-limit metrics and SDK
441
+ dropped-event metrics. Missing metrics are not a successful zero result.
442
+
443
+ For implementation and deployment details, see the
444
+ [Audit Service source](https://github.com/GovAlta/adsp-monorepo/tree/main/apps/audit-service/src),
445
+ [deployment manifest](https://github.com/GovAlta/adsp-monorepo/blob/main/.openshift/managed/audit-service.yml)
446
+ and [environment settings](https://github.com/GovAlta/adsp-monorepo/blob/main/.openshift/configuration/audit-service.yml).