saaslayer 0.4.2 → 0.5.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/bin/saaslayer.js +23 -11
- package/package.json +7 -7
- package/src/cdn-aws.js +67 -0
- package/src/cdn-publication.js +146 -0
- package/src/cdn-publisher.js +166 -0
- package/src/commands/cdn.js +66 -0
- package/src/commands/deploy.js +4 -3
- package/src/commands/lifecycle.js +20 -2
- package/src/commands/operations.js +8 -3
- package/src/commands/stacks.js +2 -0
- package/src/commands/users-management.js +2 -2
- package/src/deployments.js +5 -2
- package/src/module-catalog.js +15 -5
- package/src/sms/scope.js +4 -2
- package/src/source-branch.js +36 -0
- package/src/users-import/ids.js +1 -1
- package/templates/saaslayer-foundation.yml +215 -281
- package/vendor/config/login-domain.js +213 -0
- package/vendor/discovery/index.d.mts +109 -0
- package/vendor/discovery/index.mjs +409 -0
- package/vendor/ids/index.d.ts +21 -0
- package/vendor/ids/index.js +237 -0
- package/vendor/migrations/backups.js +118 -0
- package/vendor/migrations/child.js +78 -0
- package/vendor/migrations/credentials.js +103 -0
- package/vendor/migrations/errors.js +30 -0
- package/vendor/migrations/exec-child.js +78 -0
- package/vendor/migrations/gate.js +51 -0
- package/vendor/migrations/index.js +30 -0
- package/vendor/migrations/inventory.js +92 -0
- package/vendor/migrations/log.js +14 -0
- package/vendor/migrations/release.js +45 -0
- package/vendor/migrations/report.js +129 -0
- package/vendor/migrations/rules.js +104 -0
- package/vendor/migrations/run.js +311 -0
- package/vendor/migrations/session-policy.js +37 -0
- package/vendor/migrations/step-guard.js +82 -0
- package/vendor/operations/activity.d.ts +21 -0
- package/vendor/operations/activity.js +126 -0
- package/vendor/operations/index.d.ts +72 -0
- package/vendor/operations/index.js +510 -0
- package/vendor/permissions-engine-core/account-status.js +270 -0
- package/vendor/permissions-engine-core/delegation.js +174 -0
- package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
- package/vendor/permissions-engine-core/sso-claims.js +206 -0
- package/vendor/user-management/cognito/emails/token-registry.js +48 -0
- package/vendor/user-management/email/validate.js +207 -0
- package/vendor/user-management/extensibility/hook-contract.js +720 -0
- package/vendor/user-management/extensibility/safe-webhook.js +85 -0
- package/vendor/user-management/identity/admission.js +215 -0
- package/vendor/user-management/identity/attr.js +27 -0
- package/vendor/user-management/identity/attribute-registry.js +115 -0
- package/vendor/user-management/identity/email.js +25 -0
- package/vendor/user-management/identity/ensure-suid.js +74 -0
- package/vendor/user-management/identity/pointers.js +192 -0
- package/vendor/user-management/identity/stitch-provider.js +275 -0
- package/vendor/user-management/management/apply-request.js +227 -0
- package/vendor/user-management/management/core-profile.js +110 -0
- package/vendor/user-management/management/index.js +23 -0
- package/vendor/user-management/management/purposes.js +94 -0
- package/vendor/user-management/management/registry.js +569 -0
- package/vendor/user-management/store/table.js +332 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// The live account-status contract: how a reader interprets user-service's status endpoint answer for a token (account,
|
|
2
|
+
// binding, connection policy, revocation and session deadline) and, contract 2, for one SSO session by its reference (with the
|
|
3
|
+
// connection's delegated-token policy). Fail closed: only a well-formed current-contract `active: true` is active.
|
|
4
|
+
// Also the status client (configured endpoint + server key, never cached) and the SSO standing gates permission transports run.
|
|
5
|
+
const { isSsoSession, readSsoClaims } = require('./sso-claims')
|
|
6
|
+
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 3000
|
|
8
|
+
|
|
9
|
+
/** Status contract versions this reader reads (`attributes.contract`, required). */
|
|
10
|
+
const READABLE_ACCOUNT_STATUS = Object.freeze([1])
|
|
11
|
+
|
|
12
|
+
/** The status contract of a session answer (a session reference asked, not a token). */
|
|
13
|
+
const SESSION_STATUS_CONTRACT = 2
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What an SSO connection lets its sessions mint from themselves (permissions session tokens: assumed roles, delegated
|
|
17
|
+
* sessions, exchanged access requests): nothing, or tokens capped to the SSO session's remaining life and a short maximum.
|
|
18
|
+
*/
|
|
19
|
+
const DELEGATED_TOKEN_POLICIES = Object.freeze(['blocked', 'short_lived'])
|
|
20
|
+
|
|
21
|
+
/** JSON:API resource type of the status answer. */
|
|
22
|
+
const ACCOUNT_STATUS_TYPE = 'auth-status'
|
|
23
|
+
|
|
24
|
+
const FIELDS = Object.freeze(['contract', 'active', 'reason', 'suid', 'connectionId', 'sessionExpiresAt'])
|
|
25
|
+
const SESSION_FIELDS = Object.freeze([...FIELDS, 'delegatedTokens'])
|
|
26
|
+
const REASON = /^[a-z][a-z0-9_]{0,63}$/
|
|
27
|
+
const OPAQUE_ID = /^[\x21-\x7e]{1,256}$/
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @typedef {Readonly<{ active: true, contract: number, suid: string, connectionId: string|null, sessionExpiresAt: number|null }>} ActiveStatus
|
|
31
|
+
* connectionId: the SSO connection the session signed in through (null for a native/social session); sessionExpiresAt: its
|
|
32
|
+
* fixed session deadline in unix seconds (null when no SSO cap applies)
|
|
33
|
+
* @typedef {Readonly<{ active: false, reason: string, contract?: number, retryable?: boolean, action?: 'upgrade_reader', message?: string }>} InactiveStatus
|
|
34
|
+
* reason: the server's code (e.g. binding_inactive, connection_disabled), or this reader's status_unavailable,
|
|
35
|
+
* status_malformed, status_newer_than_reader or session_expired
|
|
36
|
+
* @typedef {ActiveStatus | InactiveStatus} AccountStatus
|
|
37
|
+
* @typedef {Readonly<{ active: true, contract: number, suid: string, connectionId: string, sessionExpiresAt: number, delegatedTokens: 'blocked'|'short_lived' }>} ActiveSessionStatus
|
|
38
|
+
* one SSO session's standing: its connection, fixed deadline and what it may mint from itself (DELEGATED_TOKEN_POLICIES)
|
|
39
|
+
* @typedef {ActiveSessionStatus | InactiveStatus} SessionStatus
|
|
40
|
+
* @typedef {{ suid: string, connectionId: string, sub: string, originJti: string, authTime: number, securityVersion: number }} SessionReference
|
|
41
|
+
* one SSO session: the person, the connection, the SSO credential's Cognito sub, the session's origin_jti (kept across
|
|
42
|
+
* refreshes), its sign-in time and the account security version it was issued at
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/** @param {unknown} v @returns {v is Record<string, any>} */
|
|
46
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
47
|
+
|
|
48
|
+
/** @param {string} message @returns {InactiveStatus} */
|
|
49
|
+
const malformed = (message) => ({ active: false, reason: 'status_malformed', message })
|
|
50
|
+
|
|
51
|
+
/** @param {unknown} v */
|
|
52
|
+
const isUnixSeconds = (v) => Number.isInteger(v) && /** @type {number} */ (v) >= 0
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Read one status endpoint answer. A non-200 answer (or no answer, `httpStatus: 0`) is `status_unavailable`; 5xx/429 are
|
|
56
|
+
* retryable, other statuses are configuration problems (wrong key or endpoint). There is no cache: a caller that needs the
|
|
57
|
+
* live answer asks again, and an outage is never read as the last success.
|
|
58
|
+
* @param {{ httpStatus: number, body: unknown, now?: () => number }} input
|
|
59
|
+
* @returns {AccountStatus}
|
|
60
|
+
*/
|
|
61
|
+
function readAccountStatus({ httpStatus, body, now = Date.now }) {
|
|
62
|
+
const read = readStatusAnswer({ httpStatus, body, now }, { readable: READABLE_ACCOUNT_STATUS, fields: FIELDS })
|
|
63
|
+
if (!read.active) return read
|
|
64
|
+
const a = read.attributes
|
|
65
|
+
return { active: true, contract: a.contract, suid: a.suid, connectionId: a.connectionId, sessionExpiresAt: a.sessionExpiresAt }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Read one session status answer (contract 2, a session reference asked): as readAccountStatus, and an active answer always
|
|
70
|
+
* names the session's connection, its fixed deadline and the connection's delegated-token policy.
|
|
71
|
+
* @param {{ httpStatus: number, body: unknown, now?: () => number }} input
|
|
72
|
+
* @returns {SessionStatus}
|
|
73
|
+
*/
|
|
74
|
+
function readSessionStatus({ httpStatus, body, now = Date.now }) {
|
|
75
|
+
const read = readStatusAnswer({ httpStatus, body, now }, { readable: [SESSION_STATUS_CONTRACT], fields: SESSION_FIELDS })
|
|
76
|
+
if (!read.active) return read
|
|
77
|
+
const a = read.attributes
|
|
78
|
+
if (a.connectionId === null) return malformed('a session answer names its connection')
|
|
79
|
+
if (a.sessionExpiresAt === null) return malformed('a session answer names its deadline')
|
|
80
|
+
if (!DELEGATED_TOKEN_POLICIES.includes(a.delegatedTokens)) return malformed(`attributes.delegatedTokens must be one of ${DELEGATED_TOKEN_POLICIES.join(', ')}`)
|
|
81
|
+
return { active: true, contract: a.contract, suid: a.suid, connectionId: a.connectionId, sessionExpiresAt: a.sessionExpiresAt, delegatedTokens: a.delegatedTokens }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The shared reading of a status answer: the envelope, a readable contract, known fields, an inactive answer's reason and an
|
|
86
|
+
* active answer's account, connection and deadline (an expired deadline is inactive session_expired).
|
|
87
|
+
* @param {{ httpStatus: number, body: unknown, now: () => number }} input
|
|
88
|
+
* @param {{ readable: readonly number[], fields: readonly string[] }} contract
|
|
89
|
+
* @returns {InactiveStatus | { active: true, attributes: Record<string, any> }}
|
|
90
|
+
*/
|
|
91
|
+
function readStatusAnswer({ httpStatus, body, now }, { readable, fields }) {
|
|
92
|
+
if (httpStatus !== 200) return { active: false, reason: 'status_unavailable', retryable: httpStatus === 0 || httpStatus === 429 || httpStatus >= 500 }
|
|
93
|
+
const data = isPlainObject(body) ? body.data : undefined
|
|
94
|
+
if (!isPlainObject(data) || data.type !== ACCOUNT_STATUS_TYPE || !isPlainObject(data.attributes)) return malformed(`the answer must be a JSON:API '${ACCOUNT_STATUS_TYPE}' resource`)
|
|
95
|
+
const a = data.attributes
|
|
96
|
+
if (!Number.isInteger(a.contract) || a.contract < 1) return malformed('attributes.contract must be a positive integer')
|
|
97
|
+
if (!readable.includes(a.contract)) {
|
|
98
|
+
if (a.contract > Math.max(...readable)) {
|
|
99
|
+
return { active: false, reason: 'status_newer_than_reader', contract: a.contract, action: 'upgrade_reader', message: `account status contract ${a.contract} is newer than this reader (reads ${readable.join(', ')}); upgrade the reader` }
|
|
100
|
+
}
|
|
101
|
+
return malformed(`account status contract ${a.contract} is not readable`)
|
|
102
|
+
}
|
|
103
|
+
const unknown = Object.keys(a).find((k) => !fields.includes(k))
|
|
104
|
+
if (unknown) return malformed(`attributes.${unknown} is not a field of status contract ${a.contract}`)
|
|
105
|
+
if (typeof a.active !== 'boolean') return malformed('attributes.active must be a boolean')
|
|
106
|
+
if (!a.active) {
|
|
107
|
+
if (typeof a.reason !== 'string' || !REASON.test(a.reason)) return malformed('an inactive answer needs attributes.reason (a lowercase code)')
|
|
108
|
+
return { active: false, contract: a.contract, reason: a.reason }
|
|
109
|
+
}
|
|
110
|
+
if (a.reason !== undefined) return malformed('an active answer carries no reason')
|
|
111
|
+
if (typeof a.suid !== 'string' || !OPAQUE_ID.test(a.suid)) return malformed('attributes.suid must be an id')
|
|
112
|
+
if (a.connectionId !== null && (typeof a.connectionId !== 'string' || !OPAQUE_ID.test(a.connectionId))) return malformed('attributes.connectionId must be an id or null')
|
|
113
|
+
if (a.sessionExpiresAt !== null && !isUnixSeconds(a.sessionExpiresAt)) return malformed('attributes.sessionExpiresAt must be unix seconds or null')
|
|
114
|
+
if (a.sessionExpiresAt !== null && a.sessionExpiresAt * 1000 <= now()) return { active: false, contract: a.contract, reason: 'session_expired' }
|
|
115
|
+
return { active: true, attributes: a }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The session reference of a verified SSO token whose standing answered active for `suid` through `connectionId`: its sub,
|
|
120
|
+
* origin_jti, auth_time and security version (custom:sv, 0 when absent). null when the token cannot name one session.
|
|
121
|
+
* @param {Record<string, unknown>} claims @param {{ suid: string, connectionId: string }} standing
|
|
122
|
+
* @returns {SessionReference|null}
|
|
123
|
+
*/
|
|
124
|
+
function sessionReferenceOf(claims, { suid, connectionId }) {
|
|
125
|
+
const c = claims || {}
|
|
126
|
+
const sv = c['custom:sv'] === undefined || c['custom:sv'] === null ? 0 : Number(c['custom:sv'])
|
|
127
|
+
const authTime = Number(c.auth_time)
|
|
128
|
+
if (typeof suid !== 'string' || !OPAQUE_ID.test(suid) || typeof connectionId !== 'string' || !OPAQUE_ID.test(connectionId)) return null
|
|
129
|
+
if (typeof c.sub !== 'string' || !OPAQUE_ID.test(c.sub) || typeof c.origin_jti !== 'string' || !OPAQUE_ID.test(c.origin_jti)) return null
|
|
130
|
+
if (!Number.isInteger(authTime) || authTime < 0 || !Number.isInteger(sv) || sv < 0) return null
|
|
131
|
+
return { suid, connectionId, sub: c.sub, originJti: c.origin_jti, authTime, securityVersion: sv }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* @typedef {{ endpoint: string, apiKey: string, fetch?: typeof globalThis.fetch | ((url: string, init: any) => Promise<any>),
|
|
136
|
+
* timeoutMs?: number, now?: () => number }} AccountStatusClientOptions
|
|
137
|
+
* endpoint: user-service's status endpoint (https, pinned: never taken from a token); apiKey: its server key
|
|
138
|
+
* @typedef {{ check: (token: string) => Promise<AccountStatus>, checkSession: (session: SessionReference|null|undefined) => Promise<SessionStatus> }} AccountStatusClient
|
|
139
|
+
*/
|
|
140
|
+
|
|
141
|
+
/** @param {unknown} endpoint */
|
|
142
|
+
function httpsEndpoint(endpoint) {
|
|
143
|
+
if (typeof endpoint !== 'string' || !endpoint) throw new TypeError('createAccountStatusClient: endpoint is required (an https URL)')
|
|
144
|
+
let url
|
|
145
|
+
try {
|
|
146
|
+
url = new URL(endpoint)
|
|
147
|
+
} catch {
|
|
148
|
+
throw new TypeError('createAccountStatusClient: endpoint must be an https URL')
|
|
149
|
+
}
|
|
150
|
+
if (url.protocol !== 'https:') throw new TypeError('createAccountStatusClient: endpoint must be an https URL')
|
|
151
|
+
return endpoint
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Create a client for the live account-status check. Each `check(token)` makes one request: there is no cache and no
|
|
156
|
+
* stale success. It never throws; anything but a well-formed current-contract `active: true` answer is
|
|
157
|
+
* `{ active: false, reason }`. A successful answer is authentication standing, not authorization for an org operation.
|
|
158
|
+
* @param {AccountStatusClientOptions} options
|
|
159
|
+
* @returns {AccountStatusClient}
|
|
160
|
+
*/
|
|
161
|
+
function createAccountStatusClient({ endpoint, apiKey, fetch = globalThis.fetch, timeoutMs = DEFAULT_TIMEOUT_MS, now = Date.now }) {
|
|
162
|
+
const url = httpsEndpoint(endpoint)
|
|
163
|
+
if (typeof apiKey !== 'string' || !apiKey) throw new TypeError('createAccountStatusClient: apiKey (the status endpoint server key) is required')
|
|
164
|
+
if (typeof fetch !== 'function') throw new TypeError('createAccountStatusClient: a fetch implementation is required')
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* One status request: POST `payload`, the answer read by `reader`. Never throws.
|
|
168
|
+
* @template T @param {Record<string, unknown>} payload @param {(input: { httpStatus: number, body: unknown, now: () => number }) => T}
|
|
169
|
+
* reader @returns {Promise<T | InactiveStatus>}
|
|
170
|
+
*/
|
|
171
|
+
async function ask(payload, reader) {
|
|
172
|
+
const controller = new AbortController()
|
|
173
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
174
|
+
let res
|
|
175
|
+
try {
|
|
176
|
+
res = await fetch(url, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
redirect: 'error',
|
|
179
|
+
signal: controller.signal,
|
|
180
|
+
headers: { 'content-type': 'application/json', 'x-api-key': apiKey },
|
|
181
|
+
body: JSON.stringify(payload),
|
|
182
|
+
})
|
|
183
|
+
} catch {
|
|
184
|
+
return reader({ httpStatus: 0, body: undefined, now })
|
|
185
|
+
} finally {
|
|
186
|
+
clearTimeout(timer)
|
|
187
|
+
}
|
|
188
|
+
if (res.status !== 200) return reader({ httpStatus: res.status, body: undefined, now })
|
|
189
|
+
let body
|
|
190
|
+
try {
|
|
191
|
+
body = await res.json()
|
|
192
|
+
} catch {
|
|
193
|
+
return { active: false, reason: 'status_malformed', message: 'the answer is not JSON' }
|
|
194
|
+
}
|
|
195
|
+
return reader({ httpStatus: 200, body, now })
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** @param {string} token @returns {Promise<AccountStatus>} */
|
|
199
|
+
async function check(token) {
|
|
200
|
+
if (typeof token !== 'string' || !token) return { active: false, reason: 'token_missing' }
|
|
201
|
+
return ask({ token }, readAccountStatus)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The live standing of one SSO session by its reference (contract 2). @param {SessionReference|null|undefined} session @returns {Promise<SessionStatus>} */
|
|
205
|
+
async function checkSession(session) {
|
|
206
|
+
if (!isPlainObject(session)) return { active: false, reason: 'session_reference_missing' }
|
|
207
|
+
return ask({ session }, readSessionStatus)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return { check, checkSession }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The live standing a SaaSLayer permission check needs before granting anything to a verified first-party token: null for a
|
|
215
|
+
* native or social session (nothing to ask) unless its email domain is under SSO enforcement now (`nativeEnforced`), else the
|
|
216
|
+
* account-status answer for this exact token. Fail closed: no configured transport is `current_state_unconfigured`, a
|
|
217
|
+
* throwing client is `status_unavailable`, and an active answer for another person, or another (or no) SSO connection than
|
|
218
|
+
* the token's (a connection for a native token), is `status_mismatch`. One request per call; never cached.
|
|
219
|
+
* @param {{ token: string, claims: Record<string, unknown>, suid: string, client: { check: (token: string) => Promise<AccountStatus> } | null | undefined,
|
|
220
|
+
* nativeEnforced?: boolean }} input
|
|
221
|
+
* suid: the token's own (real, never impersonated) principal; client: the configured account-status transport;
|
|
222
|
+
* nativeEnforced: the token's email domain is enforced now (the trusted-clients registry's enforcedDomains)
|
|
223
|
+
* @returns {Promise<AccountStatus|null>}
|
|
224
|
+
*/
|
|
225
|
+
async function checkSsoStanding({ token, claims, suid, client, nativeEnforced = false }) {
|
|
226
|
+
const sso = isSsoSession(claims)
|
|
227
|
+
if (!sso && !nativeEnforced) return null
|
|
228
|
+
if (!client) return { active: false, reason: 'current_state_unconfigured' }
|
|
229
|
+
/** @type {AccountStatus} */
|
|
230
|
+
let status
|
|
231
|
+
try {
|
|
232
|
+
status = await client.check(token)
|
|
233
|
+
} catch {
|
|
234
|
+
return { active: false, reason: 'status_unavailable', retryable: true }
|
|
235
|
+
}
|
|
236
|
+
if (!status || !status.active) return status || { active: false, reason: 'status_malformed' }
|
|
237
|
+
if (!sso) return status.suid === suid && status.connectionId === null ? status : { active: false, reason: 'status_mismatch' }
|
|
238
|
+
const read = readSsoClaims(claims)
|
|
239
|
+
const claimedConnection = read.ok && read.sso ? read.sso.connectionId : null
|
|
240
|
+
if (status.suid !== suid || !status.connectionId || (claimedConnection && claimedConnection !== status.connectionId)) {
|
|
241
|
+
return { active: false, reason: 'status_mismatch' }
|
|
242
|
+
}
|
|
243
|
+
return status
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The live standing of one SSO session by its reference (a token minted from an SSO session is re-checked through it): the
|
|
248
|
+
* session answer, fail closed. No transport is `current_state_unconfigured`, a throwing one `status_unavailable`, and an active
|
|
249
|
+
* answer for another person or connection `status_mismatch`. One request per call; never cached.
|
|
250
|
+
* @param {{ session: SessionReference, client: { checkSession: (session: SessionReference) => Promise<SessionStatus> } | null | undefined }} input
|
|
251
|
+
* @returns {Promise<SessionStatus>}
|
|
252
|
+
*/
|
|
253
|
+
async function checkSessionStanding({ session, client }) {
|
|
254
|
+
if (!client) return { active: false, reason: 'current_state_unconfigured' }
|
|
255
|
+
/** @type {SessionStatus} */
|
|
256
|
+
let status
|
|
257
|
+
try {
|
|
258
|
+
status = await client.checkSession(session)
|
|
259
|
+
} catch {
|
|
260
|
+
return { active: false, reason: 'status_unavailable', retryable: true }
|
|
261
|
+
}
|
|
262
|
+
if (!status || !status.active) return status || { active: false, reason: 'status_malformed' }
|
|
263
|
+
if (status.suid !== session.suid || status.connectionId !== session.connectionId) return { active: false, reason: 'status_mismatch' }
|
|
264
|
+
return status
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
module.exports = {
|
|
268
|
+
READABLE_ACCOUNT_STATUS, ACCOUNT_STATUS_TYPE, SESSION_STATUS_CONTRACT, DELEGATED_TOKEN_POLICIES,
|
|
269
|
+
readAccountStatus, readSessionStatus, sessionReferenceOf, createAccountStatusClient, checkSsoStanding, checkSessionStanding,
|
|
270
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Delegation decisions for managed roles (authorization matrix §5): a product catalog's own delegation table, or the
|
|
2
|
+
// SaaSLayer-owned deployment delegation table for the caller's deployment-scope and org-scope roles. Pure; permissions-service and @saaslayer/permissions/server share it.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The reserved roles, the one place their ids and user-facing labels are defined: every service, the CLI and the console
|
|
6
|
+
* read them from here. Renaming one is this edit plus a role-rename migration (permissions-service src/role-rename.js).
|
|
7
|
+
* accessAdmin: manages who can sign in and what they can do across the whole deployment (matrix §4), deployment scope only.
|
|
8
|
+
* orgOwner: owns one org (matrix Q19), bound only at that org's own (account) scope.
|
|
9
|
+
* trustManager: manages the deployment's external login providers (trust policies), deployment scope only; held by
|
|
10
|
+
* people, machines or (through their keys) API keys, conferred only by an access admin in person, never onward.
|
|
11
|
+
* orgDeployer: updates an org's deployments and cancels its own runs (control plane only), bound at that org's own scope.
|
|
12
|
+
* platformOperator: SaaSLayer staff's read view of every org's deployments (control plane only), deployment scope; bound
|
|
13
|
+
* only by the seed from the PlatformOperators setting, so no delegation row confers it.
|
|
14
|
+
* supportViewOnly / supportActAs: a deployment's support staff, who view as members of any org without belonging to it
|
|
15
|
+
* (view-only refuses every write; act-as also allows them), deployment scope only, conferred only by an access admin in person.
|
|
16
|
+
*/
|
|
17
|
+
const RESERVED_ROLES = Object.freeze({
|
|
18
|
+
accessAdmin: Object.freeze({ id: 'saaslayer:access-admin', label: 'Access admin' }),
|
|
19
|
+
orgOwner: Object.freeze({ id: 'saaslayer:org-owner', label: 'Org owner' }),
|
|
20
|
+
trustManager: Object.freeze({ id: 'saaslayer:trust-manager', label: 'Trust manager' }),
|
|
21
|
+
orgDeployer: Object.freeze({ id: 'saaslayer:org-deployer', label: 'Org deployer' }),
|
|
22
|
+
internalUser: Object.freeze({ id: 'saaslayer:internal-user', label: 'Internal user' }),
|
|
23
|
+
platformOperator: Object.freeze({ id: 'saaslayer:platform-operator', label: 'Platform operator' }),
|
|
24
|
+
supportViewOnly: Object.freeze({ id: 'saaslayer:support-view-only', label: 'Support (view only)' }),
|
|
25
|
+
supportActAs: Object.freeze({ id: 'saaslayer:support-act-as', label: 'Support (act as)' }),
|
|
26
|
+
})
|
|
27
|
+
/** The reserved access-admin role id. */
|
|
28
|
+
const ACCESS_ADMIN = RESERVED_ROLES.accessAdmin.id
|
|
29
|
+
/** The reserved org-owner role id. */
|
|
30
|
+
const ORG_OWNER = RESERVED_ROLES.orgOwner.id
|
|
31
|
+
/** The reserved trust-manager role id. */
|
|
32
|
+
const TRUST_MANAGER = RESERVED_ROLES.trustManager.id
|
|
33
|
+
/** The reserved org-deployer role id. */
|
|
34
|
+
const ORG_DEPLOYER = RESERVED_ROLES.orgDeployer.id
|
|
35
|
+
/** Explicit entry to the internal application, independent of fleet authority. */
|
|
36
|
+
const INTERNAL_USER = RESERVED_ROLES.internalUser.id
|
|
37
|
+
/** The reserved platform-operator role id. */
|
|
38
|
+
const PLATFORM_OPERATOR = RESERVED_ROLES.platformOperator.id
|
|
39
|
+
/** The reserved support-view-only role id. */
|
|
40
|
+
const SUPPORT_VIEW_ONLY = RESERVED_ROLES.supportViewOnly.id
|
|
41
|
+
/** The reserved support-act-as role id. */
|
|
42
|
+
const SUPPORT_ACT_AS = RESERVED_ROLES.supportActAs.id
|
|
43
|
+
/** Every role id in this namespace is SaaSLayer's: customers can't create, edit, inherit from or delegate it. */
|
|
44
|
+
const RESERVED_ROLE_PREFIX = 'saaslayer:'
|
|
45
|
+
/** The scope kind of a deployment-scope (engine `'*'`) grant. */
|
|
46
|
+
const DEPLOYMENT_SCOPE_KIND = 'deployment'
|
|
47
|
+
/** The scope kind of a grant at an org itself (not a typed site scope inside it). */
|
|
48
|
+
const ACCOUNT_SCOPE_KIND = 'account'
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @typedef {'grant' | 'revoke' | 'remove' | 'transfer'} DelegationAction
|
|
52
|
+
* @typedef {{ grants?: Array<{ grantor: string, may: string[], scopes: string[], canSetExpiry?: boolean }>,
|
|
53
|
+
* removals?: Array<{ remover: string, mayRemove: string[] }>, transfer?: string[] }} Delegation
|
|
54
|
+
* @typedef {{ id: string, grantableScopes?: string[], allowExpiry?: boolean }} DelegationRole
|
|
55
|
+
* @typedef {{ roles: DelegationRole[], delegation?: Delegation }} DelegationCatalog
|
|
56
|
+
* @typedef {{ grantorRoles: string[], action: DelegationAction, targetRole: string, scopeKind: string, expiry?: boolean }} DelegationRequest
|
|
57
|
+
* grantorRoles: the caller's account-level roles in the target org
|
|
58
|
+
* @typedef {{ ok: boolean, status: 200 | 400 | 403 | 404, reason?: string }} DelegationResult
|
|
59
|
+
* @typedef {{ grantor: string, held: 'deployment' | 'org', targets: 'catalog-roles' | readonly string[], actions: readonly DelegationAction[],
|
|
60
|
+
* scopes: 'role-grantable' | readonly string[], expiry: 'role' | 'allowed' | 'never' }} DeploymentDelegationRule
|
|
61
|
+
* held 'deployment' = the grantor role held at deployment scope; 'org' = held at the target's org (account level).
|
|
62
|
+
* targets 'catalog-roles' = every role of the customer catalog the target belongs to; scopes 'role-grantable' = that
|
|
63
|
+
* role's grantableScopes; expiry 'role' = only when the role has allowExpiry, 'allowed' = always, 'never' = never
|
|
64
|
+
* @typedef {{ deploymentTable?: readonly DeploymentDelegationRule[], deploymentRoles?: string[] }} DelegationOptions
|
|
65
|
+
* deploymentRoles: the roles the caller holds at deployment scope
|
|
66
|
+
*/
|
|
67
|
+
|
|
68
|
+
/** Bump with any rule change (a SaaSLayer release); customers can't edit or widen the table. */
|
|
69
|
+
const DEPLOYMENT_DELEGATION_VERSION = 5
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The deployment delegation table (matrix §5.2), v3: v1's access-admin rows; v2's co-owners — a holder of
|
|
73
|
+
* org-owner at an org grants and revokes org-owner at that org, and so does the access admin; v3's trust manager —
|
|
74
|
+
* only the access admin grants and revokes it, at deployment scope (no row lets a holder confer it onward); and the org
|
|
75
|
+
* deployer — the access admin, or an org-owner held at the target's org, grants and revokes it at that org; v4's support
|
|
76
|
+
* roles — only the access admin grants (optionally until an expiry) and revokes them, at deployment scope; v5 adds
|
|
77
|
+
* explicit internal-application entry, granted/revoked only by the access admin at deployment scope.
|
|
78
|
+
* @type {readonly DeploymentDelegationRule[]}
|
|
79
|
+
*/
|
|
80
|
+
const DEPLOYMENT_DELEGATION = Object.freeze([
|
|
81
|
+
Object.freeze({ grantor: ACCESS_ADMIN, held: /** @type {const} */ ('deployment'), targets: Object.freeze([INTERNAL_USER]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([DEPLOYMENT_SCOPE_KIND]), expiry: /** @type {const} */ ('never') }),
|
|
82
|
+
Object.freeze({ grantor: ACCESS_ADMIN, held: /** @type {const} */ ('deployment'), targets: /** @type {const} */ ('catalog-roles'), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke', 'remove', 'transfer'])), scopes: /** @type {const} */ ('role-grantable'), expiry: /** @type {const} */ ('role') }),
|
|
83
|
+
Object.freeze({ grantor: ACCESS_ADMIN, held: /** @type {const} */ ('deployment'), targets: Object.freeze([ACCESS_ADMIN]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([DEPLOYMENT_SCOPE_KIND]), expiry: /** @type {const} */ ('never') }),
|
|
84
|
+
Object.freeze({ grantor: ACCESS_ADMIN, held: /** @type {const} */ ('deployment'), targets: Object.freeze([ORG_OWNER]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([ACCOUNT_SCOPE_KIND]), expiry: /** @type {const} */ ('never') }),
|
|
85
|
+
Object.freeze({ grantor: ORG_OWNER, held: /** @type {const} */ ('org'), targets: Object.freeze([ORG_OWNER]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([ACCOUNT_SCOPE_KIND]), expiry: /** @type {const} */ ('never') }),
|
|
86
|
+
Object.freeze({ grantor: ACCESS_ADMIN, held: /** @type {const} */ ('deployment'), targets: Object.freeze([TRUST_MANAGER]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([DEPLOYMENT_SCOPE_KIND]), expiry: /** @type {const} */ ('never') }),
|
|
87
|
+
Object.freeze({ grantor: ACCESS_ADMIN, held: /** @type {const} */ ('deployment'), targets: Object.freeze([ORG_DEPLOYER]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([ACCOUNT_SCOPE_KIND]), expiry: /** @type {const} */ ('never') }),
|
|
88
|
+
Object.freeze({ grantor: ORG_OWNER, held: /** @type {const} */ ('org'), targets: Object.freeze([ORG_DEPLOYER]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([ACCOUNT_SCOPE_KIND]), expiry: /** @type {const} */ ('never') }),
|
|
89
|
+
Object.freeze({ grantor: ACCESS_ADMIN, held: /** @type {const} */ ('deployment'), targets: Object.freeze([SUPPORT_VIEW_ONLY, SUPPORT_ACT_AS]), actions: Object.freeze(/** @type {DelegationAction[]} */ (['grant', 'revoke'])), scopes: Object.freeze([DEPLOYMENT_SCOPE_KIND]), expiry: /** @type {const} */ ('allowed') }),
|
|
90
|
+
])
|
|
91
|
+
|
|
92
|
+
const allow = () => /** @type {DelegationResult} */ ({ ok: true, status: 200 })
|
|
93
|
+
/** @param {400 | 403 | 404} status @param {string} reason */
|
|
94
|
+
const refuse = (status, reason) => /** @type {DelegationResult} */ ({ ok: false, status, reason })
|
|
95
|
+
|
|
96
|
+
/** @param {unknown} id */
|
|
97
|
+
function isReservedRoleId(id) {
|
|
98
|
+
return typeof id === 'string' && id.startsWith(RESERVED_ROLE_PREFIX)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The catalog's own table: the caller's account-level roles in the org.
|
|
103
|
+
* @param {DelegationCatalog} catalog @param {DelegationRole} role @param {DelegationRequest} req
|
|
104
|
+
* @returns {DelegationResult}
|
|
105
|
+
*/
|
|
106
|
+
function catalogDecision(catalog, role, { grantorRoles, action, targetRole, scopeKind, expiry = false }) {
|
|
107
|
+
const d = catalog.delegation || {}
|
|
108
|
+
const held = new Set(grantorRoles || [])
|
|
109
|
+
|
|
110
|
+
if (action === 'transfer') {
|
|
111
|
+
return (d.transfer || []).some((id) => held.has(id)) ? allow() : refuse(403, 'only a transfer role may transfer ownership')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (action === 'revoke' || action === 'remove') {
|
|
115
|
+
const may = (d.removals || []).some((r) => held.has(r.remover) && r.mayRemove.includes(targetRole))
|
|
116
|
+
return may ? allow() : refuse(403, `your roles may not ${action} ${targetRole}`)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (action !== 'grant') return refuse(400, `unknown delegation action "${action}"`)
|
|
120
|
+
if (!(role.grantableScopes || ['account']).includes(scopeKind)) {
|
|
121
|
+
return refuse(400, `${targetRole} cannot be granted at ${scopeKind} scope`)
|
|
122
|
+
}
|
|
123
|
+
const rules = (d.grants || []).filter((g) => held.has(g.grantor) && g.may.includes(targetRole) && g.scopes.includes(scopeKind))
|
|
124
|
+
if (!rules.length) return refuse(403, `your roles may not grant ${targetRole} at ${scopeKind} scope`)
|
|
125
|
+
if (expiry) {
|
|
126
|
+
if (!role.allowExpiry) return refuse(400, `${targetRole} cannot be granted with an expiry`)
|
|
127
|
+
if (!rules.some((g) => g.canSetExpiry)) return refuse(400, `your roles may not set an expiry on ${targetRole}`)
|
|
128
|
+
}
|
|
129
|
+
return allow()
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The deployment table: each rule's grantor held where the rule says (deployment scope, or the target's org). `role` is
|
|
134
|
+
* the target's catalog role (null when the target is no customer catalog role).
|
|
135
|
+
* @param {readonly DeploymentDelegationRule[]} table @param {{ deployment: Set<string>, org: Set<string> }} held
|
|
136
|
+
* @param {DelegationRole|null} role @param {DelegationRequest} req
|
|
137
|
+
* @returns {DelegationResult}
|
|
138
|
+
*/
|
|
139
|
+
function deploymentDecision(table, held, role, { action, targetRole, scopeKind, expiry = false }) {
|
|
140
|
+
const rules = table.filter((r) => held[r.held].has(r.grantor) && r.actions.includes(action)
|
|
141
|
+
&& (r.targets === 'catalog-roles' ? Boolean(role) : r.targets.includes(targetRole)))
|
|
142
|
+
if (!rules.length) return refuse(403, `your roles may not ${action} ${targetRole}`)
|
|
143
|
+
if (action !== 'grant') return allow()
|
|
144
|
+
const scoped = rules.filter((r) => (r.scopes === 'role-grantable' ? (role && role.grantableScopes) || ['account'] : r.scopes).includes(scopeKind))
|
|
145
|
+
if (!scoped.length) return refuse(400, `${targetRole} cannot be granted at ${scopeKind} scope`)
|
|
146
|
+
if (expiry && !scoped.some((r) => r.expiry === 'allowed' || (r.expiry === 'role' && role && role.allowExpiry))) return refuse(400, `${targetRole} cannot be granted with an expiry`)
|
|
147
|
+
return allow()
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* May the caller grant, revoke, remove or transfer `targetRole` at `scopeKind`? Allowed when the catalog's own table
|
|
152
|
+
* allows it for the caller's account-level roles in the org, or the deployment table allows it for the caller's
|
|
153
|
+
* deployment-scope roles (or, for its org-held rules, the caller's account-level roles). A catalog can never delegate
|
|
154
|
+
* a reserved (`saaslayer:`) role. Refusals keep the catalog's statuses (400/403/404).
|
|
155
|
+
* @param {DelegationCatalog|null} catalog the target role's catalog (null: the target is no customer catalog role)
|
|
156
|
+
* @param {DelegationRequest} req
|
|
157
|
+
* @param {DelegationOptions} [opts]
|
|
158
|
+
* @returns {DelegationResult}
|
|
159
|
+
*/
|
|
160
|
+
function canDelegate(catalog, req, { deploymentTable = DEPLOYMENT_DELEGATION, deploymentRoles = [] } = {}) {
|
|
161
|
+
const reserved = isReservedRoleId(req.targetRole)
|
|
162
|
+
const role = !reserved && catalog ? (catalog.roles || []).find((r) => r.id === req.targetRole) || null : null
|
|
163
|
+
const own = role && catalog
|
|
164
|
+
? catalogDecision(catalog, role, req)
|
|
165
|
+
: refuse(reserved ? 403 : 404, reserved ? `${req.targetRole} is reserved and cannot be delegated by a catalog` : `role ${req.targetRole} is not in the catalog`)
|
|
166
|
+
if (own.ok) return own
|
|
167
|
+
const held = { deployment: new Set(deploymentRoles || []), org: new Set(req.grantorRoles || []) }
|
|
168
|
+
const deployment = deploymentDecision(deploymentTable, held, role, req)
|
|
169
|
+
// A deployment rule that matched the grantor but not the request (scope, expiry) says why; otherwise the catalog does
|
|
170
|
+
if (deployment.ok || deployment.status !== 403) return deployment
|
|
171
|
+
return reserved ? deployment : own
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
module.exports = { canDelegate, isReservedRoleId, DEPLOYMENT_DELEGATION, DEPLOYMENT_DELEGATION_VERSION, ACCESS_ADMIN, ORG_OWNER, TRUST_MANAGER, ORG_DEPLOYER, PLATFORM_OPERATOR, INTERNAL_USER, SUPPORT_VIEW_ONLY, SUPPORT_ACT_AS, RESERVED_ROLES, DEPLOYMENT_SCOPE_KIND, ACCOUNT_SCOPE_KIND, RESERVED_ROLE_PREFIX }
|