@astram/guard 0.37.0 → 0.40.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 (69) hide show
  1. package/dist/agent/agent-provenance.d.ts +24 -0
  2. package/dist/agent/agent-provenance.d.ts.map +1 -1
  3. package/dist/agent/agent-provenance.js +33 -1
  4. package/dist/auth/auth.controller.d.ts.map +1 -1
  5. package/dist/auth/auth.controller.js +5 -1
  6. package/dist/auth/auth.module.d.ts.map +1 -1
  7. package/dist/auth/auth.module.js +40 -2
  8. package/dist/auth/dto.d.ts +2 -0
  9. package/dist/auth/dto.d.ts.map +1 -1
  10. package/dist/auth/tokens.d.ts +14 -0
  11. package/dist/auth/tokens.d.ts.map +1 -1
  12. package/dist/auth/tokens.js +16 -2
  13. package/dist/authentication/service-account-principal.d.ts +29 -0
  14. package/dist/authentication/service-account-principal.d.ts.map +1 -0
  15. package/dist/authentication/service-account-principal.js +55 -0
  16. package/dist/authz/mariadb-policy-store.d.ts +38 -3
  17. package/dist/authz/mariadb-policy-store.d.ts.map +1 -1
  18. package/dist/authz/mariadb-policy-store.js +61 -4
  19. package/dist/completeness/catalog-reconciler.d.ts +10 -1
  20. package/dist/completeness/catalog-reconciler.d.ts.map +1 -1
  21. package/dist/completeness/catalog-reconciler.js +23 -4
  22. package/dist/completeness/ports/catalog-store.d.ts +19 -2
  23. package/dist/completeness/ports/catalog-store.d.ts.map +1 -1
  24. package/dist/enforcement/facts-version.d.ts +22 -0
  25. package/dist/enforcement/facts-version.d.ts.map +1 -0
  26. package/dist/enforcement/facts-version.js +34 -0
  27. package/dist/enforcement/global-enforcement.guard.d.ts +9 -26
  28. package/dist/enforcement/global-enforcement.guard.d.ts.map +1 -1
  29. package/dist/enforcement/global-enforcement.guard.js +48 -177
  30. package/dist/enforcement/session-facts-reload.d.ts +66 -0
  31. package/dist/enforcement/session-facts-reload.d.ts.map +1 -0
  32. package/dist/enforcement/session-facts-reload.js +168 -0
  33. package/dist/identity/auth-facts.controller.d.ts.map +1 -1
  34. package/dist/identity/auth-facts.controller.js +5 -1
  35. package/dist/identity/identity-actions.d.ts +9 -1
  36. package/dist/identity/identity-actions.d.ts.map +1 -1
  37. package/dist/identity/identity-actions.js +12 -1
  38. package/dist/identity/module-registry.bridge.d.ts +16 -0
  39. package/dist/identity/module-registry.bridge.d.ts.map +1 -1
  40. package/dist/identity/module-registry.bridge.js +45 -0
  41. package/dist/identity/permission-facts.adapter.d.ts +41 -1
  42. package/dist/identity/permission-facts.adapter.d.ts.map +1 -1
  43. package/dist/identity/permission-facts.adapter.js +98 -1
  44. package/dist/index.d.ts +6 -5
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +12 -6
  47. package/dist/internal.d.ts +23 -0
  48. package/dist/internal.d.ts.map +1 -1
  49. package/dist/internal.js +36 -1
  50. package/dist/module/shield-tokens.d.ts +87 -11
  51. package/dist/module/shield-tokens.d.ts.map +1 -1
  52. package/dist/module/shield-tokens.js +8 -1
  53. package/dist/notifications/notification.service.d.ts +3 -0
  54. package/dist/notifications/notification.service.d.ts.map +1 -1
  55. package/dist/notifications/notification.service.js +9 -0
  56. package/dist/request-auth/request-principal.d.ts +5 -0
  57. package/dist/request-auth/request-principal.d.ts.map +1 -1
  58. package/dist/request-auth/request-principal.js +7 -1
  59. package/dist/request-auth/session-token-binder.d.ts +79 -6
  60. package/dist/request-auth/session-token-binder.d.ts.map +1 -1
  61. package/dist/request-auth/session-token-binder.js +264 -173
  62. package/dist/session/call-principals.d.ts +54 -0
  63. package/dist/session/call-principals.d.ts.map +1 -0
  64. package/dist/session/call-principals.js +38 -0
  65. package/dist/session/session-principal.d.ts +86 -0
  66. package/dist/session/session-principal.d.ts.map +1 -0
  67. package/dist/session/session-principal.js +139 -0
  68. package/migrations/1710000000143-AddPermissionGroup.cjs +41 -0
  69. package/package.json +5 -5
@@ -41,9 +41,14 @@ class CatalogReconciler {
41
41
  * a reactivation stamps `lastActivatedAt` only. First-seen fields are never sent anywhere
42
42
  * but the insert (spec §11, §13). A registered row whose text differs from `opts.text` is
43
43
  * rewritten through ONE `store.updateText` call (skipped when the store lacks it).
44
+ *
45
+ * Permission groups (SPEC §5): with `opts.groups`, an insert writes the key's group and a
46
+ * registered row whose stored group differs is queued in the same `updateText` call (listed in
47
+ * `relabelled`); without it, groups are never touched.
44
48
  */
45
49
  async reconcile(registry, store, nowIso, opts) {
46
50
  const text = opts?.text;
51
+ const groups = opts?.groups;
47
52
  const release = opts?.release ?? null;
48
53
  const stored = await store.listPermissions();
49
54
  const storedByKey = new Map(stored.map((r) => [r.permissionKey, r]));
@@ -70,6 +75,7 @@ class CatalogReconciler {
70
75
  firstSeenAt: nowIso,
71
76
  firstSeenVersion: release,
72
77
  lastActivatedAt: nowIso,
78
+ ...(groups !== undefined ? { group: groups.get(key) ?? null } : {}),
73
79
  });
74
80
  if (inserted)
75
81
  added.push(key);
@@ -78,12 +84,18 @@ class CatalogReconciler {
78
84
  if (existing.status === 'orphaned')
79
85
  reactivated.push(key);
80
86
  const t = text?.get(key);
81
- if (t && textDiffers(existing, t)) {
87
+ const textChanged = t !== undefined && textDiffers(existing, t);
88
+ // Permission groups (SPEC §5): only with `opts.groups`; a key missing from it has no group.
89
+ const codeGroup = groups !== undefined ? (groups.get(key) ?? null) : undefined;
90
+ const groupChanged = codeGroup !== undefined && groupDiffers(existing.group, codeGroup);
91
+ if (textChanged || groupChanged) {
92
+ const base = textChanged ? t : existing;
82
93
  textUpdates.push({
83
94
  permissionKey: key,
84
- label: t.label,
85
- description: t.description,
86
- caution: t.caution,
95
+ label: base.label,
96
+ description: base.description ?? null,
97
+ caution: base.caution ?? null,
98
+ ...(codeGroup !== undefined ? { group: codeGroup } : {}),
87
99
  });
88
100
  }
89
101
  }
@@ -104,6 +116,13 @@ class CatalogReconciler {
104
116
  }
105
117
  }
106
118
  exports.CatalogReconciler = CatalogReconciler;
119
+ /** Stored vs code group; an absent stored group counts as null. */
120
+ function groupDiffers(stored, code) {
121
+ const s = stored ?? null;
122
+ if (s === null || code === null)
123
+ return s !== code;
124
+ return s.key !== code.key || s.label !== code.label || s.order !== code.order;
125
+ }
107
126
  /** Stored vs code text, with absent/undefined normalised to null. */
108
127
  function textDiffers(row, t) {
109
128
  return (row.label !== t.label ||
@@ -28,13 +28,29 @@ export interface CatalogPermissionRow {
28
28
  readonly firstSeenVersion?: string | null;
29
29
  /** When the key last became active (insert or orphaned → active), ISO. */
30
30
  readonly lastActivatedAt?: string | null;
31
+ /**
32
+ * Permission groups (SPEC §5): the display-only group of the key's type, `null` = none.
33
+ * OPTIONAL and additive; never read by grants, wildcards or decide().
34
+ */
35
+ readonly group?: CatalogPermissionGroup | null;
36
+ }
37
+ /** A stored permission group: key, label and the effective sort order. */
38
+ export interface CatalogPermissionGroup {
39
+ readonly key: string;
40
+ readonly label: string;
41
+ readonly order: number;
31
42
  }
32
- /** One text rewrite the reconciler asks for (code text replaces stored text, G-027). */
43
+ /**
44
+ * One text rewrite the reconciler asks for (code text replaces stored text, G-027). With
45
+ * `group` present (permission groups), the store also writes the group (`null` clears it);
46
+ * absent ⇒ the stored group is left alone.
47
+ */
33
48
  export interface CatalogTextUpdate {
34
49
  readonly permissionKey: string;
35
50
  readonly label: string;
36
51
  readonly description: string | null;
37
52
  readonly caution: string | null;
53
+ readonly group?: CatalogPermissionGroup | null;
38
54
  }
39
55
  /** The result of one mutating reconcile pass — surfaced via /health/catalog + logged. */
40
56
  export interface ReconcileReport {
@@ -61,7 +77,8 @@ export interface CatalogStore {
61
77
  markActive(keys: readonly string[], nowIso?: string): Promise<void>;
62
78
  /**
63
79
  * OPTIONAL (G-027): rewrite label/description/caution of existing rows to the code's text.
64
- * Writes only those three fields. A store without it still reconciles (no relabelling).
80
+ * Writes only those three fields, plus the group when the row carries `group`. A store
81
+ * without it still reconciles (no relabelling).
65
82
  */
66
83
  updateText?(rows: readonly CatalogTextUpdate[]): Promise<void>;
67
84
  }
@@ -1 +1 @@
1
- {"version":3,"file":"cat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IACjD,eAAe,IAAI,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAC;IACnD;;;OAGG;IACH,gBAAgB,CAAC,GAAG,EAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9E,kEAAkE;IAClE,YAAY,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD;;;OAGG;IACH,UAAU,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE;;;;OAIG;IACH,UAAU,CAAC,CAAC,IAAI,EAAE,SAAS,iBAAiB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAChE"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The permission-version rules the enforcement guard applies to a principal it derives (ADR-0035,
3
+ * G-036 M1 SPEC §5 run-loop "Manifest"). Shared by {@link import('./global-enforcement.guard.js').GlobalEnforcementGuard}
4
+ * and the per-call session principal (`session/session-principal.ts`, background-agent-tasks SPEC
5
+ * §5 B), so both stamp a principal with the same version under the same rule (Shield #3).
6
+ */
7
+ import type { CoarseGrants, Principal } from '@astram/core';
8
+ /**
9
+ * The binding's cached facts as gate 5 may use them (ADR-0035): absent, or at/past their
10
+ * `validUntilMs` time bound ⇒ `null` (gate 5 reloads). Never fabricated.
11
+ */
12
+ export declare function usableCachedFacts(facts: CoarseGrants | undefined, nowMs: number): CoarseGrants | null;
13
+ /**
14
+ * The permission version a principal was derived under: gate 5's reload version, else the version
15
+ * of the cached facts it served. `undefined` (callers fail closed) when there is neither, when the
16
+ * principal is ROOT and nothing was reloaded (gate 5 loads and checks no grants for root, so cached
17
+ * facts it never compared say nothing, SPEC v8), when a due subtree re-derive failed
18
+ * (`subtreeStale`: the subtree belongs to no single version), or when the value is not a
19
+ * non-negative safe integer.
20
+ */
21
+ export declare function derivedFactsVersion(principal: Pick<Principal, 'isRoot'>, reloaded: CoarseGrants | undefined, usableFacts: CoarseGrants | null, subtreeStale: boolean): number | undefined;
22
+ //# sourceMappingURL=facts-version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"facts-version.d.ts","sourceRoot":"","sources":["../../src/enforcement/facts-version.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAE5D;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,YAAY,GAAG,SAAS,EAC/B,KAAK,EAAE,MAAM,GACZ,YAAY,GAAG,IAAI,CAIrB;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,EACpC,QAAQ,EAAE,YAAY,GAAG,SAAS,EAClC,WAAW,EAAE,YAAY,GAAG,IAAI,EAChC,YAAY,EAAE,OAAO,GACpB,MAAM,GAAG,SAAS,CAapB"}
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.usableCachedFacts = usableCachedFacts;
4
+ exports.derivedFactsVersion = derivedFactsVersion;
5
+ /**
6
+ * The binding's cached facts as gate 5 may use them (ADR-0035): absent, or at/past their
7
+ * `validUntilMs` time bound ⇒ `null` (gate 5 reloads). Never fabricated.
8
+ */
9
+ function usableCachedFacts(facts, nowMs) {
10
+ if (facts === undefined)
11
+ return null;
12
+ if (typeof facts.validUntilMs === 'number' && nowMs >= facts.validUntilMs)
13
+ return null;
14
+ return facts;
15
+ }
16
+ /**
17
+ * The permission version a principal was derived under: gate 5's reload version, else the version
18
+ * of the cached facts it served. `undefined` (callers fail closed) when there is neither, when the
19
+ * principal is ROOT and nothing was reloaded (gate 5 loads and checks no grants for root, so cached
20
+ * facts it never compared say nothing, SPEC v8), when a due subtree re-derive failed
21
+ * (`subtreeStale`: the subtree belongs to no single version), or when the value is not a
22
+ * non-negative safe integer.
23
+ */
24
+ function derivedFactsVersion(principal, reloaded, usableFacts, subtreeStale) {
25
+ const derivedUnder = reloaded?.permissionsVersion ??
26
+ (principal.isRoot ? undefined : usableFacts?.permissionsVersion);
27
+ if (!subtreeStale &&
28
+ typeof derivedUnder === 'number' &&
29
+ Number.isSafeInteger(derivedUnder) &&
30
+ derivedUnder >= 0) {
31
+ return derivedUnder;
32
+ }
33
+ return undefined;
34
+ }
@@ -1,7 +1,7 @@
1
1
  import { CanActivate, ExecutionContext } from '@nestjs/common';
2
2
  import { Reflector } from '@nestjs/core';
3
3
  import type { CoreDecisionAuthority } from './core-seam.js';
4
- import { type SessionTokenBinder } from '../request-auth/session-token-binder.js';
4
+ import type { SessionTokenBinder } from '../request-auth/session-token-binder.js';
5
5
  import type { ServiceAuthenticator } from '@astram/core';
6
6
  import type { ScopeSubtreeResolver } from '../auth/ports/scope-subtree-resolver.js';
7
7
  import { type MfaRequirementService } from '../session/mfa-requirement-service.js';
@@ -17,6 +17,14 @@ import { type MfaRequirementService } from '../session/mfa-requirement-service.j
17
17
  * On `@astram/guard/internal` for `@astram/agent`'s run-start snapshot check.
18
18
  */
19
19
  export declare function requestFactsVersion(req: unknown): number | undefined;
20
+ /**
21
+ * The key version the enforcement guard verified this request's `ask_` key at (core
22
+ * `ServiceAuthResult.keyVersion`). `undefined` for a session request, a request the guard did not
23
+ * authenticate, a public route, a non-object, or an authenticator that reported none (callers fail
24
+ * closed). On `@astram/guard/internal` for `@astram/agent` only: an unattended task stores it, so a
25
+ * key rotation stops the task. Never an input to a decision.
26
+ */
27
+ export declare function requestServiceKeyVersion(req: unknown): number | undefined;
20
28
  /**
21
29
  * Global, fail-closed enforcement guard (ADR-0002) — now with REAL request
22
30
  * authorization for classified routes.
@@ -61,30 +69,5 @@ export declare class GlobalEnforcementGuard implements CanActivate {
61
69
  * `mfa_enrollment_required`). Fail closed: an allowlist, so an unknown route is denied too.
62
70
  */
63
71
  private enforceRestriction;
64
- /**
65
- * Write gate 5's reloaded grants and the live roles onto the session binding (ADR-0035). Session
66
- * bindings only: a service-account key has no binding (its roles and scope are read live per
67
- * request by the key store). Best-effort and conditional (same session, same tenant, fresher
68
- * facts, `XX`): a miss or a Redis error only means the next request reloads again.
69
- */
70
- private rebindReloadedGrants;
71
- /**
72
- * Re-derive the session's scope subtree after gate 5 reloaded facts at `reloadedVersion`
73
- * (security hardening Phase 1C). Identity bumps a tenant's permission version when a company is
74
- * created, moved or deleted under it, so a reload at a version newer than the bound subtree's
75
- * stamp means the subtree may be stale: resolve it again with the SAME resolver login uses,
76
- * rebind it (token + session entries) and return the principal the handler should see.
77
- *
78
- * Off the hot path: runs only for a session binding that carries a subtree, with a resolver
79
- * wired, and a reload NEWER than its stamp (or no stamp yet — once, then stamped). That is the
80
- * only DB read added (one closure query), and only on a version change.
81
- *
82
- * FAIL-CLOSED, NON-WIDENING: a resolver error, a non-array or an EMPTY result →
83
- * {@link SUBTREE_REDERIVE_FAILED}: the bound subtree stays (never replaced by a guess, never
84
- * widened), the stamp is not advanced, the reloaded facts are not cached (ADR-0035), and the next
85
- * request reloads and retries. `null` = no re-derive was due. A failed Redis rebind still returns the fresh principal for this request
86
- * (the DB answer is authoritative); the next reload retries the rebind.
87
- */
88
- private rederiveSubtreeOnVersionMove;
89
72
  }
90
73
  //# sourceMappingURL=global-enforcement.guard.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"global-enforcement.guard.d.ts","sourceRoot":"","sources":["../../src/enforcement/global-enforcement.guard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,gBAAgB,EAMjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAOzC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAK5D,OAAO,EAGL,KAAK,kBAAkB,EACxB,MAAM,yCAAyC,CAAC;AACjD,O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uC9D,mFAAmF;YACrE,mBAAmB;IAkHjC;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;CAU3B"}
@@ -14,21 +14,19 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.GlobalEnforcementGuard = void 0;
16
16
  exports.requestFactsVersion = requestFactsVersion;
17
+ exports.requestServiceKeyVersion = requestServiceKeyVersion;
17
18
  const common_1 = require("@nestjs/common");
18
19
  const core_1 = require("@nestjs/core");
19
20
  const classification_decorator_js_1 = require("./classification.decorator.js");
20
21
  const shield_tokens_js_1 = require("../module/shield-tokens.js");
21
22
  const tokens_js_1 = require("../request-auth/tokens.js");
22
- const session_token_binder_js_1 = require("../request-auth/session-token-binder.js");
23
23
  const request_principal_js_1 = require("../request-auth/request-principal.js");
24
24
  const tokens_js_2 = require("../auth/tokens.js");
25
- const session_facts_als_js_1 = require("../request-auth/session-facts-als.js");
26
25
  const request_principal_als_js_1 = require("../request-auth/request-principal-als.js");
27
26
  const reenroll_allowlist_js_1 = require("./reenroll-allowlist.js");
28
27
  const session_restriction_js_1 = require("../session/session-restriction.js");
29
28
  const mfa_requirement_service_js_1 = require("../session/mfa-requirement-service.js");
30
- /** A subtree re-derive that was due but could not be done (resolver error / empty / junk). */
31
- const SUBTREE_REDERIVE_FAILED = Symbol('subtree-rederive-failed');
29
+ const session_facts_reload_js_1 = require("./session-facts-reload.js");
32
30
  /**
33
31
  * The permission version gate 5 derived each request's `req.principal` (roles and subtree) under
34
32
  * (G-036 M1, agent-read-capabilities SPEC §5 run-loop "Manifest"). Keyed by the request object, so
@@ -53,15 +51,24 @@ function requestFactsVersion(req) {
53
51
  return REQUEST_FACTS_VERSION.get(req);
54
52
  }
55
53
  /**
56
- * The binding's cached facts as gate 5 may use them (ADR-0035): absent, or at/past their
57
- * `validUntilMs` time bound ⇒ `null` (gate 5 reloads). Never fabricated.
54
+ * The verified `ask_` key version of each request whose principal is a service account
55
+ * (background-agent-tasks SPEC v3 §5 B), keyed by the request object like
56
+ * {@link REQUEST_FACTS_VERSION}: nothing on the request can set or spoof it. Written only by
57
+ * {@link GlobalEnforcementGuard}, beside `req.principal`; read only through
58
+ * {@link requestServiceKeyVersion}.
58
59
  */
59
- function usableCachedFacts(facts, nowMs) {
60
- if (facts === undefined)
61
- return null;
62
- if (typeof facts.validUntilMs === 'number' && nowMs >= facts.validUntilMs)
63
- return null;
64
- return facts;
60
+ const REQUEST_SERVICE_KEY_VERSION = new WeakMap();
61
+ /**
62
+ * The key version the enforcement guard verified this request's `ask_` key at (core
63
+ * `ServiceAuthResult.keyVersion`). `undefined` for a session request, a request the guard did not
64
+ * authenticate, a public route, a non-object, or an authenticator that reported none (callers fail
65
+ * closed). On `@astram/guard/internal` for `@astram/agent` only: an unattended task stores it, so a
66
+ * key rotation stops the task. Never an input to a decision.
67
+ */
68
+ function requestServiceKeyVersion(req) {
69
+ if (req === null || typeof req !== 'object')
70
+ return undefined;
71
+ return REQUEST_SERVICE_KEY_VERSION.get(req);
65
72
  }
66
73
  /**
67
74
  * Global, fail-closed enforcement guard (ADR-0002) — now with REAL request
@@ -166,101 +173,42 @@ let GlobalEnforcementGuard = class GlobalEnforcementGuard {
166
173
  this.enforceRestriction(claims, req);
167
174
  // Attach the resolved principal so downstream handlers can act as this user.
168
175
  req.principal = principal;
169
- // ── ADR-0011 SESSION-FACTS HOT PATH ──────────────────────────────────────────
170
- // Enter the per-request session-facts ALS scope with THIS request's cached grants
171
- // (from the binding — same bearer token → same principal → same facts) around the
172
- // decide() call. The app-owned `SessionFactsReader` (an ALS-backed reader wired into
173
- // the decision authority) reads the SAME `SHIELD_SESSION_FACTS_ALS` store inside
174
- // decide(), so gate 5 gets these facts and can serve the coarse decision from cache
175
- // (no DB reload) when the cached version is still fresh.
176
- //
177
- // CROSS-PRINCIPAL ISOLATION: `als.run(store, cb)` binds `store` to this async
178
- // context and everything decide() awaits, and ONLY that context — a concurrent
179
- // request runs its own `run()` with its own store, so getStore() never returns
180
- // another request's facts. The store is built HERE from THIS request's claims.
181
- //
182
- // FAIL-CLOSED: no projector wired / absent / malformed binding → `claims.cachedFacts`
183
- // is undefined → the store carries `cachedFacts: null` → gate 5 DB-reloads (today's
184
- // behavior). The cache is only ever consulted; it never fabricates a permit.
185
- //
186
- // RELOAD SIGNAL (security hardening Phase 1C): when gate 5 reloads THIS principal's grants,
187
- // the framework-built authority reports the reloaded (authoritative) version here.
188
- //
189
- // TIME BOUND (ADR-0035): cached facts at or past their `validUntilMs` (the next start or end of
190
- // a role posting's window — a change no version bump marks) are treated as ABSENT, so gate 5
191
- // reloads them (and the roles with them, below).
192
- let reloaded;
193
- const usableFacts = usableCachedFacts(claims.cachedFacts, Date.now());
194
- const factsStore = {
195
- cachedFacts: usableFacts,
196
- permissionsVersion: usableFacts?.permissionsVersion ?? 0,
197
- onReload: (principalId, tenantId, grants) => {
198
- if (principalId === principal.id && tenantId === principal.tenantId) {
199
- reloaded = grants;
200
- }
201
- },
202
- };
203
- const decision = await session_facts_als_js_1.SHIELD_SESSION_FACTS_ALS.run(factsStore, () => this.decisionAuthority.decide(principal, { key: classification.action }, { level: 'object_type', typeKey: classification.typeKey, tenantId: principal.tenantId }, { isAuthenticated: true }));
204
- // The type-level decision above is on the principal's OWN tenant, which every subtree
205
- // contains, so it does not depend on the subtree; the handler (engine record checks, the
206
- // ADR-0034 create wall) is what reads it. Hence: decide first, then hand the handler the
207
- // re-derived principal.
208
- //
209
- // LIVE ROLES (ADR-0035, GAPS #4): the reload also carries the principal's in-effect roles (when
210
- // the app port reports them). The handler gets them on THIS request (role-keyed record rules,
211
- // list scope, shares, the engine's record checks all read `req.principal.roleIds`), and the
212
- // binding is rewritten with the reloaded facts + roles together, so the next requests are
213
- // served from the cache (GAPS #6) with the same live roles.
214
- // MANDATORY 2FA (auth capabilities R2.5, AC-9): re-evaluate when the permission version moved
215
- // past the session's requirement stamp — gate 5 just told us the version (its reload, or the
216
- // fresh cached facts it served). Unchanged version ⇒ no DB query. A failed evaluation denies
217
- // this request (503) and caches nothing, so the next request reloads and retries.
218
- let enforced = claims;
219
- let mfaFailed = false;
220
- const mfa = this.mfaRequirement;
221
- if (mfa !== undefined && mfa !== null) {
222
- const token = (0, request_principal_js_1.extractBearerToken)(authHeader);
223
- try {
224
- enforced = await mfa.refresh(token ?? '', claims, {
225
- version: reloaded?.permissionsVersion ?? usableFacts?.permissionsVersion,
226
- grants: reloaded ?? usableFacts ?? undefined,
227
- });
228
- }
229
- catch {
230
- mfaFailed = true;
231
- }
176
+ // Background-agent-tasks SPEC v3 §5 B: the verified `ask_` key version beside it (service
177
+ // accounts only; cleared otherwise so a reused request object never carries a stale one).
178
+ if (principal.kind === 'service_account' && resolved.keyVersion !== undefined) {
179
+ REQUEST_SERVICE_KEY_VERSION.set(req, resolved.keyVersion);
232
180
  }
233
- let subtreeStale = false;
234
- if (reloaded !== undefined && !mfaFailed) {
235
- const liveRoles = (0, session_token_binder_js_1.liveRoleIds)(reloaded);
236
- const current = liveRoles !== undefined ? { ...claims, roleIds: liveRoles } : claims;
237
- const rederived = await this.rederiveSubtreeOnVersionMove(authHeader, current, reloaded.permissionsVersion);
238
- subtreeStale = rederived === SUBTREE_REDERIVE_FAILED;
239
- // A subtree re-derive that was due but FAILED (resolver error / empty) keeps the facts
240
- // uncached, so the next request reloads and retries it (the Phase 1C retry guarantee).
241
- if (rederived !== SUBTREE_REDERIVE_FAILED) {
242
- await this.rebindReloadedGrants(authHeader, claims, reloaded, liveRoles);
243
- }
244
- if (rederived !== null && rederived !== SUBTREE_REDERIVE_FAILED) {
245
- req.principal = rederived;
246
- }
247
- else if (liveRoles !== undefined) {
248
- const withRoles = (0, request_principal_js_1.principalFromClaims)(current);
249
- if (withRoles !== null)
250
- req.principal = withRoles;
251
- }
181
+ else {
182
+ REQUEST_SERVICE_KEY_VERSION.delete(req);
252
183
  }
184
+ // ── GATE 5 ON THE SESSION FACTS, AND WHAT FOLLOWS IT (ADR-0011, ADR-0035) ────
185
+ // decide() inside the session-facts ALS scope (cached facts served while fresh and inside
186
+ // their time bound, else gate 5 reloads them), the mandatory-2FA recompute, the live roles,
187
+ // the subtree re-derive and the write-back of a reload. ONE implementation, shared with the
188
+ // off-request session facts refresh (background-agent-tasks SPEC v9 §5 C), Shield #3: see
189
+ // `session-facts-reload.ts`. The handler gets the re-derived principal (subtree / live roles).
190
+ const outcome = await (0, session_facts_reload_js_1.decideOnSessionFacts)({
191
+ decisionAuthority: this.decisionAuthority,
192
+ tokenBinder: this.tokenBinder,
193
+ scopeSubtreeResolver: this.scopeSubtreeResolver,
194
+ mfaRequirement: this.mfaRequirement,
195
+ }, {
196
+ principal,
197
+ claims,
198
+ accessToken: (0, request_principal_js_1.extractBearerToken)(authHeader),
199
+ classification,
200
+ nowMs: Date.now(),
201
+ });
202
+ const { decision, enforced, mfaFailed } = outcome;
203
+ if (outcome.principal !== principal)
204
+ req.principal = outcome.principal;
253
205
  // G-036 M1 (SPEC §5 run-loop): record the version the principal above was derived under, from
254
206
  // what gate 5 already reported (no new read). Absent when gate 5 reported none or the subtree
255
207
  // re-derive failed (the principal's subtree then belongs to no single version). For a ROOT
256
208
  // principal gate 5 loads and checks no grants (core decides root by its flag and plane), so
257
209
  // cached facts it never compared with the tenant's version say nothing (SPEC v8): absent.
258
- const derivedUnder = reloaded?.permissionsVersion ??
259
- (principal.isRoot ? undefined : usableFacts?.permissionsVersion);
260
- if (!subtreeStale &&
261
- typeof derivedUnder === 'number' &&
262
- Number.isSafeInteger(derivedUnder) &&
263
- derivedUnder >= 0) {
210
+ const derivedUnder = outcome.factsVersion;
211
+ if (derivedUnder !== undefined) {
264
212
  REQUEST_FACTS_VERSION.set(req, derivedUnder);
265
213
  }
266
214
  else {
@@ -297,83 +245,6 @@ let GlobalEnforcementGuard = class GlobalEnforcementGuard {
297
245
  throw new common_1.ForbiddenException({ error: (0, session_restriction_js_1.restrictionErrorCode)(reason) });
298
246
  }
299
247
  }
300
- /**
301
- * Write gate 5's reloaded grants and the live roles onto the session binding (ADR-0035). Session
302
- * bindings only: a service-account key has no binding (its roles and scope are read live per
303
- * request by the key store). Best-effort and conditional (same session, same tenant, fresher
304
- * facts, `XX`): a miss or a Redis error only means the next request reloads again.
305
- */
306
- async rebindReloadedGrants(authHeader, claims, grants, liveRoles) {
307
- if (this.tokenBinder === undefined)
308
- return;
309
- if (claims.sessionId === '' || claims.kind === 'service_account')
310
- return;
311
- const token = (0, request_principal_js_1.extractBearerToken)(authHeader);
312
- if (token === null)
313
- return;
314
- try {
315
- await this.tokenBinder.refreshGrants(token, claims.sessionId, claims.tenantId, grants, liveRoles);
316
- }
317
- catch {
318
- // Best-effort: the decision and the handler's principal already use the reloaded grants.
319
- }
320
- }
321
- /**
322
- * Re-derive the session's scope subtree after gate 5 reloaded facts at `reloadedVersion`
323
- * (security hardening Phase 1C). Identity bumps a tenant's permission version when a company is
324
- * created, moved or deleted under it, so a reload at a version newer than the bound subtree's
325
- * stamp means the subtree may be stale: resolve it again with the SAME resolver login uses,
326
- * rebind it (token + session entries) and return the principal the handler should see.
327
- *
328
- * Off the hot path: runs only for a session binding that carries a subtree, with a resolver
329
- * wired, and a reload NEWER than its stamp (or no stamp yet — once, then stamped). That is the
330
- * only DB read added (one closure query), and only on a version change.
331
- *
332
- * FAIL-CLOSED, NON-WIDENING: a resolver error, a non-array or an EMPTY result →
333
- * {@link SUBTREE_REDERIVE_FAILED}: the bound subtree stays (never replaced by a guess, never
334
- * widened), the stamp is not advanced, the reloaded facts are not cached (ADR-0035), and the next
335
- * request reloads and retries. `null` = no re-derive was due. A failed Redis rebind still returns the fresh principal for this request
336
- * (the DB answer is authoritative); the next reload retries the rebind.
337
- */
338
- async rederiveSubtreeOnVersionMove(authHeader, claims, reloadedVersion) {
339
- const resolver = this.scopeSubtreeResolver;
340
- if (resolver === undefined || resolver === null || this.tokenBinder === undefined)
341
- return null;
342
- // Session bindings only: a service-account key has no binding (its scope is read live per
343
- // request by the key store) and no session id.
344
- if (claims.sessionId === '' || claims.kind === 'service_account')
345
- return null;
346
- // Only a binding that carries a subtree: an absent one is the self-node fallback (no resolver
347
- // or a failed login-time resolve) and stays that way until the next login/refresh.
348
- if (claims.scopeSubtreeNodeIds === undefined || claims.scopeSubtreeNodeIds.length === 0) {
349
- return null;
350
- }
351
- const stamp = claims.scopeSubtreeVersion;
352
- if (stamp !== undefined && reloadedVersion <= stamp)
353
- return null;
354
- let subtree;
355
- try {
356
- const resolved = await resolver.resolveSubtree(claims.tenantId);
357
- if (!Array.isArray(resolved) || resolved.length === 0)
358
- return SUBTREE_REDERIVE_FAILED;
359
- if (resolved.some((n) => typeof n !== 'string' || n.length === 0)) {
360
- return SUBTREE_REDERIVE_FAILED;
361
- }
362
- subtree = [...resolved];
363
- }
364
- catch {
365
- return SUBTREE_REDERIVE_FAILED;
366
- }
367
- const token = (0, request_principal_js_1.extractBearerToken)(authHeader);
368
- if (token !== null) {
369
- await this.tokenBinder.rederiveScopeSubtree(token, claims.sessionId, claims.tenantId, subtree, reloadedVersion);
370
- }
371
- return (0, request_principal_js_1.principalFromClaims)({
372
- ...claims,
373
- scopeSubtreeNodeIds: subtree,
374
- scopeSubtreeVersion: reloadedVersion,
375
- });
376
- }
377
248
  };
378
249
  exports.GlobalEnforcementGuard = GlobalEnforcementGuard;
379
250
  exports.GlobalEnforcementGuard = GlobalEnforcementGuard = __decorate([
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Gate 5 on a session's facts, and everything the enforcement guard does after it (ADR-0011,
3
+ * ADR-0035, security hardening Phase 1C, auth capabilities R2.5): the ONE implementation shared by
4
+ * {@link import('./global-enforcement.guard.js').GlobalEnforcementGuard} (every classified request)
5
+ * and the off-request session facts refresh (`session/session-principal.ts`
6
+ * `refreshSessionFacts`, background-agent-tasks SPEC v9 §5 C), so both reload, recompute and write
7
+ * back the same way (Shield #3).
8
+ *
9
+ * In order:
10
+ * 1. `decide()` inside the session-facts ALS scope with the binding's USABLE cached facts (absent
11
+ * or past `validUntilMs` ⇒ none, so gate 5 reloads them through the app's
12
+ * `PermissionFactsPort.loadCoarseGrants`: the one MariaDB read of a reload). The reload, if
13
+ * any, is reported through `onReload`.
14
+ * 2. The mandatory-2FA recompute (`MfaRequirementService.refresh`), which reads the database only
15
+ * when the version moved past the session's requirement stamp.
16
+ * 3. After a reload: the live roles, the scope-subtree re-derive when the reload is newer than the
17
+ * bound subtree's stamp (one closure read, only then), and the write-back of the reloaded facts
18
+ * and roles onto the binding (`SessionTokenBinder.refreshGrants`, conditional and best-effort).
19
+ * 4. The version the returned principal was derived under ({@link derivedFactsVersion}).
20
+ *
21
+ * The caller decides what a deny, an MFA failure or a restriction means for it (the guard answers
22
+ * 403 / 503; the refresh answers `null`). A `decide()` error propagates.
23
+ */
24
+ import type { Principal } from '@astram/core';
25
+ import type { CoreDecision, CoreDecisionAuthority } from './core-seam.js';
26
+ import { type BoundPrincipalClaims, type SessionTokenBinder } from '../request-auth/session-token-binder.js';
27
+ import type { ScopeSubtreeResolver } from '../auth/ports/scope-subtree-resolver.js';
28
+ import type { MfaRequirementService } from '../session/mfa-requirement-service.js';
29
+ /** What the shared path needs (the guard's own collaborators). */
30
+ export interface SessionFactsReloadDeps {
31
+ readonly decisionAuthority: CoreDecisionAuthority;
32
+ readonly tokenBinder: Pick<SessionTokenBinder, 'refreshGrants' | 'rederiveScopeSubtree'>;
33
+ readonly scopeSubtreeResolver?: ScopeSubtreeResolver | null | undefined;
34
+ readonly mfaRequirement?: MfaRequirementService | null | undefined;
35
+ }
36
+ export interface SessionFactsReloadInput {
37
+ /** The principal built from `claims` ({@link principalFromClaims}). */
38
+ readonly principal: Principal;
39
+ readonly claims: BoundPrincipalClaims;
40
+ /**
41
+ * The access token whose binding is written back beside the session-claims entry: the bearer
42
+ * token of the request; `null` off-request (the binder then uses the token currently bound to
43
+ * the session, if any).
44
+ */
45
+ readonly accessToken: string | null;
46
+ /** The route classification `decide()` runs for (the gate 5 reload happens inside it). */
47
+ readonly classification: {
48
+ readonly typeKey: string;
49
+ readonly action: string;
50
+ };
51
+ readonly nowMs: number;
52
+ }
53
+ export interface SessionFactsReloadResult {
54
+ readonly decision: CoreDecision;
55
+ /** The principal to act as: re-derived subtree or live roles after a reload, else the input. */
56
+ readonly principal: Principal;
57
+ /** The claims after the mandatory-2FA recompute (the input claims when nothing changed). */
58
+ readonly enforced: BoundPrincipalClaims;
59
+ /** The recompute failed: the guard answers 503, the refresh `null`; nothing was cached. */
60
+ readonly mfaFailed: boolean;
61
+ /** {@link derivedFactsVersion} for the returned principal (`undefined` ⇒ callers fail closed). */
62
+ readonly factsVersion: number | undefined;
63
+ }
64
+ /** Steps 1–4 above. Throws only what `decide()` throws. */
65
+ export declare function decideOnSessionFacts(deps: SessionFactsReloadDeps, input: SessionFactsReloadInput): Promise<SessionFactsReloadResult>;
66
+ //# sourceMappingURL=session-facts-reload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-facts-reload.d.ts","sourceRoot":"","sources":["../../src/enforcement/session-facts-reload.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,KAAK,EAAgB,SAAS,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,EAEL,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACxB,MAAM,yCAAyC,CAAC;AAMjD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAMnF,kEAAkE;AAClE,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,iBAAiB,EAAE,qBAAqB,CAAC;IAClD,QAAQ,CAAC,WAAW,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,GAAG,sBAAsB,CAAC,CAAC;IACzF,QAAQ,CAAC,oBAAoB,CAAC,EAAE,oBA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