@zudojs/permissions 1.1.0 → 1.3.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 (45) hide show
  1. package/README.md +120 -31
  2. package/dist/ability/ability.core.js +4 -24
  3. package/dist/cache/cache.actorDigest.d.ts +26 -0
  4. package/dist/cache/cache.actorDigest.js +90 -0
  5. package/dist/cache/cache.core.d.ts +7 -1
  6. package/dist/cache/cache.core.js +9 -2
  7. package/dist/cache/index.d.ts +1 -0
  8. package/dist/cache/index.js +1 -0
  9. package/dist/evaluator/authorizationEngine.d.ts +58 -5
  10. package/dist/evaluator/authorizationEngine.js +76 -68
  11. package/dist/evaluator/engineSupport/authorizationEngine.validation.d.ts +37 -0
  12. package/dist/evaluator/engineSupport/authorizationEngine.validation.js +90 -0
  13. package/dist/evaluator/engineSupport/evaluator.cacheKey.d.ts +28 -0
  14. package/dist/evaluator/engineSupport/evaluator.cacheKey.js +70 -0
  15. package/dist/evaluator/engineSupport/evaluator.observed.d.ts +18 -0
  16. package/dist/evaluator/engineSupport/evaluator.observed.js +49 -0
  17. package/dist/evaluator/engineSupport/index.d.ts +10 -0
  18. package/dist/evaluator/engineSupport/index.js +10 -0
  19. package/dist/evaluator/evaluator.core.js +19 -37
  20. package/dist/evaluator/evaluator.pipeline.d.ts +11 -0
  21. package/dist/evaluator/evaluator.pipeline.js +25 -3
  22. package/dist/http/httpMiddleware.core.d.ts +15 -5
  23. package/dist/http/httpMiddleware.core.js +18 -4
  24. package/dist/http/httpResource.helper.d.ts +30 -0
  25. package/dist/http/httpResource.helper.js +32 -0
  26. package/dist/http/httpTypes.d.ts +17 -4
  27. package/dist/http/index.d.ts +7 -5
  28. package/dist/http/index.js +6 -4
  29. package/dist/permission/index.d.ts +1 -1
  30. package/dist/permission/index.js +1 -1
  31. package/dist/permission/permission.core.d.ts +12 -0
  32. package/dist/permission/permission.core.js +20 -1
  33. package/dist/permission/permissionRegistry.d.ts +14 -1
  34. package/dist/permission/permissionRegistry.js +15 -2
  35. package/dist/policy/policyRegistry.d.ts +12 -0
  36. package/dist/policy/policyRegistry.js +17 -1
  37. package/dist/role/roleRegistry.d.ts +9 -0
  38. package/dist/role/roleRegistry.js +19 -1
  39. package/dist/rule/rule.core.d.ts +14 -22
  40. package/dist/rule/rule.core.js +49 -86
  41. package/dist/rule/rule.pattern.d.ts +44 -0
  42. package/dist/rule/rule.pattern.js +72 -0
  43. package/dist/utils/utils.notifier.d.ts +19 -0
  44. package/dist/utils/utils.notifier.js +31 -0
  45. package/package.json +2 -10
@@ -5,10 +5,11 @@
5
5
  */
6
6
  import { evaluate, evaluateWithTrace } from "./evaluator.core.js";
7
7
  import { createAbility } from "../ability/ability.core.js";
8
- import { PermissionDeniedError, InvalidRoleError, } from "../permissionErrors/index.js";
9
- import { isValidPermission } from "../permission/permission.core.js";
8
+ import { PermissionDeniedError } from "../permissionErrors/index.js";
10
9
  import { memoizeRoleLookup } from "../role/roleHierarchy.js";
11
10
  import { freezeRoleDefinition } from "../role/roleRegistry.js";
11
+ import { validatePolicy, validateRole, validateRoles, validateRule, } from "./engineSupport/index.js";
12
+ import { observed } from "./engineSupport/index.js";
12
13
  function isRoleSource(roles) {
13
14
  return (roles !== undefined &&
14
15
  !Array.isArray(roles) &&
@@ -19,35 +20,20 @@ function isPolicySource(policies) {
19
20
  !Array.isArray(policies) &&
20
21
  typeof policies.names === "function");
21
22
  }
22
- /** Rejects a role whose grants could never match. */
23
- function validateRole(role) {
24
- if (!role.name || role.name.trim() === "") {
25
- throw new InvalidRoleError("Role name cannot be empty");
26
- }
27
- for (const permission of role.permissions) {
28
- if (!isValidPermission(permission)) {
29
- // A malformed grant can never match, so it is a silent no-op unless
30
- // it is rejected here.
31
- throw new InvalidRoleError(`Role "${role.name}" grants "${permission}", which is not a valid ` +
32
- `"resource:action" permission`);
33
- }
34
- }
35
- }
36
- function validateRoles(roles) {
37
- const seen = new Set();
38
- for (const role of roles) {
39
- validateRole(role);
40
- if (seen.has(role.name)) {
41
- throw new InvalidRoleError(`Role "${role.name}" is defined more than once`);
42
- }
43
- seen.add(role.name);
44
- }
23
+ function isImpliedPermissionSource(source) {
24
+ return (source !== undefined &&
25
+ typeof source !== "function" &&
26
+ typeof source.expandImplied === "function");
45
27
  }
46
28
  /**
47
29
  * Create a permission engine.
48
30
  */
49
31
  export function createPermissionEngine(options) {
50
32
  const validateConfiguration = options?.validateConfiguration ?? true;
33
+ if (validateConfiguration) {
34
+ for (const rule of options?.rules ?? [])
35
+ validateRule(rule);
36
+ }
51
37
  let roleLookup;
52
38
  let invalidateRoleCache;
53
39
  if (isRoleSource(options?.roles)) {
@@ -81,13 +67,70 @@ export function createPermissionEngine(options) {
81
67
  const policyList = policySource
82
68
  ? undefined
83
69
  : (options?.policies ?? []);
70
+ if (validateConfiguration)
71
+ policyList?.forEach(validatePolicy);
72
+ // A policy source is read lazily, so its validation is lazy too. Each
73
+ // definition is checked once; a malformed one makes the check throw, which
74
+ // never reads as an allow.
75
+ const validatedPolicies = new WeakSet();
84
76
  const resolvePolicies = () => {
85
77
  if (!policySource)
86
78
  return policyList ?? [];
87
79
  return policySource
88
80
  .names()
89
81
  .map((name) => policySource.get(name))
90
- .filter((policy) => policy !== undefined);
82
+ .filter((policy) => policy !== undefined)
83
+ .map((policy) => {
84
+ if (validateConfiguration && !validatedPolicies.has(policy)) {
85
+ validatePolicy(policy);
86
+ validatedPolicies.add(policy);
87
+ }
88
+ return policy;
89
+ });
90
+ };
91
+ // Every change to the configuration bumps the generation, which is part
92
+ // of every decision-cache key: an entry written under an older role or
93
+ // policy set can no longer be found, whatever cache adapter is in use.
94
+ let generation = 0;
95
+ const invalidateConfiguration = () => {
96
+ generation += 1;
97
+ invalidateRoleCache();
98
+ const cleared = options?.cache?.clear?.();
99
+ cleared?.catch((error) => {
100
+ options?.onError?.(error, "PermissionCache.clear");
101
+ });
102
+ };
103
+ if (isRoleSource(options?.roles)) {
104
+ options.roles.subscribe?.(invalidateConfiguration);
105
+ }
106
+ policySource?.subscribe?.(invalidateConfiguration);
107
+ // The third registry the README wires in. Without this, revoking an
108
+ // implication left every decision it granted in the cache for the full TTL
109
+ // — `skipCache: true` said "deny" while `can()` kept saying "allow".
110
+ const impliedSource = isImpliedPermissionSource(options?.expandImplied)
111
+ ? options.expandImplied
112
+ : undefined;
113
+ const expandImplied = impliedSource
114
+ ? (permission) => impliedSource.expandImplied(permission)
115
+ : options?.expandImplied;
116
+ const impliedWatched = impliedSource?.subscribe?.(invalidateConfiguration) !== undefined;
117
+ // Two inputs the cache key cannot describe. An implication source that
118
+ // cannot announce a change, and a resolver reading state the engine does
119
+ // not own, both make a cached allow outlive the grant behind it — so the
120
+ // decision is not cached at all unless the caller closes the gap.
121
+ const impliedUnwatched = expandImplied !== undefined && !impliedWatched;
122
+ const resolverConfigured = options?.permissionResolver !== undefined ||
123
+ options?.roleResolver !== undefined;
124
+ const resolverCacheKey = options?.resolverCacheKey;
125
+ const cacheScope = (actor) => {
126
+ if (impliedUnwatched)
127
+ return undefined;
128
+ if (!resolverConfigured)
129
+ return `g${generation}`;
130
+ if (!resolverCacheKey)
131
+ return undefined;
132
+ const scope = resolverCacheKey(actor);
133
+ return scope === undefined ? undefined : `g${generation}|r${scope}`;
91
134
  };
92
135
  // One live view over the configuration. `policies` is a getter so a
93
136
  // registry-backed engine re-reads the registry on every evaluation — an
@@ -106,40 +149,15 @@ export function createPermissionEngine(options) {
106
149
  cacheTtlMs: options?.cacheTtlMs,
107
150
  permissionResolver: options?.permissionResolver,
108
151
  roleResolver: options?.roleResolver,
109
- expandImplied: options?.expandImplied,
152
+ expandImplied,
110
153
  onError: options?.onError,
154
+ cacheScope,
111
155
  };
112
156
  const evaluatorOptions = () => liveOptions;
113
157
  const emitter = options?.emitter;
114
- /**
115
- * Runs a check and emits an audit event whichever way it ends — including
116
- * when it throws. An authorization trail that records only the successful
117
- * paths is not a trail.
118
- */
119
- async function runCheck(actor, permission, resource, authOptions) {
120
- const start = performance.now();
121
- let decision;
122
- let failure;
123
- try {
124
- decision = await evaluate(actor, permission, resource, evaluatorOptions(), authOptions);
125
- return decision;
126
- }
127
- catch (error) {
128
- failure = error;
129
- throw error;
130
- }
131
- finally {
132
- emitter?.emit({
133
- actorId: actor.id,
134
- permission,
135
- resourceType: resourceTypeOf(resource),
136
- allowed: decision?.allowed ?? false,
137
- reason: decision?.reason ??
138
- (failure instanceof Error ? `error:${failure.name}` : undefined),
139
- durationMs: performance.now() - start,
140
- errored: failure !== undefined,
141
- });
142
- }
158
+ /** Runs a check and emits an audit event whichever way it ends. */
159
+ function runCheck(actor, permission, resource, authOptions) {
160
+ return observed(emitter, actor, permission, resource, () => evaluate(actor, permission, resource, evaluatorOptions(), authOptions), (decision) => decision);
143
161
  }
144
162
  return {
145
163
  async can(actor, permission, resource, authOptions) {
@@ -163,7 +181,7 @@ export function createPermissionEngine(options) {
163
181
  }
164
182
  },
165
183
  async explain(actor, permission, resource, authOptions) {
166
- return evaluateWithTrace(actor, permission, resource, evaluatorOptions(), authOptions);
184
+ return observed(emitter, actor, permission, resource, () => evaluateWithTrace(actor, permission, resource, evaluatorOptions(), authOptions), (result) => result.decision);
167
185
  },
168
186
  createAbility(actor) {
169
187
  return createAbility(actor, evaluatorOptions(), emitter);
@@ -172,18 +190,8 @@ export function createPermissionEngine(options) {
172
190
  await options?.cache?.invalidateActor(actorId);
173
191
  },
174
192
  invalidateRoles() {
175
- invalidateRoleCache();
193
+ invalidateConfiguration();
176
194
  },
177
195
  };
178
196
  }
179
- /** Best-effort resource type for an audit event. */
180
- function resourceTypeOf(resource) {
181
- if (typeof resource !== "object" || resource === null)
182
- return undefined;
183
- const record = resource;
184
- if (typeof record.type === "string")
185
- return record.type;
186
- const name = record.constructor?.name;
187
- return name && name !== "Object" ? name : undefined;
188
- }
189
197
  //# sourceMappingURL=authorizationEngine.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Configuration validation for the authorization engine.
3
+ *
4
+ * A malformed pattern can never match. In a grant that is a silent no-op; in
5
+ * a denying policy or a deny rule it is a restriction that fails open. The
6
+ * same pattern therefore has to be rejected wherever it can be written, not
7
+ * only in a role's grant list.
8
+ *
9
+ * @module evaluator/authorizationEngine.validation
10
+ */
11
+ import type { PermissionPolicyDefinition, PermissionRule, RoleDefinition } from "../../permissionTypes/index.js";
12
+ /**
13
+ * The first `resource:action` pair a rule names that is not a valid
14
+ * permission pattern, or `undefined` when every pair is valid.
15
+ */
16
+ export declare function invalidRulePattern(rule: PermissionRule): string | undefined;
17
+ /**
18
+ * Reject a rule whose resource or action could never match.
19
+ *
20
+ * @throws {InvalidPermissionError} naming the offending pair.
21
+ */
22
+ export declare function validateRule(rule: PermissionRule): void;
23
+ /**
24
+ * Reject a policy scoped to a pattern that could never match.
25
+ *
26
+ * @throws {InvalidPermissionError} naming the offending pattern.
27
+ */
28
+ export declare function validatePolicy(policy: PermissionPolicyDefinition): void;
29
+ /**
30
+ * Reject a role whose grants or rules could never match.
31
+ *
32
+ * @throws {InvalidRoleError} naming the role and the offending pattern.
33
+ */
34
+ export declare function validateRole(role: RoleDefinition): void;
35
+ /** Validate a role list, rejecting duplicates as well. */
36
+ export declare function validateRoles(roles: readonly RoleDefinition[]): void;
37
+ //# sourceMappingURL=authorizationEngine.validation.d.ts.map
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Configuration validation for the authorization engine.
3
+ *
4
+ * A malformed pattern can never match. In a grant that is a silent no-op; in
5
+ * a denying policy or a deny rule it is a restriction that fails open. The
6
+ * same pattern therefore has to be rejected wherever it can be written, not
7
+ * only in a role's grant list.
8
+ *
9
+ * @module evaluator/authorizationEngine.validation
10
+ */
11
+ import { InvalidPermissionError, InvalidRoleError, } from "../../permissionErrors/index.js";
12
+ import { isValidPermission } from "../../permission/permission.core.js";
13
+ function patterns(value) {
14
+ return Array.isArray(value) ? value : [value];
15
+ }
16
+ /**
17
+ * The first `resource:action` pair a rule names that is not a valid
18
+ * permission pattern, or `undefined` when every pair is valid.
19
+ */
20
+ export function invalidRulePattern(rule) {
21
+ const resources = patterns(rule.resource);
22
+ const actions = patterns(rule.action);
23
+ if (resources.length === 0 || actions.length === 0) {
24
+ return `${resources.join(",")}:${actions.join(",")}`;
25
+ }
26
+ for (const resource of resources) {
27
+ for (const action of actions) {
28
+ const pair = `${String(resource)}:${String(action)}`;
29
+ if (!isValidPermission(pair))
30
+ return pair;
31
+ }
32
+ }
33
+ return undefined;
34
+ }
35
+ /**
36
+ * Reject a rule whose resource or action could never match.
37
+ *
38
+ * @throws {InvalidPermissionError} naming the offending pair.
39
+ */
40
+ export function validateRule(rule) {
41
+ const invalid = invalidRulePattern(rule);
42
+ if (invalid !== undefined)
43
+ throw new InvalidPermissionError(invalid);
44
+ }
45
+ /**
46
+ * Reject a policy scoped to a pattern that could never match.
47
+ *
48
+ * @throws {InvalidPermissionError} naming the offending pattern.
49
+ */
50
+ export function validatePolicy(policy) {
51
+ for (const pattern of policy.permissions) {
52
+ if (!isValidPermission(pattern))
53
+ throw new InvalidPermissionError(pattern);
54
+ }
55
+ }
56
+ /**
57
+ * Reject a role whose grants or rules could never match.
58
+ *
59
+ * @throws {InvalidRoleError} naming the role and the offending pattern.
60
+ */
61
+ export function validateRole(role) {
62
+ if (!role.name || role.name.trim() === "") {
63
+ throw new InvalidRoleError("Role name cannot be empty");
64
+ }
65
+ for (const permission of role.permissions) {
66
+ if (!isValidPermission(permission)) {
67
+ throw new InvalidRoleError(`Role "${role.name}" grants "${permission}", which is not a valid ` +
68
+ `"resource:action" permission`);
69
+ }
70
+ }
71
+ for (const rule of role.rules ?? []) {
72
+ const invalid = invalidRulePattern(rule);
73
+ if (invalid !== undefined) {
74
+ throw new InvalidRoleError(`Role "${role.name}" has a rule on "${invalid}", which is not a valid ` +
75
+ `"resource:action" pattern`);
76
+ }
77
+ }
78
+ }
79
+ /** Validate a role list, rejecting duplicates as well. */
80
+ export function validateRoles(roles) {
81
+ const seen = new Set();
82
+ for (const role of roles) {
83
+ validateRole(role);
84
+ if (seen.has(role.name)) {
85
+ throw new InvalidRoleError(`Role "${role.name}" is defined more than once`);
86
+ }
87
+ seen.add(role.name);
88
+ }
89
+ }
90
+ //# sourceMappingURL=authorizationEngine.validation.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Decision cache key for one evaluation.
3
+ *
4
+ * @module evaluator/evaluator.cacheKey
5
+ */
6
+ import type { AuthorizationOptions, PermissionActor } from "../../permissionTypes/index.js";
7
+ import type { EvaluatorOptions } from "../evaluator.pipeline.js";
8
+ /**
9
+ * The cache key for a decision, or `undefined` when it must not be cached.
10
+ *
11
+ * Only a decision the key can describe completely may be cached:
12
+ *
13
+ * - A resource with no derivable id would collapse the key to
14
+ * `actor|permission`, so an allow for `{ ownerId: "ada" }` would answer for
15
+ * `{ ownerId: "bob" }`.
16
+ * - Request metadata is not in the key, and `tenantIsolation()` reads the
17
+ * tenant from it.
18
+ * - The actor's roles, permissions, type and any other field it carries are
19
+ * in the key as a digest; an actor the digest cannot describe is not cached.
20
+ * - The engine's configuration generation is in the key, so a role removed
21
+ * from a live registry cannot be served from an entry written before.
22
+ * - An external resolver reads state the key knows nothing about, so a
23
+ * resolver-backed engine is uncacheable unless it supplies
24
+ * `resolverCacheKey`. So is one whose implication source cannot announce a
25
+ * change.
26
+ */
27
+ export declare function decisionCacheKey(actor: PermissionActor, permissionStr: string, resource: unknown, options: EvaluatorOptions, authOptions?: AuthorizationOptions): string | undefined;
28
+ //# sourceMappingURL=evaluator.cacheKey.d.ts.map
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Decision cache key for one evaluation.
3
+ *
4
+ * @module evaluator/evaluator.cacheKey
5
+ */
6
+ import { permissionCacheKey } from "../../cache/cache.core.js";
7
+ import { actorCacheDigest } from "../../cache/cache.actorDigest.js";
8
+ /** True when the caller supplied request metadata the cache key cannot carry. */
9
+ function hasMetadata(metadata) {
10
+ if (!metadata)
11
+ return false;
12
+ if (metadata instanceof Map)
13
+ return metadata.size > 0;
14
+ return Object.keys(metadata).length > 0;
15
+ }
16
+ /** Best-effort resource identity for the cache key. */
17
+ function resourceIdOf(resource) {
18
+ if (typeof resource !== "object" || resource === null)
19
+ return undefined;
20
+ const id = resource.id;
21
+ if (typeof id === "string")
22
+ return id;
23
+ if (typeof id === "number")
24
+ return String(id);
25
+ return undefined;
26
+ }
27
+ /**
28
+ * The cache key for a decision, or `undefined` when it must not be cached.
29
+ *
30
+ * Only a decision the key can describe completely may be cached:
31
+ *
32
+ * - A resource with no derivable id would collapse the key to
33
+ * `actor|permission`, so an allow for `{ ownerId: "ada" }` would answer for
34
+ * `{ ownerId: "bob" }`.
35
+ * - Request metadata is not in the key, and `tenantIsolation()` reads the
36
+ * tenant from it.
37
+ * - The actor's roles, permissions, type and any other field it carries are
38
+ * in the key as a digest; an actor the digest cannot describe is not cached.
39
+ * - The engine's configuration generation is in the key, so a role removed
40
+ * from a live registry cannot be served from an entry written before.
41
+ * - An external resolver reads state the key knows nothing about, so a
42
+ * resolver-backed engine is uncacheable unless it supplies
43
+ * `resolverCacheKey`. So is one whose implication source cannot announce a
44
+ * change.
45
+ */
46
+ export function decisionCacheKey(actor, permissionStr, resource, options, authOptions) {
47
+ if (!options.cache || authOptions?.skipCache === true)
48
+ return undefined;
49
+ const resourceId = authOptions?.resourceId ?? resourceIdOf(resource);
50
+ if (resource !== undefined && resourceId === undefined)
51
+ return undefined;
52
+ if (hasMetadata(authOptions?.metadata))
53
+ return undefined;
54
+ const digest = actorCacheDigest(actor);
55
+ if (digest === undefined)
56
+ return undefined;
57
+ // An engine that cannot describe its own configuration for this actor
58
+ // returns `undefined` here — an external resolver with no
59
+ // `resolverCacheKey`, or an implication source that cannot announce a
60
+ // change. Both would otherwise keep answering from a revoked grant.
61
+ let generation = "";
62
+ if (options.cacheScope !== undefined) {
63
+ const scope = options.cacheScope(actor);
64
+ if (scope === undefined)
65
+ return undefined;
66
+ generation = scope;
67
+ }
68
+ return permissionCacheKey(actor.id, permissionStr, resourceId, `${generation}${digest}`);
69
+ }
70
+ //# sourceMappingURL=evaluator.cacheKey.js.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Audit-event wrapper shared by every path that makes a decision.
3
+ *
4
+ * @module evaluator/evaluator.observed
5
+ */
6
+ import type { PermissionActor, PermissionDecision } from "../../permissionTypes/index.js";
7
+ import type { PermissionEventEmitter } from "../../observability/observability.core.js";
8
+ /** Best-effort resource type for an audit event. */
9
+ export declare function resourceTypeOf(resource: unknown): string | undefined;
10
+ /**
11
+ * Run one authorization and emit an audit event whichever way it ends —
12
+ * including when it throws. An authorization trail that records only the
13
+ * successful paths is not a trail, and one that skips `explain()` misses
14
+ * decisions that are real: they run the same evaluation and write the same
15
+ * cache entries that later checks are served from.
16
+ */
17
+ export declare function observed<T>(emitter: PermissionEventEmitter | undefined, actor: PermissionActor, permission: string, resource: unknown, run: () => Promise<T>, decisionOf: (result: T) => PermissionDecision): Promise<T>;
18
+ //# sourceMappingURL=evaluator.observed.d.ts.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Audit-event wrapper shared by every path that makes a decision.
3
+ *
4
+ * @module evaluator/evaluator.observed
5
+ */
6
+ /** Best-effort resource type for an audit event. */
7
+ export function resourceTypeOf(resource) {
8
+ if (typeof resource !== "object" || resource === null)
9
+ return undefined;
10
+ const record = resource;
11
+ if (typeof record.type === "string")
12
+ return record.type;
13
+ const name = record.constructor?.name;
14
+ return name && name !== "Object" ? name : undefined;
15
+ }
16
+ /**
17
+ * Run one authorization and emit an audit event whichever way it ends —
18
+ * including when it throws. An authorization trail that records only the
19
+ * successful paths is not a trail, and one that skips `explain()` misses
20
+ * decisions that are real: they run the same evaluation and write the same
21
+ * cache entries that later checks are served from.
22
+ */
23
+ export async function observed(emitter, actor, permission, resource, run, decisionOf) {
24
+ const start = performance.now();
25
+ let decision;
26
+ let failure;
27
+ try {
28
+ const result = await run();
29
+ decision = decisionOf(result);
30
+ return result;
31
+ }
32
+ catch (error) {
33
+ failure = error;
34
+ throw error;
35
+ }
36
+ finally {
37
+ emitter?.emit({
38
+ actorId: actor.id,
39
+ permission,
40
+ resourceType: resourceTypeOf(resource),
41
+ allowed: decision?.allowed ?? false,
42
+ reason: decision?.reason ??
43
+ (failure instanceof Error ? `error:${failure.name}` : undefined),
44
+ durationMs: performance.now() - start,
45
+ errored: failure !== undefined,
46
+ });
47
+ }
48
+ }
49
+ //# sourceMappingURL=evaluator.observed.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Support for the authorization engine: configuration validation, the
3
+ * decision-cache key, and the audit-event wrapper every decision path uses.
4
+ *
5
+ * @module evaluator/engineSupport
6
+ */
7
+ export { invalidRulePattern, validatePolicy, validateRole, validateRoles, validateRule, } from "./authorizationEngine.validation.js";
8
+ export { decisionCacheKey } from "./evaluator.cacheKey.js";
9
+ export { observed, resourceTypeOf } from "./evaluator.observed.js";
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Support for the authorization engine: configuration validation, the
3
+ * decision-cache key, and the audit-event wrapper every decision path uses.
4
+ *
5
+ * @module evaluator/engineSupport
6
+ */
7
+ export { invalidRulePattern, validatePolicy, validateRole, validateRoles, validateRule, } from "./authorizationEngine.validation.js";
8
+ export { decisionCacheKey } from "./evaluator.cacheKey.js";
9
+ export { observed, resourceTypeOf } from "./evaluator.observed.js";
10
+ //# sourceMappingURL=index.js.map
@@ -8,12 +8,13 @@
8
8
  *
9
9
  * @module evaluator/evaluator
10
10
  */
11
- import { parsePermissionSafe, matches } from "../permission/permission.core.js";
11
+ import { parsePermissionSafe, matches, permissionsOverlap, } from "../permission/permission.core.js";
12
12
  import { InvalidPermissionError } from "../permissionErrors/index.js";
13
13
  import { compileRules, findMatchingRules } from "../rule/ruleCompiler.js";
14
14
  import { evaluateRules } from "../rule/rule.core.js";
15
+ import { isWildcardTarget } from "../rule/rule.pattern.js";
15
16
  import { assertNotAborted, evaluatePolicies, resolveActorGrants, toMetadataMap, } from "./evaluator.pipeline.js";
16
- import { permissionCacheKey } from "../cache/cache.core.js";
17
+ import { decisionCacheKey } from "./engineSupport/index.js";
17
18
  export { evaluateWithExplain } from "./evaluator.explain.js";
18
19
  /** A public message that names nothing internal. */
19
20
  const PUBLIC_DENIED = "Access denied";
@@ -66,7 +67,10 @@ export async function evaluate(actor, permissionStr, resource, options, authOpti
66
67
  });
67
68
  continue;
68
69
  }
69
- if (matches(deny, permissionStr)) {
70
+ // Overlap, not match: for a concrete target the two are the same, but a
71
+ // wildcard target (`post:*`) asks about every action under it, and a
72
+ // deny on one of them has to refuse it.
73
+ if (permissionsOverlap(deny, permissionStr)) {
70
74
  trace?.push({
71
75
  type: "deny",
72
76
  detail: `Explicit deny: ${deny}`,
@@ -76,19 +80,7 @@ export async function evaluate(actor, permissionStr, resource, options, authOpti
76
80
  }
77
81
  }
78
82
  /* ── Cache ───────────────────────────────────────────────────────────── */
79
- const resourceId = authOptions?.resourceId ?? resourceIdOf(resource);
80
- // Only a decision the key can fully describe may be cached.
81
- //
82
- // A resource with no derivable id is the sharp case: the key would collapse
83
- // to `actor|permission`, so an allow for `{ ownerId: "ada" }` would answer
84
- // for `{ ownerId: "bob" }` on the next call. Request metadata is the other:
85
- // `tenantIsolation()` reads the tenant from it, and it is not part of the
86
- // key, so a decision made for one tenant must not answer for another.
87
- const keyable = (resource === undefined || resourceId !== undefined) &&
88
- !hasMetadata(authOptions?.metadata);
89
- const cacheKey = options.cache && authOptions?.skipCache !== true && keyable
90
- ? permissionCacheKey(actor.id, permissionStr, resourceId)
91
- : undefined;
83
+ const cacheKey = decisionCacheKey(actor, permissionStr, resource, options, authOptions);
92
84
  if (options.cache && cacheKey) {
93
85
  try {
94
86
  const cached = await options.cache.get(cacheKey);
@@ -160,9 +152,16 @@ export async function evaluate(actor, permissionStr, resource, options, authOpti
160
152
  })),
161
153
  ...grants.rules,
162
154
  ];
163
- const ruleResult = await evaluateRules(findMatchingRules(compileRules(rules), permission), permission, context, {
155
+ // A wildcard target is not a key the index can look up, and the deny
156
+ // rules that merely overlap it are exactly the ones an index lookup misses,
157
+ // so it is checked against every rule.
158
+ let conditionFailed = false;
159
+ const ruleResult = await evaluateRules(isWildcardTarget(permission)
160
+ ? rules
161
+ : findMatchingRules(compileRules(rules), permission), permission, context, {
164
162
  algorithm: options.algorithm,
165
163
  onConditionError: (rule, error) => {
164
+ conditionFailed = true;
166
165
  options.onError?.(error, `RuleCondition.${rule.name ?? "unnamed"}`);
167
166
  },
168
167
  });
@@ -188,7 +187,9 @@ export async function evaluate(actor, permissionStr, resource, options, authOpti
188
187
  }
189
188
  const decision = combine(ruleResult, outcome.decision, permissionStr);
190
189
  /* ── Cache write ─────────────────────────────────────────────────────── */
191
- if (options.cache && cacheKey && outcome.cacheable) {
190
+ // A decision forced by a condition that threw describes the failure, not
191
+ // the actor, and must not outlive it.
192
+ if (options.cache && cacheKey && outcome.cacheable && !conditionFailed) {
192
193
  try {
193
194
  await options.cache.set(cacheKey, decision, {
194
195
  ttl: options.cacheTtlMs,
@@ -235,25 +236,6 @@ function combine(ruleResult, policyDecision, permissionStr) {
235
236
  return policyDecision;
236
237
  return denied("no_matching_rule");
237
238
  }
238
- /** True when the caller supplied request metadata the cache key cannot carry. */
239
- function hasMetadata(metadata) {
240
- if (!metadata)
241
- return false;
242
- if (metadata instanceof Map)
243
- return metadata.size > 0;
244
- return Object.keys(metadata).length > 0;
245
- }
246
- /** Best-effort resource identity for the cache key. */
247
- function resourceIdOf(resource) {
248
- if (typeof resource !== "object" || resource === null)
249
- return undefined;
250
- const id = resource.id;
251
- if (typeof id === "string")
252
- return id;
253
- if (typeof id === "number")
254
- return String(id);
255
- return undefined;
256
- }
257
239
  /**
258
240
  * Evaluate and collect the trace, in one pass.
259
241
  *
@@ -31,6 +31,17 @@ export interface EvaluatorOptions {
31
31
  readonly expandImplied?: (permission: string) => readonly string[];
32
32
  /** Reports a failure that authorization swallowed to stay fail-closed. */
33
33
  readonly onError?: (error: unknown, source: string) => void;
34
+ /**
35
+ * Extra decision-cache key scope, read on every evaluation. The engine
36
+ * passes its configuration generation, so a role change invalidates every
37
+ * entry written before it.
38
+ *
39
+ * Returning `undefined` means this decision must not be cached: the engine
40
+ * uses that for the inputs the key cannot describe — an implication source
41
+ * that cannot announce a change, and an external resolver with no
42
+ * `resolverCacheKey`.
43
+ */
44
+ readonly cacheScope?: (actor: PermissionActor) => string | undefined;
34
45
  }
35
46
  /** The permissions and rules an actor holds, once everything is resolved. */
36
47
  export interface ResolvedGrants {