saaslayer 0.2.0 → 0.4.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.
Files changed (68) hide show
  1. package/README.md +132 -16
  2. package/bin/saaslayer.js +387 -61
  3. package/package.json +3 -2
  4. package/src/api-client.js +37 -1
  5. package/src/aws-sigv4.js +74 -26
  6. package/src/cognito-user-api.js +80 -0
  7. package/src/commands/access-admins.js +2 -2
  8. package/src/commands/account-email.js +43 -0
  9. package/src/commands/admin-allowlist.js +65 -0
  10. package/src/commands/api-keys.js +83 -0
  11. package/src/commands/audit.js +77 -0
  12. package/src/commands/aws.js +355 -82
  13. package/src/commands/binding-handoff.js +174 -0
  14. package/src/commands/bindings.js +111 -0
  15. package/src/commands/catalog.js +30 -3
  16. package/src/commands/deploy.js +33 -10
  17. package/src/commands/env-export.js +58 -0
  18. package/src/commands/first-admin.js +15 -4
  19. package/src/commands/foundation.js +75 -117
  20. package/src/commands/hooks.js +271 -0
  21. package/src/commands/integration-credentials.js +1 -1
  22. package/src/commands/lifecycle.js +149 -24
  23. package/src/commands/login-domain.js +259 -0
  24. package/src/commands/login.js +53 -16
  25. package/src/commands/org-members.js +109 -0
  26. package/src/commands/permission-orgs.js +80 -0
  27. package/src/commands/release-manifest.js +17 -8
  28. package/src/commands/service-principals.js +42 -5
  29. package/src/commands/settings.js +21 -5
  30. package/src/commands/sms-registration.js +182 -0
  31. package/src/commands/sms.js +178 -0
  32. package/src/commands/social.js +265 -0
  33. package/src/commands/support-staff.js +72 -0
  34. package/src/commands/trust-policies.js +172 -0
  35. package/src/commands/users-management.js +2 -20
  36. package/src/commands/users.js +56 -11
  37. package/src/commands/versions.js +61 -0
  38. package/src/connection-proof.js +41 -0
  39. package/src/deployment-api-auth.js +166 -8
  40. package/src/deployments.js +1 -1
  41. package/src/foundation-change-set.js +180 -0
  42. package/src/foundation-home.js +121 -0
  43. package/src/foundation-template.js +51 -10
  44. package/src/foundation-trust-write.js +379 -0
  45. package/src/iam-session.js +14 -8
  46. package/src/login-domain.js +139 -0
  47. package/src/login-methods.js +118 -0
  48. package/src/module-catalog.js +3 -2
  49. package/src/permissions-request.js +15 -9
  50. package/src/release-manifest.js +11 -4
  51. package/src/scope.js +3 -1
  52. package/src/settings.js +85 -13
  53. package/src/sms/number.js +37 -0
  54. package/src/sms/registration-fields.js +167 -0
  55. package/src/sms/registration-validate.js +151 -0
  56. package/src/sms/registration.js +216 -0
  57. package/src/sms/release.js +55 -0
  58. package/src/sms/scope.js +86 -0
  59. package/src/sms/status.js +181 -0
  60. package/src/ssm-api.js +31 -0
  61. package/src/trust-entries.js +350 -0
  62. package/src/user-service-instance.js +27 -0
  63. package/src/users-api.js +55 -8
  64. package/src/users-import/checkpoint.js +76 -0
  65. package/src/users-import/import.js +233 -24
  66. package/src/versions.js +80 -0
  67. package/templates/saaslayer-foundation-region.yml +45 -1
  68. package/templates/saaslayer-foundation.yml +747 -296
@@ -0,0 +1,172 @@
1
+ // `saaslayer permissions trust-policies list|get|add|update|disable|enable|delete`: the external login providers (OIDC issuers)
2
+ // a deployment trusts, through the permissions /trust-policies API. Policies made here are always external, never impersonating.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { permissionsRequest } = require('../permissions-request')
6
+
7
+ /**
8
+ * @typedef {import('../permissions-request').PermissionsFlags & { audience?: string|string[], subject?: string|string[],
9
+ * 'allow-any-subject'?: boolean, 'principal-claim'?: string, 'jwks-uri'?: string, description?: string, reason?: string }} TrustFlags
10
+ * @typedef {{ exchange?: typeof exchangeIamToken, ask?: (question: string) => Promise<string> }} Deps
11
+ */
12
+
13
+ // What the API's refusals mean for the person running the command.
14
+ const HINTS = {
15
+ FIRST_PARTY_POLICY: 'this policy is the deployment\'s own login pool (first-party); it is managed by the deployment, not through this command',
16
+ LAST_ADMIN_PROVIDER: 'this provider is the last sign-in path of every usable access admin; add another provider (or an admin who signs in elsewhere) first',
17
+ }
18
+
19
+ /** @param {string|string[]|undefined} v @returns {string[]|undefined} */
20
+ const listOf = (v) => (v === undefined ? undefined : Array.isArray(v) ? v : [v])
21
+
22
+ /** @param {string} label @param {string[]} positional @param {string} what */
23
+ function required(label, positional, what) {
24
+ if (!positional[0]) throw new Error(`${label}: <${what}> is required`)
25
+ return positional[0]
26
+ }
27
+
28
+ /**
29
+ * Call a trust-policies route; a refusal with a known code gains a hint.
30
+ * @param {string} label @param {TrustFlags} flags @param {Deps} deps @param {string} method @param {string} path @param {object} [body]
31
+ */
32
+ async function call(label, flags, deps, method, path, body) {
33
+ try {
34
+ return await permissionsRequest(label, flags, deps, method, path, body)
35
+ } catch (err) {
36
+ const hint = ((/** @type {{ codes?: string[] }} */ (err).codes) || []).map((c) => HINTS[/** @type {keyof typeof HINTS} */ (c)]).find(Boolean)
37
+ if (hint) err.message = `${err.message} — ${hint}`
38
+ throw err
39
+ }
40
+ }
41
+
42
+ /** @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
43
+ const policyOf = (body) => ({ id: body.data.id, ...body.data.attributes })
44
+
45
+ /**
46
+ * The subject rule: --subject (repeatable allowlist) or --allow-any-subject, never both.
47
+ * @param {string} label @param {TrustFlags} flags
48
+ * @returns {{ subjects?: string[], allowAnySubject?: boolean }}
49
+ */
50
+ function subjectRule(label, flags) {
51
+ const subjects = listOf(flags.subject)
52
+ if (subjects && flags['allow-any-subject']) throw new Error(`${label}: pass --subject S (repeatable) or --allow-any-subject, not both`)
53
+ if (subjects) return { subjects, allowAnySubject: false }
54
+ if (flags['allow-any-subject']) return { allowAnySubject: true }
55
+ return {}
56
+ }
57
+
58
+ /**
59
+ * The provider's OIDC discovery document; refuses unless its issuer is exactly the given one (tokens must match it exactly).
60
+ * @param {string} label @param {string} issuerUrl
61
+ * @returns {Promise<{ issuer: string, jwks_uri?: string }>}
62
+ */
63
+ async function providerConfiguration(label, issuerUrl) {
64
+ const url = `${issuerUrl.replace(/\/+$/, '')}/.well-known/openid-configuration`
65
+ /** @type {any} */
66
+ let config
67
+ try {
68
+ const res = await fetch(url, { method: 'GET', headers: { accept: 'application/json' } })
69
+ if (!res.ok) throw new Error(`${res.status}`)
70
+ config = await res.json()
71
+ } catch (err) {
72
+ throw new Error(`${label}: could not read ${url} (${err.message}) — is ${issuerUrl} an OIDC issuer?`)
73
+ }
74
+ if (!config || config.issuer !== issuerUrl) {
75
+ throw new Error(`${label}: ${url} says its issuer is "${config && config.issuer}", not "${issuerUrl}" — use the exact iss value the provider's ID tokens carry`)
76
+ }
77
+ return config
78
+ }
79
+
80
+ /** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
81
+ async function trustPoliciesList(positional, flags, deps = {}) {
82
+ const body = await call('permissions trust-policies list', flags, deps, 'GET', '/trust-policies')
83
+ return (body.data || []).map((/** @type {{ id: string, attributes: object }} */ d) => ({ id: d.id, ...d.attributes }))
84
+ }
85
+
86
+ /** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
87
+ async function trustPoliciesGet(positional, flags, deps = {}) {
88
+ const label = 'permissions trust-policies get'
89
+ const id = required(label, positional, 'policyId')
90
+ return policyOf(await call(label, flags, deps, 'GET', `/trust-policies/${encodeURIComponent(id)}`))
91
+ }
92
+
93
+ /**
94
+ * Trust an external login provider: <issuerUrl> --audience A [--audience B] (--subject S … | --allow-any-subject)
95
+ * [--principal-claim sub] [--jwks-uri URL] [--description D]. The issuer is checked against its openid-configuration.
96
+ * @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
97
+ */
98
+ async function trustPoliciesAdd(positional, flags, deps = {}) {
99
+ const label = 'permissions trust-policies add'
100
+ const issuerUrl = required(label, positional, 'issuerUrl')
101
+ if (!/^https:\/\//.test(issuerUrl)) throw new Error(`${label}: <issuerUrl> must be an https URL (the exact iss of the provider's ID tokens)`)
102
+ const audience = listOf(flags.audience)
103
+ if (!audience) throw new Error(`${label}: --audience <app client id> is required (repeatable)`)
104
+ const subjects = subjectRule(label, flags)
105
+ if (subjects.allowAnySubject === undefined) throw new Error(`${label}: pass --subject S (repeatable) or --allow-any-subject — a policy with neither authorizes nobody`)
106
+ const config = await providerConfiguration(label, issuerUrl)
107
+ const jwksUri = flags['jwks-uri'] || config.jwks_uri
108
+ const request = {
109
+ issuerUrl,
110
+ audience,
111
+ ...(jwksUri ? { jwksUri } : {}),
112
+ claimMapping: { principalId: flags['principal-claim'] || 'sub' },
113
+ ...subjects,
114
+ ...(flags.description ? { description: flags.description } : {}),
115
+ external: true,
116
+ allowImpersonation: false,
117
+ }
118
+ return policyOf(await call(label, flags, deps, 'POST', '/trust-policies', request))
119
+ }
120
+
121
+ /**
122
+ * Change a provider's audience, subject rule, JWKS URI or description. The issuer and principal claim never change (they key
123
+ * every principal the provider signs in).
124
+ * @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
125
+ */
126
+ async function trustPoliciesUpdate(positional, flags, deps = {}) {
127
+ const label = 'permissions trust-policies update'
128
+ const id = required(label, positional, 'policyId')
129
+ if (flags['principal-claim'] !== undefined) throw new Error(`${label}: --principal-claim cannot change — it keys every principal this provider signs in; add a new provider instead`)
130
+ const audience = listOf(flags.audience)
131
+ const patch = {
132
+ ...(audience ? { audience } : {}),
133
+ ...(flags['jwks-uri'] ? { jwksUri: flags['jwks-uri'] } : {}),
134
+ ...(flags.description !== undefined ? { description: String(flags.description) } : {}),
135
+ ...subjectRule(label, flags),
136
+ }
137
+ if (Object.keys(patch).length === 0) throw new Error(`${label}: nothing to update — give --audience, --subject, --allow-any-subject, --jwks-uri or --description`)
138
+ return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, patch))
139
+ }
140
+
141
+ /** Stop trusting a provider without deleting it. @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
142
+ async function trustPoliciesDisable(positional, flags, deps = {}) {
143
+ const label = 'permissions trust-policies disable'
144
+ const id = required(label, positional, 'policyId')
145
+ return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, { enabled: false }))
146
+ }
147
+
148
+ /** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
149
+ async function trustPoliciesEnable(positional, flags, deps = {}) {
150
+ const label = 'permissions trust-policies enable'
151
+ const id = required(label, positional, 'policyId')
152
+ return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, { enabled: true }))
153
+ }
154
+
155
+ /**
156
+ * Delete a provider: --reason, then its issuer typed to confirm (--yes confirms). Its people can no longer sign in.
157
+ * @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
158
+ */
159
+ async function trustPoliciesDelete(positional, flags, deps = {}) {
160
+ const label = 'permissions trust-policies delete'
161
+ const id = required(label, positional, 'policyId')
162
+ if (!flags.reason || typeof flags.reason !== 'string') throw new Error(`${label}: --reason <text> is required`)
163
+ const path = `/trust-policies/${encodeURIComponent(id)}`
164
+ const policy = policyOf(await call(label, flags, deps, 'GET', path))
165
+ const issuer = String(policy.issuerUrl)
166
+ const ask = deps.ask || require('../prompt').ask
167
+ const typed = flags.yes ? issuer : await ask(`Delete trust in ${issuer}? Everyone who signs in through it loses access. Type the issuer "${issuer}" to confirm: `)
168
+ if (typed !== issuer) throw new Error(`${label}: not confirmed — nothing deleted`)
169
+ return policyOf(await call(label, flags, deps, 'DELETE', path, { reason: flags.reason }))
170
+ }
171
+
172
+ module.exports = { trustPoliciesList, trustPoliciesGet, trustPoliciesAdd, trustPoliciesUpdate, trustPoliciesDisable, trustPoliciesEnable, trustPoliciesDelete }
@@ -6,7 +6,7 @@ const path = require('path')
6
6
  const crypto = require('crypto')
7
7
  const { execFileSync } = require('child_process')
8
8
  const { apiCall } = require('../api-client')
9
- const { signRequest } = require('../aws-sigv4')
9
+ const { ssmApi } = require('../ssm-api')
10
10
  const { awsCredentials } = require('../iam-session')
11
11
 
12
12
  // The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
@@ -165,25 +165,7 @@ function checkedManifest(file, instance, management) {
165
165
  * @param {{ region: string, credentials: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, basePath: string, fetchImpl: typeof fetch }} deps
166
166
  */
167
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
- }
168
+ const call = ssmApi({ region, credentials, fetchImpl })
187
169
  const name = (/** @type {string} */ keyId) => `${basePath}/${keyId}`
188
170
  return {
189
171
  async put(/** @type {string} */ keyId, /** @type {string} */ raw) {
@@ -6,8 +6,9 @@ const path = require('path')
6
6
  const { execFileSync } = require('child_process')
7
7
  const { getProvider } = require('../users-import/providers')
8
8
  const { buildManifest, validateManifest } = require('../users-import/manifest')
9
- const { planImport, applyImport, formatPlan } = require('../users-import/import')
9
+ const { planImport, applyImport, formatPlan, checkProfiles } = require('../users-import/import')
10
10
  const { mintSuid } = require('../users-import/ids')
11
+ const { checkpointPath } = require('../users-import/checkpoint')
11
12
  const { authHeaders } = require('../deployment-api-auth')
12
13
  const { exchangeIamToken } = require('../iam-session')
13
14
  const creds = require('../credentials')
@@ -39,6 +40,8 @@ async function usersExport(flags, deps = {}) {
39
40
  const users = manifest.accounts.reduce((n, a) => n + a.users.length, 0)
40
41
  log(`exported ${users} users in ${manifest.accounts.length} accounts to ${flags.out}`)
41
42
  log('The manifest holds personal data (emails, names, phones). Keep it private and delete it after the import.')
43
+ log('It holds no passwords or MFA secrets: imported users set a new password and set up MFA again.')
44
+ log('It reads one pool: a SaaSLayer deployment\'s second sign-in pool (phone or email) is not exported; those sign-ins are linked again after the import.')
42
45
  if (errors.length) log(`fix before importing:\n ${errors.join('\n ')}`)
43
46
  return manifest
44
47
  }
@@ -47,7 +50,8 @@ async function usersExport(flags, deps = {}) {
47
50
  * Dry run by default (prints the plan); --apply imports and writes a report next to the manifest (or --report).
48
51
  * @param {Record<string, any>} flags
49
52
  * @param {{ exec?: typeof defaultExec, fetch?: typeof fetch, log?: (line: string) => void, now?: () => Date,
50
- * mint?: () => string, sleep?: (ms: number) => Promise<void>, authHeaders?: () => Promise<Record<string, string>> }} [deps]
53
+ * mint?: () => string, sleep?: (ms: number) => Promise<void>, authHeaders?: () => Promise<Record<string, string>>,
54
+ * exchange?: typeof exchangeIamToken }} [deps]
51
55
  */
52
56
  async function usersImport(flags, deps = {}) {
53
57
  const { exec = defaultExec, log = console.log, now = () => new Date() } = deps
@@ -55,6 +59,8 @@ async function usersImport(flags, deps = {}) {
55
59
  const manifest = JSON.parse(fs.readFileSync(path.resolve(flags.manifest), 'utf8'))
56
60
  const errors = validateManifest(manifest)
57
61
  if (errors.length) throw new Error(`users import: the manifest is invalid:\n ${errors.join('\n ')}`)
62
+ // A --token is a Permissions API key; user-service (profiles) takes x-api-key only for its own integration credentials.
63
+ if (flags.apply && !flags.iam) throw new Error("users import --apply needs --iam: user-service (profiles) doesn't accept Permissions API keys")
58
64
  const target = {
59
65
  userPoolId: flags['user-pool-id'],
60
66
  region: flags.region || process.env.AWS_REGION,
@@ -62,23 +68,37 @@ async function usersImport(flags, deps = {}) {
62
68
  apiBase: flags['api-base'] || process.env.SAASLAYER_API_BASE,
63
69
  product: flags.product,
64
70
  logsRoleArn: flags['logs-role-arn'],
71
+ iam: flags.iam,
72
+ checkpointFile: path.resolve(checkpointPath(flags.manifest)),
65
73
  }
66
74
  const plan = await planImport(manifest, target, { exec })
67
75
  log(formatPlan(plan, { apply: Boolean(flags.apply) }))
68
- if (!flags.apply) return { plan }
69
- const report = await applyImport(plan, target, {
76
+ const io = {
70
77
  exec,
71
78
  fetch: deps.fetch || fetch,
79
+ authHeaders: deps.authHeaders || (() => authHeaders(target.apiBase, flags, { exchange: deps.exchange || exchangeIamToken })),
80
+ }
81
+ if (!flags.apply) {
82
+ if (!flags.iam) log('profiles are checked and created at --apply (needs --iam)')
83
+ else for (const line of await checkProfiles(plan, target, io)) log(line)
84
+ return { plan }
85
+ }
86
+ const report = await applyImport(plan, target, {
87
+ ...io,
72
88
  mint: deps.mint || mintSuid,
73
89
  sleep: deps.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
74
- authHeaders: deps.authHeaders || (() => authHeaders(target.apiBase, flags, { exchange: exchangeIamToken })),
75
90
  now,
76
91
  })
77
92
  const reportPath = path.resolve(flags.report || flags.manifest.replace(/\.json$/, '') + '.import-report.json')
78
93
  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2) + '\n', { mode: 0o600 })
79
94
  const s = report.summary
80
- log(`imported: ${s.created} created, ${s.linked} linked, ${s.failed} failed, ${s.skipped} skipped; ${s.orgsCreated} orgs created, ${s.ownersGranted} owners granted`)
81
- log(`report: ${reportPath}${s.failed ? ' — re-run to retry the failed users' : ''}`)
95
+ log(`imported: ${s.created} created, ${s.linked} linked, ${s.failed} failed, ${s.skipped} skipped; ${s.orgsCreated} orgs created, ${s.ownersGranted} owners granted; ${s.profilesCreated} profiles created, ${s.profilesExisting} existing, ${s.profilesFailed} failed`)
96
+ log(`report: ${reportPath}${s.failed || s.profilesFailed ? ' — re-run to retry the failed users and profiles' : ''}`)
97
+ // Incomplete only after the report is written: the caller sets the exit code.
98
+ if (s.failed || s.profilesFailed) {
99
+ log(`incomplete: ${s.failed} users and ${s.profilesFailed} profiles need attention (see ${reportPath})`)
100
+ return { plan, report, exitCode: 1 }
101
+ }
82
102
  return { plan, report }
83
103
  }
84
104
 
@@ -145,8 +165,11 @@ async function targetSuid(command, args, flags, api) {
145
165
  throw new Error(`users ${command}: <suid>, --suid or --email is required`)
146
166
  }
147
167
 
148
- /** --attr name=value (repeatable) plus --name, as profile attributes. @param {Record<string, any>} flags */
149
- function profileAttributes(flags) {
168
+ // Attributes only the user service's reserved-attributes route changes (it needs saaslayer:users:account:update-reserved).
169
+ const RESERVED_ATTRIBUTES = ['email', 'email_verified', 'soid']
170
+
171
+ /** --attr name=value (repeatable) plus --name, as written. @param {Record<string, any>} flags */
172
+ function updateAttributes(flags) {
150
173
  /** @type {Record<string, string>} */
151
174
  const attrs = flags.name ? { name: String(flags.name) } : {}
152
175
  for (const pair of [].concat(flags.attr || [])) {
@@ -158,6 +181,27 @@ function profileAttributes(flags) {
158
181
  return attrs
159
182
  }
160
183
 
184
+ /**
185
+ * The update as one request: profile attributes, or reserved ones (email_verified typed as a boolean). A mix is refused
186
+ * before any request, so it is never mistaken for one atomic change.
187
+ * @param {Record<string, string>} attrs
188
+ * @returns {{ reserved: false, attributes: Record<string, string> } | { reserved: true, attributes: Record<string, string|boolean> }}
189
+ */
190
+ function updateRequest(attrs) {
191
+ const names = Object.keys(attrs)
192
+ const reserved = names.filter((n) => RESERVED_ATTRIBUTES.includes(n))
193
+ if (!reserved.length) return { reserved: false, attributes: attrs }
194
+ const profile = names.filter((n) => !RESERVED_ATTRIBUTES.includes(n))
195
+ if (profile.length) throw new Error(`users update: profile attributes (${profile.join(', ')}) and reserved attributes (${reserved.join(', ')}) are separate requests; run them as two updates`)
196
+ /** @type {Record<string, string|boolean>} */
197
+ const typed = { ...attrs }
198
+ if ('email_verified' in attrs) {
199
+ if (attrs.email_verified !== 'true' && attrs.email_verified !== 'false') throw new Error(`users update: email_verified must be true or false, got ${attrs.email_verified}`)
200
+ typed.email_verified = attrs.email_verified === 'true'
201
+ }
202
+ return { reserved: true, attributes: typed }
203
+ }
204
+
161
205
  /**
162
206
  * Create a user (a durable operation). --password-stdin gives a permanent password (password initialization: never
163
207
  * prod); --delivery invitation mails a temporary one. Re-running the same command replays the same operation (the
@@ -223,8 +267,9 @@ const HANDLERS = {
223
267
  return api.list({ email: flags.email, defaultOrg: flags['default-org'] }, { limit: flags.limit, cursor: flags.cursor })
224
268
  },
225
269
  update: async (api, args, flags) => {
226
- const attributes = profileAttributes(flags)
227
- return api.update(await targetSuid('update', args, flags, api), attributes)
270
+ const request = updateRequest(updateAttributes(flags))
271
+ const suid = await targetSuid('update', args, flags, api)
272
+ return request.reserved ? api.updateReserved(suid, request.attributes) : api.update(suid, request.attributes)
228
273
  },
229
274
  disable: async (api, args, flags) => api.disable(await targetSuid('disable', args, flags, api)),
230
275
  enable: async (api, args, flags) => api.enable(await targetSuid('enable', args, flags, api)),
@@ -0,0 +1,61 @@
1
+ // `saaslayer versions [--project P] [--json]`: the versions a deployment may move to (GET /api/versions), highest first,
2
+ // with the channels on each, breaking releases flagged and, with a project, which of its deployments run each one.
3
+ 'use strict'
4
+ const { apiCall } = require('../api-client')
5
+ const { resolveScope, printScope } = require('../scope')
6
+ const { fetchVersions } = require('../versions')
7
+
8
+ /**
9
+ * The project's live deployments by environment, or null when no project is selected.
10
+ * @param {object} flags
11
+ * @returns {Promise<Array<{ label: string, version: string|null, commitSha: string|null }>|null>}
12
+ */
13
+ async function projectDeployments(flags) {
14
+ let scope
15
+ try {
16
+ scope = resolveScope(flags, { env: 'all' })
17
+ } catch {
18
+ return null
19
+ }
20
+ printScope(scope, flags)
21
+ const view = await apiCall('GET', `/api/projects/${encodeURIComponent(scope.project.value)}/deployments`, undefined, flags)
22
+ return (view.environments || []).flatMap((g) => (g.instances || []).map((i) => ({
23
+ label: `${g.environment}${i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''}`,
24
+ version: i.version || null,
25
+ commitSha: i.commitSha || null,
26
+ })))
27
+ }
28
+
29
+ /**
30
+ * @param {object} flags
31
+ * @returns {Promise<Array<import('../versions').Version & { deployments: string[] }>>}
32
+ */
33
+ async function versions(flags) {
34
+ const list = await fetchVersions(flags)
35
+ const deployments = await projectDeployments(flags)
36
+ const rows = list.map((v) => ({ ...v, deployments: (deployments || []).filter((d) => d.version === v.version).map((d) => d.label) }))
37
+ if (flags.json) {
38
+ console.log(JSON.stringify(rows, null, 2))
39
+ return rows
40
+ }
41
+ if (!rows.length) {
42
+ console.log('no versions yet: SaaSLayer has not published one for this control plane')
43
+ return rows
44
+ }
45
+ const width = Math.max(...rows.map((r) => r.version.length))
46
+ const channelWidth = Math.max(1, ...rows.map((r) => (r.channels.length ? r.channels.join(',') : '—').length))
47
+ console.log('Versions (highest first):')
48
+ for (const r of rows) {
49
+ const channels = (r.channels.length ? r.channels.join(',') : '—').padEnd(channelWidth)
50
+ const on = r.deployments.length ? ` ← ${r.deployments.join(', ')}` : ''
51
+ console.log(` ${r.version.padEnd(width)} ${channels} ${r.compat.padEnd(12)} ${(r.cutAt || '').slice(0, 10)}${on}`)
52
+ }
53
+ const known = new Set(rows.map((r) => r.version))
54
+ const off = (deployments || []).filter((d) => !d.version || !known.has(d.version))
55
+ if (off.length) console.log(` not on a version: ${off.map((d) => `${d.label} (${d.version || (d.commitSha ? d.commitSha.slice(0, 8) : '—')})`).join(', ')}`)
56
+ console.log('')
57
+ console.log('Move a deployment with: saaslayer update --version <version> [--env E] (or --channel stable)')
58
+ return rows
59
+ }
60
+
61
+ module.exports = { versions }
@@ -0,0 +1,41 @@
1
+ // Org connection proof for `saaslayer aws connect` (ADR 0005 §4): an sts:GetCallerIdentity request presigned with the
2
+ // caller's AWS credentials for 15 minutes, signing X-SaaSLayer-Connection-Binding: <orgId>:<controlPlaneId>:<scope>:<nonce>.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { presignUrl } = require('./aws-sigv4')
6
+
7
+ /** The signed header that binds the proof to one org, control plane and scope. */
8
+ const BINDING_HEADER = 'X-SaaSLayer-Connection-Binding'
9
+ /** A proof is valid at most 15 minutes (the control plane refuses longer). */
10
+ const PROOF_SECONDS = 900
11
+
12
+ /**
13
+ * The connection scope a proof binds: `org`, or `projects:<id>` when one project is named and the connect is not org-wide.
14
+ * @param {{ orgWide?: boolean, projectId?: string }} input
15
+ * @returns {string}
16
+ */
17
+ function proofScope({ orgWide, projectId }) {
18
+ return orgWide || !projectId ? 'org' : `projects:${projectId}`
19
+ }
20
+
21
+ /**
22
+ * A fresh connection proof. The presigned URL carries the caller's session token: never log or persist it.
23
+ * @param {{ orgId: string, controlPlaneId: string, scope: string, region: string,
24
+ * credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date, nonce?: string }} input
25
+ * @returns {{ presignedUrl: string, binding: string }}
26
+ */
27
+ function buildConnectionProof({ orgId, controlPlaneId, scope, region, credentials, now = new Date(), nonce = crypto.randomBytes(16).toString('hex') }) {
28
+ const binding = `${orgId}:${controlPlaneId}:${scope}:${nonce}`
29
+ const presignedUrl = presignUrl({
30
+ url: `https://sts.${region}.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15`,
31
+ headers: { [BINDING_HEADER]: binding },
32
+ region,
33
+ service: 'sts',
34
+ expires: PROOF_SECONDS,
35
+ credentials,
36
+ now,
37
+ })
38
+ return { presignedUrl, binding }
39
+ }
40
+
41
+ module.exports = { BINDING_HEADER, PROOF_SECONDS, proofScope, buildConnectionProof }
@@ -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 }
@@ -20,7 +20,7 @@ async function resolveDeployment(flags) {
20
20
  }
21
21
  if (instances.length > 1) throw new Error(`multiple ${env} deployments — pass --region <r>: ${instances.map((i) => i.region).join(', ')}`)
22
22
  const inst = instances[0]
23
- return { project, env, region: inst.region, deploymentId: inst.deploymentId, status: inst.status }
23
+ return { project, env, region: inst.region, deploymentId: inst.deploymentId, status: inst.status, commitSha: inst.commitSha || null, version: inst.version || null }
24
24
  }
25
25
 
26
26
  module.exports = { resolveDeployment }