@fabrika/iam 0.0.0-stage → 0.9.0-dev.26
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/fabrika.config.ts +267 -0
- package/migrations/0001_init.sql +316 -0
- package/migrations/0002_oauth.sql +38 -0
- package/migrations/0003_contract_apps.sql +11 -0
- package/migrations/0004_membership.sql +93 -0
- package/migrations/0005_workloads.sql +23 -0
- package/migrations/0006_membership_transport_keys.sql +16 -0
- package/migrations/0007_member_directory.sql +7 -0
- package/migrations/0008_durable_audit.sql +28 -0
- package/migrations/0009_member_lookups.sql +7 -0
- package/migrations/0010_workload_issues.sql +6 -0
- package/migrations/0011_app_presentation.sql +15 -0
- package/migrations/0012_external_principals.sql +10 -0
- package/migrations/0013_app_mail_templates.sql +14 -0
- package/migrations/0014_invitation_wording.sql +8 -0
- package/migrations/0015_app_schema_revisions.sql +15 -0
- package/migrations/0016_principal_grant_revision.sql +9 -0
- package/migrations/0017_app_sign_ins.sql +12 -0
- package/migrations/0018_app_members.sql +13 -0
- package/migrations/0019_app_mail_html.sql +7 -0
- package/migrations/0020_public_workloads.sql +34 -0
- package/migrations/0021_installation_brand.sql +19 -0
- package/migrations/0022_password_policy.sql +12 -0
- package/migrations/0023_terminals.sql +155 -0
- package/migrations/0024_app_terminals.sql +10 -0
- package/migrations/0025_terminal_completion.sql +10 -0
- package/migrations/0026_terminal_generation.sql +12 -0
- package/migrations/0027_application_exact_actions.sql +28 -0
- package/migrations/0028_oauth_client_assertions.sql +10 -0
- package/migrations/0029_role_via.sql +6 -0
- package/migrations/0030_membership_role_via.sql +12 -0
- package/migrations/0031_person_locale.sql +11 -0
- package/migrations-postgres/0001_init.sql +331 -0
- package/migrations-postgres/0002_oauth.sql +36 -0
- package/migrations-postgres/0003_contract_apps.sql +8 -0
- package/migrations-postgres/0004_membership.sql +92 -0
- package/migrations-postgres/0005_workloads.sql +18 -0
- package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
- package/migrations-postgres/0007_member_directory.sql +7 -0
- package/migrations-postgres/0008_durable_audit.sql +8 -0
- package/migrations-postgres/0009_member_lookups.sql +7 -0
- package/migrations-postgres/0010_workload_issues.sql +6 -0
- package/migrations-postgres/0011_app_presentation.sql +15 -0
- package/migrations-postgres/0012_external_principals.sql +10 -0
- package/migrations-postgres/0013_app_mail_templates.sql +14 -0
- package/migrations-postgres/0014_invitation_wording.sql +8 -0
- package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
- package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
- package/migrations-postgres/0017_app_sign_ins.sql +12 -0
- package/migrations-postgres/0018_app_members.sql +13 -0
- package/migrations-postgres/0019_app_mail_html.sql +7 -0
- package/migrations-postgres/0020_public_workloads.sql +9 -0
- package/migrations-postgres/0021_installation_brand.sql +19 -0
- package/migrations-postgres/0022_password_policy.sql +12 -0
- package/migrations-postgres/0023_terminals.sql +70 -0
- package/migrations-postgres/0024_app_terminals.sql +10 -0
- package/migrations-postgres/0025_terminal_completion.sql +10 -0
- package/migrations-postgres/0026_terminal_generation.sql +12 -0
- package/migrations-postgres/0027_application_exact_actions.sql +28 -0
- package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
- package/migrations-postgres/0029_role_via.sql +4 -0
- package/migrations-postgres/0030_membership_role_via.sql +7 -0
- package/migrations-postgres/0031_person_locale.sql +11 -0
- package/package.json +70 -5
- package/src/admin/access.ts +47 -0
- package/src/admin/api-keys.ts +280 -0
- package/src/admin/app-people.ts +209 -0
- package/src/admin/app-schema.ts +308 -0
- package/src/admin/audit.ts +81 -0
- package/src/admin/brand.ts +54 -0
- package/src/admin/connections.ts +48 -0
- package/src/admin/context.ts +70 -0
- package/src/admin/grant-support.ts +192 -0
- package/src/admin/grants.ts +189 -0
- package/src/admin/handlers.ts +102 -0
- package/src/admin/http.ts +24 -0
- package/src/admin/membership-keys.ts +38 -0
- package/src/admin/pagination.ts +28 -0
- package/src/admin/password-policy.ts +48 -0
- package/src/admin/passwords.ts +78 -0
- package/src/admin/policies.ts +136 -0
- package/src/admin/principals.ts +226 -0
- package/src/admin/router.ts +291 -0
- package/src/admin/rpc.ts +387 -0
- package/src/admin/sessions.ts +115 -0
- package/src/admin/share-links.ts +127 -0
- package/src/admin/terminals.ts +115 -0
- package/src/admin/user-admin.ts +76 -0
- package/src/admin/workloads.ts +85 -0
- package/src/app-presentation.ts +178 -0
- package/src/app.ts +158 -0
- package/src/auth/cookies.ts +64 -0
- package/src/auth/failure.ts +25 -0
- package/src/auth/handoff.ts +136 -0
- package/src/auth/http.ts +88 -0
- package/src/auth/invitations.ts +220 -0
- package/src/auth/known-device.ts +44 -0
- package/src/auth/login.ts +162 -0
- package/src/auth/oidc-flight.ts +91 -0
- package/src/auth/oidc.ts +148 -0
- package/src/auth/password.ts +416 -0
- package/src/auth/routes.ts +108 -0
- package/src/auth/sessions.ts +249 -0
- package/src/auth/terminals.ts +284 -0
- package/src/auth.ts +193 -0
- package/src/binding-identity.ts +25 -0
- package/src/bounded-body.ts +35 -0
- package/src/catalog/cs.ts +147 -0
- package/src/catalog/en.ts +148 -0
- package/src/catalog/index.ts +122 -0
- package/src/catalog/uk.ts +164 -0
- package/src/client-address.ts +39 -0
- package/src/common-passwords.ts +37 -0
- package/src/contract-rules.ts +80 -0
- package/src/cron.ts +54 -0
- package/src/db.ts +128 -0
- package/src/delegation.ts +100 -0
- package/src/device-http.ts +39 -0
- package/src/device.ts +269 -0
- package/src/email-identity.ts +2 -0
- package/src/env.ts +132 -0
- package/src/handoff.ts +175 -0
- package/src/html.ts +4 -0
- package/src/human-admission.ts +40 -0
- package/src/identification.ts +185 -0
- package/src/index.ts +292 -0
- package/src/installation-brand.ts +82 -0
- package/src/issue.ts +265 -0
- package/src/json.ts +30 -0
- package/src/log.ts +26 -0
- package/src/membership-http.ts +135 -0
- package/src/membership.ts +1210 -0
- package/src/messages.ts +44 -0
- package/src/narrow-permissions.ts +26 -0
- package/src/node/browser-identity.ts +69 -0
- package/src/node/migrate.ts +52 -0
- package/src/node/prune.ts +34 -0
- package/src/node/runtime.ts +221 -0
- package/src/node/server.ts +104 -0
- package/src/oauth-client-auth.ts +93 -0
- package/src/oauth-client.ts +145 -0
- package/src/oauth-config.ts +72 -0
- package/src/oauth-http.ts +262 -0
- package/src/oauth.ts +272 -0
- package/src/oidc.ts +260 -0
- package/src/origin.ts +29 -0
- package/src/password-crypto.ts +148 -0
- package/src/password-db.ts +419 -0
- package/src/password-minimum.ts +44 -0
- package/src/password-pages.ts +397 -0
- package/src/password-policy.ts +79 -0
- package/src/password-service.ts +67 -0
- package/src/person-locale.ts +103 -0
- package/src/proxy-proof.ts +36 -0
- package/src/relay-mail.ts +64 -0
- package/src/repositories/app-schema.ts +550 -0
- package/src/repositories/audit.ts +405 -0
- package/src/repositories/brand.ts +66 -0
- package/src/repositories/credentials.ts +331 -0
- package/src/repositories/device.ts +137 -0
- package/src/repositories/grants.ts +404 -0
- package/src/repositories/handoff.ts +103 -0
- package/src/repositories/membership-transport.ts +49 -0
- package/src/repositories/membership.ts +875 -0
- package/src/repositories/oauth.ts +122 -0
- package/src/repositories/password-policy.ts +44 -0
- package/src/repositories/principals.ts +358 -0
- package/src/repositories/sessions.ts +339 -0
- package/src/repositories/sql.ts +23 -0
- package/src/repositories/terminals.ts +346 -0
- package/src/repositories/workloads.ts +134 -0
- package/src/request-id.ts +46 -0
- package/src/resolve.ts +396 -0
- package/src/retention.ts +34 -0
- package/src/roles.ts +54 -0
- package/src/rpc-http.ts +333 -0
- package/src/rpc-inputs.ts +110 -0
- package/src/rpc.ts +440 -0
- package/src/secret.ts +45 -0
- package/src/service.ts +59 -0
- package/src/services.ts +199 -0
- package/src/signing.ts +260 -0
- package/src/stored-chain.ts +23 -0
- package/src/stored-permissions.ts +34 -0
- package/src/terminals.ts +15 -0
- package/src/tokens.ts +506 -0
- package/src/workload-token.ts +130 -0
- package/types/fabrika.config.d.ts +11 -0
- package/types/src/admin/access.d.ts +19 -0
- package/types/src/admin/api-keys.d.ts +26 -0
- package/types/src/admin/app-people.d.ts +8 -0
- package/types/src/admin/app-schema.d.ts +32 -0
- package/types/src/admin/audit.d.ts +10 -0
- package/types/src/admin/brand.d.ts +10 -0
- package/types/src/admin/connections.d.ts +5 -0
- package/types/src/admin/context.d.ts +46 -0
- package/types/src/admin/grant-support.d.ts +59 -0
- package/types/src/admin/grants.d.ts +8 -0
- package/types/src/admin/handlers.d.ts +82 -0
- package/types/src/admin/http.d.ts +9 -0
- package/types/src/admin/membership-keys.d.ts +8 -0
- package/types/src/admin/pagination.d.ts +5 -0
- package/types/src/admin/password-policy.d.ts +9 -0
- package/types/src/admin/passwords.d.ts +5 -0
- package/types/src/admin/policies.d.ts +15 -0
- package/types/src/admin/principals.d.ts +15 -0
- package/types/src/admin/router.d.ts +75 -0
- package/types/src/admin/rpc.d.ts +6 -0
- package/types/src/admin/sessions.d.ts +14 -0
- package/types/src/admin/share-links.d.ts +21 -0
- package/types/src/admin/terminals.d.ts +13 -0
- package/types/src/admin/user-admin.d.ts +30 -0
- package/types/src/admin/workloads.d.ts +5 -0
- package/types/src/app-presentation.d.ts +86 -0
- package/types/src/app.d.ts +62 -0
- package/types/src/auth/cookies.d.ts +29 -0
- package/types/src/auth/failure.d.ts +47 -0
- package/types/src/auth/handoff.d.ts +66 -0
- package/types/src/auth/http.d.ts +29 -0
- package/types/src/auth/invitations.d.ts +18 -0
- package/types/src/auth/known-device.d.ts +12 -0
- package/types/src/auth/login.d.ts +10 -0
- package/types/src/auth/oidc-flight.d.ts +39 -0
- package/types/src/auth/oidc.d.ts +7 -0
- package/types/src/auth/password.d.ts +7 -0
- package/types/src/auth/routes.d.ts +15 -0
- package/types/src/auth/sessions.d.ts +60 -0
- package/types/src/auth/terminals.d.ts +47 -0
- package/types/src/auth.d.ts +70 -0
- package/types/src/binding-identity.d.ts +12 -0
- package/types/src/bounded-body.d.ts +12 -0
- package/types/src/catalog/cs.d.ts +2 -0
- package/types/src/catalog/en.d.ts +2 -0
- package/types/src/catalog/index.d.ts +112 -0
- package/types/src/catalog/uk.d.ts +2 -0
- package/types/src/client-address.d.ts +31 -0
- package/types/src/common-passwords.d.ts +2 -0
- package/types/src/contract-rules.d.ts +25 -0
- package/types/src/cron.d.ts +15 -0
- package/types/src/db.d.ts +58 -0
- package/types/src/delegation.d.ts +38 -0
- package/types/src/device-http.d.ts +2 -0
- package/types/src/device.d.ts +11 -0
- package/types/src/email-identity.d.ts +1 -0
- package/types/src/env.d.ts +127 -0
- package/types/src/handoff.d.ts +57 -0
- package/types/src/html.d.ts +2 -0
- package/types/src/human-admission.d.ts +22 -0
- package/types/src/identification.d.ts +30 -0
- package/types/src/index.d.ts +62 -0
- package/types/src/installation-brand.d.ts +22 -0
- package/types/src/issue.d.ts +62 -0
- package/types/src/json.d.ts +15 -0
- package/types/src/log.d.ts +15 -0
- package/types/src/membership-http.d.ts +8 -0
- package/types/src/membership.d.ts +156 -0
- package/types/src/messages.d.ts +20 -0
- package/types/src/narrow-permissions.d.ts +7 -0
- package/types/src/node/browser-identity.d.ts +1 -0
- package/types/src/node/migrate.d.ts +4 -0
- package/types/src/node/prune.d.ts +1 -0
- package/types/src/node/runtime.d.ts +51 -0
- package/types/src/node/server.d.ts +5 -0
- package/types/src/oauth-client-auth.d.ts +26 -0
- package/types/src/oauth-client.d.ts +17 -0
- package/types/src/oauth-config.d.ts +16 -0
- package/types/src/oauth-http.d.ts +7 -0
- package/types/src/oauth.d.ts +51 -0
- package/types/src/oidc.d.ts +81 -0
- package/types/src/origin.d.ts +9 -0
- package/types/src/password-crypto.d.ts +37 -0
- package/types/src/password-db.d.ts +134 -0
- package/types/src/password-minimum.d.ts +23 -0
- package/types/src/password-pages.d.ts +143 -0
- package/types/src/password-policy.d.ts +19 -0
- package/types/src/password-service.d.ts +24 -0
- package/types/src/person-locale.d.ts +50 -0
- package/types/src/proxy-proof.d.ts +21 -0
- package/types/src/relay-mail.d.ts +25 -0
- package/types/src/repositories/app-schema.d.ts +244 -0
- package/types/src/repositories/audit.d.ts +187 -0
- package/types/src/repositories/brand.d.ts +41 -0
- package/types/src/repositories/credentials.d.ts +148 -0
- package/types/src/repositories/device.d.ts +50 -0
- package/types/src/repositories/grants.d.ts +177 -0
- package/types/src/repositories/handoff.d.ts +52 -0
- package/types/src/repositories/membership-transport.d.ts +31 -0
- package/types/src/repositories/membership.d.ts +273 -0
- package/types/src/repositories/oauth.d.ts +55 -0
- package/types/src/repositories/password-policy.d.ts +25 -0
- package/types/src/repositories/principals.d.ts +159 -0
- package/types/src/repositories/sessions.d.ts +150 -0
- package/types/src/repositories/sql.d.ts +13 -0
- package/types/src/repositories/terminals.d.ts +144 -0
- package/types/src/repositories/workloads.d.ts +61 -0
- package/types/src/request-id.d.ts +25 -0
- package/types/src/resolve.d.ts +118 -0
- package/types/src/retention.d.ts +18 -0
- package/types/src/roles.d.ts +34 -0
- package/types/src/rpc-http.d.ts +53 -0
- package/types/src/rpc-inputs.d.ts +707 -0
- package/types/src/rpc.d.ts +4 -0
- package/types/src/secret.d.ts +21 -0
- package/types/src/service.d.ts +19 -0
- package/types/src/services.d.ts +72 -0
- package/types/src/signing.d.ts +72 -0
- package/types/src/stored-chain.d.ts +6 -0
- package/types/src/stored-permissions.d.ts +12 -0
- package/types/src/terminals.d.ts +7 -0
- package/types/src/tokens.d.ts +113 -0
- package/types/src/workload-token.d.ts +7 -0
- package/README.md +0 -3
package/src/tokens.ts
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minting per-app access tokens — the heart of IAM-native auth.
|
|
3
|
+
*
|
|
4
|
+
* Two fronts over one resolve→sign core:
|
|
5
|
+
* - `mintToken` — from the browser's opaque SSO session cookie (a principal-bound credential in a
|
|
6
|
+
* cookie). Validates the session, resolves the principal's permissions for the calling app.
|
|
7
|
+
* - `mintFromKey` — from an opaque `px_` credential (API key / share link) presented as a bearer or
|
|
8
|
+
* URL-path token. Resolves the credential's EFFECTIVE permissions (the 2×2: principal? ∩ inline).
|
|
9
|
+
*
|
|
10
|
+
* Both end in `signAccessToken`: sign a short-lived token the SDK then verifies locally, so this runs
|
|
11
|
+
* ≈ once per TTL per app, not per request. `mintToken` always yields a principal token; `mintFromKey`
|
|
12
|
+
* yields a principal token (bound credential) or an anonymous one (frozen inline grants).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
type AccessTokenClaims,
|
|
17
|
+
buildAccessClaims,
|
|
18
|
+
DEFAULT_TOKEN_TTL_SECONDS,
|
|
19
|
+
isReservedScopeType,
|
|
20
|
+
type KeyGrant,
|
|
21
|
+
type LinkTokenClaims,
|
|
22
|
+
MAX_ACCESS_TOKEN_BYTES,
|
|
23
|
+
MAX_APPLICATION_TOKEN_BYTES,
|
|
24
|
+
type MintFromKeyResult,
|
|
25
|
+
type MintTokenInput,
|
|
26
|
+
type MintTokenResult,
|
|
27
|
+
type PermissionEntry,
|
|
28
|
+
permits,
|
|
29
|
+
type Scope,
|
|
30
|
+
type TokenPrincipalType,
|
|
31
|
+
} from '@fabrika/auth-core'
|
|
32
|
+
import { sessionUsable } from './auth'
|
|
33
|
+
import type { CredentialGrantRow, CredentialRow, PrincipalRow, SessionTerminal } from './db'
|
|
34
|
+
import { principalStatus, sessionTerminal } from './db'
|
|
35
|
+
import { issuerAuthority, issuerCoverage } from './delegation'
|
|
36
|
+
import type { Env } from './env'
|
|
37
|
+
import { narrowPermissions } from './narrow-permissions'
|
|
38
|
+
import { authorityDeadline, reachesCrossAppAuthority, resolveAuthorityAt, type ResolvedAuthority } from './resolve'
|
|
39
|
+
import { hashToken } from './secret'
|
|
40
|
+
import type { Services } from './services'
|
|
41
|
+
import { getSigner } from './signing'
|
|
42
|
+
import { parseStoredChain } from './stored-chain'
|
|
43
|
+
|
|
44
|
+
/** The env slice minting needs (the signing keys + environment for `getSigner`). */
|
|
45
|
+
type MintEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* `principalId` (resolved session subject, or null on failure) and the session's terminal are surfaced for the
|
|
49
|
+
* auth_log row.
|
|
50
|
+
*/
|
|
51
|
+
export interface MintOutcome {
|
|
52
|
+
result: MintTokenResult
|
|
53
|
+
principalId: string | null
|
|
54
|
+
terminal: SessionTerminal | null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function mintToken(services: Services, env: MintEnv, input: MintTokenInput): Promise<MintOutcome> {
|
|
58
|
+
if (!input.session) {
|
|
59
|
+
return { result: { ok: false, reason: 'no_session' }, principalId: null, terminal: null }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const tokenHash = await hashToken(input.session)
|
|
63
|
+
const session = await services.repositories.sessions.getActiveSessionByHash(tokenHash)
|
|
64
|
+
if (!session) {
|
|
65
|
+
// A revoked or expired session still names its principal and terminal in the refusal's `auth_log` row (ADR-0067 §6).
|
|
66
|
+
const stored = await services.repositories.sessions.getSessionByHashForAudit(tokenHash)
|
|
67
|
+
return {
|
|
68
|
+
result: { ok: false, reason: 'invalid_session' },
|
|
69
|
+
principalId: stored?.principal_id ?? null,
|
|
70
|
+
terminal: stored === null ? null : sessionTerminal(stored),
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const terminal = sessionTerminal(session)
|
|
74
|
+
const refused = (reason: Exclude<MintTokenResult, { ok: true }>['reason'], principalId: string | null): MintOutcome => ({
|
|
75
|
+
result: { ok: false, reason },
|
|
76
|
+
principalId,
|
|
77
|
+
terminal,
|
|
78
|
+
})
|
|
79
|
+
// An app-bound child session (ADR-0022) mints for its own app and nothing else. The cookie is
|
|
80
|
+
// host-only so a sibling app cannot read it; this is the second lock, for a value that leaks anyway.
|
|
81
|
+
if (session.app !== null && session.app !== input.app) {
|
|
82
|
+
return refused('invalid_session', session.principal_id)
|
|
83
|
+
}
|
|
84
|
+
// A session asserted at a terminal mints only for the application that asserted it (ADR-0067 §4).
|
|
85
|
+
if (terminal !== null && terminal.assertedBy !== input.app) {
|
|
86
|
+
return refused('invalid_session', session.principal_id)
|
|
87
|
+
}
|
|
88
|
+
// A session outlives the configuration that issued it; refuse it once its method is off.
|
|
89
|
+
if (!sessionUsable(session, services.config)) {
|
|
90
|
+
return refused('invalid_session', session.principal_id)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const principal = await services.repositories.principals.getPrincipalById(session.principal_id)
|
|
94
|
+
if (!principal) {
|
|
95
|
+
// The session outlived its principal (deleted) — treat as unknown.
|
|
96
|
+
return refused('unknown_principal', null)
|
|
97
|
+
}
|
|
98
|
+
if (principalStatus(principal) === 'disabled') {
|
|
99
|
+
return refused('disabled', principal.id)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Resolve permissions for the requesting app. Sessions are a USER credential (OIDC login).
|
|
103
|
+
const authority = await resolveAuthorityAt(services, principal, input.app)
|
|
104
|
+
const onTerminal = terminal === null ? null : await terminalAuthority(services, terminal, input.app)
|
|
105
|
+
if (terminal !== null && onTerminal === null) {
|
|
106
|
+
return refused('invalid_session', principal.id)
|
|
107
|
+
}
|
|
108
|
+
const permissions = onTerminal === null ? authority.permissions : withinTerminal(authority.permissions, onTerminal)
|
|
109
|
+
|
|
110
|
+
const now = Math.floor(Date.now() / 1000)
|
|
111
|
+
// Clamped to the session, exactly as `mintFromKey` clamps to the credential's expiry: a token
|
|
112
|
+
// minted a minute before the session ends must not outlive it, or logging out (or an expiry) would
|
|
113
|
+
// leave a valid token in the app's hands for the rest of its TTL (SEC-27). Nor may it outlive a grant it carries.
|
|
114
|
+
// In a grant's last 30 s (the proxy's TOKEN_REFRESH_SKEW_SECONDS) the proxy re-mints per request; cache.test.ts pins it.
|
|
115
|
+
const expiresAt = Math.min(
|
|
116
|
+
now + DEFAULT_TOKEN_TTL_SECONDS,
|
|
117
|
+
session.expires_at,
|
|
118
|
+
authorityDeadline(authority, onTerminal === null ? permissions : narrowPermissions(authority.permissions, onTerminal.ceiling), now)
|
|
119
|
+
?? Number.POSITIVE_INFINITY,
|
|
120
|
+
// A terminal's own entries are its principal's grants, and end with them.
|
|
121
|
+
(onTerminal === null ? null : authorityDeadline(onTerminal.authority, onTerminal.additions, now)) ?? Number.POSITIVE_INFINITY,
|
|
122
|
+
)
|
|
123
|
+
const token = await boundedToken(
|
|
124
|
+
signAccessToken(services, env, {
|
|
125
|
+
app: input.app,
|
|
126
|
+
subject: principal.id,
|
|
127
|
+
type: principal.type,
|
|
128
|
+
label: principal.label,
|
|
129
|
+
...mailboxClaim(principal),
|
|
130
|
+
session: true,
|
|
131
|
+
...(onTerminal === null ? {} : { terminal: { id: onTerminal.id, label: onTerminal.label } }),
|
|
132
|
+
permissions,
|
|
133
|
+
issuedAt: now,
|
|
134
|
+
expiresAt,
|
|
135
|
+
}),
|
|
136
|
+
{ app: input.app, subject: principal.id, bytes: await proxyMintedBound(services, input.app) },
|
|
137
|
+
)
|
|
138
|
+
if (token === null) {
|
|
139
|
+
return refused('token_too_large', principal.id)
|
|
140
|
+
}
|
|
141
|
+
return { result: { ok: true, token, expiresAt }, principalId: principal.id, terminal }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** What a terminal brings to a session on it at one application: its ceiling and its own grants there. */
|
|
145
|
+
interface TerminalAuthority {
|
|
146
|
+
id: string
|
|
147
|
+
label: string
|
|
148
|
+
ceiling: KeyGrant[]
|
|
149
|
+
additions: PermissionEntry[]
|
|
150
|
+
/** The terminal principal's own authority, which `additions` come from. */
|
|
151
|
+
authority: ResolvedAuthority
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The terminal's authority at `app`, or null when the session may no longer mint there: `app` is a platform audience,
|
|
156
|
+
* whose tokens carry cross-app authority, the terminal is gone or revoked, no longer lists `app` as an asserter, `app`
|
|
157
|
+
* no longer declares a terminal, or the terminal's principal is disabled. The validity join already refused a revoked terminal; this read is the one the ceiling comes
|
|
158
|
+
* from, so it checks again.
|
|
159
|
+
*/
|
|
160
|
+
async function terminalAuthority(services: Services, terminal: SessionTerminal, app: string): Promise<TerminalAuthority | null> {
|
|
161
|
+
if (reachesCrossAppAuthority(services.config, app)) {
|
|
162
|
+
return null
|
|
163
|
+
}
|
|
164
|
+
const row = await services.repositories.terminals.getById(terminal.terminalId)
|
|
165
|
+
if (row === null || row.revoked_at !== null) {
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
const asserter = await services.repositories.terminals.getAsserter(row.principal_id, app)
|
|
169
|
+
// An application that no longer declares a terminal is no asserter: its framework may not read a terminal token.
|
|
170
|
+
if (asserter === null || await services.repositories.appSchema.getTerminalIdentifyPath(app) === null) {
|
|
171
|
+
return null
|
|
172
|
+
}
|
|
173
|
+
const principal = await services.repositories.principals.getPrincipalById(row.principal_id)
|
|
174
|
+
if (principal === null || principalStatus(principal) === 'disabled') {
|
|
175
|
+
return null
|
|
176
|
+
}
|
|
177
|
+
const granted = await resolveAuthorityAt(services, principal, app)
|
|
178
|
+
return {
|
|
179
|
+
id: row.principal_id,
|
|
180
|
+
label: row.label,
|
|
181
|
+
ceiling: asserter.ceiling.map((action): KeyGrant => ({ action })),
|
|
182
|
+
additions: granted.permissions.map((entry): PermissionEntry => ({ ...entry, source: 'terminal' })),
|
|
183
|
+
authority: granted,
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* A person's live authority at `app` on the terminal `terminalId` that asserted them there (ADR-0067 §4): the set a
|
|
189
|
+
* mint would sign now, and the grants behind it, the terminal principal's included; null when the terminal could no
|
|
190
|
+
* longer mint for `app`. What a terminal session's token is re-resolved against.
|
|
191
|
+
*/
|
|
192
|
+
export async function authorityOnTerminal(
|
|
193
|
+
services: Services,
|
|
194
|
+
principal: PrincipalRow,
|
|
195
|
+
terminalId: string,
|
|
196
|
+
app: string,
|
|
197
|
+
): Promise<ResolvedAuthority | null> {
|
|
198
|
+
const terminal = await terminalAuthority(services, { terminalId, assertedBy: app }, app)
|
|
199
|
+
if (terminal === null) {
|
|
200
|
+
return null
|
|
201
|
+
}
|
|
202
|
+
const personal = await resolveAuthorityAt(services, principal, app)
|
|
203
|
+
return { permissions: withinTerminal(personal.permissions, terminal), supports: [...personal.supports, ...terminal.authority.supports] }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* A person's permissions on a terminal (ADR-0067 §4): each of their own entries narrowed by the ceiling patterns it
|
|
208
|
+
* overlaps, keeping its scope, and then the terminal's own, with the source `terminal`. A person's `*` under a ceiling
|
|
209
|
+
* `a.read` keeps `a.read`; an empty ceiling keeps none of the person's.
|
|
210
|
+
*/
|
|
211
|
+
function withinTerminal(personal: PermissionEntry[], terminal: TerminalAuthority): PermissionEntry[] {
|
|
212
|
+
return [...narrowPermissions(personal, terminal.ceiling), ...terminal.additions]
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** `principalId`/`credentialId` are surfaced for the auth_log row. */
|
|
216
|
+
export interface MintFromKeyOutcome {
|
|
217
|
+
result: MintFromKeyResult
|
|
218
|
+
principalId: string | null
|
|
219
|
+
credentialId: string | null
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Resolve an opaque `px_` credential into an access token. The credential's EFFECTIVE permissions
|
|
224
|
+
* follow the 2×2: principal-bound → that principal's live resolved perms (∩ inline restriction when
|
|
225
|
+
* present); anonymous → its frozen inline grants. The signed token is principal-bound (carries
|
|
226
|
+
* `ptype`) iff the credential is.
|
|
227
|
+
*/
|
|
228
|
+
export async function mintFromKey(
|
|
229
|
+
services: Services,
|
|
230
|
+
env: MintEnv,
|
|
231
|
+
input: { app: string; key: string; requestId: string },
|
|
232
|
+
): Promise<MintFromKeyOutcome> {
|
|
233
|
+
const cred = await services.repositories.credentials.getActiveCredentialByHash(await hashToken(input.key))
|
|
234
|
+
if (!cred) {
|
|
235
|
+
return { result: { ok: false, reason: 'invalid_key' }, principalId: null, credentialId: null }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const effective = await resolveCredential(services, cred, input.app)
|
|
239
|
+
if (!effective.ok) {
|
|
240
|
+
// `wrong_app` is reported as `invalid_key`: a caller holding a credential for another app must
|
|
241
|
+
// not learn that it exists, and there is nothing it can do differently here. Nor whose authority it rested on.
|
|
242
|
+
const reason = effective.reason === 'wrong_app' || effective.reason === 'issuer_unauthorized' ? 'invalid_key' : effective.reason
|
|
243
|
+
return { result: { ok: false, reason }, principalId: cred.principal_id, credentialId: cred.id }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const now = Math.floor(Date.now() / 1000)
|
|
247
|
+
const expiresAt = Math.min(
|
|
248
|
+
now + DEFAULT_TOKEN_TTL_SECONDS,
|
|
249
|
+
cred.expires_at ?? Number.POSITIVE_INFINITY,
|
|
250
|
+
effective.expiresAt ?? Number.POSITIVE_INFINITY,
|
|
251
|
+
)
|
|
252
|
+
const token = await boundedToken(
|
|
253
|
+
signAccessToken(services, env, {
|
|
254
|
+
app: input.app,
|
|
255
|
+
subject: effective.subject,
|
|
256
|
+
...(effective.type === undefined ? {} : { type: effective.type }),
|
|
257
|
+
...(effective.workload === undefined ? {} : { workload: effective.workload }),
|
|
258
|
+
label: effective.label,
|
|
259
|
+
...(effective.email === undefined ? {} : { email: effective.email }),
|
|
260
|
+
permissions: effective.permissions,
|
|
261
|
+
...(effective.link === undefined ? {} : { link: effective.link }),
|
|
262
|
+
issuedAt: now,
|
|
263
|
+
expiresAt,
|
|
264
|
+
}),
|
|
265
|
+
{ app: input.app, subject: effective.subject, bytes: await proxyMintedBound(services, input.app) },
|
|
266
|
+
)
|
|
267
|
+
if (token === null) {
|
|
268
|
+
return { result: { ok: false, reason: 'token_too_large' }, principalId: cred.principal_id, credentialId: cred.id }
|
|
269
|
+
}
|
|
270
|
+
return { result: { ok: true, token, expiresAt }, principalId: cred.principal_id, credentialId: cred.id }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The token of a job's or a webhook's own key, for `POST /auth/workload/token`. The kind and the application are
|
|
275
|
+
* checked before anything about the principal is read, so every key that is not a live job or webhook key of `app` —
|
|
276
|
+
* absent, revoked, expired, of another kind or app, or of a disabled principal — answers the same `invalid_key`.
|
|
277
|
+
* A storage failure throws: the route answers it as "IAM could not be asked", never as a refusal.
|
|
278
|
+
*/
|
|
279
|
+
export async function mintFromWorkloadKey(services: Services, env: MintEnv, input: { app: string; key: string }): Promise<MintFromKeyOutcome> {
|
|
280
|
+
const refused: MintFromKeyOutcome = { result: { ok: false, reason: 'invalid_key' }, principalId: null, credentialId: null }
|
|
281
|
+
const cred = await services.repositories.credentials.getActiveCredentialByHash(await hashToken(input.key))
|
|
282
|
+
if (cred === null || cred.principal_id === null || cred.app !== input.app) {
|
|
283
|
+
return refused
|
|
284
|
+
}
|
|
285
|
+
const workload = await services.repositories.workloads.getByPrincipal(cred.principal_id)
|
|
286
|
+
if (workload === null || workload.kind === 'app' || workload.app !== input.app) {
|
|
287
|
+
return refused
|
|
288
|
+
}
|
|
289
|
+
const effective = await resolveCredential(services, cred, input.app)
|
|
290
|
+
if (!effective.ok || effective.type !== workload.kind) {
|
|
291
|
+
return refused
|
|
292
|
+
}
|
|
293
|
+
const now = Math.floor(Date.now() / 1000)
|
|
294
|
+
const expiresAt = Math.min(now + DEFAULT_TOKEN_TTL_SECONDS, cred.expires_at ?? Number.POSITIVE_INFINITY)
|
|
295
|
+
const token = await boundedToken(
|
|
296
|
+
signAccessToken(services, env, {
|
|
297
|
+
app: input.app,
|
|
298
|
+
subject: effective.subject,
|
|
299
|
+
type: workload.kind,
|
|
300
|
+
workload: workload.name,
|
|
301
|
+
label: effective.label,
|
|
302
|
+
permissions: effective.permissions,
|
|
303
|
+
issuedAt: now,
|
|
304
|
+
expiresAt,
|
|
305
|
+
}),
|
|
306
|
+
{ app: input.app, subject: effective.subject },
|
|
307
|
+
)
|
|
308
|
+
if (token === null) {
|
|
309
|
+
return refused
|
|
310
|
+
}
|
|
311
|
+
return { result: { ok: true, token, expiresAt }, principalId: cred.principal_id, credentialId: cred.id }
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* The credential's effective permissions + the token subject/type/label, or a typed failure.
|
|
316
|
+
* `wrong_app` is IAM-internal: every mint front reports it as `invalid_key`, because "this key is
|
|
317
|
+
* not for you" and "there is no such key" must look the same to a caller who holds neither.
|
|
318
|
+
*/
|
|
319
|
+
export type ResolvedCredential =
|
|
320
|
+
| {
|
|
321
|
+
ok: true
|
|
322
|
+
subject: string
|
|
323
|
+
type?: TokenPrincipalType
|
|
324
|
+
/** A workload principal's name (`job`, `webhook`), or a connector's consuming application (`app`). */
|
|
325
|
+
workload?: string
|
|
326
|
+
label: string | null
|
|
327
|
+
/** A user principal's mailbox. */
|
|
328
|
+
email?: string
|
|
329
|
+
permissions: PermissionEntry[]
|
|
330
|
+
/** When the earliest carried permission loses its last supporting grant; `null` when none expires. */
|
|
331
|
+
expiresAt: number | null
|
|
332
|
+
link?: LinkTokenClaims
|
|
333
|
+
}
|
|
334
|
+
| { ok: false; reason: 'unknown_principal' | 'disabled' | 'wrong_app' | 'issuer_unauthorized' }
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Resolve a credential's effective permissions FOR ONE APP.
|
|
338
|
+
*
|
|
339
|
+
* **The app binding is checked first, and it is not optional for an anonymous credential.** Inline
|
|
340
|
+
* grants are frozen at issue and were delegation-checked against the issuer's permissions *for the
|
|
341
|
+
* issuing app*; without a binding that authority was granted per app and spent installation-wide, so
|
|
342
|
+
* an app-scoped admin of the least important app could issue `{ action: '*' }` and present the key to
|
|
343
|
+
* every other app behind the proxy (SEC-2). A `NULL` app on an anonymous credential is therefore
|
|
344
|
+
* refused rather than treated as cross-app — a credential issued before the binding existed must be
|
|
345
|
+
* reissued, a hard cutover.
|
|
346
|
+
*
|
|
347
|
+
* A principal-bound credential may be cross-app (`NULL`) because it carries no frozen authority: its
|
|
348
|
+
* permissions are resolved per app from `grants`, which are themselves app-filtered. When it names an
|
|
349
|
+
* app, that is a downscope and is enforced the same way.
|
|
350
|
+
*/
|
|
351
|
+
export async function resolveCredential(services: Services, cred: CredentialRow, app: string): Promise<ResolvedCredential> {
|
|
352
|
+
if (cred.app !== null && cred.app !== app) {
|
|
353
|
+
return { ok: false, reason: 'wrong_app' }
|
|
354
|
+
}
|
|
355
|
+
if (cred.principal_id === null && cred.app === null) {
|
|
356
|
+
return { ok: false, reason: 'wrong_app' }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const rows = await services.repositories.credentials.getCredentialGrants(cred.id)
|
|
360
|
+
const inline = rows.flatMap(credentialGrantToEntry)
|
|
361
|
+
|
|
362
|
+
if (cred.principal_id === null) {
|
|
363
|
+
// Anonymous: the frozen inline grants ARE the permission set, delegated by the issuer, who must still hold them.
|
|
364
|
+
if (cred.link_mount === null) {
|
|
365
|
+
const issuer = await issuerAuthority(services, cred.issued_by, app, null, inline.map((entry) => ({ action: entry.action, on: [entry.scope] })))
|
|
366
|
+
if (!issuer.ok) return issuer
|
|
367
|
+
return { ok: true, subject: cred.id, label: cred.label, permissions: inline, expiresAt: issuer.expiresAt }
|
|
368
|
+
}
|
|
369
|
+
// A share link's token names its mount and chain, which the framework re-checks per request.
|
|
370
|
+
const chain = cred.link_chain === null ? null : parseStoredChain(cred.link_chain)
|
|
371
|
+
if (chain === null) {
|
|
372
|
+
return { ok: false, reason: 'wrong_app' }
|
|
373
|
+
}
|
|
374
|
+
const mount = await services.repositories.appSchema.getLinkMount(app, cred.link_mount)
|
|
375
|
+
if (mount === null || mount.dimension !== cred.link_dimension) {
|
|
376
|
+
return { ok: false, reason: 'issuer_unauthorized' }
|
|
377
|
+
}
|
|
378
|
+
// As `issueLink` checked: the mount's `issuedBy` and every frozen action, each held on some link of the chain.
|
|
379
|
+
const required = [mount.issued_by, ...inline.map((entry) => entry.action)].map((action) => ({ action, on: chain }))
|
|
380
|
+
const issuer = await issuerAuthority(services, cred.issued_by, app, cred.link_mount, required)
|
|
381
|
+
if (!issuer.ok) return issuer
|
|
382
|
+
return {
|
|
383
|
+
ok: true,
|
|
384
|
+
subject: cred.id,
|
|
385
|
+
label: cred.label,
|
|
386
|
+
permissions: inline,
|
|
387
|
+
expiresAt: issuer.expiresAt,
|
|
388
|
+
link: { mount: cred.link_mount, chain },
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const principal = await services.repositories.principals.getPrincipalById(cred.principal_id)
|
|
393
|
+
if (!principal) {
|
|
394
|
+
return { ok: false, reason: 'unknown_principal' }
|
|
395
|
+
}
|
|
396
|
+
if (principalStatus(principal) === 'disabled') {
|
|
397
|
+
return { ok: false, reason: 'disabled' }
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// A workload's authority is what the app's schema declares for it now: exact actions, app-wide. Its grants, if an
|
|
401
|
+
// administrator wrote any, give it nothing more.
|
|
402
|
+
const workload = await services.repositories.workloads.getByPrincipal(principal.id)
|
|
403
|
+
if (workload !== null) {
|
|
404
|
+
if (workload.app !== app) {
|
|
405
|
+
return { ok: false, reason: 'wrong_app' }
|
|
406
|
+
}
|
|
407
|
+
const actions = (await services.repositories.workloads.declaredActions(workload.app, workload.kind, workload.name)) ?? []
|
|
408
|
+
const declared = actions.map((action): PermissionEntry => ({ action, scope: null, source: 'grant' }))
|
|
409
|
+
return {
|
|
410
|
+
ok: true,
|
|
411
|
+
subject: principal.id,
|
|
412
|
+
type: workload.kind,
|
|
413
|
+
workload: workload.name,
|
|
414
|
+
label: principal.label,
|
|
415
|
+
permissions: declared,
|
|
416
|
+
expiresAt: null,
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const authority = await resolveAuthorityAt(services, principal, app)
|
|
421
|
+
const resolved = authority.permissions
|
|
422
|
+
|
|
423
|
+
// Inline grants on a bound credential are a DOWNSCOPE restriction: keep only what the principal
|
|
424
|
+
// actually holds (effective = resolve(principal) ∩ inline). No inline → the principal's full set.
|
|
425
|
+
const held = rows.length === 0 ? resolved : inline.filter((e) => permits(resolved, e.action, e.scope ?? undefined))
|
|
426
|
+
const heldUntil = authorityDeadline(authority, held, Math.floor(Date.now() / 1000))
|
|
427
|
+
if (cred.issued_by === null || cred.issued_by === principal.id) {
|
|
428
|
+
return {
|
|
429
|
+
ok: true,
|
|
430
|
+
subject: principal.id,
|
|
431
|
+
type: principal.type,
|
|
432
|
+
label: principal.label,
|
|
433
|
+
...mailboxClaim(principal),
|
|
434
|
+
permissions: held,
|
|
435
|
+
expiresAt: heldUntil,
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
// A key one principal issued for another (a service or device key) is delegation too: no more than its issuer covers (S8).
|
|
439
|
+
const issued = await issuerCoverage(services, cred.issued_by, app, held)
|
|
440
|
+
if (!issued.ok) return issued
|
|
441
|
+
const expiresAt = heldUntil === null ? issued.expiresAt : issued.expiresAt === null ? heldUntil : Math.min(heldUntil, issued.expiresAt)
|
|
442
|
+
return {
|
|
443
|
+
ok: true,
|
|
444
|
+
subject: principal.id,
|
|
445
|
+
type: principal.type,
|
|
446
|
+
label: principal.label,
|
|
447
|
+
...mailboxClaim(principal),
|
|
448
|
+
permissions: issued.permissions,
|
|
449
|
+
expiresAt,
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* A user's mailbox for its token: `principals.email`, normalized by `PrincipalRepository`, the address the person signs
|
|
455
|
+
* in with. An application mails it as `ctx.principal.email`, so it is never `label`, the spelling the person sees.
|
|
456
|
+
*/
|
|
457
|
+
function mailboxClaim(principal: PrincipalRow): { email?: string } {
|
|
458
|
+
return principal.type === 'user' && principal.email !== null ? { email: principal.email } : {}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* A `credential_grants` row → its `PermissionEntry` (source 'grant'; both scope cols null = global). A row stored before
|
|
463
|
+
* `~` was reserved gives none: IAM alone derives a `~` entry. It still counts as a row, so it keeps a key downscoped.
|
|
464
|
+
*/
|
|
465
|
+
function credentialGrantToEntry(row: CredentialGrantRow): PermissionEntry[] {
|
|
466
|
+
if (row.scope_type !== null && isReservedScopeType(row.scope_type)) return []
|
|
467
|
+
const scope: Scope | null = row.scope_type === null || row.scope_value === null ? null : { type: row.scope_type, value: row.scope_value }
|
|
468
|
+
return [{ action: row.action, scope, source: 'grant' }]
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* The size bound of a token the proxy mints from a session or a `px_` key: `MAX_APPLICATION_TOKEN_BYTES` at a contract
|
|
473
|
+
* application, whose token only the proxy injects toward the application; `MAX_ACCESS_TOKEN_BYTES` at an installation
|
|
474
|
+
* service, whose Bun keeps its default header limit.
|
|
475
|
+
*/
|
|
476
|
+
async function proxyMintedBound(services: Services, app: string): Promise<number> {
|
|
477
|
+
return (await services.repositories.appSchema.isContractApp(app)) ? MAX_APPLICATION_TOKEN_BYTES : MAX_ACCESS_TOKEN_BYTES
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* The signed token, or null — with a warning naming the subject and the size — when it is above `who.bytes`
|
|
482
|
+
* (`MAX_ACCESS_TOKEN_BYTES` unless given). Every bearer IAM issues passes here: native tokens and OAuth resource tokens.
|
|
483
|
+
*/
|
|
484
|
+
export async function boundedToken(
|
|
485
|
+
signed: Promise<string>,
|
|
486
|
+
who: { app: string; subject: string; bytes?: number },
|
|
487
|
+
): Promise<string | null> {
|
|
488
|
+
const token = await signed
|
|
489
|
+
const bound = who.bytes ?? MAX_ACCESS_TOKEN_BYTES
|
|
490
|
+
if (token.length <= bound) {
|
|
491
|
+
return token
|
|
492
|
+
}
|
|
493
|
+
console.warn(`access token for '${who.subject}' at app '${who.app}' is ${token.length} bytes, above the ${bound}-byte bound; refused`)
|
|
494
|
+
return null
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** Sign an access token with the isolate's active signing key. Shared by every mint front. */
|
|
498
|
+
export async function signAccessToken(
|
|
499
|
+
services: Services,
|
|
500
|
+
env: MintEnv,
|
|
501
|
+
params: Omit<Parameters<typeof buildAccessClaims>[0], 'iss'>,
|
|
502
|
+
): Promise<string> {
|
|
503
|
+
const signer = await getSigner(env)
|
|
504
|
+
const claims: AccessTokenClaims = buildAccessClaims({ ...params, iss: services.config.issuer })
|
|
505
|
+
return signer.sign(claims)
|
|
506
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// `POST /auth/workload/token`: a job or a webhook of a contract application exchanges its own `px_` key for an access
|
|
2
|
+
// token (ADR-0022 "Principal kinds"). The key is the whole authority: the route answers only for a workload key of the
|
|
3
|
+
// named app, so it is no oracle for any other credential, and the token it signs is accepted by no mount.
|
|
4
|
+
//
|
|
5
|
+
// The route is public, so a request's cost is bounded before any lookup: the key's format first, then a body of at most
|
|
6
|
+
// 4 KiB, then the per-client bucket the password and device routes use (only where the composition names a trusted
|
|
7
|
+
// client address; without one there is no bucket, never a guess), then one lookup by the key's hash. A refusal writes
|
|
8
|
+
// no auth-log row; refusals are counted and logged once per interval.
|
|
9
|
+
|
|
10
|
+
import type { MintFromKeyResult } from '@fabrika/auth-core'
|
|
11
|
+
import { z } from 'zod'
|
|
12
|
+
import { readBoundedText } from './bounded-body'
|
|
13
|
+
import type { Env, RequestContext } from './env'
|
|
14
|
+
import { parseJsonOrNull } from './json'
|
|
15
|
+
import { logError } from './log'
|
|
16
|
+
import { hashToken, ISSUED_KEY_FORMAT } from './secret'
|
|
17
|
+
import type { Services } from './services'
|
|
18
|
+
import { mintFromWorkloadKey } from './tokens'
|
|
19
|
+
|
|
20
|
+
const bodySchema = z.object({ app: z.string().min(1).max(160) }).strict()
|
|
21
|
+
/** `{ app }` is at most a few hundred bytes. */
|
|
22
|
+
const BODY_MAX_BYTES = 4_096
|
|
23
|
+
|
|
24
|
+
/** Generous on purpose: a project's jobs and webhooks may share one egress address, and each mints once per token lifetime. */
|
|
25
|
+
const CLIENT_WINDOW_SECONDS = 600
|
|
26
|
+
const CLIENT_MAX_ATTEMPTS = 1_000
|
|
27
|
+
const CLIENT_BLOCK_SECONDS = 600
|
|
28
|
+
const REFUSAL_LOG_INTERVAL_MS = 60_000
|
|
29
|
+
|
|
30
|
+
const INVALID_KEY: MintFromKeyResult = { ok: false, reason: 'invalid_key' }
|
|
31
|
+
|
|
32
|
+
/** Refusals since the last summary line, per isolate or process. */
|
|
33
|
+
const refusals = { count: 0, since: Date.now() }
|
|
34
|
+
|
|
35
|
+
function countRefusal(): void {
|
|
36
|
+
refusals.count += 1
|
|
37
|
+
const now = Date.now()
|
|
38
|
+
if (now - refusals.since >= REFUSAL_LOG_INTERVAL_MS) {
|
|
39
|
+
console.warn(`workload token: ${refusals.count} refused exchange(s) in the last ${Math.round((now - refusals.since) / 1000)} s`)
|
|
40
|
+
refusals.count = 0
|
|
41
|
+
refusals.since = now
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function bearerOf(request: Request): string | null {
|
|
46
|
+
const match = /^Bearer\s+(\S+)$/i.exec(request.headers.get('Authorization')?.trim() ?? '')
|
|
47
|
+
const key = match?.[1] ?? null
|
|
48
|
+
return key !== null && ISSUED_KEY_FORMAT.test(key) ? key : null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function appOf(text: string): string | null {
|
|
52
|
+
const parsed = bodySchema.safeParse(parseJsonOrNull(text))
|
|
53
|
+
return parsed.success ? parsed.data.app : null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function decided(result: MintFromKeyResult): Response {
|
|
57
|
+
return Response.json(result, { headers: { 'cache-control': 'no-store' } })
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function unavailable(): Response {
|
|
61
|
+
return Response.json({ error: 'unavailable' }, { status: 503, headers: { 'cache-control': 'no-store' } })
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** One attempt in this client's bucket; true when the client is over it. Counted before the key is looked up. */
|
|
65
|
+
async function clientBlocked(services: Services, clientAddress: string | null): Promise<boolean> {
|
|
66
|
+
if (clientAddress === null) return false
|
|
67
|
+
const row = await services.repositories.passwords.recordLoginFailure({
|
|
68
|
+
loginKeyHash: await hashToken(`workload-token:client:${clientAddress}`),
|
|
69
|
+
windowSeconds: CLIENT_WINDOW_SECONDS,
|
|
70
|
+
maxAttempts: CLIENT_MAX_ATTEMPTS,
|
|
71
|
+
blockSeconds: CLIENT_BLOCK_SECONDS,
|
|
72
|
+
})
|
|
73
|
+
return (row.blocked_until ?? 0) > Math.floor(Date.now() / 1000)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* A decided outcome is a 200 like the proxy's mint surface: `{ ok: false }` is "IAM said no". A storage failure is a
|
|
78
|
+
* 503, so the application reports "IAM could not be asked", never a refused key.
|
|
79
|
+
*/
|
|
80
|
+
export async function handleWorkloadToken(
|
|
81
|
+
request: Request,
|
|
82
|
+
services: Services,
|
|
83
|
+
env: Env,
|
|
84
|
+
ctx: RequestContext,
|
|
85
|
+
requestId: string,
|
|
86
|
+
clientAddress: string | null,
|
|
87
|
+
): Promise<Response> {
|
|
88
|
+
if (request.method !== 'POST') {
|
|
89
|
+
return new Response('method not allowed', { status: 405, headers: { allow: 'POST' } })
|
|
90
|
+
}
|
|
91
|
+
const key = bearerOf(request)
|
|
92
|
+
if (key === null) {
|
|
93
|
+
countRefusal()
|
|
94
|
+
return decided(INVALID_KEY)
|
|
95
|
+
}
|
|
96
|
+
const body = await readBoundedText(request, BODY_MAX_BYTES)
|
|
97
|
+
if (!body.ok && body.reason === 'too_large') {
|
|
98
|
+
return Response.json({ error: 'the body is too large' }, { status: 413 })
|
|
99
|
+
}
|
|
100
|
+
const app = body.ok ? appOf(body.text) : null
|
|
101
|
+
if (app === null) {
|
|
102
|
+
return Response.json({ error: 'the body is { app }' }, { status: 400 })
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
if (await clientBlocked(services, clientAddress)) {
|
|
106
|
+
countRefusal()
|
|
107
|
+
return Response.json({ error: 'rate_limited' }, { status: 429, headers: { 'retry-after': String(CLIENT_BLOCK_SECONDS) } })
|
|
108
|
+
}
|
|
109
|
+
const { result, principalId, credentialId } = await mintFromWorkloadKey(services, env, { app, key })
|
|
110
|
+
if (!result.ok) {
|
|
111
|
+
countRefusal()
|
|
112
|
+
return decided(result)
|
|
113
|
+
}
|
|
114
|
+
ctx.waitUntil(
|
|
115
|
+
services.repositories.audit.writeAuthLog({
|
|
116
|
+
requestId,
|
|
117
|
+
app,
|
|
118
|
+
kind: 'authenticate',
|
|
119
|
+
principalId,
|
|
120
|
+
credentialId,
|
|
121
|
+
decision: 'allow',
|
|
122
|
+
reason: 'mint_workload_key',
|
|
123
|
+
}),
|
|
124
|
+
)
|
|
125
|
+
return decided(result)
|
|
126
|
+
} catch (err) {
|
|
127
|
+
logError(`workload token failed for request '${requestId}'`, err)
|
|
128
|
+
return unavailable()
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type ResourceContext, Worker } from '@fabrika/provider-cloudflare';
|
|
2
|
+
type EnvironmentSource = Readonly<Record<string, string | undefined>>;
|
|
3
|
+
export declare const iamPipelineVars: (source: EnvironmentSource) => string[];
|
|
4
|
+
export declare const iamPipelineSecrets: (source: EnvironmentSource) => string[];
|
|
5
|
+
/**
|
|
6
|
+
* Build IAM's only Cloudflare resource graph. Both fabrika and the standalone Oblaka adapter
|
|
7
|
+
* call this function.
|
|
8
|
+
*/
|
|
9
|
+
export declare const buildIamWorker: (ctx: ResourceContext, source?: EnvironmentSource) => Worker;
|
|
10
|
+
declare const _default: import("@fabrika/provider-cloudflare").CloudflareAppConfig;
|
|
11
|
+
export default _default;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Services } from '../services';
|
|
2
|
+
import type { ResolvedAdmin } from './router';
|
|
3
|
+
/** The audit action of one privileged request: an installation admin used `/admin/*`, a read as much as a change. */
|
|
4
|
+
export declare const ADMIN_ACCESS_ACTION = "iam.admin.access";
|
|
5
|
+
/** One `/admin/*` operation as it is recorded: the method, the route template, and for `/admin/rpc` the procedure. */
|
|
6
|
+
export interface AdminAccess {
|
|
7
|
+
readonly method: string;
|
|
8
|
+
readonly route: string;
|
|
9
|
+
/** The procedure an `/admin/rpc` body names, when it is a well-formed name; null otherwise. */
|
|
10
|
+
readonly procedure?: string | null;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Write the access row before the operation runs, so a request is recorded whatever it then does. The row's `app` is
|
|
14
|
+
* the audience the admin's credential was verified for — the console gateway, or IAM itself for a `px_` key. A request
|
|
15
|
+
* whose access cannot be recorded does not run.
|
|
16
|
+
*/
|
|
17
|
+
export declare function recordAdminAccess(services: Services, admin: ResolvedAdmin, requestId: string, access: AdminAccess): Promise<void>;
|
|
18
|
+
/** The procedure an `/admin/rpc` request names, read from a copy of its body; null when the body names none it may. */
|
|
19
|
+
export declare function rpcProcedureOf(request: Request): Promise<string | null>;
|