@fabrika/iam 0.9.0-dev.27 → 0.9.0-dev.29

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/iam",
3
- "version": "0.9.0-dev.27",
3
+ "version": "0.9.0-dev.29",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -56,15 +56,15 @@
56
56
  "prune:auth-log": "bun src/node/prune.ts"
57
57
  },
58
58
  "dependencies": {
59
- "@fabrika/app": "0.9.0-dev.27",
60
- "@fabrika/auth": "0.9.0-dev.27",
61
- "@fabrika/auth-core": "0.9.0-dev.27",
62
- "@fabrika/email": "0.9.0-dev.27",
63
- "@fabrika/iam-contract": "0.9.0-dev.27",
64
- "@fabrika/platform": "0.9.0-dev.27",
65
- "@fabrika/platform-node": "0.9.0-dev.27",
66
- "@fabrika/provider-cloudflare": "0.9.0-dev.27",
67
- "@fabrika/proxy-core": "0.9.0-dev.27",
59
+ "@fabrika/app": "0.9.0-dev.29",
60
+ "@fabrika/auth": "0.9.0-dev.29",
61
+ "@fabrika/auth-core": "0.9.0-dev.29",
62
+ "@fabrika/email": "0.9.0-dev.29",
63
+ "@fabrika/iam-contract": "0.9.0-dev.29",
64
+ "@fabrika/platform": "0.9.0-dev.29",
65
+ "@fabrika/platform-node": "0.9.0-dev.29",
66
+ "@fabrika/provider-cloudflare": "0.9.0-dev.29",
67
+ "@fabrika/proxy-core": "0.9.0-dev.29",
68
68
  "jose": "^5.9.0",
69
69
  "zod": "^3.25.76"
70
70
  }
@@ -111,7 +111,7 @@ export async function provisionApiKeyUseCase(c: AdminContext, input: ProvisionAp
111
111
  if (!scope.ok) {
112
112
  return fail(400, 'scopeType and scopeValue must be both set or both omitted')
113
113
  }
114
- const contractProblem = await contractGrantProblem(c.services.repositories.appSchema, app, { ...roleOrInline, scopeType: scope.scopeType })
114
+ const contractProblem = await contractGrantProblem(c.services.repositories.appSchema, app, { ...roleOrInline, scopeType: scope.scopeType }, false)
115
115
  if (contractProblem !== null) {
116
116
  return fail(400, contractProblem)
117
117
  }
@@ -160,7 +160,7 @@ export async function grantAppRole(ctx: IamAppContext, input: GrantAppRoleReques
160
160
  if (target === null || target.type !== 'user') {
161
161
  return fail(404, 'IAM knows no person by that address; an IAM administrator invites people')
162
162
  }
163
- const contract = await contractGrantProblem(appSchema, administered.app, { roleKey: role.role_key, permissions: null, scopeType: null })
163
+ const contract = await contractGrantProblem(appSchema, administered.app, { roleKey: role.role_key, permissions: null, scopeType: null }, false)
164
164
  if (contract !== null) return fail(400, contract)
165
165
  try {
166
166
  // S8: the grant ends no later than the administrator's own grants of `manage` and of every action the role carries.
@@ -25,15 +25,20 @@ export async function createGrantUseCase(c: AdminContext, input: CreateGrantRequ
25
25
  if (!scope.ok) {
26
26
  return fail(400, 'scopeType and scopeValue must be both set or both omitted')
27
27
  }
28
- const contractProblem = await contractGrantProblem(c.services.repositories.appSchema, app, { ...roleOrInline, scopeType: scope.scopeType })
29
- if (contractProblem !== null) {
30
- return fail(400, contractProblem)
31
- }
32
- const expiresAt = Number.isFinite(input.expiresAt) ? input.expiresAt ?? null : null
33
28
  const principal = await c.services.repositories.principals.getPrincipalById(principalId)
34
29
  if (!principal) {
35
30
  return fail(404, 'principal not found')
36
31
  }
32
+ const contractProblem = await contractGrantProblem(
33
+ c.services.repositories.appSchema,
34
+ app,
35
+ { ...roleOrInline, scopeType: scope.scopeType },
36
+ principal.type === 'user',
37
+ )
38
+ if (contractProblem !== null) {
39
+ return fail(400, contractProblem)
40
+ }
41
+ const expiresAt = Number.isFinite(input.expiresAt) ? input.expiresAt ?? null : null
37
42
  requireGrantablePrincipal(c, principal)
38
43
  const external = await externalGrantProblem(c.services.repositories.appSchema, principal, app, roleOrInline)
39
44
  if (external !== null) {
@@ -118,7 +123,12 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
118
123
  if (!authorization.ok) return fail(400, authorization.message)
119
124
  const scope = parseScope(input)
120
125
  if (!scope.ok) return fail(400, 'scopeType and scopeValue must be both set or both omitted')
121
- const problem = await contractGrantProblem(c.services.repositories.appSchema, grant.app, { ...authorization, scopeType: scope.scopeType })
126
+ const problem = await contractGrantProblem(
127
+ c.services.repositories.appSchema,
128
+ grant.app,
129
+ { ...authorization, scopeType: scope.scopeType },
130
+ principal.type === 'user',
131
+ )
122
132
  ?? await externalGrantProblem(c.services.repositories.appSchema, principal, grant.app, authorization)
123
133
  if (problem !== null) return fail(409, problem)
124
134
  const expiresAt = input.expiresAt ?? null
@@ -1,6 +1,6 @@
1
1
  import type { AppSchemaRepository } from './repositories/app-schema'
2
2
  import type { PrincipalRow } from './repositories/principals'
3
- import { BUILTIN_ROLES } from './roles'
3
+ import { ADMIN_ROLE_KEY, BUILTIN_ROLES } from './roles'
4
4
  import { parseStoredPermissions } from './stored-permissions'
5
5
 
6
6
  // ADR-0022 rule 6: what IAM refuses to write, on every write path. A CONTRACT application (its schema
@@ -25,13 +25,15 @@ export async function contractPatternsProblem(appSchema: ContractSchema, app: st
25
25
  /**
26
26
  * Why this grant may not be written at `app`, or null. A membership role is granted only in a value of its
27
27
  * own scope dimension, never globally. For a contract application a grant also carries no wildcard,
28
- * inline or through its role, the built-in `admin` included. A cross-app grant (`app` null) is not
29
- * checked: it never reaches an application token.
28
+ * inline or through its role. The one exception is the built-in `admin` given to a person (`toPerson`), which resolves
29
+ * there to the declared actions (`listContractAdminActions`); a key's never does, so it never grows with the catalog.
30
+ * A cross-app grant (`app` null) is not checked: it never reaches an application token.
30
31
  */
31
32
  export async function contractGrantProblem(
32
33
  appSchema: ContractSchema,
33
34
  app: string | null,
34
35
  grant: { roleKey: string | null; permissions: readonly string[] | null; scopeType: string | null },
36
+ toPerson: boolean,
35
37
  ): Promise<string | null> {
36
38
  if (app === null) {
37
39
  return null
@@ -47,6 +49,9 @@ export async function contractGrantProblem(
47
49
  const wildcard = firstWildcard(grant.permissions ?? [])
48
50
  return wildcard === undefined ? null : `a contract application lists exact actions, not the wildcard: ${wildcard}`
49
51
  }
52
+ if (grant.roleKey === ADMIN_ROLE_KEY) {
53
+ return toPerson ? null : `role '${ADMIN_ROLE_KEY}' is granted only to a person in a contract application: a key lists exact actions`
54
+ }
50
55
  const permissions = role === null ? BUILTIN_ROLES[grant.roleKey]?.permissions ?? [] : parseStoredPermissions(role.permissions)
51
56
  const wildcard = firstWildcard(permissions)
52
57
  return wildcard === undefined ? null : `role '${grant.roleKey}' lists the wildcard ${wildcard} and cannot be granted in a contract application`
package/src/issue.ts CHANGED
@@ -236,8 +236,9 @@ function credentialGrantToKeyGrant(row: CredentialGrantRow): KeyGrant[] {
236
236
  * app cannot probe or end another app's keys. Within the app, authorization mirrors the old capability
237
237
  * revoke: the original issuer may always revoke; otherwise, for an ANONYMOUS credential (a share
238
238
  * link), the caller must be able to re-issue its grants — hold every granted action, checked with the
239
- * same `findUncoveredGrant` as issue. A principal-bound credential is managed through the principal
240
- * path (the api-keys page), so a non-issuer caller cannot revoke it by id here. Idempotent — a second
239
+ * same `findUncoveredGrant` as issue; one with no grant but reserved rows is the issuer's alone. A
240
+ * principal-bound credential is managed through the principal path (the api-keys page), so a
241
+ * non-issuer caller cannot revoke it by id here. Idempotent — a second
241
242
  * revoke returns `{ ok: true, revoked: false }`.
242
243
  */
243
244
  export async function revokeKey(
@@ -256,7 +257,8 @@ export async function revokeKey(
256
257
  return { ok: false, reason: 'not_allowed' }
257
258
  }
258
259
  const grants = (await services.repositories.credentials.getCredentialGrants(cred.id)).flatMap(credentialGrantToKeyGrant)
259
- if (findUncoveredGrant(revoker.permissions, grants) !== null) {
260
+ // No grant left to re-issue (a legacy key of reserved rows only) proves no right over the key: its issuer's alone.
261
+ if (grants.length === 0 || findUncoveredGrant(revoker.permissions, grants) !== null) {
260
262
  return { ok: false, reason: 'not_allowed' }
261
263
  }
262
264
  }
package/src/membership.ts CHANGED
@@ -270,7 +270,7 @@ async function roleAuthorityProblem(
270
270
  roleKey: role.role_key,
271
271
  permissions: null,
272
272
  scopeType: scope.type,
273
- })
273
+ }, false)
274
274
  return contract === null ? null : invalid(contract)
275
275
  }
276
276
 
@@ -374,7 +374,7 @@ export async function createScope(services: Services, env: CallerEnv, ctx: Reque
374
374
  roleKey: role.role_key,
375
375
  permissions: null,
376
376
  scopeType: input.dimension,
377
- })
377
+ }, false)
378
378
  if (contract !== null) return invalid(contract)
379
379
  const external = await externalGrantProblem(services.repositories.appSchema, caller.principal, caller.app, { roleKey: role.role_key })
380
380
  if (external !== null) return invalid(external)
@@ -1,4 +1,4 @@
1
- import { terminalIdentifyProblem, type WorkloadKind } from '@fabrika/auth-core'
1
+ import { parseJsonStringArray, terminalIdentifyProblem, type WorkloadKind } from '@fabrika/auth-core'
2
2
  import { type SqlDatabase, type SqlStatement } from '@fabrika/platform'
3
3
 
4
4
  import { type AuditEventInput, auditEventStatement, AuditWriter } from './audit'
@@ -294,6 +294,28 @@ export class AppSchemaRepository {
294
294
  return results
295
295
  }
296
296
 
297
+ /**
298
+ * What a person's grant of the built-in `admin` holds at a contract application: every declared action but those of
299
+ * its public procedures, which no role may grant (ADR-0022 rule 6). One statement reads both, so a reconcile never
300
+ * pairs one revision's catalog with another's public actions; a public procedure whose actions do not parse to a
301
+ * non-empty list (the schema requires one) gives nothing at all.
302
+ */
303
+ async listContractAdminActions(app: string): Promise<string[]> {
304
+ const { results } = await this.db
305
+ .prepare(`SELECT 'action' AS kind, action AS value FROM app_actions WHERE app = ?
306
+ UNION ALL SELECT 'public' AS kind, actions AS value FROM app_workloads WHERE app = ? AND kind = 'public'`)
307
+ .bind(app, app)
308
+ .all<{ kind: string; value: string }>()
309
+ const publicActions = new Set<string>()
310
+ for (const row of results) {
311
+ if (row.kind !== 'public') continue
312
+ const actions = parseJsonStringArray(row.value)
313
+ if (actions.length === 0) return []
314
+ for (const action of actions) publicActions.add(action)
315
+ }
316
+ return results.filter((row) => row.kind === 'action' && !publicActions.has(row.value)).map((row) => row.value).sort()
317
+ }
318
+
297
319
  async listAppActions(app: string): Promise<AppActionRow[]> {
298
320
  const { results } = await this.db
299
321
  .prepare('SELECT * FROM app_actions WHERE app = ? ORDER BY action')
package/src/resolve.ts CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  import type { AuditEventInput, GrantRow, IamRepositories, PrincipalRow, RoleRow } from './db'
15
15
  import { normalizeEmailIdentity } from './email-identity'
16
16
  import { logWarn } from './log'
17
- import { makeRoleSource } from './roles'
17
+ import { ADMIN_ROLE_KEY, makeRoleSource } from './roles'
18
18
  import type { Config } from './services'
19
19
  import { parseStoredPermissions, parseStoredVia } from './stored-permissions'
20
20
 
@@ -38,10 +38,16 @@ export interface ResolutionInputs {
38
38
  */
39
39
  affiliation: PrincipalAffiliation
40
40
  /**
41
- * A contract application holds exact actions of its approved catalog: a pattern (a stored `*` or `prefix.*`, the
42
- * built-in `admin` included) contributes nothing there, so nothing tracks the catalog beyond its approved revision.
41
+ * A contract application holds exact actions of its approved catalog: a pattern (a stored `*` or `prefix.*`)
42
+ * contributes nothing there, so nothing tracks the catalog beyond its approved revision. The built-in `admin` holds
43
+ * `contractAdmin` there instead, or nothing without it.
43
44
  */
44
45
  exactActions?: boolean
46
+ /**
47
+ * At a contract application, what an internal user's grant of the built-in `admin` at that application holds: its
48
+ * declared actions but those of its public procedures. Absent, such a grant contributes nothing.
49
+ */
50
+ contractAdmin?: readonly string[]
45
51
  }
46
52
 
47
53
  /**
@@ -154,7 +160,11 @@ export function computeAuthority(inputs: ResolutionInputs, roles: RoleSource): R
154
160
  // A row stored before `~` was reserved: IAM alone derives a `~` entry, so the row grants nothing.
155
161
  continue
156
162
  }
157
- if (grant.role_key !== null) {
163
+ if (grant.role_key === ADMIN_ROLE_KEY && grant.app === inputs.app && inputs.contractAdmin !== undefined && !external) {
164
+ for (const action of inputs.contractAdmin) {
165
+ add(action, scope, 'grant', grant.expires_at)
166
+ }
167
+ } else if (grant.role_key !== null) {
158
168
  expandRole(grant.role_key, scope, 'grant', grant.expires_at)
159
169
  } else if (grant.permissions !== null) {
160
170
  for (const pattern of parseStoredPermissions(grant.permissions)) {
@@ -392,5 +402,9 @@ export async function resolveAuthorityAt(
392
402
  && services.config.bootstrapAdmins.has(normalizeEmailIdentity(principal.email))
393
403
  const roles = await loadRoleSource(services.repositories, app)
394
404
  const exactActions = await services.repositories.appSchema.isContractApp(app)
395
- return computeAuthority({ app, grants, isBootstrapAdmin, affiliation: principal.affiliation, exactActions }, roles)
405
+ // Only a person's own grant of `admin` at the application reads the catalog; a key never grows with it.
406
+ const personAdmin = exactActions && principal.type === 'user' && principal.affiliation === 'internal'
407
+ && grants.some((grant) => grant.role_key === ADMIN_ROLE_KEY && grant.app === app)
408
+ const contractAdmin = personAdmin ? await services.repositories.appSchema.listContractAdminActions(app) : undefined
409
+ return computeAuthority({ app, grants, isBootstrapAdmin, affiliation: principal.affiliation, exactActions, contractAdmin }, roles)
396
410
  }
package/src/roles.ts CHANGED
@@ -18,6 +18,9 @@ export const BUILTIN_ROLES: Record<string, RoleDef> = {
18
18
  admin: { name: 'Admin', permissions: ['*'] },
19
19
  }
20
20
 
21
+ /** The built-in `admin`. At a contract application a person's grant of it holds the declared actions instead of `*`. */
22
+ export const ADMIN_ROLE_KEY = 'admin'
23
+
21
24
  /**
22
25
  * Build a request-scoped `RoleSource` over the built-ins layered on top of an app's
23
26
  * DB roles, already loaded into `appRoles` (role_key -> def). Resolution stays PURE:
@@ -6,14 +6,15 @@ export declare function contractPatternsProblem(appSchema: ContractSchema, app:
6
6
  /**
7
7
  * Why this grant may not be written at `app`, or null. A membership role is granted only in a value of its
8
8
  * own scope dimension, never globally. For a contract application a grant also carries no wildcard,
9
- * inline or through its role, the built-in `admin` included. A cross-app grant (`app` null) is not
10
- * checked: it never reaches an application token.
9
+ * inline or through its role. The one exception is the built-in `admin` given to a person (`toPerson`), which resolves
10
+ * there to the declared actions (`listContractAdminActions`); a key's never does, so it never grows with the catalog.
11
+ * A cross-app grant (`app` null) is not checked: it never reaches an application token.
11
12
  */
12
13
  export declare function contractGrantProblem(appSchema: ContractSchema, app: string | null, grant: {
13
14
  roleKey: string | null;
14
15
  permissions: readonly string[] | null;
15
16
  scopeType: string | null;
16
- }): Promise<string | null>;
17
+ }, toPerson: boolean): Promise<string | null>;
17
18
  /**
18
19
  * Why `principal` may not hold this grant, or null (ADR-0051). An external principal holds only a role of one
19
20
  * application that the role's schema declares external: no inline permissions, no cross-app grant, no built-in role and
@@ -54,8 +54,9 @@ export declare function issueKey(services: Services, input: IssueKeyInput, issue
54
54
  * app cannot probe or end another app's keys. Within the app, authorization mirrors the old capability
55
55
  * revoke: the original issuer may always revoke; otherwise, for an ANONYMOUS credential (a share
56
56
  * link), the caller must be able to re-issue its grants — hold every granted action, checked with the
57
- * same `findUncoveredGrant` as issue. A principal-bound credential is managed through the principal
58
- * path (the api-keys page), so a non-issuer caller cannot revoke it by id here. Idempotent — a second
57
+ * same `findUncoveredGrant` as issue; one with no grant but reserved rows is the issuer's alone. A
58
+ * principal-bound credential is managed through the principal path (the api-keys page), so a
59
+ * non-issuer caller cannot revoke it by id here. Idempotent — a second
59
60
  * revoke returns `{ ok: true, revoked: false }`.
60
61
  */
61
62
  export declare function revokeKey(services: Services, input: RevokeKeyInput, revoker: Issuer, app: string, record?: AuditEventInput): Promise<RevokeKeyResult>;
@@ -150,6 +150,13 @@ export declare class AppSchemaRepository {
150
150
  getDelegatedEndpoint(app: string, endpoint: string): Promise<DelegatedEndpointRow | null>;
151
151
  listDelegatedEndpoints(app: string): Promise<DelegatedEndpointRow[]>;
152
152
  listAppScopes(app: string): Promise<AppScopeRow[]>;
153
+ /**
154
+ * What a person's grant of the built-in `admin` holds at a contract application: every declared action but those of
155
+ * its public procedures, which no role may grant (ADR-0022 rule 6). One statement reads both, so a reconcile never
156
+ * pairs one revision's catalog with another's public actions; a public procedure whose actions do not parse to a
157
+ * non-empty list (the schema requires one) gives nothing at all.
158
+ */
159
+ listContractAdminActions(app: string): Promise<string[]>;
153
160
  listAppActions(app: string): Promise<AppActionRow[]>;
154
161
  /**
155
162
  * Idempotent reconcile of an app's declared vocabulary in one atomic batch. Validation (patterns
@@ -19,10 +19,16 @@ export interface ResolutionInputs {
19
19
  */
20
20
  affiliation: PrincipalAffiliation;
21
21
  /**
22
- * A contract application holds exact actions of its approved catalog: a pattern (a stored `*` or `prefix.*`, the
23
- * built-in `admin` included) contributes nothing there, so nothing tracks the catalog beyond its approved revision.
22
+ * A contract application holds exact actions of its approved catalog: a pattern (a stored `*` or `prefix.*`)
23
+ * contributes nothing there, so nothing tracks the catalog beyond its approved revision. The built-in `admin` holds
24
+ * `contractAdmin` there instead, or nothing without it.
24
25
  */
25
26
  exactActions?: boolean;
27
+ /**
28
+ * At a contract application, what an internal user's grant of the built-in `admin` at that application holds: its
29
+ * declared actions but those of its public procedures. Absent, such a grant contributes nothing.
30
+ */
31
+ contractAdmin?: readonly string[];
26
32
  }
27
33
  /**
28
34
  * A principal's resolved permissions and how long they hold. `supports` keeps, per identical action-and-scope entry,
@@ -14,6 +14,8 @@ import type { RoleDef, RoleSource } from '@fabrika/auth-core';
14
14
  * Its keys are `BUILTIN_ROLE_KEYS` (`@fabrika/auth-core`), which the schema parser reserves; a test pins the two.
15
15
  */
16
16
  export declare const BUILTIN_ROLES: Record<string, RoleDef>;
17
+ /** The built-in `admin`. At a contract application a person's grant of it holds the declared actions instead of `*`. */
18
+ export declare const ADMIN_ROLE_KEY = "admin";
17
19
  /**
18
20
  * Build a request-scoped `RoleSource` over the built-ins layered on top of an app's
19
21
  * DB roles, already loaded into `appRoles` (role_key -> def). Resolution stays PURE: