@intfw/auth 0.0.0-stage → 4.0.0-alpha.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.
package/LICENSE ADDED
File without changes
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @intfw/auth
2
+
3
+ RBAC authorizer and dependency-free identity providers for the Integration Framework. The service layer owns the `Authorizer` and `IdentityProvider` contracts; this package implements them.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @intfw/auth
9
+ ```
10
+
11
+ Requires Node.js 20 or newer; the package is ESM only. It depends on `@intfw/core` and `@intfw/service`, which npm installs with it. Version 4.0.0-alpha is a pre-release: the API may still change before 4.0.0.
12
+
13
+ ## Entry points
14
+
15
+ | Export | Provides |
16
+ |--------|----------|
17
+ | `@intfw/auth` | Authorizers, identity providers and the `authz` / `authn` slot configuration classes. |
18
+
19
+ Deep imports outside `exports` fail with `ERR_PACKAGE_PATH_NOT_EXPORTED`.
20
+
21
+ ## What is inside
22
+
23
+ - **Authorization**
24
+ - `RbacAuthorizer`: roles `viewer`, `editor`, `approver`, `operator`, `designer`, `admin`, mapped to operations by `OPERATION_ROLE_MAP`. `can(principal, operation, resource)` returns `{ allowed, reason?, hide? }`; `hide: true` means the caller must see 404 instead of 403. Also `permissions()`, `authorize()` (throws problem details), `canRead()`, `filterVisible()` and `filter(principal, operation)`, the exact list predicate: the OR over the grants whose role permits the operation of the AND of each grant's scope dimensions.
25
+ - `DevAllowAllAuthorizer`: allows everything and logs a warning. Only for local development.
26
+ - `createAuthorizer(authzConfig, { coreConfig, logger })`: builds one of the two from `authz.mode`.
27
+ - **Identity providers** (each returns an object with `authenticate({ headers })` giving a `Principal` or `null`, which the HTTP layer turns into 401):
28
+ - `ApiKeyIdentityProvider(keyMap, { allowInsecure, production })`: static `Authorization: Bearer <key>` or `x-api-key` table; refuses to start in production unless `allowInsecure` is set. Development and tests only.
29
+ - `TrustedHeaderIdentityProvider({ subjectHeader, roleHeader, namespaceHeader }, { iAcceptGatewayResponsibility })`: reads identity from headers set by a trusted gateway; throws unless the acknowledgement flag is `true`. `namespaceHeader` (optional) names the header with the caller's namespaces (comma separated, `*` for central access).
30
+ - `JwtIdentityProvider({ verifyToken, claimsToGrants, ... })`: maps a bearer token to a principal using a host-supplied verifier. `@intfw/auth-central` provides one for Central Auth.
31
+ - **Configuration:** `RbacConfig`, `ApiKeyConfig`, `TrustedHeaderConfig`.
32
+
33
+ A `Principal` is `{ subject, kind, grants: [{ role, scope?: { environments, domains, accountIds, namespaces } }], displayName?, email? }`.
34
+
35
+ Scope matching fails closed: a grant restricted by `environments`, `domains`, `accountIds` or `namespaces` does not match a resource that lacks that attribute. A dimension the grant does not list is unrestricted. `createServices` throws `AUTHORIZER_REQUIRED` when it is given no authorizer, so a host cannot start without one by accident.
36
+
37
+ ## Usage
38
+
39
+ ```js
40
+ import { createAuthorizer, ApiKeyIdentityProvider, JwtIdentityProvider } from '@intfw/auth';
41
+
42
+ const authorizer = createAuthorizer(config.slot('authz'), { coreConfig, logger });
43
+ const identityProvider = ApiKeyIdentityProvider(authn.keys, { allowInsecure: authn.allowInsecure, production });
44
+ // or: JwtIdentityProvider({ verifyToken, claimsToGrants })
45
+ ```
46
+
47
+ A custom authorizer extends `Authorizer` from `@intfw/service` and is checked with `authorizerContract` from `@intfw/service/testing`.
48
+
49
+ ## Configuration
50
+
51
+ | Slot | Class | Keys and defaults |
52
+ |------|-------|-------------------|
53
+ | `authz` | `RbacConfig` | `mode: 'rbac'` (`'rbac'` \| `'dev-allow-all'`); `roleMap: {}` overrides which roles may perform an operation (keys must be known operations) |
54
+ | `authn` | `ApiKeyConfig` | `keys: {}` (**sensitive**; token to `{ subject, grants }`), `allowInsecure: false` |
55
+ | `authn` | `TrustedHeaderConfig` | `subjectHeader: 'x-forwarded-user'`, `roleHeader: 'x-forwarded-roles'`, `namespaceHeader: null`, `iAcceptGatewayResponsibility: false` |
56
+
57
+ Which `authn` class applies depends on which keys the configuration contains; the host chooses the class for the slot.
58
+
59
+ ## Related packages
60
+
61
+ `@intfw/core` and `@intfw/service` (contracts), `@intfw/auth-central` (Central Auth tokens for `JwtIdentityProvider`), `@intfw/express` (the HTTP binding that calls the authorizer).
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
- {
2
- "name": "@intfw/auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@intfw/auth",
3
+ "version": "4.0.0-alpha.0",
4
+ "description": "RBAC authorizer and dependency-free identity providers for the Integration Framework.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": "./src/index.js"
9
+ },
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "scripts": {
17
+ "test": "node test/run.js"
18
+ },
19
+ "dependencies": {
20
+ "@intfw/core": "^4.0.0-alpha.0",
21
+ "@intfw/service": "^4.0.0-alpha.0"
22
+ }
23
+ }
@@ -0,0 +1,35 @@
1
+ // DevAllowAllAuthorizer: allows everything. Only for local development, and only when `authz.mode` says so (AUTH-7).
2
+ import { Authorizer, OPERATIONS } from '@intfw/service';
3
+ import { filters } from '@intfw/core';
4
+ import { RbacAuthorizer } from './RbacAuthorizer.js';
5
+
6
+ export class DevAllowAllAuthorizer extends Authorizer {
7
+ /** @param {{ logger?: { warn(msg: string): void } }} [opts] */
8
+ constructor({ logger = console } = {}) {
9
+ super();
10
+ logger.warn('[intfw] authz.mode is "dev-allow-all": every request is authorized. Never use this outside local development.');
11
+ this.pluginOperations = [];
12
+ }
13
+
14
+ registerOperations(operations) {
15
+ this.pluginOperations.push(...operations.map((o) => o.name));
16
+ return this;
17
+ }
18
+
19
+ async can() { return { allowed: true }; }
20
+
21
+ async filter() { return { exact: true, expr: filters.TRUE }; }
22
+
23
+ async permissions() { return Object.fromEntries([...OPERATIONS, ...this.pluginOperations].map((op) => [op, true])); }
24
+ }
25
+
26
+ /**
27
+ * Build the authorizer named by the `authz` slice.
28
+ * @param {{ mode: string, roleMap?: object }} config RbacConfig
29
+ * @param {{ coreConfig?: object, logger?: { warn(msg: string): void } }} [deps]
30
+ */
31
+ export function createAuthorizer(config, { coreConfig, logger } = {}) {
32
+ return config.mode === 'dev-allow-all'
33
+ ? new DevAllowAllAuthorizer({ logger })
34
+ : new RbacAuthorizer({ coreConfig, config, logger });
35
+ }
@@ -0,0 +1,301 @@
1
+ // RbacAuthorizer.js — RBAC authorization (FR-SEC-2, FR-SEC-3, FR-SEC-4).
2
+ //
3
+ // The framework owns roles, permissions, scoping, and separation of duties.
4
+ // The host supplies a verified Principal; the framework checks authorization.
5
+ //
6
+ // Authorization rule:
7
+ // A grant authorizes an operation iff:
8
+ // 1. The grant's role permits the operation (per OPERATION_ROLE_MAP), AND
9
+ // 2. Every scope dimension present on the grant includes the resource's value(s). Fails closed (D21): a restricted
10
+ // dimension does not match a resource that lacks the attribute. A dimension absent from the grant is unrestricted.
11
+ //
12
+ // Existence privacy (FR-SEC-4):
13
+ // Resources outside a principal's VISIBLE scope return 404, not 403.
14
+ // 403 is used when the principal can see the resource but lacks the specific action.
15
+
16
+ import { makeProblems, CoreConfig, filters, allowsWithoutDirectory, namespaceKeyOf, namespaceScopeOf } from '@intfw/core';
17
+ import { Authorizer } from '@intfw/service';
18
+
19
+ const { and, or, inSet, simplify } = filters;
20
+
21
+ /** The namespaces a resource is in: a webhook lists several, anything else has one (absent means `global`). */
22
+ const namespacesOf = (resource) => (Array.isArray(resource?.namespaces) ? resource.namespaces : [namespaceKeyOf(resource)]);
23
+
24
+ // ---------------------------------------------------------------- Operation × Role matrix (FR-SEC-2, API spec §4.3)
25
+
26
+ const V = 'viewer', E = 'editor', AP = 'approver', OP = 'operator', DE = 'designer', AD = 'admin';
27
+
28
+ /**
29
+ * Maps each operation to the minimum set of roles that can perform it.
30
+ * Multiple entries mean ANY of those roles (OR logic).
31
+ */
32
+ export const OPERATION_ROLE_MAP = Object.freeze({
33
+ // Reads
34
+ 'config:read': [V, E, AP, OP, DE, AD],
35
+ 'snapshot:read': [V, E, AP, OP, DE, AD],
36
+ 'revision:read': [V, E, AP, OP, DE, AD],
37
+ 'event:read': [V, E, AP, OP, DE, AD],
38
+ 'unit:read': [V, E, AP, OP, DE, AD],
39
+ 'variant:read': [V, E, AP, OP, DE, AD],
40
+ 'integrationType:read': [V, E, AP, OP, DE, AD],
41
+ 'environment:read': [V, E, AP, OP, DE, AD],
42
+ 'webhook:read': [AD],
43
+ 'approval:read': [AP, AD],
44
+ 'lookup:search': [V, E, AP, OP, DE, AD],
45
+
46
+ // Config mutations
47
+ 'config:create': [E, AD],
48
+ 'config:edit': [E, AD],
49
+ 'config:delete': [E, AD],
50
+ 'config:restore': [E, AD],
51
+ 'config:instantiate': [E, AD],
52
+ 'config:revert': [E, AD],
53
+
54
+ // Purge
55
+ 'config:purge': [AD],
56
+
57
+ // Snapshot / approval workflow
58
+ 'snapshot:create': [E, AD], // submit + manual pin
59
+ 'snapshot:approve': [AP, AD],
60
+ 'snapshot:reject': [AP, AD],
61
+ 'snapshot:activate': [OP, AD], // also rollback
62
+
63
+ // Promotion + variants
64
+ 'config:promote': [OP, AD],
65
+
66
+ // Validation + testing
67
+ 'config:validate': [V, E, AP, OP, DE, AD],
68
+ 'config:test-connection': [E, OP, AD],
69
+
70
+ // Unit ops
71
+ 'unit:unquarantine': [OP, AD],
72
+ 'unit:reset-cursor': [OP, AD],
73
+ 'unit:retire': [OP, AD],
74
+
75
+ // Admin
76
+ 'environment:manage': [AD],
77
+ 'webhook:manage': [AD],
78
+
79
+ // Integration types defined at runtime (D44): the designer role exists for this alone
80
+ 'integrationType:manage': [DE, AD],
81
+ 'integrationType:import': [DE, AD],
82
+
83
+ // Bundles (D43)
84
+ 'bundle:export': [OP, AD],
85
+ 'bundle:import': [OP, AD],
86
+
87
+ // Index health of resolved search (C2.3)
88
+ 'search:diagnostics': [OP, AD],
89
+
90
+ // Namespaces (D45): every role may see the namespaces it can see; changing a record needs the admin role on that namespace
91
+ 'namespace:read': [V, E, AP, OP, DE, AD],
92
+ 'namespace:manage': [AD],
93
+ });
94
+
95
+ // ---------------------------------------------------------------- RbacAuthorizer
96
+
97
+ export class RbacAuthorizer extends Authorizer {
98
+ /**
99
+ * @param {object} [opts]
100
+ * @param {object} [opts.coreConfig] CoreConfig (problem URIs)
101
+ * @param {{ roleMap?: Record<string, string[]> }} [opts.config] the `authz` slice (RbacConfig); its roleMap overrides per operation
102
+ * @param {Record<string, string[]>} [opts.roleMap] operation -> roles; defaults to OPERATION_ROLE_MAP
103
+ * @param {{ warn?: (msg: string) => void }} [opts.logger] receives the one-time fail-closed notice
104
+ */
105
+ constructor({ coreConfig = new CoreConfig(), config, roleMap, logger = null } = {}) {
106
+ super();
107
+ const overrides = roleMap ? {} : { ...(config?.roleMap ?? {}) };
108
+ this.roleMap = roleMap ?? {
109
+ ...OPERATION_ROLE_MAP,
110
+ ...Object.fromEntries(Object.entries(overrides).filter(([op]) => op in OPERATION_ROLE_MAP)),
111
+ };
112
+ /** Role overrides from the `authz` slice, kept so an operation a plugin declares later still honours them (C3.1). */
113
+ this.overrides = overrides;
114
+ this.pluginReadOperations = new Set();
115
+ this.problems = makeProblems(coreConfig);
116
+ /** @type {import('@intfw/core').NamespaceDirectory|null} the visibility graph a namespace-limited grant is judged with */
117
+ this.directory = null;
118
+ logger?.warn?.('[intfw] scope matching fails closed: a grant restricted by environments, domains, accountIds or namespaces does not match a resource that lacks that attribute (for example a template without an environment). Grants without a scope are unaffected.');
119
+ }
120
+
121
+ /** The service hands over its namespace directory; without one a namespace-limited grant matches only the namespaces it lists. */
122
+ bindNamespaces(directory) {
123
+ this.directory = directory;
124
+ directory?.markReadOperations?.(this.pluginReadOperations);
125
+ return this;
126
+ }
127
+
128
+ /** Operations a plugin declared (C3.1): the role map gains them, and an override from `authz.roleMap` wins over the plugin's default. */
129
+ registerOperations(operations) {
130
+ for (const o of operations) {
131
+ this.roleMap[o.name] = this.overrides[o.name] ?? [...o.roles];
132
+ if (o.access === 'read') this.pluginReadOperations.add(o.name);
133
+ }
134
+ this.directory?.markReadOperations?.(this.pluginReadOperations);
135
+ return this;
136
+ }
137
+
138
+ /** Overrides in `authz.roleMap` that name an operation nobody declared: a typo or a plugin that is not loaded. */
139
+ unknownOverrides() { return Object.keys(this.overrides).filter((op) => !(op in this.roleMap)); }
140
+
141
+ /**
142
+ * @param {import('@intfw/service').Principal|null} principal
143
+ * @param {string} operation unknown operations throw (programming error)
144
+ * @param {object} [resource] { environment?, domain?, accountIds?, namespace?, namespaces?, kind?, id? }
145
+ * @returns {Promise<import('@intfw/service').Decision>}
146
+ */
147
+ async can(principal, operation, resource = {}) {
148
+ const allowedRoles = this.roleMap[operation];
149
+ if (!allowedRoles) throw new Error(`Unknown operation "${operation}" — add it to the role map`);
150
+ if (!principal) return { allowed: false, reason: 'unauthenticated' };
151
+ for (const grant of principal.grants ?? []) {
152
+ if (allowedRoles.includes(grant.role) && this._scopeMatches(grant.scope, resource, operation)) return { allowed: true };
153
+ }
154
+ return {
155
+ allowed: false,
156
+ reason: allowedRoles.join(' | '),
157
+ hide: !this._canRead(principal, resource),
158
+ };
159
+ }
160
+
161
+ /**
162
+ * The exact list predicate for `operation`: the OR over the grants whose role permits it of the AND of each grant's scope
163
+ * dimensions. Dimensions never combine across grants, so two narrow grants cannot add up to a broad one. It equals `can()`
164
+ * for every resource, and the tests check that.
165
+ * @returns {Promise<{ exact: true, expr: object }>}
166
+ */
167
+ async filter(principal, operation) {
168
+ const allowedRoles = this.roleMap[operation];
169
+ if (!allowedRoles) throw new Error(`Unknown operation "${operation}" — add it to the role map`);
170
+ const grants = (principal?.grants ?? []).filter((g) => allowedRoles.includes(g.role));
171
+ const perGrant = grants.map((g) => and(
172
+ ...(g.scope?.environments?.length > 0 ? [inSet('environment', g.scope.environments)] : []),
173
+ ...(g.scope?.domains?.length > 0 ? [inSet('domain', g.scope.domains)] : []),
174
+ ...(g.scope?.accountIds?.length > 0 ? [inSet('accountIds', g.scope.accountIds)] : []),
175
+ this._namespaceExpr(g.scope, operation),
176
+ ));
177
+ return { exact: true, expr: simplify(or(...perGrant)) };
178
+ }
179
+
180
+ /** The condition on `namespace` alone, for records that have a namespace and no other scope attribute (D45). */
181
+ async namespaceFilter(principal, operation) {
182
+ const allowedRoles = this.roleMap[operation];
183
+ if (!allowedRoles) throw new Error(`Unknown operation "${operation}" — add it to the role map`);
184
+ const grants = (principal?.grants ?? []).filter((g) => allowedRoles.includes(g.role));
185
+ return { exact: true, expr: simplify(or(...grants.map((g) => this._namespaceExpr(g.scope, operation)))) };
186
+ }
187
+
188
+ async namespacesFor(principal, operation) {
189
+ const allowedRoles = this.roleMap[operation];
190
+ if (!allowedRoles) throw new Error(`Unknown operation "${operation}" — add it to the role map`);
191
+ const keys = new Set();
192
+ for (const g of (principal?.grants ?? []).filter((x) => allowedRoles.includes(x.role))) {
193
+ const s = namespaceScopeOf(g.scope);
194
+ if (s.unrestricted) return { unrestricted: true };
195
+ for (const k of s.keys) keys.add(k);
196
+ }
197
+ return { unrestricted: false, namespaces: [...keys].sort() };
198
+ }
199
+
200
+ /**
201
+ * Operations granted by role alone (no resource scoping), for `/me`.
202
+ * @param {import('@intfw/service').Principal|null} principal
203
+ * @returns {Promise<Record<string, boolean>>}
204
+ */
205
+ async permissions(principal) {
206
+ const roles = (principal?.grants ?? []).map((g) => g.role);
207
+ return Object.fromEntries(Object.entries(this.roleMap).map(([op, allowed]) => [op, roles.some((r) => allowed.includes(r))]));
208
+ }
209
+
210
+ /**
211
+ * Check whether the principal can perform `operation` on a resource with `resourceAttrs`.
212
+ * Throws 403 PERMISSION_DENIED or 404 NOT_FOUND (existence privacy) as appropriate.
213
+ *
214
+ * @param {import('@intfw/service').Principal} principal
215
+ * @param {string} operation One of the keys in OPERATION_ROLE_MAP
216
+ * @param {object} resourceAttrs { environment?, domain?, accountIds?, kind? }
217
+ * @param {{ resourceExists?: boolean }} [opts] Set `resourceExists: false` to trigger 404 on scope miss
218
+ */
219
+ authorize(principal, operation, resourceAttrs = {}, { resourceExists = true } = {}) {
220
+ if (!principal) throw this.problems.unauthenticated();
221
+
222
+ const allowedRoles = this.roleMap[operation];
223
+ if (!allowedRoles) throw new Error(`Unknown operation "${operation}" — add it to OPERATION_ROLE_MAP`);
224
+
225
+ for (const grant of principal.grants ?? []) {
226
+ if (!allowedRoles.includes(grant.role)) continue;
227
+ if (this._scopeMatches(grant.scope, resourceAttrs, operation)) return true; // authorized
228
+ }
229
+
230
+ // Not authorized — choose 404 vs 403 based on visibility
231
+ const canRead = this._canRead(principal, resourceAttrs);
232
+ if (!canRead || !resourceExists) {
233
+ throw this.problems.notFound(resourceAttrs.kind ?? 'Resource', resourceAttrs.id ?? '?');
234
+ }
235
+ throw this.problems.permissionDenied(operation, allowedRoles[0]);
236
+ }
237
+
238
+ /**
239
+ * Returns true if the principal has any read-level access to the resource.
240
+ * Used to decide between 404 (invisible) and 403 (visible but forbidden).
241
+ */
242
+ canRead(principal, resourceAttrs = {}) {
243
+ if (!principal) return false;
244
+ return this._canRead(principal, resourceAttrs);
245
+ }
246
+
247
+ /**
248
+ * Filter a list of resources to those visible to the principal.
249
+ * @param {import('@intfw/service').Principal} principal
250
+ * @param {object[]} items
251
+ * @param {(item: object) => object} toAttrs Extracts resourceAttrs from an item
252
+ * @returns {object[]}
253
+ */
254
+ filterVisible(principal, items, toAttrs) {
255
+ if (!principal) return [];
256
+ return items.filter((item) => this._canRead(principal, toAttrs(item)));
257
+ }
258
+
259
+ // ---------------------------------------------------------------- private helpers
260
+
261
+ _canRead(principal, resourceAttrs) {
262
+ const readRoles = this.roleMap['config:read'];
263
+ for (const grant of principal.grants ?? []) {
264
+ if (readRoles.includes(grant.role) && this._scopeMatches(grant.scope, resourceAttrs, 'config:read')) return true;
265
+ }
266
+ return false;
267
+ }
268
+
269
+ /** The grant's namespaces as a list condition: the read set for a read operation, the write set otherwise (D45). `global` also admits records with no namespace. */
270
+ _namespaceExpr(scope, operation) {
271
+ const set = this.directory ? this.directory.setFor(scope, operation) : (namespaceScopeOf(scope).unrestricted ? null : new Set(namespaceScopeOf(scope).keys));
272
+ if (set === null) return filters.TRUE;
273
+ return inSet('namespace', [...set], { orMissing: set.has('global') });
274
+ }
275
+
276
+ /**
277
+ * Scope evaluation: every restricted dimension must include the resource's value(s), and a resource without the
278
+ * attribute does not match (D21). A dimension the grant does not list is unrestricted. The namespace dimension is judged with
279
+ * the read set or the write set of the grant, by `operation`; a resource with no namespace is in `global`.
280
+ */
281
+ _scopeMatches(scope, resourceAttrs, operation = 'config:read') {
282
+ if (!scope) return true; // unscoped grant — matches everything
283
+ if (scope.environments?.length > 0) {
284
+ if (!resourceAttrs.environment || !scope.environments.includes(resourceAttrs.environment)) return false;
285
+ }
286
+ if (scope.domains?.length > 0) {
287
+ if (!resourceAttrs.domain || !scope.domains.includes(resourceAttrs.domain)) return false;
288
+ }
289
+ if (scope.accountIds?.length > 0) {
290
+ if (!resourceAttrs.accountIds?.some((a) => scope.accountIds.includes(a))) return false;
291
+ }
292
+ if (scope.namespaces !== undefined) {
293
+ const ok = this.directory ? this.directory.allows(scope, operation, namespacesOf(resourceAttrs)) : allowsWithoutDirectory(scope, namespacesOf(resourceAttrs));
294
+ if (!ok) return false;
295
+ }
296
+ return true;
297
+ }
298
+ }
299
+
300
+ /** v3 name, kept so existing callers keep working. */
301
+ export { RbacAuthorizer as AuthzService };
package/src/config.js ADDED
@@ -0,0 +1,67 @@
1
+ // Config for the auth package: the `authz` slot (RbacConfig) and the `authn` slot (ApiKeyConfig, TrustedHeaderConfig).
2
+ import { PackageConfig } from '@intfw/core';
3
+ import { OPERATION_ROLE_MAP } from './RbacAuthorizer.js';
4
+
5
+ const ROLES = ['viewer', 'editor', 'approver', 'operator', 'designer', 'admin'];
6
+ const PLUGIN_OPERATION = /^[a-z][a-z0-9]*(-[a-z0-9]+)*:[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
7
+
8
+ /** `authz` slot. `roleMap` overrides which roles may perform an operation; `mode` must name dev-allow-all explicitly (AUTH-7). */
9
+ export class RbacConfig extends PackageConfig {
10
+ static defaults = {
11
+ mode: 'rbac',
12
+ roleMap: {},
13
+ };
14
+
15
+ validate() {
16
+ const issues = this.requireOneOf('mode', ['rbac', 'dev-allow-all']);
17
+ for (const [op, roles] of Object.entries(this.get('roleMap') ?? {})) {
18
+ // a plugin's operations are not known until the plugins load: a well-formed `scope:action` passes here and is checked at startup
19
+ if (!(op in OPERATION_ROLE_MAP) && !PLUGIN_OPERATION.test(op)) issues.push({ path: `roleMap.${op}`, message: 'is not a known operation' });
20
+ else if (!Array.isArray(roles) || roles.length === 0 || roles.some((r) => !ROLES.includes(r))) {
21
+ issues.push({ path: `roleMap.${op}`, message: `must be a non-empty array of: ${ROLES.join(', ')}` });
22
+ }
23
+ }
24
+ return issues;
25
+ }
26
+ }
27
+
28
+ /** `authn` slot for static API keys (dev and test). The key table is a secret. */
29
+ export class ApiKeyConfig extends PackageConfig {
30
+ static defaults = {
31
+ keys: {},
32
+ allowInsecure: false,
33
+ };
34
+
35
+ static sensitive = ['keys'];
36
+
37
+ validate() {
38
+ const issues = this.requireBool('allowInsecure');
39
+ for (const [token, p] of Object.entries(this.get('keys') ?? {})) {
40
+ if (!p || typeof p.subject !== 'string' || !Array.isArray(p.grants)) {
41
+ issues.push({ path: 'keys', message: `entry for a key must have a string subject and a grants array (key ${token.slice(0, 2)}...)` });
42
+ }
43
+ }
44
+ return issues;
45
+ }
46
+ }
47
+
48
+ /** `authn` slot for a gateway that sets identity headers. `namespaceHeader` (D45) names the header holding the caller's namespaces (comma-separated, `*` for central); unset means grants carry no namespace scope. */
49
+ export class TrustedHeaderConfig extends PackageConfig {
50
+ static defaults = {
51
+ subjectHeader: 'x-forwarded-user',
52
+ roleHeader: 'x-forwarded-roles',
53
+ namespaceHeader: null,
54
+ iAcceptGatewayResponsibility: false,
55
+ };
56
+
57
+ static types = { namespaceHeader: 'string' };
58
+
59
+ validate() {
60
+ return [
61
+ ...this.requireString('subjectHeader'),
62
+ ...this.requireString('roleHeader'),
63
+ ...(this.get('namespaceHeader') === null ? [] : this.requireString('namespaceHeader')),
64
+ ...this.requireBool('iAcceptGatewayResponsibility'),
65
+ ];
66
+ }
67
+ }
@@ -0,0 +1,57 @@
1
+ // claimMapper.js — maps the verified claims of any JWT/OIDC token to role grants, with optional namespace scope (D45).
2
+ //
3
+ // Provider-neutral: the framework only knows `Principal.grants[].scope.namespaces`; which claims carry it is configuration.
4
+ // Namespace scope is opt-in. It is emitted only when a namespace claim or a group map is configured; once configured, a token with
5
+ // roles and no namespace information gets an empty list and sees nothing (it never falls back to everything). With neither
6
+ // configured the mapper behaves exactly as before: grants carry a role and no scope.
7
+ import { ALL_NAMESPACES, NAMESPACE_KEY } from '@intfw/core';
8
+
9
+ export const GRANT_ROLES = Object.freeze(['viewer', 'editor', 'approver', 'operator', 'designer', 'admin']);
10
+
11
+ /** The value at a dotted path (`realm_access.roles`); a claim whose own name has a dot is read first as that exact name. */
12
+ function claimAt(claims, path) {
13
+ if (claims == null || !path) return undefined;
14
+ if (Object.hasOwn(claims, path)) return claims[path];
15
+ return path.split('.').reduce((o, k) => (o != null && typeof o === 'object' ? o[k] : undefined), claims);
16
+ }
17
+
18
+ /** A claim as a list of non-empty strings: a string is one value, an array its strings; anything else nothing. */
19
+ const listOf = (v) => (typeof v === 'string' ? [v] : Array.isArray(v) ? v : []).filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim());
20
+
21
+ /**
22
+ * The scope a list of namespace keys makes: `"*"` anywhere means central (no scope); otherwise the valid keys, sorted and
23
+ * de-duplicated. An empty result is a grant that matches nothing, never an unrestricted one.
24
+ * @param {string[]} keys
25
+ * @returns {{ namespaces: string[] }|undefined} undefined for a central caller
26
+ */
27
+ export function namespaceScopeFor(keys) {
28
+ if (keys.includes(ALL_NAMESPACES)) return undefined;
29
+ return { namespaces: [...new Set(keys.filter((k) => NAMESPACE_KEY.test(k)))].sort() };
30
+ }
31
+
32
+ /**
33
+ * @param {object} [opts]
34
+ * @param {string} [opts.rolesClaim] claim holding the roles (dotted path); a string or an array. Default `roles`.
35
+ * @param {string|null} [opts.namespacesClaim] claim holding the namespaces; `"*"` means central. Unset: no namespace scope.
36
+ * @param {string|null} [opts.groupsClaim] claim holding group names, looked up in `groupNamespaces`
37
+ * @param {Record<string, string|string[]>} [opts.groupNamespaces] group name to the namespace(s) it grants (`"*"` is central)
38
+ * @param {readonly string[]} [opts.roles] the roles a token may carry; others are dropped
39
+ * @param {boolean} [opts.singleRole] accept a string as one role (some providers send one); default true. A string is never promoted when false.
40
+ * @returns {(claims: object) => { role: string, scope?: { namespaces: string[] } }[]}
41
+ */
42
+ export function makeClaimMapper({ rolesClaim = 'roles', namespacesClaim = null, groupsClaim = null, groupNamespaces = {}, roles: validRoles = GRANT_ROLES, singleRole = true } = {}) {
43
+ const valid = new Set(validRoles);
44
+ const groups = new Map(Object.entries(groupNamespaces ?? {}));
45
+ const scoped = Boolean(namespacesClaim) || (Boolean(groupsClaim) && groups.size > 0);
46
+ return (claims) => {
47
+ const rolesValue = claimAt(claims, rolesClaim);
48
+ const roles = listOf(singleRole || Array.isArray(rolesValue) ? rolesValue : undefined).filter((r) => valid.has(r));
49
+ if (!scoped) return [...new Set(roles)].map((role) => ({ role }));
50
+ const keys = [
51
+ ...(namespacesClaim ? listOf(claimAt(claims, namespacesClaim)) : []),
52
+ ...(groupsClaim ? listOf(claimAt(claims, groupsClaim)).flatMap((g) => listOf(groups.get(g))) : []),
53
+ ];
54
+ const scope = namespaceScopeFor(keys);
55
+ return [...new Set(roles)].map((role) => ({ role, ...(scope ? { scope: { namespaces: [...scope.namespaces] } } : {}) }));
56
+ };
57
+ }
@@ -0,0 +1,130 @@
1
+ // IdentityProvider.js — Port for host-supplied identity (FR-SEC-1, D2).
2
+ //
3
+ // The framework NEVER authenticates. The host supplies a verified Principal via this port.
4
+ // Shipped adapters: JwtIdentityProvider, ApiKeyIdentityProvider, TrustedHeaderIdentityProvider.
5
+ // Identity comes from a verified credential, never from a header the client asserts; unauthenticated requests → 401 UNAUTHENTICATED.
6
+
7
+ import { namespaceScopeFor } from './claimMapper.js';
8
+
9
+ /**
10
+ * @typedef {import('@intfw/service').RoleGrant} RoleGrant
11
+ * @typedef {import('@intfw/service').Principal} Principal
12
+ */
13
+
14
+ /**
15
+ * @interface IdentityProvider
16
+ * authenticate(req) → Principal | null
17
+ * Return a verified Principal or null (→ 401).
18
+ * Implementations MUST verify credentials, not merely trust what the caller claims.
19
+ */
20
+
21
+ // ---------------------------------------------------------------- ApiKeyIdentityProvider
22
+
23
+ /**
24
+ * Static API-key → Principal map. For development and testing only.
25
+ * Refuses to start in production unless `allowInsecure` is passed; the host says whether it is production.
26
+ *
27
+ * @param {Map<string, Principal>|Record<string, Principal>} keyMap key → Principal
28
+ * @param {{ allowInsecure?: boolean, production?: boolean }} [opts]
29
+ */
30
+ export function ApiKeyIdentityProvider(keyMap, { allowInsecure = false, production = false } = {}) {
31
+ if (production && !allowInsecure) {
32
+ throw new Error(
33
+ 'ApiKeyIdentityProvider: refusing to start in production. '
34
+ + 'Pass { allowInsecure: true } to explicitly accept this risk.',
35
+ );
36
+ }
37
+ const map = keyMap instanceof Map ? keyMap : new Map(Object.entries(keyMap));
38
+ return {
39
+ async authenticate(req) {
40
+ const auth = req.headers?.authorization ?? '';
41
+ const token = auth.startsWith('Bearer ') ? auth.slice(7) : (req.headers?.['x-api-key'] ?? '');
42
+ return map.get(token) ?? null;
43
+ },
44
+ };
45
+ }
46
+
47
+ // ---------------------------------------------------------------- TrustedHeaderIdentityProvider
48
+
49
+ /**
50
+ * Read principal identity from gateway-set request headers.
51
+ * ONLY use behind a trusted reverse proxy that sets these headers after authentication.
52
+ * Constructor requires an explicit acknowledgement flag to prevent accidental use.
53
+ *
54
+ * @param {{ subjectHeader?: string, roleHeader?: string, namespaceHeader?: string|null }} [opts]
55
+ * `namespaceHeader` (D45): a comma-separated list of namespaces, `*` for central. When it is set, a request without the header (or
56
+ * with an empty one) gets an empty list and sees nothing; when it is not set, grants carry no namespace scope.
57
+ * @param {{ iAcceptGatewayResponsibility: true }} confirm Must be passed explicitly.
58
+ */
59
+ export function TrustedHeaderIdentityProvider(
60
+ { subjectHeader = 'x-forwarded-user', roleHeader = 'x-forwarded-roles', namespaceHeader = null } = {},
61
+ { iAcceptGatewayResponsibility } = {},
62
+ ) {
63
+ if (!iAcceptGatewayResponsibility) {
64
+ throw new Error(
65
+ 'TrustedHeaderIdentityProvider: you must pass { iAcceptGatewayResponsibility: true } '
66
+ + 'to confirm this adapter is behind a verified gateway that sets the header.',
67
+ );
68
+ }
69
+ console.warn(
70
+ '[integration-framework] TrustedHeaderIdentityProvider: ensure this service is only '
71
+ + 'reachable from a trusted gateway that sets the identity headers.',
72
+ );
73
+ const namespaceKey = namespaceHeader ? String(namespaceHeader).toLowerCase() : null; // Node lower-cases request header names
74
+ return {
75
+ async authenticate(req) {
76
+ const subject = req.headers?.[subjectHeader];
77
+ if (!subject) return null;
78
+ const rawRoles = req.headers?.[roleHeader] ?? 'viewer';
79
+ const scope = namespaceKey
80
+ ? namespaceScopeFor(String(req.headers?.[namespaceKey] ?? '').split(',').map((k) => k.trim()).filter(Boolean))
81
+ : undefined;
82
+ const grants = rawRoles.split(',').map((r) => ({ role: r.trim(), ...(scope ? { scope: { namespaces: [...scope.namespaces] } } : {}) }));
83
+ return { subject, kind: 'user', grants };
84
+ },
85
+ };
86
+ }
87
+
88
+ // ---------------------------------------------------------------- JwtIdentityProvider
89
+ // The token check is the host's: it needs a JWKS client, which this dependency-free package does not carry
90
+ // (`@intfw/auth-central` ships one for Central Auth).
91
+
92
+ /**
93
+ * JWT/OIDC bearer token identity provider.
94
+ * The host supplies a `verifyToken(token) → claims | null` function that handles
95
+ * JWKS fetch, signature verification, iss/aud pinning, and expiry checking.
96
+ * This adapter maps verified claims to a Principal using the host-supplied `claimsToGrants`.
97
+ *
98
+ * @param {object} opts
99
+ * @param {(token: string) => Promise<object|null>} opts.verifyToken Host-supplied; returns claims or null.
100
+ * @param {(claims: object) => RoleGrant[]} opts.claimsToGrants Map verified claims → role grants.
101
+ * @param {(claims: object) => string} [opts.extractSubject] Default: claims.sub
102
+ * @param {(claims: object) => string} [opts.extractDisplayName] Default: claims.name
103
+ * @param {(claims: object) => string} [opts.extractEmail] Default: claims.email
104
+ */
105
+ export function JwtIdentityProvider({
106
+ verifyToken,
107
+ claimsToGrants,
108
+ extractSubject = (c) => c.sub,
109
+ extractDisplayName = (c) => c.name,
110
+ extractEmail = (c) => c.email,
111
+ }) {
112
+ if (typeof verifyToken !== 'function') throw new Error('JwtIdentityProvider: verifyToken must be a function');
113
+ if (typeof claimsToGrants !== 'function') throw new Error('JwtIdentityProvider: claimsToGrants must be a function');
114
+ return {
115
+ async authenticate(req) {
116
+ const auth = req.headers?.authorization ?? '';
117
+ if (!auth.startsWith('Bearer ')) return null;
118
+ const token = auth.slice(7);
119
+ const claims = await verifyToken(token);
120
+ if (!claims) return null;
121
+ return {
122
+ subject: extractSubject(claims),
123
+ displayName: extractDisplayName(claims),
124
+ email: extractEmail(claims),
125
+ kind: 'user',
126
+ grants: claimsToGrants(claims),
127
+ };
128
+ },
129
+ };
130
+ }
package/src/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // Public surface of @intfw/auth: RBAC authorizer and dependency-free identity providers.
2
+ export * from './RbacAuthorizer.js';
3
+ export * from './DevAllowAllAuthorizer.js';
4
+ export * from './config.js';
5
+ export * from './identity/providers.js';
6
+ export * from './identity/claimMapper.js';