@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
@@ -77,6 +77,7 @@
77
77
  */
78
78
  import type { ListScopeSpec, ScopeCondition } from '@astram/core';
79
79
  import { type ObjectType } from '@astram/engine';
80
+ import { AuthorizationUnavailableError } from '@astram/core';
80
81
  /** The translated fragment: a boolean WHERE expression + its ordered bind params. */
81
82
  export interface TranslatedListScope {
82
83
  /** A SQL boolean expression carrying ONLY `?` placeholders + backtick columns. */
@@ -93,7 +94,27 @@ export interface TranslatedListScope {
93
94
  export interface ListScopePrincipal {
94
95
  readonly principalId: string;
95
96
  readonly principalTenantId: string;
97
+ /**
98
+ * The viewer's department codes for `in_my_departments` / `not_in_my_departments`
99
+ * (department-scoped policies, spec §5 D): the codes of the viewer's in-effect postings in
100
+ * `principalTenantId`. `null` / absent = NOT LOADED: the wiring loads the set whenever a
101
+ * group uses a department operator, so a department operator meeting an unloaded set is a
102
+ * programming error and the translator THROWS {@link UnloadedDepartmentSetError} (fail
103
+ * closed, never `TRUE`). The owning-tenant (cross-tenant) deny branch is always translated
104
+ * with an EMPTY set (D3), whatever this holds.
105
+ */
106
+ readonly departmentCodes?: readonly string[] | null | undefined;
107
+ }
108
+ /**
109
+ * Thrown when a department operator is translated without a loaded viewer department set (a
110
+ * wiring error). It IS an {@link AuthorizationUnavailableError} (branded), so the read fails
111
+ * 503 like any other unanswerable access decision (spec §13), never an unbounded list.
112
+ */
113
+ export declare class UnloadedDepartmentSetError extends AuthorizationUnavailableError {
114
+ constructor(typeKey: string);
96
115
  }
116
+ /** Whether any condition of any group uses a department operator (the wiring's load trigger). */
117
+ export declare function groupsUseDepartmentOperator(groups: readonly (readonly ScopeCondition[])[]): boolean;
97
118
  /** Error thrown when a scope condition references a field the type does not register. */
98
119
  export declare class UnknownScopeFieldError extends Error {
99
120
  constructor(typeKey: string, field: string);
@@ -1 +1 @@
1
- {"version":3,"file":"list-scope-sql.d.ts","sourceRoot":"","sources":["../../src/authz/list-scope-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4EG;AAEH,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EAIf,MAAM,cAAc,CAAC;AACtB,OAAO,EAML,KAAK,UAAU,EAChB,MAAM,gBAAgB,CAAC;AAGxB,qFAAqF;AACrF,MAAM,WAAW,mBAAmB;IAClC,kFAAkF;IAClF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,gFAAgF;IAChF,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;CAC5B;AAED;;;;;GAKG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;CACpC;AAED,yFAAyF;AACzF,qBAAa,sBAAuB,SAAQ,KAAK;gBACnC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;CAO3C;AAmID;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,aAAa,EACnB,GAAG,EAAE,UAAU,EACf,SAAS,EAAE,kBAAkB,EAC7B,IAAI,EAAE;IACJ;;;;;;OAMG;IACH,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,MAAM,CAAC;IACrB;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EAAE,SAAS,CAAC,SAAS,cAAc,EAAE,CAAC,EAAE,CAAC;CAC3D,GACA,mBAAmB,CAyJrB"}
1
+ {"version":3,"file":"list-scope-sql.d.ts","sourceRoot":"","sources":["../../src/authz/list-scope-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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D,GACA,mBAAmB,CAgKrB"}
@@ -77,10 +77,34 @@
77
77
  * PURE — no DB, no I/O. `translateListScope(spec, reg, principal) → { sql, params }`.
78
78
  */
79
79
  Object.defineProperty(exports, "__esModule", { value: true });
80
- exports.UnknownScopeFieldError = void 0;
80
+ exports.UnknownScopeFieldError = exports.UnloadedDepartmentSetError = void 0;
81
+ exports.groupsUseDepartmentOperator = groupsUseDepartmentOperator;
81
82
  exports.translateListScope = translateListScope;
82
83
  const engine_1 = require("@astram/engine");
83
84
  const core_1 = require("@astram/core");
85
+ /**
86
+ * Thrown when a department operator is translated without a loaded viewer department set (a
87
+ * wiring error). It IS an {@link AuthorizationUnavailableError} (branded), so the read fails
88
+ * 503 like any other unanswerable access decision (spec §13), never an unbounded list.
89
+ */
90
+ class UnloadedDepartmentSetError extends core_1.AuthorizationUnavailableError {
91
+ constructor(typeKey) {
92
+ super(`list-scope: a department operator on type '${typeKey}' met an unloaded viewer ` +
93
+ `department set (wiring error); the read fails closed.`);
94
+ this.name = 'UnloadedDepartmentSetError';
95
+ Object.setPrototypeOf(this, UnloadedDepartmentSetError.prototype);
96
+ }
97
+ }
98
+ exports.UnloadedDepartmentSetError = UnloadedDepartmentSetError;
99
+ /** The department operators (department-scoped policies). */
100
+ const DEPARTMENT_OPERATORS = new Set([
101
+ 'in_my_departments',
102
+ 'not_in_my_departments',
103
+ ]);
104
+ /** Whether any condition of any group uses a department operator (the wiring's load trigger). */
105
+ function groupsUseDepartmentOperator(groups) {
106
+ return groups.some((g) => g.some((c) => DEPARTMENT_OPERATORS.has(c.operator)));
107
+ }
84
108
  /** Error thrown when a scope condition references a field the type does not register. */
85
109
  class UnknownScopeFieldError extends Error {
86
110
  constructor(typeKey, field) {
@@ -183,6 +207,23 @@ function translateCondition(cond, reg, principal, p) {
183
207
  case 'is_not_owner':
184
208
  // Same guards, mirrored for the negative ownership operator.
185
209
  return `(${col} IS NOT NULL AND ${col} <> '' AND ${col} <> ${p.bind(principal.principalId)})`;
210
+ case 'in_my_departments':
211
+ case 'not_in_my_departments': {
212
+ // Department-scoped policies (spec §5 D, D5). Mirrors `conditionHolds`: in = a non-empty
213
+ // value that equals (byte for byte — `CAST(… AS BINARY)`, so no case- or pad-insensitive
214
+ // collation can widen the list past decide()'s `===`) one of the viewer's codes; not_in =
215
+ // its null-safe negation. Every code is a bound `?`; none reaches the SQL text.
216
+ const codes = principal.departmentCodes;
217
+ if (codes === null || codes === undefined)
218
+ throw new UnloadedDepartmentSetError(reg.typeKey);
219
+ const negate = op === 'not_in_my_departments';
220
+ if (codes.length === 0)
221
+ return negate ? 'TRUE' : 'FALSE';
222
+ const placeholders = codes.map((c) => `CAST(${p.bind(c)} AS BINARY)`).join(', ');
223
+ return negate
224
+ ? `(${col} IS NULL OR ${col} = '' OR CAST(${col} AS BINARY) NOT IN (${placeholders}))`
225
+ : `(${col} IS NOT NULL AND ${col} <> '' AND CAST(${col} AS BINARY) IN (${placeholders}))`;
226
+ }
186
227
  default:
187
228
  // Unknown operator → a condition that never matches (fail-closed; never widen).
188
229
  return 'FALSE';
@@ -352,7 +393,9 @@ function translateListScope(spec, reg, principal, opts) {
352
393
  if (!rootUnbounded) {
353
394
  const crossTenant = translateCrossTenant(spec, reg, schema, nowMs, p);
354
395
  if (crossTenant !== null) {
355
- const owningDeny = translateGroups(opts.owningTenantDeny ?? [], reg, principal, p);
396
+ // D3: a record reached only by a cross-tenant grant is judged with an EMPTY viewer
397
+ // department set (decide() does the same for a resource outside the subtree).
398
+ const owningDeny = translateGroups(opts.owningTenantDeny ?? [], reg, { ...principal, departmentCodes: [] }, p);
356
399
  const crossBranch = owningDeny !== null ? `( ${crossTenant} ) AND NOT ( ${owningDeny} )` : crossTenant;
357
400
  result = `( ${sameTenantBranch} OR ${crossBranch} )`;
358
401
  }
@@ -1 +1 @@
1
- {"version":3,"file":"mariadb-list-scope-adapter.d.ts","sourceRoot":"","sources":["../../src/authz/mariadb-list-scope-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;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B,YAAW,aAAa;IAC3D,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAqB;IACxC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEpB,EAAE,EAAE,kBAAkB,EAAE,IAAI,GAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO;IAO5D,oBAAoB,CACxB,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,SAAS,MAAM,EAAE,EAChC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,oBAAoB,CAAC;CA8EjC"}
@@ -44,31 +44,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
44
44
  exports.MariaDbListScopeAdapter = exports.SHIELD_LIST_SCOPE_PORT = void 0;
45
45
  const core_1 = require("@astram/core");
46
46
  const framework_schema_names_js_1 = require("../config/framework-schema-names.js");
47
+ const rule_subject_js_1 = require("./rule-subject.js");
47
48
  /** The DI token the adapter is bound under (parity with the rule-port token). */
48
49
  exports.SHIELD_LIST_SCOPE_PORT = Symbol('SHIELD_LIST_SCOPE_PORT');
49
- /**
50
- * Whether a rule group's SUBJECT matches the requesting principal — the EXACT mirror of the
51
- * per-record rule adapter's `subjectMatches` ({@link MariaDbRecordPermissionRuleAdapter}):
52
- * • `everyone` → always matches.
53
- * • `role` → matches IFF the principal HOLDS the named role
54
- * (`subject.roleIds.includes(rpr_subject_value)`, value non-null).
55
- * • any other / unknown kind → does NOT match (fail-closed).
56
- * A group's subject is consistent across its rows (the store writes one subject per policy),
57
- * so it is read from the group's HEAD row (like the effect). A group that FAILS the subject
58
- * match contributes to NEITHER allow NOR deny — it is simply not this principal's rule (a
59
- * role-subjected DENY not aimed at the principal must NOT over-restrict them, the symmetric
60
- * divergence — so BOTH sides are filtered identically).
61
- */
62
- function subjectMatches(head, subject) {
63
- const kind = head.rpr_subject_kind;
64
- if (kind === 'everyone')
65
- return true;
66
- if (kind === 'role') {
67
- return head.rpr_subject_value !== null && subject.roleIds.includes(head.rpr_subject_value);
68
- }
69
- // Unknown subject kind → does NOT match (fail-closed).
70
- return false;
71
- }
50
+ // Subject matching is the ONE shared helper (`rule-subject.ts`) the per-record rule adapter
51
+ // also uses (department-scoped policies D4), so list and decide() agree on who a rule
52
+ // applies to. A group that FAILS the subject match contributes to NEITHER allow NOR deny —
53
+ // it is simply not this principal's rule (a role-subjected DENY not aimed at the principal
54
+ // must NOT over-restrict them — so BOTH sides are filtered identically). Like `evaluate`,
55
+ // every row of the group must subject-match (the store writes one subject per policy, so
56
+ // this equals the head-row check on well-formed data and stays identical on malformed data).
72
57
  /**
73
58
  * The concrete list-scope adapter. Reads the ADMIN rules for `(tenant, type_key, action|*)`
74
59
  * and projects them into allow/deny {@link ScopeCondition} AND-groups for the translator.
@@ -93,7 +78,7 @@ class MariaDbListScopeAdapter {
93
78
  : `rpr_tenant_uuid IS NULL`;
94
79
  let rows;
95
80
  try {
96
- rows = (await this.db.query(`SELECT rpr_policy_uuid, rpr_effect, rpr_subject_kind, rpr_subject_value, rpr_field, rpr_operator, rpr_value
81
+ rows = (await this.db.query(`SELECT rpr_policy_uuid, rpr_effect, rpr_subject_kind, rpr_subject_value, rpr_subject_role_uuids, rpr_field, rpr_operator, rpr_value
97
82
  FROM \`${this.schema}\`.\`record_permission_rule\`
98
83
  WHERE rpr_type_key = ?
99
84
  AND ${tenantClause}
@@ -132,7 +117,7 @@ class MariaDbListScopeAdapter {
132
117
  // A group whose subject does NOT match this principal contributes to NEITHER allow NOR
133
118
  // deny (it is not this principal's rule). Applied identically to allow AND deny so a
134
119
  // role-subjected deny not aimed at the principal cannot over-restrict them.
135
- if (!subjectMatches(head, subject))
120
+ if (!groupRows.every((row) => (0, rule_subject_js_1.subjectMatches)(row, subject.roleIds)))
136
121
  continue;
137
122
  // A NULL-field row contributes NO condition (unconditional). A group of only such
138
123
  // rows → an EMPTY condition list, which the translator renders as `(TRUE)` — a
@@ -28,10 +28,13 @@
28
28
  * • `rpr_type_key` — the policy's `typeKey` (same on every row).
29
29
  * • `rpr_action` — the policy's `action` (same on every row).
30
30
  * • `rpr_effect` — the policy's `effect` ('allow' | 'deny'; same every row).
31
- * • `rpr_subject_kind` — always `'everyone'` (v1 mapping — a GuidedPolicy carries
32
- * NO role subject; role-subjected policies are a future
33
- * extension. See recon C gap #5 / Task 0.3).
34
- * • `rpr_subject_value`— always NULL (no role subject in v1).
31
+ * • `rpr_subject_kind` — the policy's subject kind (department-scoped policies, D4):
32
+ * `'everyone'` (absent subject — the pre-existing mapping),
33
+ * `'roles'` or `'except_roles'`. Same on every row.
34
+ * • `rpr_subject_value`— always NULL (the legacy single-`role` kind is read, never written).
35
+ * • `rpr_subject_role_uuids` — NULL for `everyone`; else the JSON array of the subject's
36
+ * role ids, sorted and distinct (guard migration 141). Same on
37
+ * every row.
35
38
  * • `rpr_field` — the condition's `field` (NULL for a 0-condition policy).
36
39
  * • `rpr_operator` — the condition's operator, persisted with core's CANONICAL
37
40
  * name (`eq`, `ne`, `is_owner`, …). The read adapter
@@ -1 +1 @@
1
- {"version":3,"file":"mariadb-policy-store.d.ts","sourceRoot":"","sources":["../../src/authz/mariadb-policy-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,WAAW,EAAmB,MAAM,cAAc,CAAC;AAGvF,sFAAsF;AACtF,eAAO,MAAM,mBAAmB,eAAgC,CAAC;AAEjE,kFAAkF;AAClF,MAAM,WAAW,aAAa;IAC5B,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACnE;AAgCD;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,WAAW;IACpD,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAgB;IACnC,OAAO,CAAC,QAAQ,CA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A;KAAO;IAO7D;;;;;OAKG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC;IAiDzE;;;;OAIG;IACG,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,MAAM,EAAE,CAAC;IAmDjF;;;;OAIG;IACG,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQnD;;;;;;;;;;OAUG;IACG,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CASjF"}
@@ -29,10 +29,13 @@
29
29
  * • `rpr_type_key` — the policy's `typeKey` (same on every row).
30
30
  * • `rpr_action` — the policy's `action` (same on every row).
31
31
  * • `rpr_effect` — the policy's `effect` ('allow' | 'deny'; same every row).
32
- * • `rpr_subject_kind` — always `'everyone'` (v1 mapping — a GuidedPolicy carries
33
- * NO role subject; role-subjected policies are a future
34
- * extension. See recon C gap #5 / Task 0.3).
35
- * • `rpr_subject_value`— always NULL (no role subject in v1).
32
+ * • `rpr_subject_kind` — the policy's subject kind (department-scoped policies, D4):
33
+ * `'everyone'` (absent subject — the pre-existing mapping),
34
+ * `'roles'` or `'except_roles'`. Same on every row.
35
+ * • `rpr_subject_value`— always NULL (the legacy single-`role` kind is read, never written).
36
+ * • `rpr_subject_role_uuids` — NULL for `everyone`; else the JSON array of the subject's
37
+ * role ids, sorted and distinct (guard migration 141). Same on
38
+ * every row.
36
39
  * • `rpr_field` — the condition's `field` (NULL for a 0-condition policy).
37
40
  * • `rpr_operator` — the condition's operator, persisted with core's CANONICAL
38
41
  * name (`eq`, `ne`, `is_owner`, …). The read adapter
@@ -70,6 +73,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
70
73
  exports.MariaDbPolicyStore = exports.SHIELD_POLICY_STORE = void 0;
71
74
  const node_crypto_1 = require("node:crypto");
72
75
  const framework_schema_names_js_1 = require("../config/framework-schema-names.js");
76
+ const rule_subject_js_1 = require("./rule-subject.js");
73
77
  /** The DI token the policy store is bound under (parity with the rule-port token). */
74
78
  exports.SHIELD_POLICY_STORE = Symbol('SHIELD_POLICY_STORE');
75
79
  /**
@@ -82,7 +86,39 @@ const OPERAND_LESS_OPERATORS = new Set([
82
86
  'is_not_null',
83
87
  'is_owner',
84
88
  'is_not_owner',
89
+ 'in_my_departments',
90
+ 'not_in_my_departments',
85
91
  ]);
92
+ /** The `(rpr_subject_kind, rpr_subject_role_uuids)` pair written on every row of a policy. */
93
+ function subjectColumns(subject) {
94
+ if (subject === undefined || subject.kind === 'everyone')
95
+ return ['everyone', null];
96
+ const ids = [...new Set(subject.roleIds)].sort();
97
+ return [subject.kind, JSON.stringify(ids)];
98
+ }
99
+ /**
100
+ * Rebuild a policy's subject from its group's first row. A legacy `role` row reads as
101
+ * `{ kind: 'roles', roleIds: [value] }`. A row whose subject the enforcement helper would never
102
+ * match (unknown kind, malformed / empty JSON) reads as `{ kind: 'roles', roleIds: [] }` — "applies
103
+ * to nobody", which is what enforcement does with it — so the admin still sees (and can delete)
104
+ * the rule. A row with no subject columns at all (pre-subject reader) reads as `everyone`.
105
+ */
106
+ function subjectOf(row) {
107
+ const kind = row.rpr_subject_kind;
108
+ if (kind === undefined || kind === 'everyone')
109
+ return { kind: 'everyone' };
110
+ if (kind === 'role') {
111
+ return typeof row.rpr_subject_value === 'string' && row.rpr_subject_value !== ''
112
+ ? { kind: 'roles', roleIds: [row.rpr_subject_value] }
113
+ : { kind: 'roles', roleIds: [] };
114
+ }
115
+ if (kind === 'roles' || kind === 'except_roles') {
116
+ const ids = (0, rule_subject_js_1.parseSubjectRoleIds)(row.rpr_subject_role_uuids);
117
+ if (ids !== null)
118
+ return { kind, roleIds: [...ids] };
119
+ }
120
+ return { kind: 'roles', roleIds: [] };
121
+ }
86
122
  /** Serialize a condition operand to the VARCHAR form the enforcement adapter reads. */
87
123
  function serializeValue(condition) {
88
124
  if (OPERAND_LESS_OPERATORS.has(condition.operator))
@@ -124,22 +160,26 @@ class MariaDbPolicyStore {
124
160
  operator: c.operator, // canonical core name (eq/ne/is_owner/…)
125
161
  value: serializeValue(c),
126
162
  }));
163
+ // ONE subject for the whole policy, written onto every row (D4).
164
+ const [subjectKind, subjectRoleUuids] = subjectColumns(policy.subject);
127
165
  for (const row of rows) {
128
166
  await this.db.query(`INSERT INTO \`${this.schema}\`.\`record_permission_rule\`
129
167
  (rpr_uuid, rpr_policy_uuid, rpr_tenant_uuid, rpr_type_key, rpr_action,
130
- rpr_effect, rpr_subject_kind, rpr_subject_value, rpr_field, rpr_operator, rpr_value)
131
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
168
+ rpr_effect, rpr_subject_kind, rpr_subject_value, rpr_field, rpr_operator, rpr_value,
169
+ rpr_subject_role_uuids)
170
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
132
171
  (0, node_crypto_1.randomUUID)(), // rpr_uuid — a fresh per-row id
133
172
  policyUuid, // rpr_policy_uuid — the SHARED group id
134
173
  tenantId, // rpr_tenant_uuid
135
174
  policy.typeKey, // rpr_type_key
136
175
  policy.action, // rpr_action
137
176
  policy.effect, // rpr_effect
138
- 'everyone', // rpr_subject_kind — v1 mapping (no role subject)
139
- null, // rpr_subject_value
177
+ subjectKind, // rpr_subject_kind — everyone | roles | except_roles
178
+ null, // rpr_subject_value (legacy single-role kind is never written)
140
179
  row.field, // rpr_field
141
180
  row.operator, // rpr_operator
142
181
  row.value, // rpr_value
182
+ subjectRoleUuids, // rpr_subject_role_uuids — JSON array, or NULL for everyone
143
183
  ]);
144
184
  }
145
185
  return { policyId: policyUuid, tenantId, policy };
@@ -150,7 +190,8 @@ class MariaDbPolicyStore {
150
190
  * (its conditions = its rows, in row order). Returns `[]` when none exist (NORMAL).
151
191
  */
152
192
  async listPolicies(typeKey, tenantId) {
153
- const rows = (await this.db.query(`SELECT rpr_policy_uuid, rpr_action, rpr_effect, rpr_field, rpr_operator, rpr_value
193
+ const rows = (await this.db.query(`SELECT rpr_policy_uuid, rpr_action, rpr_effect, rpr_subject_kind, rpr_subject_value,
194
+ rpr_subject_role_uuids, rpr_field, rpr_operator, rpr_value
154
195
  FROM \`${this.schema}\`.\`record_permission_rule\`
155
196
  WHERE rpr_type_key = ?
156
197
  AND rpr_tenant_uuid = ?
@@ -191,6 +232,7 @@ class MariaDbPolicyStore {
191
232
  action: first.rpr_action ?? '',
192
233
  effect: first.rpr_effect === 'deny' ? 'deny' : 'allow',
193
234
  conditions,
235
+ subject: subjectOf(first),
194
236
  },
195
237
  });
196
238
  }
@@ -38,7 +38,9 @@
38
38
  * 14-operator {@link import('@astram/core').PolicyOperator} model (unified with
39
39
  * the guided policy builder, Task 0.2): `eq/ne` (dual-accept legacy
40
40
  * `equals`/`not_equals`), `in/not_in`, `gt/lt/gte/lte`, `contains/not_contains`,
41
- * `is_null/is_not_null`, `is_owner/is_not_owner`. An unknown operator makes the
41
+ * `is_null/is_not_null`, `is_owner/is_not_owner`, plus the principal-relative
42
+ * `in_my_departments/not_in_my_departments` (department-scoped policies: the viewer's
43
+ * department codes, read lazily once per evaluate). An unknown operator makes the
42
44
  * rule NOT match (fail-closed, never a spurious allow) — see `conditionHolds`
43
45
  * below for the exact per-operator semantics and the documented edge-case choices.
44
46
  */
@@ -56,9 +58,25 @@ export interface RuleQueryable {
56
58
  export declare class MariaDbRecordPermissionRuleAdapter implements RecordPermissionRulePort {
57
59
  private readonly db;
58
60
  private readonly schema;
61
+ private readonly appSchema;
62
+ private readonly now;
59
63
  constructor(db: RuleQueryable, opts?: {
60
64
  schema?: string;
65
+ /**
66
+ * The org (`<app>`) database the viewer-department reader joins (memberships, postings,
67
+ * departments). Checked; absent ⇒ resolved from `SHIELD_DB_NAMESPACE` here, once.
68
+ */
69
+ appSchema?: string;
70
+ /** Clock for the posting in-effect window (epoch ms). */
71
+ now?: () => number;
61
72
  });
73
+ /**
74
+ * The viewer department set `D` for this evaluation (spec §5 C, D3):
75
+ * - root and a record reached outside the principal's subtree (cross-tenant grant) ⇒ empty;
76
+ * - otherwise the codes of the principal's in-effect postings in `principal.tenantId`.
77
+ * A reader failure throws {@link AuthorizationUnavailableError} (fail closed).
78
+ */
79
+ private departmentsFor;
62
80
  evaluate(input: RulePermitInput): Promise<RulePermit>;
63
81
  }
64
82
  //# sourceMappingURL=mariadb-record-rule-adapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mariadb-record-rule-adapter.d.ts","sourceRoot":"","sources":["../../src/authz/mariadb-record-rule-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAI1F,qFAAqF;AACrF,eAAO,MAAM,uBAAuB,eAAoC,CAAC;AAEzE,oFAAoF;AACpF,MAAM,WAAW,aAAa;IAC5B,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACnE;AAmLD;;;GAGG;AACH,qBAAa,kCAAmC,YAAW,wBAAwB;IACjF,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAgB;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;gBAEpB,EAAE,EAAE,aAAa,EAAE,IAAI,GAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO;IAOvD,QAAQ,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,UAAU,CAAC;CAuE5D"}
1
+ {"version":3,"file":"mariadb-record-rule-adapter.d.ts","sourceRoot":"","sources":["../../src/authz/mariadb-record-rule-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAU1F,qFAAqF;AACrF,eAAO,MAAM,uBAAuB,eAAoC,CAAC;AAEzE,oFAAoF;AACpF,MAAM,WAAW,aAAa;IAC5B,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACnE;AAmMD;;;GAGG;AACH,qBAAa,kCAAmC,YAAW,wBAAwB;IACjF,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAgB;IACnC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;gBAGjC,EAAE,EAAE,aAAa,EACjB,IAAI,GAAE;QACJ,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB;;;WAGG;QACH,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,yDAAyD;QACzD,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;KACf;IAaR;;;;;OAKG;YACW,cAAc;IAoBtB,QAAQ,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,UAAU,CAAC;CAmF5D"}
@@ -39,7 +39,9 @@
39
39
  * 14-operator {@link import('@astram/core').PolicyOperator} model (unified with
40
40
  * the guided policy builder, Task 0.2): `eq/ne` (dual-accept legacy
41
41
  * `equals`/`not_equals`), `in/not_in`, `gt/lt/gte/lte`, `contains/not_contains`,
42
- * `is_null/is_not_null`, `is_owner/is_not_owner`. An unknown operator makes the
42
+ * `is_null/is_not_null`, `is_owner/is_not_owner`, plus the principal-relative
43
+ * `in_my_departments/not_in_my_departments` (department-scoped policies: the viewer's
44
+ * department codes, read lazily once per evaluate). An unknown operator makes the
43
45
  * rule NOT match (fail-closed, never a spurious allow) — see `conditionHolds`
44
46
  * below for the exact per-operator semantics and the documented edge-case choices.
45
47
  */
@@ -47,18 +49,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
47
49
  exports.MariaDbRecordPermissionRuleAdapter = exports.SHIELD_RECORD_RULE_PORT = void 0;
48
50
  const core_1 = require("@astram/core");
49
51
  const framework_schema_names_js_1 = require("../config/framework-schema-names.js");
52
+ const rule_subject_js_1 = require("./rule-subject.js");
53
+ const viewer_departments_js_1 = require("./viewer-departments.js");
50
54
  /** The DI token the adapter is bound under (parity with the session store token). */
51
55
  exports.SHIELD_RECORD_RULE_PORT = Symbol('SHIELD_RECORD_RULE_PORT');
52
- /** Whether the rule's subject matches this principal (role membership / everyone). */
53
- function subjectMatches(row, input) {
54
- const kind = row.rpr_subject_kind;
55
- if (kind === 'everyone')
56
- return true;
57
- if (kind === 'role') {
58
- return (row.rpr_subject_value !== null && input.principal.roleIds.includes(row.rpr_subject_value));
59
- }
60
- // Unknown subject kind → does NOT match (fail-closed).
61
- return false;
56
+ /** The department operators (department-scoped policies, spec §5 C). */
57
+ const DEPARTMENT_OPERATORS = new Set([
58
+ 'in_my_departments',
59
+ 'not_in_my_departments',
60
+ ]);
61
+ /**
62
+ * `in_my_departments`: the attribute is a non-empty string AND is (exactly, `===`) one of the
63
+ * viewer's department codes `D`. `not_in_my_departments` is its plain negation, so it holds on
64
+ * an absent / null / empty attribute and on every row when `D` is empty (deny-only, D2).
65
+ */
66
+ function inDepartments(actual, departments) {
67
+ return typeof actual === 'string' && actual !== '' && departments.includes(actual);
62
68
  }
63
69
  /** Resolve a rule value token against the request (e.g. `$actor.id`) or use the literal. */
64
70
  function resolveValue(raw, input) {
@@ -140,7 +146,7 @@ function orderedCompare(actual, expected) {
140
146
  * → does NOT hold for either (fail-closed — no owner to compare, and an
141
147
  * empty attribute must never "match" an empty `principal.id`).
142
148
  */
143
- function conditionHolds(row, input) {
149
+ function conditionHolds(row, input, departments) {
144
150
  if (row.rpr_field === null)
145
151
  return true; // unconditional
146
152
  const actual = fieldValue(row.rpr_field, input);
@@ -208,6 +214,15 @@ function conditionHolds(row, input) {
208
214
  // absent OR empty-string → does NOT hold (fail-closed; same hardening,
209
215
  // mirrored for the negative ownership operator).
210
216
  return isPresent(actual) && actual !== '' && actual !== input.principal.id;
217
+ case 'in_my_departments':
218
+ // `departments` is loaded by `evaluate` before any group with a department operator is
219
+ // evaluated; `null` here would be a wiring bug → the condition does not hold (and for
220
+ // the negative operator see below).
221
+ return departments !== null && inDepartments(actual, departments);
222
+ case 'not_in_my_departments':
223
+ // NOT `in_my_departments` (deny-only, D2). An unloaded set (`null`, a wiring bug) is
224
+ // treated as the empty set: the condition holds, so a deny applies (fail closed).
225
+ return departments === null || !inDepartments(actual, departments);
211
226
  default:
212
227
  return false; // unknown operator → fail-closed (rule does not apply)
213
228
  }
@@ -219,11 +234,36 @@ function conditionHolds(row, input) {
219
234
  class MariaDbRecordPermissionRuleAdapter {
220
235
  db;
221
236
  schema;
237
+ appSchema;
238
+ now;
222
239
  constructor(db, opts = {}) {
223
240
  this.db = db;
224
241
  // The `record_permission_rule` database: `opts.schema` (checked), else the resolved authz
225
242
  // name (configurable-framework-db), fixed at construction.
226
243
  this.schema = (0, framework_schema_names_js_1.authzSchemaAtConstruction)(opts.schema);
244
+ this.appSchema =
245
+ opts.appSchema !== undefined
246
+ ? (0, core_1.assertSchemaName)(opts.appSchema, 'opts.appSchema')
247
+ : (0, core_1.resolveFrameworkSchemas)(process.env).app;
248
+ this.now = opts.now ?? Date.now;
249
+ }
250
+ /**
251
+ * The viewer department set `D` for this evaluation (spec §5 C, D3):
252
+ * - root and a record reached outside the principal's subtree (cross-tenant grant) ⇒ empty;
253
+ * - otherwise the codes of the principal's in-effect postings in `principal.tenantId`.
254
+ * A reader failure throws {@link AuthorizationUnavailableError} (fail closed).
255
+ */
256
+ async departmentsFor(input) {
257
+ const { principal, resource } = input;
258
+ if (principal.isRoot)
259
+ return [];
260
+ const recordTenant = resource.tenantId;
261
+ if (recordTenant !== undefined &&
262
+ recordTenant !== null &&
263
+ !principal.scopeSubtreeNodeIds.includes(recordTenant)) {
264
+ return [];
265
+ }
266
+ return (0, viewer_departments_js_1.readViewerDepartmentCodes)(this.db, this.appSchema, principal.id, principal.tenantId, this.now());
227
267
  }
228
268
  async evaluate(input) {
229
269
  // tenant scoping: match rows for the resource's tenant OR the global/system baseline
@@ -231,7 +271,7 @@ class MariaDbRecordPermissionRuleAdapter {
231
271
  const tenantId = input.resource.tenantId ?? input.principal.tenantId;
232
272
  let rows;
233
273
  try {
234
- rows = (await this.db.query(`SELECT rpr_policy_uuid, rpr_effect, rpr_subject_kind, rpr_subject_value, rpr_field, rpr_operator, rpr_value
274
+ rows = (await this.db.query(`SELECT rpr_policy_uuid, rpr_effect, rpr_subject_kind, rpr_subject_value, rpr_subject_role_uuids, rpr_field, rpr_operator, rpr_value
235
275
  FROM \`${this.schema}\`.\`record_permission_rule\`
236
276
  WHERE rpr_type_key = ?
237
277
  AND (rpr_tenant_uuid = ? OR rpr_tenant_uuid IS NULL)
@@ -266,6 +306,10 @@ class MariaDbRecordPermissionRuleAdapter {
266
306
  }
267
307
  let allow = false;
268
308
  let explicitDeny = false;
309
+ // The viewer department set, read LAZILY: at most once per evaluate, and only when a
310
+ // subject-matching group uses a department operator (a request without such a policy
311
+ // pays no extra query — spec §5 B, §12 case 11).
312
+ let departments = null;
269
313
  for (const groupRows of groups.values()) {
270
314
  const head = groupRows[0];
271
315
  if (head === undefined)
@@ -274,7 +318,14 @@ class MariaDbRecordPermissionRuleAdapter {
274
318
  // Its effect is consistent across rows (the store writes one effect per policy);
275
319
  // we take the group's effect from its first row and ignore any anomalous mix
276
320
  // fail-closed (a non-'allow'/'deny' effect contributes nothing).
277
- const applies = groupRows.every((row) => subjectMatches(row, input) && conditionHolds(row, input));
321
+ if (!groupRows.every((row) => (0, rule_subject_js_1.subjectMatches)(row, input.principal.roleIds)))
322
+ continue;
323
+ if (departments === null &&
324
+ groupRows.some((row) => row.rpr_field !== null && DEPARTMENT_OPERATORS.has(row.rpr_operator ?? ''))) {
325
+ departments = await this.departmentsFor(input); // throws on outage (fail closed)
326
+ }
327
+ const set = departments;
328
+ const applies = groupRows.every((row) => conditionHolds(row, input, set));
278
329
  if (!applies)
279
330
  continue;
280
331
  const effect = head.rpr_effect;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * One subject matcher for `record_permission_rule` rows, shared by the single-record adapter
3
+ * (`decide()` / get) and the list-scope adapter (list / aggregate) so the two paths can never
4
+ * disagree on who a rule applies to (department-scoped policies, spec §5 C/D, D4; Shield #8).
5
+ *
6
+ * Kinds (fixed list, spec §10):
7
+ * - `everyone` — every principal (the pre-existing default);
8
+ * - `role` — LEGACY single-role row: `rpr_subject_value` is one role uuid;
9
+ * - `roles` — the principal holds at least one role of `rpr_subject_role_uuids`;
10
+ * - `except_roles` — the principal holds none of them.
11
+ *
12
+ * FAIL CLOSED (Shield #1): an unknown kind, or a `roles` / `except_roles` row whose JSON is
13
+ * malformed, empty, not an array or holds a non-string / empty entry, never matches. For an
14
+ * `except_roles` deny this loses the deny for that group; that is reachable only by a direct DB
15
+ * write (the store never writes it) and is pinned by a unit test (spec §13).
16
+ */
17
+ /** The subject columns of a rule row. The JSON column may arrive as a string or parsed. */
18
+ export interface RuleSubjectColumns {
19
+ readonly rpr_subject_kind: string;
20
+ readonly rpr_subject_value: string | null;
21
+ readonly rpr_subject_role_uuids?: unknown;
22
+ }
23
+ /**
24
+ * The role ids of a `roles` / `except_roles` row, or `null` when the stored value is not a
25
+ * non-empty array of non-empty strings. The `mariadb` driver returns a JSON column either as
26
+ * its text or as the parsed value (depending on server type info / `autoJsonMap`), so both are
27
+ * accepted.
28
+ */
29
+ export declare function parseSubjectRoleIds(raw: unknown): readonly string[] | null;
30
+ /** Whether the rule's subject applies to a principal holding `roleIds`. */
31
+ export declare function subjectMatches(row: RuleSubjectColumns, roleIds: readonly string[]): boolean;
32
+ //# sourceMappingURL=rule-subject.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rule-subject.d.ts","sourceRoot":"","sources":["../../src/authz/rule-subject.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,2FAA2F;AAC3F,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,QAAQ,CAAC,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAC3C;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,SAAS,MAAM,EAAE,GAAG,IAAI,CAoB1E;AAED,2EAA2E;AAC3E,wBAAgB,cAAc,CAAC,GAAG,EAAE,kBAAkB,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAiB3F"}
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ /**
3
+ * One subject matcher for `record_permission_rule` rows, shared by the single-record adapter
4
+ * (`decide()` / get) and the list-scope adapter (list / aggregate) so the two paths can never
5
+ * disagree on who a rule applies to (department-scoped policies, spec §5 C/D, D4; Shield #8).
6
+ *
7
+ * Kinds (fixed list, spec §10):
8
+ * - `everyone` — every principal (the pre-existing default);
9
+ * - `role` — LEGACY single-role row: `rpr_subject_value` is one role uuid;
10
+ * - `roles` — the principal holds at least one role of `rpr_subject_role_uuids`;
11
+ * - `except_roles` — the principal holds none of them.
12
+ *
13
+ * FAIL CLOSED (Shield #1): an unknown kind, or a `roles` / `except_roles` row whose JSON is
14
+ * malformed, empty, not an array or holds a non-string / empty entry, never matches. For an
15
+ * `except_roles` deny this loses the deny for that group; that is reachable only by a direct DB
16
+ * write (the store never writes it) and is pinned by a unit test (spec §13).
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.parseSubjectRoleIds = parseSubjectRoleIds;
20
+ exports.subjectMatches = subjectMatches;
21
+ /**
22
+ * The role ids of a `roles` / `except_roles` row, or `null` when the stored value is not a
23
+ * non-empty array of non-empty strings. The `mariadb` driver returns a JSON column either as
24
+ * its text or as the parsed value (depending on server type info / `autoJsonMap`), so both are
25
+ * accepted.
26
+ */
27
+ function parseSubjectRoleIds(raw) {
28
+ let value = raw;
29
+ if (typeof value === 'string') {
30
+ try {
31
+ value = JSON.parse(value);
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ else if (value instanceof Uint8Array) {
38
+ try {
39
+ value = JSON.parse(Buffer.from(value).toString('utf8'));
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ if (!Array.isArray(value) || value.length === 0)
46
+ return null;
47
+ for (const id of value) {
48
+ if (typeof id !== 'string' || id.length === 0)
49
+ return null;
50
+ }
51
+ return value;
52
+ }
53
+ /** Whether the rule's subject applies to a principal holding `roleIds`. */
54
+ function subjectMatches(row, roleIds) {
55
+ switch (row.rpr_subject_kind) {
56
+ case 'everyone':
57
+ return true;
58
+ case 'role':
59
+ return row.rpr_subject_value !== null && roleIds.includes(row.rpr_subject_value);
60
+ case 'roles': {
61
+ const listed = parseSubjectRoleIds(row.rpr_subject_role_uuids);
62
+ return listed !== null && listed.some((id) => roleIds.includes(id));
63
+ }
64
+ case 'except_roles': {
65
+ const listed = parseSubjectRoleIds(row.rpr_subject_role_uuids);
66
+ return listed !== null && !listed.some((id) => roleIds.includes(id));
67
+ }
68
+ default:
69
+ return false; // unknown subject kind → does NOT match (fail-closed)
70
+ }
71
+ }