@astram/guard 0.35.2 → 0.37.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.
Files changed (36) hide show
  1. package/dist/authz/list-scope-sql.d.ts +21 -0
  2. package/dist/authz/list-scope-sql.d.ts.map +1 -1
  3. package/dist/authz/list-scope-sql.js +45 -2
  4. package/dist/authz/mariadb-list-scope-adapter.d.ts.map +1 -1
  5. package/dist/authz/mariadb-list-scope-adapter.js +10 -25
  6. package/dist/authz/mariadb-policy-store.d.ts +7 -4
  7. package/dist/authz/mariadb-policy-store.d.ts.map +1 -1
  8. package/dist/authz/mariadb-policy-store.js +51 -9
  9. package/dist/authz/mariadb-record-rule-adapter.d.ts +19 -1
  10. package/dist/authz/mariadb-record-rule-adapter.d.ts.map +1 -1
  11. package/dist/authz/mariadb-record-rule-adapter.js +65 -14
  12. package/dist/authz/rule-subject.d.ts +32 -0
  13. package/dist/authz/rule-subject.d.ts.map +1 -0
  14. package/dist/authz/rule-subject.js +71 -0
  15. package/dist/authz/viewer-departments.d.ts +14 -0
  16. package/dist/authz/viewer-departments.d.ts.map +1 -0
  17. package/dist/authz/viewer-departments.js +61 -0
  18. package/dist/authz/wire-record-authorization.d.ts.map +1 -1
  19. package/dist/authz/wire-record-authorization.js +25 -2
  20. package/dist/config/app-config.d.ts +16 -4
  21. package/dist/config/app-config.d.ts.map +1 -1
  22. package/dist/config/app-config.js +47 -5
  23. package/dist/index.d.ts +2 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +13 -4
  26. package/dist/storage/object-store-boot-check.d.ts +6 -3
  27. package/dist/storage/object-store-boot-check.d.ts.map +1 -1
  28. package/dist/storage/object-store-boot-check.js +37 -4
  29. package/dist/storage/object-store-probe-error.d.ts +42 -0
  30. package/dist/storage/object-store-probe-error.d.ts.map +1 -0
  31. package/dist/storage/object-store-probe-error.js +82 -0
  32. package/dist/storage/s3-object-store.d.ts +37 -2
  33. package/dist/storage/s3-object-store.d.ts.map +1 -1
  34. package/dist/storage/s3-object-store.js +189 -58
  35. package/migrations/1710000000141-AddRecordRuleSubjectRoles.cjs +95 -0
  36. package/package.json +5 -5
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ObjectStoreProbeError = void 0;
4
+ exports.safeErrorName = safeErrorName;
5
+ exports.safeHttpStatus = safeHttpStatus;
6
+ exports.probeFailure = probeFailure;
7
+ /**
8
+ * The storage boot probe's failure (object-storage-sse-c SPEC §5 D): which probe step failed,
9
+ * plus the provider's error NAME and HTTP status when they are safe to print, so an operator can
10
+ * read `failed at put (InvalidArgument 400)` without a separate probe.
11
+ *
12
+ * It extends core's `ObjectStoreUnavailableError` (same fixed message, same `name`, no `cause`), so
13
+ * every existing `instanceof ObjectStoreUnavailableError` check still matches. Only `e.name` and
14
+ * `e.$metadata.httpStatusCode` of an SDK error are ever read: never its message, `Code`, request
15
+ * id, response, endpoint or cause (Shield #10).
16
+ *
17
+ * Kept apart from `s3-object-store.ts` so `ObjectStoreBootCheck` can import it without loading the
18
+ * store module (whose SDK load is lazy by design).
19
+ */
20
+ const core_1 = require("@astram/core");
21
+ /** A provider error name we print: an identifier, nothing that could carry a URL, key or text. */
22
+ const SAFE_ERROR_NAME = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
23
+ class ObjectStoreProbeError extends core_1.ObjectStoreUnavailableError {
24
+ op;
25
+ constructor(failure) {
26
+ super();
27
+ this.op = failure.op;
28
+ // Own properties only when present, so a serialised error carries nothing undefined.
29
+ if (failure.errorName !== undefined)
30
+ this.errorName = failure.errorName;
31
+ if (failure.httpStatus !== undefined)
32
+ this.httpStatus = failure.httpStatus;
33
+ if (failure.keyMismatch === true)
34
+ this.keyMismatch = true;
35
+ }
36
+ }
37
+ exports.ObjectStoreProbeError = ObjectStoreProbeError;
38
+ /** The SDK error's name, when it is a plain identifier (else `undefined`). Never throws. */
39
+ function safeErrorName(e) {
40
+ try {
41
+ if (typeof e !== 'object' || e === null)
42
+ return undefined;
43
+ const name = e.name;
44
+ return typeof name === 'string' && SAFE_ERROR_NAME.test(name) ? name : undefined;
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ /** The SDK error's HTTP status, when it is an integer 100-599 (else `undefined`). Never throws. */
51
+ function safeHttpStatus(e) {
52
+ try {
53
+ if (typeof e !== 'object' || e === null)
54
+ return undefined;
55
+ const meta = e.$metadata;
56
+ if (typeof meta !== 'object' || meta === null)
57
+ return undefined;
58
+ const status = meta.httpStatusCode;
59
+ return typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599
60
+ ? status
61
+ : undefined;
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ }
67
+ /**
68
+ * The probe failure for step `op` caused by `e`. An `ObjectStoreProbeError` passes through
69
+ * unchanged (an inner step already named itself).
70
+ */
71
+ function probeFailure(op, e, opts = {}) {
72
+ if (e instanceof ObjectStoreProbeError)
73
+ return e;
74
+ const errorName = safeErrorName(e);
75
+ const httpStatus = safeHttpStatus(e);
76
+ return new ObjectStoreProbeError({
77
+ op,
78
+ ...(errorName !== undefined ? { errorName } : {}),
79
+ ...(httpStatus !== undefined ? { httpStatus } : {}),
80
+ ...(opts.keyMismatch === true ? { keyMismatch: true } : {}),
81
+ });
82
+ }
@@ -3,8 +3,9 @@ import type { ObjectStorageConfig } from '../config/app-config.js';
3
3
  /**
4
4
  * The connection fields `S3ObjectStore` needs (the {@link ObjectStorageConfig} result).
5
5
  * `maxBytes` caps what `get` will buffer (default and maximum: `FILE_MAX_BYTES_CEILING`).
6
+ * `sseCustomerKey` is required with `sse: 'SSE-C'` (exactly 32 bytes) and refused otherwise.
6
7
  */
7
- export type S3ObjectStoreConfig = Pick<ObjectStorageConfig, 'endpoint' | 'bucket' | 'region' | 'accessKeyId' | 'secretAccessKey' | 'sse'> & {
8
+ export type S3ObjectStoreConfig = Pick<ObjectStorageConfig, 'endpoint' | 'bucket' | 'region' | 'accessKeyId' | 'secretAccessKey' | 'sse' | 'sseCustomerKey'> & {
8
9
  readonly maxBytes?: number;
9
10
  };
10
11
  export interface S3ObjectStoreOptions {
@@ -18,7 +19,10 @@ export interface S3ObjectStoreOptions {
18
19
  */
19
20
  readonly noOverwrite?: 'if-none-match' | 'head-first' | 'none';
20
21
  }
22
+ /** The SSE-C key canary (SPEC §5 E, §10): outside `_probe/`, never deleted or overwritten. */
23
+ export declare const SSE_C_CANARY_KEY = "_shield/sse-c-canary";
21
24
  export declare class S3ObjectStore implements ObjectStore {
25
+ #private;
22
26
  private readonly config;
23
27
  private readonly bucket;
24
28
  private readonly sse;
@@ -28,17 +32,48 @@ export declare class S3ObjectStore implements ObjectStore {
28
32
  constructor(config: S3ObjectStoreConfig, options?: S3ObjectStoreOptions);
29
33
  /** The SDK and the client, built on first use. */
30
34
  private connect;
35
+ /**
36
+ * SSE-C fields for put/get/head. The key goes as padded standard base64 of its 32 bytes: the
37
+ * SDK's ssec middleware (`@aws-sdk/middleware-sdk-s3`) keeps a valid base64 32-byte key as is and
38
+ * derives `SSECustomerKeyMD5` from the decoded bytes.
39
+ */
40
+ private sseCustomer;
31
41
  put(key: string, bytes: Uint8Array, meta: ObjectPutMeta): Promise<void>;
42
+ /** One PutObject; rethrows the raw SDK error (callers map it). */
43
+ private sendPut;
32
44
  get(key: string): Promise<StoredObject>;
45
+ /**
46
+ * One GetObject under the size cap; rethrows the raw SDK error (callers map it), or a fixed
47
+ * `ObjectStoreUnavailableError` for a missing body or an unknown / over-cap length.
48
+ */
49
+ private fetchObject;
33
50
  head(key: string): Promise<StoredObjectHead | null>;
34
51
  delete(key: string): Promise<void>;
52
+ /**
53
+ * The boot probe (SPEC §5 B, E): head-bucket, put, get, verify, then (SSE-C) the key canary.
54
+ * Throws an {@link ObjectStoreProbeError} naming the failing step.
55
+ */
35
56
  ping(): Promise<void>;
36
57
  /**
37
58
  * A write-only boot check (ai-debug-trace SPEC §5 A, §8): `HeadBucket`, then one small probe
38
59
  * object under `_probe/` that is NOT read back or deleted (the trace credential is put-only;
39
- * the bucket's lifecycle rule expires the probe). Fixed error, no cause.
60
+ * the bucket's lifecycle rule expires the probe). Throws an {@link ObjectStoreProbeError}.
40
61
  */
41
62
  pingWriteOnly(): Promise<void>;
63
+ /**
64
+ * `HeadBucket` as the `head-bucket` probe step. An SDK load failure is NOT this step: it
65
+ * propagates as is, so the boot check prints its generic message rather than blaming the bucket.
66
+ */
67
+ private probeBucket;
68
+ /** The probe put under this store's overwrite mode, as the `put` probe step. */
69
+ private probePut;
70
+ /**
71
+ * The SSE-C key canary (SPEC §5 E): read `_shield/sse-c-canary` with the configured key. Missing ⇒
72
+ * create it (always `If-None-Match: *`; a 412 means another worker won, so read again). A 400 or
73
+ * 403, or other bytes ⇒ the key does not open it (`keyMismatch`). Never deleted or overwritten.
74
+ */
75
+ private checkKeyCanary;
76
+ private readCanary;
42
77
  /**
43
78
  * Whether the bucket has a lifecycle (expiry) rule: `'rules'`, `'none'` (the backend says no
44
79
  * configuration exists) or `'unknown'` (not readable with this credential, or an error). Never
@@ -1 +1 @@
1
- {"version":3,"file":"s3-object-store.d.ts","sourceRoot":"","sources":["../../src/storage/s3-object-store.ts"],"names":[],"mappings":"AAoBA,OAAO,EAIL,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACtB,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAiBnE;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,IAAI,CACpC,mBAAmB,EACnB,UAAU,GAAG,QAAQ,GAAG,QAAQ,GAAG,aAAa,GAAG,iBAAiB,GAAG,KAAK,CAC7E,GAAG;IAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnC,MAAM,WAAW,oBAAoB;IACnC;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,CAAC,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I,OAAO,CAAC,IAAI,CAAC;IAoB3B;;;;OAIG;IACG,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAMpC;;;OAGG;YACW,WAAW;IASzB,gFAAgF;YAClE,QAAQ;IAgBtB;;;;OAIG;YACW,cAAc;YAkBd,UAAU;IAcxB;;;;OAIG;IACG,SAAS,IAAI,OAAO,CAAC,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;CAezD"}
@@ -33,27 +33,35 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.S3ObjectStore = void 0;
36
+ exports.S3ObjectStore = exports.SSE_C_CANARY_KEY = void 0;
37
37
  /**
38
38
  * `ObjectStore` over the S3 API (FILE_STORAGE SPEC §5 E) for MinIO and S3-compatible hosts.
39
39
  *
40
40
  * - Path-style addressing (`forcePathStyle`), region and credentials from {@link ObjectStorageConfig}.
41
- * - `put`: SSE-S3 (`ServerSideEncryption: 'AES256'`) on every write, no overwrite
42
- * (`IfNoneMatch: '*'`), content type, and the sha256 both as `ChecksumSHA256` (the server
43
- * verifies the bytes) and as `x-amz-meta-sha256`.
44
- * - `get`/`head`/`delete`: a missing key maps to `ObjectNotFoundError` / `null` / no-op. `get`
45
- * refuses an object whose `ContentLength` is missing or above the configured cap (at most the
46
- * 50 MiB `FILE_MAX_BYTES_CEILING`) before reading any body byte.
41
+ * - Server-side encryption (object-storage-sse-c SPEC §5 B): `sse: 'AES256'` sends SSE-S3
42
+ * (`ServerSideEncryption: 'AES256'`) on every put. `sse: 'SSE-C'` sends the customer-provided
43
+ * 256-bit key (`SSECustomerAlgorithm: 'AES256'` + `SSECustomerKey`; the SDK adds the key MD5) on
44
+ * every put, get and head, and no `ServerSideEncryption`. The key is held in a private field,
45
+ * copied from the caller, never logged and never in an error. SSE-C needs an `https:` endpoint.
46
+ * - `put`: no overwrite (`IfNoneMatch: '*'`), content type, and the sha256 both as
47
+ * `ChecksumSHA256` (the server verifies the bytes) and as `x-amz-meta-sha256`, in both modes.
48
+ * - `get`/`head`/`delete`: a missing key maps to `ObjectNotFoundError` / `null` / no-op. Only a 404
49
+ * (`NoSuchKey` / `NotFound`) is "missing": a 400 or 403 (a wrong or missing SSE-C key) is
50
+ * `ObjectStoreUnavailableError`, fail closed (SPEC §5 C2). `get` refuses an object whose
51
+ * `ContentLength` is missing or above the configured cap (at most the 50 MiB
52
+ * `FILE_MAX_BYTES_CEILING`) before reading any body byte.
47
53
  * - Every other SDK failure becomes `ObjectStoreUnavailableError` with its fixed message and NO
48
54
  * `cause`: SDK errors can carry the endpoint, request id or credentials (Shield #10).
49
- * - `ping`: `HeadBucket`, then put/get/delete of one probe object under `_probe/`, so a missing
50
- * write permission or a refused SSE header fails the boot check.
55
+ * - `ping`: `HeadBucket`, then put/get/verify/delete of one probe object under `_probe/`, then (SSE-C
56
+ * only) the key canary `_shield/sse-c-canary` (SPEC §5 E). Each failing step throws an
57
+ * `ObjectStoreProbeError` naming the step and the sanitised provider error name and status.
51
58
  *
52
59
  * `@aws-sdk/client-s3` is imported here as TYPES only. The runtime module is loaded on the first
53
60
  * operation (one cached load per process), so `require('@astram/guard')` never loads the SDK.
54
61
  */
55
62
  const node_crypto_1 = require("node:crypto");
56
63
  const core_1 = require("@astram/core");
64
+ const object_store_probe_error_js_1 = require("./object-store-probe-error.js");
57
65
  let sdkLoad;
58
66
  /** Load `@aws-sdk/client-s3` once, on first use (a failed load is retried next time). */
59
67
  function loadSdk() {
@@ -65,13 +73,21 @@ function loadSdk() {
65
73
  }
66
74
  return sdkLoad;
67
75
  }
76
+ /** SSE-C key length: AES-256 (SPEC §10). */
77
+ const SSE_C_KEY_BYTES = 32;
68
78
  const SHA256_HEX = /^[0-9a-f]{64}$/;
69
79
  const PROBE_BYTES = new TextEncoder().encode('shield object store probe');
70
80
  const PROBE_CONTENT_TYPE = 'application/octet-stream';
81
+ /** The SSE-C key canary (SPEC §5 E, §10): outside `_probe/`, never deleted or overwritten. */
82
+ exports.SSE_C_CANARY_KEY = '_shield/sse-c-canary';
83
+ const CANARY_BYTES = new TextEncoder().encode('shield sse-c canary v1');
84
+ const CANARY_SHA256 = (0, node_crypto_1.createHash)('sha256').update(CANARY_BYTES).digest('hex');
71
85
  class S3ObjectStore {
72
86
  config;
73
87
  bucket;
74
88
  sse;
89
+ /** The SSE-C key (a private copy; unreachable by inspection or enumeration). */
90
+ #sseCustomerKey;
75
91
  noOverwrite;
76
92
  maxGetBytes;
77
93
  connection;
@@ -80,7 +96,29 @@ class S3ObjectStore {
80
96
  if (!Number.isInteger(maxBytes) || maxBytes <= 0 || maxBytes > core_1.FILE_MAX_BYTES_CEILING) {
81
97
  throw new Error(`S3ObjectStore: maxBytes must be a positive integer of at most ${core_1.FILE_MAX_BYTES_CEILING}`);
82
98
  }
83
- this.config = config;
99
+ const key = config.sseCustomerKey;
100
+ if (config.sse === 'SSE-C') {
101
+ if (!(key instanceof Uint8Array) || key.length !== SSE_C_KEY_BYTES) {
102
+ throw new Error('S3ObjectStore: sse SSE-C needs a 32-byte sseCustomerKey');
103
+ }
104
+ if (!isHttpsUrl(config.endpoint)) {
105
+ throw new Error('S3ObjectStore: sse SSE-C needs an https: endpoint');
106
+ }
107
+ this.#sseCustomerKey = new Uint8Array(key);
108
+ }
109
+ else if (config.sse === 'AES256') {
110
+ if (key !== undefined) {
111
+ throw new Error("S3ObjectStore: sseCustomerKey is only valid with sse 'SSE-C'");
112
+ }
113
+ this.#sseCustomerKey = undefined;
114
+ }
115
+ else {
116
+ throw new Error("S3ObjectStore: sse must be 'AES256' or 'SSE-C'");
117
+ }
118
+ // The stored config never holds the key (only the private field does).
119
+ const { sseCustomerKey: _omit, ...rest } = config;
120
+ void _omit;
121
+ this.config = rest;
84
122
  this.bucket = config.bucket;
85
123
  this.sse = config.sse;
86
124
  this.noOverwrite = options.noOverwrite ?? 'if-none-match';
@@ -105,12 +143,33 @@ class S3ObjectStore {
105
143
  }
106
144
  return this.connection;
107
145
  }
146
+ /**
147
+ * SSE-C fields for put/get/head. The key goes as padded standard base64 of its 32 bytes: the
148
+ * SDK's ssec middleware (`@aws-sdk/middleware-sdk-s3`) keeps a valid base64 32-byte key as is and
149
+ * derives `SSECustomerKeyMD5` from the decoded bytes.
150
+ */
151
+ sseCustomer() {
152
+ const key = this.#sseCustomerKey;
153
+ if (key === undefined)
154
+ return {};
155
+ return { SSECustomerAlgorithm: 'AES256', SSECustomerKey: Buffer.from(key).toString('base64') };
156
+ }
108
157
  async put(key, bytes, meta) {
109
158
  if (!SHA256_HEX.test(meta.sha256))
110
159
  throw new core_1.ObjectStoreUnavailableError();
111
160
  if (this.noOverwrite === 'head-first' && (await this.head(key)) !== null) {
112
161
  throw new core_1.ObjectStoreUnavailableError();
113
162
  }
163
+ try {
164
+ await this.sendPut(key, bytes, meta, this.noOverwrite === 'if-none-match');
165
+ }
166
+ catch {
167
+ // A 412 (key exists) is a refusal too: never overwrite. Fixed message, no cause.
168
+ throw new core_1.ObjectStoreUnavailableError();
169
+ }
170
+ }
171
+ /** One PutObject; rethrows the raw SDK error (callers map it). */
172
+ async sendPut(key, bytes, meta, ifNoneMatch) {
114
173
  const { sdk, client } = await this.connect();
115
174
  const input = {
116
175
  Bucket: this.bucket,
@@ -118,53 +177,52 @@ class S3ObjectStore {
118
177
  Body: bytes,
119
178
  ContentType: meta.contentType,
120
179
  ContentLength: bytes.length,
121
- ServerSideEncryption: this.sse,
180
+ ...(this.sse === 'AES256' ? { ServerSideEncryption: 'AES256' } : {}),
181
+ ...this.sseCustomer(),
122
182
  ChecksumSHA256: Buffer.from(meta.sha256, 'hex').toString('base64'),
123
183
  Metadata: { sha256: meta.sha256 },
124
- ...(this.noOverwrite === 'if-none-match' ? { IfNoneMatch: '*' } : {}),
184
+ ...(ifNoneMatch ? { IfNoneMatch: '*' } : {}),
125
185
  };
126
- try {
127
- await client.send(new sdk.PutObjectCommand(input));
128
- }
129
- catch {
130
- // A 412 (key exists) is a refusal too: never overwrite. Fixed message, no cause.
131
- throw new core_1.ObjectStoreUnavailableError();
132
- }
186
+ await client.send(new sdk.PutObjectCommand(input));
133
187
  }
134
188
  async get(key) {
135
- const { sdk, client } = await this.connect();
136
- let bytes;
137
- let contentType;
138
189
  try {
139
- const out = await client.send(new sdk.GetObjectCommand({ Bucket: this.bucket, Key: key }));
140
- if (!out.Body)
141
- throw new core_1.ObjectStoreUnavailableError();
142
- const length = out.ContentLength;
143
- if (typeof length !== 'number' || length < 0 || length > this.maxGetBytes) {
144
- // Unknown or over the cap: refuse before buffering, and release the socket.
145
- discardBody(out.Body);
146
- throw new core_1.ObjectStoreUnavailableError();
147
- }
148
- bytes = await out.Body.transformToByteArray();
149
- if (bytes.length > this.maxGetBytes)
150
- throw new core_1.ObjectStoreUnavailableError();
151
- contentType = out.ContentType;
190
+ return await this.fetchObject(key);
152
191
  }
153
192
  catch (e) {
154
193
  if (isNotFound(e))
155
194
  throw new core_1.ObjectNotFoundError();
156
195
  throw new core_1.ObjectStoreUnavailableError();
157
196
  }
197
+ }
198
+ /**
199
+ * One GetObject under the size cap; rethrows the raw SDK error (callers map it), or a fixed
200
+ * `ObjectStoreUnavailableError` for a missing body or an unknown / over-cap length.
201
+ */
202
+ async fetchObject(key) {
203
+ const { sdk, client } = await this.connect();
204
+ const out = await client.send(new sdk.GetObjectCommand({ Bucket: this.bucket, Key: key, ...this.sseCustomer() }));
205
+ if (!out.Body)
206
+ throw new core_1.ObjectStoreUnavailableError();
207
+ const length = out.ContentLength;
208
+ if (typeof length !== 'number' || length < 0 || length > this.maxGetBytes) {
209
+ // Unknown or over the cap: refuse before buffering, and release the socket.
210
+ discardBody(out.Body);
211
+ throw new core_1.ObjectStoreUnavailableError();
212
+ }
213
+ const bytes = await out.Body.transformToByteArray();
214
+ if (bytes.length > this.maxGetBytes)
215
+ throw new core_1.ObjectStoreUnavailableError();
158
216
  return {
159
217
  bytes,
160
- contentType: contentType ?? PROBE_CONTENT_TYPE,
218
+ contentType: out.ContentType ?? PROBE_CONTENT_TYPE,
161
219
  sizeBytes: bytes.length,
162
220
  };
163
221
  }
164
222
  async head(key) {
165
223
  const { sdk, client } = await this.connect();
166
224
  try {
167
- const out = await client.send(new sdk.HeadObjectCommand({ Bucket: this.bucket, Key: key }));
225
+ const out = await client.send(new sdk.HeadObjectCommand({ Bucket: this.bucket, Key: key, ...this.sseCustomer() }));
168
226
  return {
169
227
  sizeBytes: out.ContentLength ?? 0,
170
228
  contentType: out.ContentType ?? PROBE_CONTENT_TYPE,
@@ -187,47 +245,102 @@ class S3ObjectStore {
187
245
  throw new core_1.ObjectStoreUnavailableError();
188
246
  }
189
247
  }
248
+ /**
249
+ * The boot probe (SPEC §5 B, E): head-bucket, put, get, verify, then (SSE-C) the key canary.
250
+ * Throws an {@link ObjectStoreProbeError} naming the failing step.
251
+ */
190
252
  async ping() {
191
- const { sdk, client } = await this.connect();
192
- try {
193
- await client.send(new sdk.HeadBucketCommand({ Bucket: this.bucket }));
194
- }
195
- catch {
196
- throw new core_1.ObjectStoreUnavailableError();
197
- }
253
+ await this.probeBucket();
198
254
  const key = `_probe/${(0, node_crypto_1.randomUUID)()}`;
199
255
  const sha256 = (0, node_crypto_1.createHash)('sha256').update(PROBE_BYTES).digest('hex');
200
- await this.put(key, PROBE_BYTES, { contentType: PROBE_CONTENT_TYPE, sha256 });
256
+ // A refused put leaves nothing to delete (as before this change: same requests on AES256).
257
+ await this.probePut(key, PROBE_BYTES, sha256);
201
258
  try {
202
- const got = await this.get(key);
259
+ let got;
260
+ try {
261
+ got = await this.fetchObject(key);
262
+ }
263
+ catch (e) {
264
+ throw (0, object_store_probe_error_js_1.probeFailure)('get', e);
265
+ }
203
266
  if (!sameBytes(got.bytes, PROBE_BYTES))
204
- throw new core_1.ObjectStoreUnavailableError();
205
- }
206
- catch {
207
- throw new core_1.ObjectStoreUnavailableError();
267
+ throw new object_store_probe_error_js_1.ObjectStoreProbeError({ op: 'verify' });
208
268
  }
209
269
  finally {
210
270
  await this.delete(key).catch(() => undefined);
211
271
  }
272
+ if (this.sse === 'SSE-C')
273
+ await this.checkKeyCanary();
212
274
  }
213
275
  /**
214
276
  * A write-only boot check (ai-debug-trace SPEC §5 A, §8): `HeadBucket`, then one small probe
215
277
  * object under `_probe/` that is NOT read back or deleted (the trace credential is put-only;
216
- * the bucket's lifecycle rule expires the probe). Fixed error, no cause.
278
+ * the bucket's lifecycle rule expires the probe). Throws an {@link ObjectStoreProbeError}.
217
279
  */
218
280
  async pingWriteOnly() {
281
+ await this.probeBucket();
282
+ const sha256 = (0, node_crypto_1.createHash)('sha256').update(PROBE_BYTES).digest('hex');
283
+ await this.probePut(`_probe/${(0, node_crypto_1.randomUUID)()}`, PROBE_BYTES, sha256);
284
+ }
285
+ /**
286
+ * `HeadBucket` as the `head-bucket` probe step. An SDK load failure is NOT this step: it
287
+ * propagates as is, so the boot check prints its generic message rather than blaming the bucket.
288
+ */
289
+ async probeBucket() {
219
290
  const { sdk, client } = await this.connect();
220
291
  try {
221
292
  await client.send(new sdk.HeadBucketCommand({ Bucket: this.bucket }));
222
293
  }
223
- catch {
224
- throw new core_1.ObjectStoreUnavailableError();
294
+ catch (e) {
295
+ throw (0, object_store_probe_error_js_1.probeFailure)('head-bucket', e);
296
+ }
297
+ }
298
+ /** The probe put under this store's overwrite mode, as the `put` probe step. */
299
+ async probePut(key, bytes, sha256) {
300
+ try {
301
+ if (this.noOverwrite === 'head-first' && (await this.head(key)) !== null) {
302
+ throw new core_1.ObjectStoreUnavailableError();
303
+ }
304
+ await this.sendPut(key, bytes, { contentType: PROBE_CONTENT_TYPE, sha256 }, this.noOverwrite === 'if-none-match');
305
+ }
306
+ catch (e) {
307
+ throw (0, object_store_probe_error_js_1.probeFailure)('put', e);
225
308
  }
226
- const sha256 = (0, node_crypto_1.createHash)('sha256').update(PROBE_BYTES).digest('hex');
227
- await this.put(`_probe/${(0, node_crypto_1.randomUUID)()}`, PROBE_BYTES, {
228
- contentType: PROBE_CONTENT_TYPE,
229
- sha256,
230
- });
309
+ }
310
+ /**
311
+ * The SSE-C key canary (SPEC §5 E): read `_shield/sse-c-canary` with the configured key. Missing ⇒
312
+ * create it (always `If-None-Match: *`; a 412 means another worker won, so read again). A 400 or
313
+ * 403, or other bytes ⇒ the key does not open it (`keyMismatch`). Never deleted or overwritten.
314
+ */
315
+ async checkKeyCanary() {
316
+ if ((await this.readCanary()) === 'match')
317
+ return;
318
+ try {
319
+ await this.sendPut(exports.SSE_C_CANARY_KEY, CANARY_BYTES, { contentType: PROBE_CONTENT_TYPE, sha256: CANARY_SHA256 }, true);
320
+ }
321
+ catch (e) {
322
+ if (!isPreconditionFailed(e))
323
+ throw (0, object_store_probe_error_js_1.probeFailure)('canary', e);
324
+ }
325
+ if ((await this.readCanary()) !== 'match') {
326
+ // Created (or raced) yet still not readable: fail closed.
327
+ throw new object_store_probe_error_js_1.ObjectStoreProbeError({ op: 'canary' });
328
+ }
329
+ }
330
+ async readCanary() {
331
+ let got;
332
+ try {
333
+ got = await this.fetchObject(exports.SSE_C_CANARY_KEY);
334
+ }
335
+ catch (e) {
336
+ if (isNotFound(e))
337
+ return 'missing';
338
+ throw (0, object_store_probe_error_js_1.probeFailure)('canary', e, { keyMismatch: isKeyRefusal(e) });
339
+ }
340
+ if (!sameBytes(got.bytes, CANARY_BYTES)) {
341
+ throw new object_store_probe_error_js_1.ObjectStoreProbeError({ op: 'canary', keyMismatch: true });
342
+ }
343
+ return 'match';
231
344
  }
232
345
  /**
233
346
  * Whether the bucket has a lifecycle (expiry) rule: `'rules'`, `'none'` (the backend says no
@@ -250,6 +363,14 @@ class S3ObjectStore {
250
363
  }
251
364
  }
252
365
  exports.S3ObjectStore = S3ObjectStore;
366
+ function isHttpsUrl(raw) {
367
+ try {
368
+ return new URL(raw).protocol === 'https:';
369
+ }
370
+ catch {
371
+ return false;
372
+ }
373
+ }
253
374
  /** Best-effort release of an unread response body (a Node stream in the SDK's Node runtime). */
254
375
  function discardBody(body) {
255
376
  const destroy = body.destroy;
@@ -271,6 +392,16 @@ function isNotFound(e) {
271
392
  return true;
272
393
  return err.$metadata?.httpStatusCode === 404 && err.name !== 'NoSuchBucket';
273
394
  }
395
+ /** A key refusal on an SSE-C object: 400 (Hetzner `InvalidArgument`, MinIO no key) or 403. */
396
+ function isKeyRefusal(e) {
397
+ const status = (0, object_store_probe_error_js_1.safeHttpStatus)(e);
398
+ return status === 400 || status === 403;
399
+ }
400
+ /** A conditional PUT refused because the object exists. */
401
+ function isPreconditionFailed(e) {
402
+ return ((0, object_store_probe_error_js_1.safeHttpStatus)(e) === 412 ||
403
+ (typeof e === 'object' && e !== null && e.name === 'PreconditionFailed'));
404
+ }
274
405
  function sameBytes(a, b) {
275
406
  return a.length === b.length && Buffer.from(a).equals(Buffer.from(b));
276
407
  }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Framework authz migration — policy subject role sets on `<authz>.record_permission_rule`
3
+ * (department-scoped policies; spec `docs/features/department-scoped-policies/SPEC.md` v2 §4; id 141
4
+ * per `docs/migrations/RESERVATIONS.md`).
5
+ *
6
+ * Adds `rpr_subject_role_uuids JSON NULL` after `rpr_subject_value`: a JSON array of 1–16 distinct
7
+ * role uuids when `rpr_subject_kind` is `roles` or `except_roles`, NULL otherwise. Every row of one
8
+ * policy (`rpr_policy_uuid` group) carries the same kind and array. `rpr_subject_kind VARCHAR(16)`
9
+ * already fits the new kinds; no other DDL. No data change: existing rows keep NULL (their kinds
10
+ * `everyone` / legacy `role` do not read the column). No ids hard-coded.
11
+ *
12
+ * Idempotent: the column is added only when `information_schema.COLUMNS` shows it absent; a re-run
13
+ * issues no DDL.
14
+ *
15
+ * `down` refuses (throws a fixed message, changes nothing) while any row has kind `roles` or
16
+ * `except_roles`: without the column those rows would never match, so an `except_roles` deny would
17
+ * silently stop applying. Otherwise it drops the column, only when present. It never deletes rules.
18
+ *
19
+ * Database name from `ctx.schemas` (`frameworkSchemasForMigration(...).authz`), so the four-database,
20
+ * namespace and single layouts all work. Sorts after `...009` (creates `record_permission_rule`) and
21
+ * above every published id (132).
22
+ */
23
+
24
+ const { frameworkSchemasForMigration } = require('@astram/core');
25
+
26
+ const MIGRATION = '1710000000141-AddRecordRuleSubjectRoles';
27
+ const TABLE = 'record_permission_rule';
28
+ const COLUMN = 'rpr_subject_role_uuids';
29
+
30
+ const DOWN_REFUSED =
31
+ `${MIGRATION}: refusing to roll back: record_permission_rule holds policies with a role subject ` +
32
+ "(rpr_subject_kind 'roles' or 'except_roles'). Delete or re-author them first; nothing was changed.";
33
+
34
+ async function exists(query, sql, params) {
35
+ const rows = await query(sql, params);
36
+ return Array.isArray(rows) && rows.length > 0;
37
+ }
38
+
39
+ const tableExists = (query, schema) =>
40
+ exists(
41
+ query,
42
+ `SELECT 1 AS n FROM information_schema.TABLES
43
+ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? LIMIT 1`,
44
+ [schema, TABLE],
45
+ );
46
+
47
+ const columnExists = (query, schema) =>
48
+ exists(
49
+ query,
50
+ `SELECT 1 AS n FROM information_schema.COLUMNS
51
+ WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1`,
52
+ [schema, TABLE, COLUMN],
53
+ );
54
+
55
+ const tbl = (schema) => `\`${schema}\`.\`${TABLE}\``;
56
+
57
+ async function up(ctx) {
58
+ const { query } = ctx;
59
+ const AUTHZ = frameworkSchemasForMigration(ctx, process.env).authz;
60
+
61
+ if (!(await tableExists(query, AUTHZ))) {
62
+ throw new Error(
63
+ `${MIGRATION}: ${AUTHZ}.${TABLE} does not exist; run 1710000000009-CreateRecordPermissionRule first.`,
64
+ );
65
+ }
66
+
67
+ if (!(await columnExists(query, AUTHZ))) {
68
+ await query(
69
+ `ALTER TABLE ${tbl(AUTHZ)} ADD COLUMN IF NOT EXISTS ${COLUMN} JSON NULL AFTER rpr_subject_value`,
70
+ );
71
+ }
72
+ }
73
+
74
+ async function down(ctx) {
75
+ const { query } = ctx;
76
+ const AUTHZ = frameworkSchemasForMigration(ctx, process.env).authz;
77
+
78
+ if (!(await tableExists(query, AUTHZ))) return;
79
+ if (!(await columnExists(query, AUTHZ))) return;
80
+
81
+ // Refuse before any change while a role-subject policy exists (never drop a live deny).
82
+ if (
83
+ await exists(
84
+ query,
85
+ `SELECT 1 AS n FROM ${tbl(AUTHZ)} WHERE rpr_subject_kind IN (?, ?) LIMIT 1`,
86
+ ['roles', 'except_roles'],
87
+ )
88
+ ) {
89
+ throw new Error(DOWN_REFUSED);
90
+ }
91
+
92
+ await query(`ALTER TABLE ${tbl(AUTHZ)} DROP COLUMN IF EXISTS ${COLUMN}`);
93
+ }
94
+
95
+ module.exports = { up, down };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astram/guard",
3
- "version": "0.35.2",
3
+ "version": "0.37.0",
4
4
  "license": "MIT",
5
5
  "description": "Astram framework — the enforcement guard + real-world adapters (the 'hands'). One global deny-by-default gate every request passes through (ADR-0002), classification decorators, boot-pool assertion (ADR-0018), the forRoot() registration seam, and the DB/Redis/crypto adapters that connect the sealed core to a real backend. Depends on @astram/core (ADR-0003, ADR-0023).",
6
6
  "type": "commonjs",
@@ -36,8 +36,8 @@
36
36
  "argon2": "^0.41.1",
37
37
  "ioredis": "^5.4.1",
38
38
  "mariadb": "^3.5.4",
39
- "@astram/core": "1.20.0",
40
- "@astram/engine": "0.22.0"
39
+ "@astram/engine": "0.22.1",
40
+ "@astram/core": "1.21.0"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@nestjs/common": "^11",
@@ -45,7 +45,7 @@
45
45
  "@nestjs/platform-express": "^11",
46
46
  "reflect-metadata": "^0.2",
47
47
  "rxjs": "^7",
48
- "@astram/messaging": "^0.1.26"
48
+ "@astram/messaging": "^0.1.28"
49
49
  },
50
50
  "peerDependenciesMeta": {
51
51
  "@astram/messaging": {
@@ -68,7 +68,7 @@
68
68
  "typescript": "^5.7.0",
69
69
  "unplugin-swc": "^1.5.1",
70
70
  "vitest": "^2.1.8",
71
- "@astram/messaging": "0.1.26"
71
+ "@astram/messaging": "0.1.28"
72
72
  },
73
73
  "repository": {
74
74
  "type": "git",