saaslayer 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,401 @@
1
+ // `saaslayer users admin bootstrap|keys|grants`: opt-in local management of one user-service instance. Standalone, with the
2
+ // owner's target-account IAM against a checked manifest; managed, through the control plane as an owner of the owning org.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const crypto = require('crypto')
7
+ const { execFileSync } = require('child_process')
8
+ const { apiCall } = require('../api-client')
9
+ const { signRequest } = require('../aws-sigv4')
10
+ const { awsCredentials } = require('../iam-session')
11
+
12
+ // The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
13
+ // vendor/user-management, synced on prepack).
14
+ const MONOREPO_MANAGEMENT = path.join(__dirname, '../../../../services/user-service/src/management')
15
+
16
+ /** The user-service management package: registry, purposes and the request flow its seed also runs. */
17
+ function loadManagement() {
18
+ try {
19
+ return require('../../vendor/user-management')
20
+ } catch (err) {
21
+ if (err && err.code !== 'MODULE_NOT_FOUND') throw err
22
+ return require(MONOREPO_MANAGEMENT)
23
+ }
24
+ }
25
+
26
+ const SUBCOMMANDS = ['bootstrap', 'keys', 'grants']
27
+ const KEY_PHASES = ['introduce', 'activate', 'retire', 'revoke', 'status']
28
+ const GRANT_PHASES = ['grant', 'revoke', 'status']
29
+ const MANIFEST_FIELDS = ['deploymentId', 'serviceRef', 'accountId', 'region', 'stackName', 'userPoolId', 'managementTableName', 'managementMaterialPath']
30
+
31
+ const USAGE = `usage: saaslayer users admin <bootstrap|keys|grants> --deployment <id> --service <ref> --account-id <id> --region <r>
32
+ [--profile <p> --manifest <file>] (standalone: your target-account IAM; otherwise through the control plane)
33
+ bootstrap --owner-suid <suid> --owner-email <email> [repeat the pair] --purpose <purpose> [repeatable] [--reason <text>]
34
+ keys --caller <id> --purpose <purpose> --phase introduce --output <private-file>
35
+ keys --caller <id> --phase activate|retire|revoke --key-id <id> [--reason <text>] | keys --phase status
36
+ grants --principal <suid> [repeatable] --purpose <purpose> --phase grant|revoke|status [--reason <text>]`
37
+
38
+ /** @param {unknown} value @returns {string[]} */
39
+ const listOf = (value) => (value === undefined || value === true ? [] : Array.isArray(value) ? value.map(String) : [String(value)])
40
+
41
+ /** @param {Record<string, any>} flags @param {string} name */
42
+ function required(flags, name) {
43
+ const value = flags[name]
44
+ if (typeof value !== 'string' || !value.trim()) throw new Error(`--${name} is required\n${USAGE}`)
45
+ return value.trim()
46
+ }
47
+
48
+ /** @param {Record<string, any>} flags @param {string} name */
49
+ const optional = (flags, name) => (typeof flags[name] === 'string' && flags[name].trim() ? flags[name].trim() : undefined)
50
+
51
+ /**
52
+ * The instance every subcommand names: deployment, service ref, account and region.
53
+ * @param {Record<string, any>} flags
54
+ */
55
+ function instanceOf(flags) {
56
+ const deploymentId = required(flags, 'deployment')
57
+ const serviceRef = required(flags, 'service')
58
+ const accountId = required(flags, 'account-id')
59
+ const region = required(flags, 'region')
60
+ if (!/^[0-9]{12}$/.test(accountId)) throw new Error('--account-id must be a 12-digit AWS account id')
61
+ if (!/^user-service(@[a-z][a-z0-9]{0,11})?$/.test(serviceRef)) throw new Error('--service must be user-service or user-service@<instance>')
62
+ return { deploymentId, serviceRef, accountId, region }
63
+ }
64
+
65
+ /**
66
+ * The checked request(s) of a subcommand, before any I/O. A grants run carries one request per --principal.
67
+ * @param {string} sub @param {Record<string, any>} flags
68
+ * @returns {Array<Record<string, any>>}
69
+ */
70
+ function requestsOf(sub, flags) {
71
+ const reason = optional(flags, 'reason')
72
+ const purposes = listOf(flags.purpose)
73
+ if (sub === 'bootstrap') {
74
+ const suids = listOf(flags['owner-suid'])
75
+ const emails = listOf(flags['owner-email'])
76
+ if (suids.length === 0) throw new Error(`--owner-suid is required\n${USAGE}`)
77
+ if (suids.length !== emails.length) throw new Error('pair every --owner-suid with an --owner-email, in the same order')
78
+ if (purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
79
+ // A reason makes this an explicit, audited owner action: adding a root to an initialized instance, or recovering one.
80
+ return [{ action: 'bootstrap', owners: suids.map((suid, i) => ({ suid, email: emails[i], purposes })), ...(reason ? { reason, recover: true } : {}) }]
81
+ }
82
+ const phase = required(flags, 'phase')
83
+ if (sub === 'keys') {
84
+ if (!KEY_PHASES.includes(phase)) throw new Error(`--phase must be one of ${KEY_PHASES.join(', ')}`)
85
+ if (phase === 'status') return [{ action: 'key', phase }]
86
+ const callerId = required(flags, 'caller')
87
+ if (phase === 'introduce') {
88
+ required(flags, 'output')
89
+ if (purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
90
+ return [{ action: 'key', phase, callerId, purposes }]
91
+ }
92
+ const keyId = required(flags, 'key-id')
93
+ if (phase === 'revoke' && !reason) throw new Error('--reason is required to revoke a key')
94
+ return [{ action: 'key', phase, callerId, keyId, ...(reason ? { reason } : {}) }]
95
+ }
96
+ if (!GRANT_PHASES.includes(phase)) throw new Error(`--phase must be one of ${GRANT_PHASES.join(', ')}`)
97
+ if (phase === 'status') return [{ action: 'grant', phase }]
98
+ const principals = listOf(flags.principal)
99
+ if (principals.length === 0) throw new Error(`--principal is required (repeatable)\n${USAGE}`)
100
+ if (phase === 'grant' && purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
101
+ if (phase === 'revoke' && !reason) throw new Error('--reason is required to revoke a grant')
102
+ return principals.map((principal) => ({ action: 'grant', phase, principal, ...(phase === 'grant' ? { purposes } : {}), ...(reason ? { reason } : {}) }))
103
+ }
104
+
105
+ /**
106
+ * Write an issued raw key to the caller's private file (0600, never overwritten). A retry re-outputting the same key is
107
+ * fine; a file holding anything else is refused.
108
+ * @param {string} file @param {string} key
109
+ */
110
+ function writeKeyFile(file, key) {
111
+ try {
112
+ fs.writeFileSync(file, `${key}\n`, { mode: 0o600, flag: 'wx' })
113
+ } catch (err) {
114
+ if (!err || /** @type {{ code?: string }} */ (err).code !== 'EEXIST') throw err
115
+ if (fs.readFileSync(file, 'utf8').trim() !== key) throw new Error(`--output ${file} already exists and holds something else; choose a new file`)
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Claim --output for a key the control plane returns once: a new private file (0600), created exclusively, so an existing
121
+ * file or a symlink is refused before anything is requested.
122
+ * @param {string} file
123
+ * @returns {number} the open file descriptor
124
+ */
125
+ function claimKeyFile(file) {
126
+ try {
127
+ return fs.openSync(file, 'wx', 0o600)
128
+ } catch (err) {
129
+ const code = /** @type {{ code?: string }} */ (err).code
130
+ if (code === 'EEXIST') throw new Error(`--output ${file} already exists (or is a link); a managed key is returned once, so choose a new file`)
131
+ throw new Error(`--output ${file} cannot be created: ${/** @type {Error} */ (err).message}`)
132
+ }
133
+ }
134
+
135
+ // ---- standalone: the owner's target-account IAM ------------------------------------------------------------------
136
+
137
+ /** @param {string} cmd @param {string[]} args */
138
+ const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] })
139
+
140
+ /**
141
+ * The manifest, checked against the flags and its own derivations before anything is called.
142
+ * @param {string} file @param {ReturnType<typeof instanceOf>} instance @param {ReturnType<typeof loadManagement>} management
143
+ */
144
+ function checkedManifest(file, instance, management) {
145
+ let manifest
146
+ try {
147
+ manifest = JSON.parse(fs.readFileSync(file, 'utf8'))
148
+ } catch (err) {
149
+ throw new Error(`--manifest ${file} is not a readable JSON file: ${/** @type {Error} */ (err).message}`)
150
+ }
151
+ const missing = MANIFEST_FIELDS.filter((f) => typeof manifest[f] !== 'string' || !manifest[f])
152
+ if (missing.length) throw new Error(`the manifest lacks ${missing.join(', ')}`)
153
+ for (const [field, flag] of [['deploymentId', 'deploymentId'], ['serviceRef', 'serviceRef'], ['accountId', 'accountId'], ['region', 'region']]) {
154
+ if (manifest[field] !== instance[/** @type {keyof typeof instance} */ (flag)]) throw new Error(`the manifest names ${field} ${manifest[field]}, not ${instance[/** @type {keyof typeof instance} */ (flag)]}; refusing a write to another target`)
155
+ }
156
+ const materialPath = management.managementMaterialPath(manifest.deploymentId, manifest.serviceRef)
157
+ if (manifest.managementMaterialPath !== materialPath) throw new Error(`the manifest's managementMaterialPath is not this instance's (${materialPath})`)
158
+ return manifest
159
+ }
160
+
161
+ /**
162
+ * The instance's pending key material in the owner-only SSM path: create-only SecureStrings, read back for a retry,
163
+ * removed once the key is no longer pending. Signed with the owner's credentials (no SDK; the raw value never reaches a
164
+ * process argument).
165
+ * @param {{ region: string, credentials: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, basePath: string, fetchImpl: typeof fetch }} deps
166
+ */
167
+ function ssmMaterial({ region, credentials, basePath, fetchImpl }) {
168
+ const host = `ssm.${region}.amazonaws.com`
169
+ /** @param {string} action @param {Record<string, unknown>} input */
170
+ async function call(action, input) {
171
+ const body = JSON.stringify(input)
172
+ const { headers } = signRequest({
173
+ method: 'POST',
174
+ url: `https://${host}/`,
175
+ body,
176
+ region,
177
+ service: 'ssm',
178
+ credentials: credentials(),
179
+ headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': `AmazonSSM.${action}`, Host: host },
180
+ })
181
+ const res = await fetchImpl(`https://${host}/`, { method: 'POST', headers, body })
182
+ const doc = await res.json().catch(() => ({}))
183
+ if (res.ok) return doc
184
+ const type = String((doc && (doc.__type || doc.code)) || '').split('#').pop()
185
+ throw Object.assign(new Error(`SSM ${action} failed (${res.status}${type ? ` ${type}` : ''})`), { name: type || 'SsmError' })
186
+ }
187
+ const name = (/** @type {string} */ keyId) => `${basePath}/${keyId}`
188
+ return {
189
+ async put(/** @type {string} */ keyId, /** @type {string} */ raw) {
190
+ await call('PutParameter', { Name: name(keyId), Value: raw, Type: 'SecureString', Overwrite: false, Description: 'pending local management key (owner only)' })
191
+ },
192
+ async get(/** @type {string} */ keyId) {
193
+ try {
194
+ const doc = await call('GetParameter', { Name: name(keyId), WithDecryption: true })
195
+ return doc.Parameter ? String(doc.Parameter.Value) : null
196
+ } catch (err) {
197
+ if (/** @type {{ name?: string }} */ (err).name === 'ParameterNotFound') return null
198
+ throw err
199
+ }
200
+ },
201
+ async remove(/** @type {string} */ keyId) {
202
+ try {
203
+ await call('DeleteParameter', { Name: name(keyId) })
204
+ } catch (err) {
205
+ if (/** @type {{ name?: string }} */ (err).name !== 'ParameterNotFound') throw err
206
+ }
207
+ },
208
+ }
209
+ }
210
+
211
+ /**
212
+ * The own pool through the aws CLI with the owner's credentials: the account holding an email (its custom:suid and sub),
213
+ * and an invitation creating one at a suid (its sub).
214
+ * @param {{ exec: typeof defaultExec, awsArgs: string[], userPoolId: string }} deps
215
+ */
216
+ function poolAccounts({ exec, awsArgs, userPoolId }) {
217
+ return {
218
+ async get(/** @type {string} */ email) {
219
+ let out
220
+ try {
221
+ out = JSON.parse(exec('aws', ['cognito-idp', 'admin-get-user', '--user-pool-id', userPoolId, '--username', email, '--output', 'json', ...awsArgs]))
222
+ } catch (err) {
223
+ if (String(/** @type {{ stderr?: unknown }} */ (err).stderr || '').includes('UserNotFoundException')) return null
224
+ throw new Error('reading the owner account failed (aws cognito-idp admin-get-user)')
225
+ }
226
+ return { suid: attributeOf(out.UserAttributes, 'custom:suid'), sub: attributeOf(out.UserAttributes, 'sub') }
227
+ },
228
+ async invite(/** @type {{ email: string, suid: string }} */ { email, suid }) {
229
+ const out = JSON.parse(exec('aws', ['cognito-idp', 'admin-create-user', '--user-pool-id', userPoolId, '--username', email, '--desired-delivery-mediums', 'EMAIL',
230
+ '--user-attributes', `Name=email,Value=${email}`, 'Name=email_verified,Value=true', `Name=custom:suid,Value=${suid}`, '--output', 'json', ...awsArgs]))
231
+ return { sub: attributeOf(out.User && out.User.Attributes, 'sub') }
232
+ },
233
+ }
234
+ }
235
+
236
+ /**
237
+ * A Cognito attribute's value from an aws CLI attribute list, or null.
238
+ * @param {unknown} attributes @param {string} name
239
+ * @returns {string|null}
240
+ */
241
+ function attributeOf(attributes, name) {
242
+ const found = (Array.isArray(attributes) ? attributes : []).find((/** @type {{ Name?: string }} */ a) => a && a.Name === name)
243
+ return found && found.Value ? String(found.Value) : null
244
+ }
245
+
246
+ /**
247
+ * Check the target (manifest vs flags, the caller's account, the stack's outputs) and build the registry and its ports
248
+ * with the owner's credentials. Nothing is written until every check passed.
249
+ * @param {Record<string, any>} flags @param {ReturnType<typeof instanceOf>} instance @param {Record<string, any>} deps
250
+ */
251
+ async function standaloneTarget(flags, instance, deps) {
252
+ const management = loadManagement()
253
+ const manifest = checkedManifest(required(flags, 'manifest'), instance, management)
254
+ const exec = deps.exec || defaultExec
255
+ const awsArgs = ['--region', manifest.region, ...(flags.profile ? ['--profile', String(flags.profile)] : [])]
256
+ const identity = JSON.parse(exec('aws', ['sts', 'get-caller-identity', '--output', 'json', ...awsArgs]))
257
+ if (identity.Account !== manifest.accountId) throw new Error(`your credentials are for account ${identity.Account}, not the manifest's ${manifest.accountId}`)
258
+ const outputs = Object.fromEntries((JSON.parse(exec('aws', ['cloudformation', 'describe-stacks', '--stack-name', manifest.stackName, '--query', 'Stacks[0].Outputs', '--output', 'json', ...awsArgs])) || [])
259
+ .map((/** @type {{ OutputKey: string, OutputValue: string }} */ o) => [o.OutputKey, o.OutputValue]))
260
+ if (outputs.UserPoolId !== manifest.userPoolId) throw new Error(`stack ${manifest.stackName} reports UserPoolId ${outputs.UserPoolId || '(none)'}, not the manifest's`)
261
+ if (outputs.ManagementTableName !== manifest.managementTableName) throw new Error(`stack ${manifest.stackName} reports ManagementTableName ${outputs.ManagementTableName || '(none)'}, not the manifest's`)
262
+ const credentials = deps.credentials || (() => awsCredentials({ profile: flags.profile }))
263
+ const doc = deps.doc || standaloneDocumentClient(manifest.region, credentials)
264
+ return {
265
+ management,
266
+ actor: { kind: 'aws-principal', id: identity.Arn },
267
+ registry: management.createManagementRegistry({ doc, tableName: manifest.managementTableName, serviceRef: manifest.serviceRef }),
268
+ accounts: poolAccounts({ exec, awsArgs, userPoolId: manifest.userPoolId }),
269
+ // The stack's own core table: an owner invitation claims its suid's onboarding marker there first, and a grant finds
270
+ // its grantee's account there.
271
+ coreTableName: outputs.CoreTableName || null,
272
+ identity: outputs.CoreTableName ? management.coreIdentity({ doc, tableName: outputs.CoreTableName }) : undefined,
273
+ material: ssmMaterial({ region: manifest.region, credentials, basePath: manifest.managementMaterialPath, fetchImpl: deps.fetch || fetch }),
274
+ }
275
+ }
276
+
277
+ /**
278
+ * DynamoDB with the owner's credentials (the registry's conditional writes are the authorization: no IAM write, no change).
279
+ * @param {string} region @param {() => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }} credentials
280
+ */
281
+ function standaloneDocumentClient(region, credentials) {
282
+ const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
283
+ const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
284
+ return DynamoDBDocumentClient.from(new DynamoDBClient({ region, credentials: async () => credentials() }), { marshallOptions: { removeUndefinedValues: true } })
285
+ }
286
+
287
+ // ---- output -------------------------------------------------------------------------------------------------------
288
+
289
+ /**
290
+ * The lines a result prints: owners and outcomes, key ids and states with age, grants; never an email, hash or raw key.
291
+ * @param {Record<string, any>} result
292
+ * @returns {string[]}
293
+ */
294
+ function formatResult(result) {
295
+ if (Array.isArray(result.owners)) return result.owners.map((o) => `${o.suid} ${o.account || ''} ${o.outcome}`.replace(/\s{3,}/g, ' '))
296
+ if (Array.isArray(result.callers)) {
297
+ const lines = []
298
+ for (const c of result.callers) {
299
+ const keys = c.keys || []
300
+ if (c.callerType === 'machine') {
301
+ if (keys.length === 0) lines.push(`${c.callerId} (no keys) ${c.purposes.join(',')}`)
302
+ for (const k of keys) lines.push(`${c.callerId} ${k.keyId} ${k.state} age ${k.ageDays}d ${c.purposes.join(',')}`)
303
+ } else {
304
+ lines.push(`${c.callerId} grant ${c.status} ${c.purposes.join(',')}`)
305
+ }
306
+ }
307
+ return lines.length ? lines : ['no local management callers']
308
+ }
309
+ if (result.principal) return [`${result.principal} ${result.outcome}`]
310
+ if (result.keyId) return [`${result.callerId} ${result.keyId} ${result.state || (result.phase === 'introduce' ? 'next (pending)' : '')}${result.reused ? ' (pending key re-issued)' : ''}`]
311
+ return [JSON.stringify(result)]
312
+ }
313
+
314
+ // ---- managed: through the control plane ---------------------------------------------------------------------------
315
+
316
+ const ROUTE = { bootstrap: 'bootstrap', keys: 'keys', grants: 'grants' }
317
+
318
+ /**
319
+ * One managed request: the deployment must be the named target; the owner route starts the operation; an issued key goes
320
+ * only to --output.
321
+ * @param {string} sub @param {Record<string, any>} request @param {ReturnType<typeof instanceOf>} instance @param {Record<string, any>} flags
322
+ * @param {(line: string) => void} log
323
+ */
324
+ async function managedRequest(sub, request, instance, flags, log) {
325
+ const { action, ...attributes } = request
326
+ if (attributes.recover) delete attributes.recover
327
+ const file = String(flags.output)
328
+ const fd = action === 'key' && request.phase === 'introduce' ? claimKeyFile(file) : null
329
+ let attrs
330
+ try {
331
+ const doc = await apiCall('POST', `/api/deployments/${encodeURIComponent(instance.deploymentId)}/services/${encodeURIComponent(instance.serviceRef)}/admin/${ROUTE[/** @type {keyof typeof ROUTE} */ (sub)]}`,
332
+ { data: { type: 'management-requests', attributes } }, flags, { headers: { 'Idempotency-Key': `cli-${crypto.randomUUID()}` } })
333
+ attrs = (doc && doc.data && doc.data.attributes) || {}
334
+ if (fd !== null && attrs.key) fs.writeSync(fd, `${attrs.key}\n`)
335
+ } catch (err) {
336
+ if (fd !== null) {
337
+ fs.closeSync(fd)
338
+ fs.rmSync(file, { force: true })
339
+ }
340
+ throw err
341
+ }
342
+ if (fd !== null) {
343
+ fs.closeSync(fd)
344
+ if (!attrs.key) fs.rmSync(file, { force: true })
345
+ }
346
+ if (attrs.key) log(`key ${attrs.keyId} for ${request.callerId} written to ${file} (pending until activated)`)
347
+ log(`operation ${attrs.operationId} ${attrs.status || 'started'} — follow with \`saaslayer operations watch ${attrs.operationId} --deployment ${instance.deploymentId}\``)
348
+ if (flags.wait) {
349
+ const { followOperation } = require('./operations')
350
+ const final = await followOperation({ deploymentId: instance.deploymentId, operationId: attrs.operationId, flags })
351
+ const component = (final.components || []).find((c) => c.name === 'management')
352
+ const result = component && component.detail && component.detail.request && component.detail.request.result
353
+ if (result) for (const line of formatResult(result)) log(line)
354
+ }
355
+ return attrs
356
+ }
357
+
358
+ /**
359
+ * Run `saaslayer users admin <sub>`. deps (tests): exec, fetch, doc, credentials, log.
360
+ * @param {string} sub @param {Record<string, any>} flags @param {Record<string, any>} [deps]
361
+ */
362
+ async function usersManagement(sub, flags, deps = {}) {
363
+ if (!SUBCOMMANDS.includes(sub)) throw new Error(USAGE)
364
+ const log = deps.log || ((/** @type {string} */ line) => console.log(line))
365
+ const instance = instanceOf(flags)
366
+ const requests = requestsOf(sub, flags)
367
+ if (!flags.manifest) {
368
+ const deployment = await apiCall('GET', `/api/deployments/${encodeURIComponent(instance.deploymentId)}`, undefined, flags)
369
+ const d = (deployment && deployment.data && deployment.data.attributes) || {}
370
+ if (d.accountId !== instance.accountId) throw new Error(`deployment ${instance.deploymentId} is in account ${d.accountId}, not ${instance.accountId}`)
371
+ if (d.region !== instance.region) throw new Error(`deployment ${instance.deploymentId} is in region ${d.region}, not ${instance.region}`)
372
+ const results = []
373
+ for (const request of requests) results.push(await managedRequest(sub, request, instance, flags, log))
374
+ return results
375
+ }
376
+ const target = await standaloneTarget(flags, instance, deps)
377
+ if (requests.some((r) => r.action === 'bootstrap' || (r.action === 'grant' && r.phase === 'grant')) && !target.coreTableName) {
378
+ throw new Error('the stack reports no CoreTableName output: deploy the release that adds it before bootstrapping or granting')
379
+ }
380
+ const results = []
381
+ for (const request of requests) {
382
+ const { management, registry, accounts, identity, material, actor } = target
383
+ let result
384
+ try {
385
+ result = await management.applyManagementRequest({ registry, accounts, identity, request, actor, material })
386
+ } catch (err) {
387
+ const e = /** @type {Error & { code?: string }} */ (err)
388
+ throw new Error(e.code ? `${e.code}: ${e.message}` : e.message)
389
+ }
390
+ if (result.key) {
391
+ writeKeyFile(String(flags.output), String(result.key))
392
+ log(`key ${result.keyId} for ${result.callerId} written to ${flags.output} (pending until activated)`)
393
+ delete result.key
394
+ }
395
+ for (const line of formatResult(result)) log(line)
396
+ results.push(result)
397
+ }
398
+ return results
399
+ }
400
+
401
+ module.exports = { usersManagement, requestsOf, formatResult, ssmMaterial, loadManagement, USAGE, SUBCOMMANDS }
@@ -1,10 +1,12 @@
1
- // Auth headers for calls to a deployment's permissions/users API from the CLI: an IAM principal token (--iam, exchanged from
2
- // your AWS identity), an API key (--token), or a deployment login (`saaslayer login --deployment`). Shared by commands.
1
+ // Auth for calls to a deployment's permissions/users API from the CLI: an IAM principal token (--iam), an API key (--token), a
2
+ // deployment login (`saaslayer login --deployment`), or an external OIDC ID token sent only to a pinned permissions API host.
3
3
  'use strict'
4
+ const fs = require('fs')
4
5
  const creds = require('./credentials')
5
6
  const { refreshIfExpired } = require('./deployment-auth')
7
+ const { decodeJwt } = require('./config')
6
8
 
7
- const CHOOSE = '--iam <principalId>, --token (or $SAASLAYER_TOKEN), or a deployment login (`saaslayer login --deployment <dep_id|env>`) is required'
9
+ const CHOOSE = '--iam <principalId>, --token (or $SAASLAYER_TOKEN), --id-token-file (or $SAASLAYER_ID_TOKEN), or a deployment login (`saaslayer login --deployment <dep_id|env>`) is required'
8
10
 
9
11
  /**
10
12
  * @param {string} token
@@ -26,15 +28,22 @@ function assertServes(profile, apiBase) {
26
28
  }
27
29
 
28
30
  /**
29
- * Request auth headers. Explicit flags win: --iam (IAM principal token as bearer), --token (api key + bearer),
31
+ * Request auth headers. An external ID token (--id-token-file / $SAASLAYER_ID_TOKEN) is sent only when apiBase is its pinned
32
+ * host (see idTokenTarget). Otherwise explicit flags win: --iam (IAM principal token as bearer), --token (api key + bearer),
30
33
  * --deployment/--as/--user-service-instance (that deployment login's id token). Without one, the ambient source is
31
34
  * used: $SAASLAYER_TOKEN or the current deployment login — both at once is ambiguous and refused.
32
35
  * @param {string} apiBase
33
- * @param {{ token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string, 'user-service-instance'?: string }} flags
34
- * @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> }} deps
36
+ * @param {IdTokenFlags & { region?: string, profile?: string }} flags
37
+ * @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> } & IdTokenDeps} deps
35
38
  * @returns {Promise<Record<string, string>>}
36
39
  */
37
- async function authHeaders(apiBase, flags, { exchange }) {
40
+ async function authHeaders(apiBase, flags, deps) {
41
+ const { exchange } = deps
42
+ const pinned = await idTokenTarget(flags, deps)
43
+ if (pinned) {
44
+ if (normBase(apiBase) !== pinned.apiBase) throw new Error(`refusing to send your ID token to ${normBase(apiBase)} — it is pinned to ${pinned.apiBase}`)
45
+ return pinned.headers
46
+ }
38
47
  if (flags.iam && flags.token) throw new Error('pass only one of --iam, --token or a deployment login (--deployment)')
39
48
  if (flags.iam) {
40
49
  const region = flags.region || process.env.AWS_REGION || 'us-west-2'
@@ -58,4 +67,153 @@ async function authHeaders(apiBase, flags, { exchange }) {
58
67
  return { authorization: `Bearer ${fresh.idToken}` }
59
68
  }
60
69
 
61
- module.exports = { authHeaders }
70
+ /** @param {string} u */
71
+ const normBase = (u) => String(u || '').replace(/\/+$/, '')
72
+
73
+ /**
74
+ * @typedef {{ token: string, source: string, explicit: boolean }} IdToken
75
+ * @typedef {{ 'api-base'?: string, 'id-token-file'?: string, token?: string, iam?: string, deployment?: string, as?: string,
76
+ * 'user-service-instance'?: string, yes?: boolean }} IdTokenFlags
77
+ * @typedef {{ ask?: (question: string) => Promise<string>, apiCall?: typeof import('./api-client').apiCall,
78
+ * resolveDeployment?: typeof import('./deployments').resolveDeployment }} IdTokenDeps
79
+ */
80
+
81
+ /**
82
+ * The external ID token, if one was given: --id-token-file (explicit) wins over $SAASLAYER_ID_TOKEN (ambient). Warns when the
83
+ * file is readable by group or others. Errors name the source, never the token.
84
+ * @param {IdTokenFlags} flags
85
+ * @returns {IdToken|null}
86
+ */
87
+ function idTokenOf(flags) {
88
+ const file = flags['id-token-file']
89
+ if (file !== undefined) {
90
+ if (typeof file !== 'string') throw new Error('--id-token-file <path> needs a path')
91
+ /** @type {string} */
92
+ let token
93
+ try {
94
+ if (fs.statSync(file).mode & 0o077) console.error(`warning: ${file} is readable by other users — chmod 600 it`)
95
+ token = fs.readFileSync(file, 'utf8').trim()
96
+ } catch (err) {
97
+ throw new Error(`--id-token-file: cannot read ${file}`)
98
+ }
99
+ return { token, source: '--id-token-file', explicit: true }
100
+ }
101
+ const env = process.env.SAASLAYER_ID_TOKEN
102
+ return env ? { token: env.trim(), source: '$SAASLAYER_ID_TOKEN', explicit: false } : null
103
+ }
104
+
105
+ /**
106
+ * Decode (no verification — the deployment verifies) and refuse a token the deployment would reject anyway: not a JWT, a
107
+ * Cognito access token, no aud, no exp, or expired. Messages carry the issuer and how to get a fresh ID token.
108
+ * @param {IdToken} idToken
109
+ * @returns {{ iss: string }}
110
+ */
111
+ function checkIdToken({ token, source }) {
112
+ /** @type {Record<string, unknown>} */
113
+ let claims
114
+ try {
115
+ claims = decodeJwt(token)
116
+ if (!claims || typeof claims !== 'object') throw new Error('not an object')
117
+ } catch (err) {
118
+ throw new Error(`${source} is not a JWT — pass the raw ID token your login provider issued`)
119
+ }
120
+ const iss = typeof claims.iss === 'string' ? claims.iss : 'your login provider'
121
+ if (claims.token_use === 'access') {
122
+ throw new Error(`${source} holds an access token, not an ID token — access tokens carry no aud; use the ID token (Cognito: AuthenticationResult.IdToken; OIDC: id_token)`)
123
+ }
124
+ if (claims.aud === undefined) throw new Error(`${source} has no aud claim — pass the ID token, whose aud is your app client id`)
125
+ if (typeof claims.exp !== 'number') throw new Error(`${source} has no exp claim — pass the ID token your login provider issued`)
126
+ if (claims.exp <= Math.floor(Date.now() / 1000)) {
127
+ const at = new Date(claims.exp * 1000).toISOString()
128
+ throw new Error(`${source} expired at ${at} — get a fresh ID token from ${iss} (sign in again; Cognito: \`aws cognito-idp admin-initiate-auth\` or initiate-auth, then AuthenticationResult.IdToken; OIDC: the id_token of a new sign-in)`)
129
+ }
130
+ return { iss }
131
+ }
132
+
133
+ /**
134
+ * Refuse an ID token next to any other credential: --iam, --token, $SAASLAYER_TOKEN, a deployment login selector, or (for
135
+ * the ambient $SAASLAYER_ID_TOKEN) the current deployment login. An explicit --id-token-file wins over a stored login.
136
+ * @param {IdToken} idToken
137
+ * @param {IdTokenFlags} flags
138
+ */
139
+ function refuseAmbiguous(idToken, flags) {
140
+ const others = [
141
+ flags.iam && '--iam',
142
+ flags.token && '--token',
143
+ process.env.SAASLAYER_TOKEN && '$SAASLAYER_TOKEN',
144
+ flags.as && '--as',
145
+ flags['user-service-instance'] && '--user-service-instance',
146
+ ].filter(Boolean)
147
+ if (others.length) throw new Error(`an external ID token (${idToken.source}) cannot be combined with ${others.join(', ')} — pass one credential`)
148
+ const current = idToken.explicit ? null : creds.currentDeploymentProfile()
149
+ if (current) {
150
+ throw new Error(`both $SAASLAYER_ID_TOKEN and the deployment login ${current.deploymentId} (${current.email || current.userId}) are available — pass --id-token-file or unset $SAASLAYER_ID_TOKEN to choose`)
151
+ }
152
+ }
153
+
154
+ /**
155
+ * A deployment's permissions API base, read through the control plane (your control-plane login): the deployment's one
156
+ * live permissions-service module (else its default instance), its public hostname winning over the raw endpoint.
157
+ * @param {IdTokenFlags} flags
158
+ * @param {IdTokenDeps} deps
159
+ * @returns {Promise<string>}
160
+ */
161
+ async function deploymentPermissionsApiBase(flags, deps) {
162
+ const apiCall = deps.apiCall || require('./api-client').apiCall
163
+ const resolveDeployment = deps.resolveDeployment || require('./deployments').resolveDeployment
164
+ const selector = String(flags.deployment)
165
+ const deploymentId = /^dep_/.test(selector) ? selector : (await resolveDeployment({ ...flags, env: selector })).deploymentId
166
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}`, undefined, flags)
167
+ /** @type {Array<{ moduleName: string|null, serviceInstance: string|null, status: string|null, outputs?: Record<string, unknown>, publicOutputs?: Record<string, unknown> }>} */
168
+ const modules = ((doc && doc.data && doc.data.attributes) || {}).modules || []
169
+ const live = modules.filter((m) => m.moduleName === 'permissions-service' && m.status !== 'DELETED')
170
+ if (live.length === 0) throw new Error(`deployment ${deploymentId} has no permissions-service`)
171
+ const chosen = live.length === 1 ? live[0] : live.find((m) => (m.serviceInstance || '_') === '_')
172
+ if (!chosen) throw new Error(`deployment ${deploymentId} has several permissions-service instances (${live.map((m) => m.serviceInstance).join(', ')}) — pass that instance's https --api-base instead of --deployment`)
173
+ const endpoint = { ...(chosen.outputs || {}), ...(chosen.publicOutputs || {}) }.ServiceEndpoint
174
+ if (typeof endpoint !== 'string' || !endpoint.startsWith('https://')) throw new Error(`deployment ${deploymentId} has no https permissions API endpoint yet`)
175
+ return normBase(endpoint)
176
+ }
177
+
178
+ /**
179
+ * The pinned destination for an external ID token: --deployment (resolved through the control plane; a different --api-base
180
+ * is refused), else an https --api-base (or $SAASLAYER_API_BASE) the user confirms by typing its host (--yes confirms).
181
+ * @param {{ iss: string }} claims
182
+ * @param {IdTokenFlags} flags
183
+ * @param {IdTokenDeps} deps
184
+ * @returns {Promise<string>}
185
+ */
186
+ async function pinnedApiBase(claims, flags, deps) {
187
+ const given = flags['api-base'] || process.env.SAASLAYER_API_BASE
188
+ if (flags.deployment) {
189
+ const apiBase = await deploymentPermissionsApiBase(flags, deps)
190
+ if (given && normBase(given) !== apiBase) throw new Error(`--api-base ${normBase(given)} is not ${flags.deployment}'s permissions API (${apiBase}) — refusing to send your ID token there`)
191
+ return apiBase
192
+ }
193
+ if (!given) throw new Error('an external ID token needs a pinned destination: --deployment <dep_id|env> (resolved through the control plane) or an https --api-base you confirm')
194
+ /** @type {URL} */
195
+ let url
196
+ try { url = new URL(given) } catch (err) { throw new Error(`--api-base ${given} must be an https URL`) }
197
+ if (url.protocol !== 'https:') throw new Error(`--api-base ${given} must be an https URL`)
198
+ const ask = deps.ask || require('./prompt').ask
199
+ const typed = flags.yes ? url.host : await ask(`Send your ID token from ${claims.iss} to ${url.host}? Type the host "${url.host}" to confirm: `)
200
+ if (typed !== url.host) throw new Error(`not confirmed — your ID token was not sent to ${url.host}`)
201
+ return normBase(given)
202
+ }
203
+
204
+ /**
205
+ * Where and how to send an external ID token, or null when none was given (other auth applies).
206
+ * @param {IdTokenFlags} flags
207
+ * @param {IdTokenDeps} [deps]
208
+ * @returns {Promise<{ apiBase: string, headers: Record<string, string> }|null>}
209
+ */
210
+ async function idTokenTarget(flags, deps = {}) {
211
+ const idToken = idTokenOf(flags)
212
+ if (!idToken) return null
213
+ refuseAmbiguous(idToken, flags)
214
+ const claims = checkIdToken(idToken)
215
+ const apiBase = await pinnedApiBase(claims, flags, deps)
216
+ return { apiBase, headers: { authorization: `Bearer ${idToken.token}` } }
217
+ }
218
+
219
+ module.exports = { authHeaders, idTokenTarget }
@@ -1,12 +1,13 @@
1
- // One call to a deployment's permissions API from a CLI command: resolves --api-base (or $SAASLAYER_API_BASE), the selected auth
2
- // (deployment login, API key or IAM), and throws with the API's error codes and messages.
1
+ // One call to a deployment's permissions API from a CLI command: resolves --api-base (or $SAASLAYER_API_BASE) and the selected
2
+ // auth (deployment login, API key, IAM, or an external ID token to a pinned host), and throws with the API's error codes.
3
3
  'use strict'
4
4
  const { exchangeIamToken } = require('./iam-session')
5
- const { authHeaders } = require('./deployment-api-auth')
5
+ const { authHeaders, idTokenTarget } = require('./deployment-api-auth')
6
6
 
7
7
  /**
8
- * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string }} PermissionsFlags
9
- * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
8
+ * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string,
9
+ * 'id-token-file'?: string, yes?: boolean }} PermissionsFlags
10
+ * @typedef {{ exchange?: typeof exchangeIamToken } & import('./deployment-api-auth').IdTokenDeps} Deps
10
11
  */
11
12
 
12
13
  /**
@@ -25,17 +26,22 @@ function apiBaseOf(label, flags) {
25
26
  * @returns {Promise<any>} the response document
26
27
  */
27
28
  async function permissionsRequest(label, flags, deps, method, path, body) {
28
- const apiBase = apiBaseOf(label, flags)
29
- const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
29
+ const pinned = await idTokenTarget(flags, deps)
30
+ const apiBase = pinned ? pinned.apiBase : apiBaseOf(label, flags)
31
+ const auth = pinned ? pinned.headers : await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
30
32
  const res = await fetch(`${apiBase}${path}`, {
31
33
  method,
32
34
  headers: body ? { ...auth, 'content-type': 'application/json' } : auth,
33
35
  ...(body ? { body: JSON.stringify(body) } : {}),
36
+ // The ID token goes only to its pinned host: a redirect would resend it wherever the 3xx points, so none is followed.
37
+ ...(pinned ? { redirect: /** @type {RequestRedirect} */ ('error') } : {}),
34
38
  })
35
39
  const json = await res.json().catch(() => ({}))
36
40
  if (!res.ok) {
37
- const detail = ((json && json.errors) || []).map((/** @type {{ code?: string, message?: string, detail?: string }} */ e) => [e.code, e.message || e.detail].filter(Boolean).join(': ')).join('; ') || JSON.stringify(json)
38
- throw new Error(`${label} failed (${res.status}${detail ? ` ${detail}` : ''})`)
41
+ /** @type {Array<{ code?: string, message?: string, detail?: string }>} */
42
+ const errors = (json && json.errors) || []
43
+ const detail = errors.map((e) => [e.code, e.message || e.detail].filter(Boolean).join(': ')).join('; ') || JSON.stringify(json)
44
+ throw Object.assign(new Error(`${label} failed (${res.status}${detail ? ` ${detail}` : ''})`), { status: res.status, codes: errors.map((e) => e.code).filter(Boolean) })
39
45
  }
40
46
  return json
41
47
  }