saaslayer 0.3.0 → 0.4.1

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 (65) hide show
  1. package/README.md +199 -18
  2. package/bin/saaslayer.js +335 -62
  3. package/package.json +3 -2
  4. package/src/aws-sigv4.js +74 -26
  5. package/src/commands/access-admins.js +2 -2
  6. package/src/commands/admin-allowlist.js +23 -3
  7. package/src/commands/api-keys.js +83 -0
  8. package/src/commands/audit.js +77 -0
  9. package/src/commands/aws.js +355 -82
  10. package/src/commands/binding-handoff.js +174 -0
  11. package/src/commands/bindings.js +111 -0
  12. package/src/commands/catalog.js +30 -3
  13. package/src/commands/deploy.js +49 -11
  14. package/src/commands/env-export.js +58 -0
  15. package/src/commands/first-admin.js +15 -4
  16. package/src/commands/foundation.js +75 -117
  17. package/src/commands/hooks.js +271 -0
  18. package/src/commands/integration-credentials.js +1 -1
  19. package/src/commands/lifecycle.js +149 -24
  20. package/src/commands/login-domain.js +259 -0
  21. package/src/commands/permission-orgs.js +80 -0
  22. package/src/commands/release-manifest.js +17 -8
  23. package/src/commands/service-principals.js +42 -5
  24. package/src/commands/settings.js +21 -5
  25. package/src/commands/sms-registration.js +182 -0
  26. package/src/commands/sms.js +178 -0
  27. package/src/commands/social.js +265 -0
  28. package/src/commands/support-staff.js +72 -0
  29. package/src/commands/users-management.js +2 -20
  30. package/src/commands/users.js +56 -11
  31. package/src/commands/versions.js +61 -0
  32. package/src/connection-proof.js +41 -0
  33. package/src/deployments.js +14 -2
  34. package/src/foundation-change-set.js +180 -0
  35. package/src/foundation-home.js +121 -0
  36. package/src/foundation-template.js +51 -10
  37. package/src/foundation-trust-write.js +379 -0
  38. package/src/iam-session.js +14 -8
  39. package/src/login-domain.js +138 -0
  40. package/src/login-methods.js +118 -0
  41. package/src/module-catalog.js +3 -2
  42. package/src/release-manifest.js +11 -4
  43. package/src/scope.js +3 -1
  44. package/src/settings.js +85 -13
  45. package/src/sms/number.js +37 -0
  46. package/src/sms/registration-fields.js +167 -0
  47. package/src/sms/registration-validate.js +151 -0
  48. package/src/sms/registration.js +216 -0
  49. package/src/sms/release.js +55 -0
  50. package/src/sms/scope.js +86 -0
  51. package/src/sms/status.js +181 -0
  52. package/src/ssm-api.js +31 -0
  53. package/src/trust-entries.js +350 -0
  54. package/src/user-service-instance.js +27 -0
  55. package/src/users-api.js +55 -8
  56. package/src/users-import/checkpoint.js +76 -0
  57. package/src/users-import/import.js +233 -24
  58. package/src/versions.js +80 -0
  59. package/templates/bootstrap/saaslayer-bootstrap-permission-set-inline-policy.json +148 -0
  60. package/templates/bootstrap/saaslayer-bootstrap-policy-email-sender.json +22 -0
  61. package/templates/bootstrap/saaslayer-bootstrap-policy-sms-number.json +22 -0
  62. package/templates/bootstrap/saaslayer-bootstrap-policy.json +114 -0
  63. package/templates/bootstrap/saaslayer-bootstrap-trust-policy.json +18 -0
  64. package/templates/saaslayer-foundation-region.yml +45 -1
  65. package/templates/saaslayer-foundation.yml +759 -309
@@ -1,10 +1,14 @@
1
1
  // `saaslayer foundation status|upgrade`: compare the installed foundation stacks with this CLI's bundled templates, upgrade
2
2
  // them in place via a reviewed change set keeping every parameter value, then have the control plane re-read the account.
3
+ // The account stack is read and upgraded in its home region; its trust is re-rendered from its own TrustEntries.
3
4
  'use strict'
4
5
  const fs = require('fs')
5
6
  const { execFileSync } = require('child_process')
6
7
  const { FOUNDATION_TEMPLATE, FOUNDATION_REGION_TEMPLATE, foundationRegionStackName, emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords } = require('./aws')
7
- const { stripComments, writeDeployableTemplate } = require('../foundation-template')
8
+ const { templateInfo, writeDeployableTemplate, stripComments } = require('../foundation-template')
9
+ const { renderFoundationTemplate } = require('../trust-entries')
10
+ const { resolveFoundationHome } = require('../foundation-home')
11
+ const { STABLE_STATUSES, NO_CHANGES, awsRunner, describeStack, waitForChangeSet, formatChanges, smsNumberRefusal } = require('../foundation-change-set')
8
12
  const { confirm: promptConfirm } = require('../prompt')
9
13
  const { apiCall } = require('../api-client')
10
14
 
@@ -15,45 +19,16 @@ const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', s
15
19
  * @typedef {(input: { accountId: string, region: string }, flags: object) => Promise<{ foundationVersion?: string|null }>} Refresh
16
20
  * @typedef {{ exec?: typeof defaultExec, log?: (...a: unknown[]) => void, confirm?: (q: string) => Promise<boolean>,
17
21
  * sleep?: (ms: number) => Promise<void>, pollMs?: number, maxPolls?: number, refresh?: Refresh }} Deps
18
- * @typedef {{ kind: 'account'|'region', stackName: string, template: string, outputKey: string, capabilities: string[] }} Target
22
+ * @typedef {{ kind: 'account'|'region', stackName: string, template: string, outputKey: string, capabilities: string[], region: string }} Target
23
+ * @typedef {{ TrustEntries: string, ConnectionAuthorizerArns: string }} Conversion explicit trust parameters that convert an
24
+ * account stack from the single ExternalId to TrustEntries (supplied by `saaslayer aws connect`)
19
25
  * @typedef {{ status: string, version: string|null, paramKeys: string[], params: Record<string, string>, outputs: Array<{ OutputKey: string, OutputValue: string }>, lastUpdated: string|null }} InstalledStack
20
- * @typedef {{ action: string, logicalId: string, type: string, replacement: string, scope: string[] }} Change
26
+ * @typedef {import('../foundation-change-set').Change} Change
21
27
  */
22
28
 
23
- /** Stack states a change set can be created and executed from. */
24
- const STABLE_STATUSES = ['CREATE_COMPLETE', 'UPDATE_COMPLETE', 'UPDATE_ROLLBACK_COMPLETE', 'IMPORT_COMPLETE', 'IMPORT_ROLLBACK_COMPLETE']
25
-
26
29
  /** Resource types whose removal would cut the control plane's access or the account's deploy spine. */
27
30
  const PROTECTED_REMOVE_TYPES = ['AWS::IAM::Role', 'AWS::IAM::ManagedPolicy', 'AWS::IAM::Policy', 'AWS::S3::Bucket']
28
31
 
29
- /** CloudFormation's change-set status reasons when the template + params match what is installed. */
30
- const NO_CHANGES = /didn't contain changes|No updates are to be performed/i
31
-
32
- /**
33
- * The bundled template's version (Mappings.Meta.<name>.Version) and its parameters with their defaults.
34
- * @param {string} text template YAML
35
- * @returns {{ version: string|null, parameters: { name: string, hasDefault: boolean, default?: string }[] }}
36
- */
37
- function templateInfo(text) {
38
- const lines = stripComments(text).split('\n')
39
- const versionMatch = /^ {2}Meta:\s*\n {4}\w+:\s*\n {6}Version:\s*'?([^'\s]+)'?/m.exec(lines.join('\n'))
40
- const parameters = []
41
- const start = lines.indexOf('Parameters:')
42
- if (start !== -1) {
43
- for (let i = start + 1; i < lines.length && !/^\S/.test(lines[i]); i++) {
44
- const name = /^ {2}(\w+):\s*$/.exec(lines[i])
45
- if (name) { parameters.push({ name: name[1], hasDefault: false }); continue }
46
- const def = /^ {4}Default:\s*(.*)$/.exec(lines[i])
47
- if (def && parameters.length) {
48
- const current = parameters[parameters.length - 1]
49
- current.hasDefault = true
50
- current.default = def[1].trim().replace(/^'(.*)'$/, '$1').replace(/^"(.*)"$/, '$1')
51
- }
52
- }
53
- }
54
- return { version: versionMatch ? versionMatch[1] : null, parameters }
55
- }
56
-
57
32
  /**
58
33
  * Change-set parameters for an upgrade: every parameter the stack already has keeps its previous value (no value is
59
34
  * ever passed), a parameter new in the template takes its default, and one the template dropped is left out.
@@ -102,58 +77,60 @@ function conditionalChanges(changes) {
102
77
  }
103
78
 
104
79
  /**
105
- * The foundation stacks a command acts on: the account-global IAM stack and the per-region stack.
80
+ * The account-global foundation stack, read and upgraded in its home region.
81
+ * @param {object} flags @param {string} homeRegion
82
+ * @returns {Target}
83
+ */
84
+ function accountTarget(flags, homeRegion) {
85
+ return { kind: 'account', stackName: flags['stack-name'] || 'saaslayer-foundation', template: FOUNDATION_TEMPLATE, outputKey: 'FoundationVersion', capabilities: ['CAPABILITY_NAMED_IAM'], region: homeRegion }
86
+ }
87
+
88
+ /**
89
+ * The foundation stacks a command acts on: the account-global IAM stack (in its home region, or the requested region when
90
+ * the account has no foundation yet) and the per-region stack of the requested region.
106
91
  * @param {object} flags
92
+ * @param {(region: string) => import('../foundation-change-set').AwsJson} awsIn
107
93
  * @returns {{ region: string, targets: Target[] }}
108
94
  */
109
- function resolveTargets(flags) {
95
+ function resolveTargets(flags, awsIn) {
110
96
  const region = flags.region || process.env.AWS_REGION || 'us-east-1'
111
97
  const only = flags.only
112
98
  if (only !== undefined && only !== 'account' && only !== 'region') throw new Error('--only expects account or region')
113
99
  /** @type {Target[]} */
114
- const all = [
115
- { kind: 'account', stackName: flags['stack-name'] || 'saaslayer-foundation', template: FOUNDATION_TEMPLATE, outputKey: 'FoundationVersion', capabilities: ['CAPABILITY_NAMED_IAM'] },
116
- { kind: 'region', stackName: foundationRegionStackName(region), template: FOUNDATION_REGION_TEMPLATE, outputKey: 'FoundationRegionVersion', capabilities: [] },
117
- ]
118
- return { region, targets: only ? all.filter((t) => t.kind === only) : all }
100
+ const targets = []
101
+ if (only !== 'region') {
102
+ const home = resolveFoundationHome({ awsIn, requestedRegion: region, stackName: flags['stack-name'] || 'saaslayer-foundation' })
103
+ targets.push(accountTarget(flags, home.state === 'home' ? home.homeRegion : region))
104
+ }
105
+ if (only !== 'account') {
106
+ targets.push({ kind: 'region', stackName: foundationRegionStackName(region), template: FOUNDATION_REGION_TEMPLATE, outputKey: 'FoundationRegionVersion', capabilities: [], region })
107
+ }
108
+ return { region, targets }
119
109
  }
120
110
 
121
111
  /**
122
- * Runs `aws <args>` with the caller's region/profile and parses the JSON reply.
123
- * @param {typeof defaultExec} exec
124
- * @param {object} flags
125
- * @param {string} region
112
+ * The account template this upgrade submits, with its trust rendered: from the installed TrustEntries, or from the
113
+ * conversion's when the stack still trusts a single ExternalId. Refuses (before any write) a stack it cannot operate on.
114
+ * @param {Target} target @param {InstalledStack} installed @param {string} label @param {Conversion} [conversion]
115
+ * @returns {string} the deployable template file
126
116
  */
127
- function awsRunner(exec, flags, region) {
128
- return (args) => {
129
- const full = [...args, '--region', region, ...(flags.profile ? ['--profile', flags.profile] : []), '--output', 'json']
130
- let out
131
- try {
132
- out = exec('aws', full)
133
- } catch (err) {
134
- const detail = String(err.stderr || err.message || '').trim()
135
- const e = new Error(`aws ${args.slice(0, 2).join(' ')} failed: ${detail}`)
136
- e.stderr = detail
137
- throw e
138
- }
139
- return out && String(out).trim() ? JSON.parse(out) : {}
117
+ function renderedAccountTemplate(target, installed, label, conversion) {
118
+ const trustEntries = installed.paramKeys.includes('TrustEntries') ? installed.params.TrustEntries : conversion && conversion.TrustEntries
119
+ if (!trustEntries) {
120
+ throw new Error(`${label} runs ${installed.version || 'an unknown version'}, which trusts a single ExternalId; it converts to per-control-plane trust entries ` +
121
+ `through \`saaslayer aws connect --aws-account <id> --region ${target.region}\` (the control plane supplies its trust entry). Nothing was changed.`)
140
122
  }
123
+ return writeDeployableTemplate(target.template, renderFoundationTemplate(stripComments(fs.readFileSync(target.template, 'utf8')), trustEntries))
141
124
  }
142
125
 
143
126
  /**
144
- * @param {ReturnType<typeof awsRunner>} aws
127
+ * @param {import('../foundation-change-set').AwsJson} aws
145
128
  * @param {Target} target
146
129
  * @returns {InstalledStack|null}
147
130
  */
148
131
  function readStack(aws, target) {
149
- let res
150
- try {
151
- res = aws(['cloudformation', 'describe-stacks', '--stack-name', target.stackName])
152
- } catch (err) {
153
- if (/does not exist/.test(err.stderr || err.message)) return null
154
- throw err
155
- }
156
- const s = res.Stacks[0]
132
+ const s = describeStack(aws, target.stackName)
133
+ if (!s) return null
157
134
  const output = (s.Outputs || []).find((o) => o.OutputKey === target.outputKey)
158
135
  return {
159
136
  status: s.StackStatus,
@@ -188,7 +165,7 @@ function versionState(installed, bundledVersion) {
188
165
  */
189
166
  /**
190
167
  * The region stack's email sender domain and its SES verification, when one is set.
191
- * @param {ReturnType<typeof awsRunner>} aws @param {InstalledStack} installed
168
+ * @param {import('../foundation-change-set').AwsJson} aws @param {InstalledStack} installed
192
169
  * @returns {{ emailSender?: { domain: string, verified: boolean, dkimStatus: string|null, records: string[] } }}
193
170
  */
194
171
  function emailSenderStatus(aws, installed) {
@@ -208,13 +185,15 @@ function emailSenderStatus(aws, installed) {
208
185
  }
209
186
 
210
187
  async function foundationStatus(flags, { exec = defaultExec, log = console.log } = {}) {
211
- const { region, targets } = resolveTargets(flags)
212
- const aws = awsRunner(exec, flags, region)
188
+ const awsIn = (r) => awsRunner(exec, { region: r, profile: flags.profile })
189
+ const { targets } = resolveTargets(flags, awsIn)
213
190
  const rows = targets.map((t) => {
191
+ const aws = awsIn(t.region)
214
192
  const installed = readStack(aws, t)
215
193
  const bundledVersion = bundled(t).version
216
194
  return {
217
195
  stackName: t.stackName,
196
+ region: t.region,
218
197
  stackStatus: installed ? installed.status : null,
219
198
  installedVersion: installed ? installed.version || 'unknown' : null,
220
199
  bundledVersion,
@@ -223,7 +202,7 @@ async function foundationStatus(flags, { exec = defaultExec, log = console.log }
223
202
  }
224
203
  })
225
204
  for (const r of rows) {
226
- log(`${r.stackName} (${region})`)
205
+ log(`${r.stackName} (${r.region})`)
227
206
  log(` status ${r.stackStatus || '-'}`)
228
207
  log(` installed ${r.installedVersion || '-'}`)
229
208
  log(` bundled ${r.bundledVersion}`)
@@ -238,33 +217,9 @@ async function foundationStatus(flags, { exec = defaultExec, log = console.log }
238
217
  return rows
239
218
  }
240
219
 
241
- /**
242
- * Waits for a change set to finish creating and returns its status + every resource change.
243
- * @param {ReturnType<typeof awsRunner>} aws
244
- * @param {Target} target
245
- * @param {string} changeSetName
246
- * @param {Required<Pick<Deps, 'sleep'|'pollMs'|'maxPolls'>>} wait
247
- */
248
- async function waitForChangeSet(aws, target, changeSetName, { sleep, pollMs, maxPolls }) {
249
- const base = ['cloudformation', 'describe-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName]
250
- for (let i = 0; i < maxPolls; i++) {
251
- const first = aws(base)
252
- if (first.Status === 'CREATE_COMPLETE' || first.Status === 'FAILED') {
253
- // The aws CLI auto-paginates describe-change-set, so Changes holds every page.
254
- /** @type {Change[]} */
255
- const changes = (first.Changes || []).filter((c) => c.Type === 'Resource').map(({ ResourceChange: rc }) => ({
256
- action: rc.Action, logicalId: rc.LogicalResourceId, type: rc.ResourceType, replacement: rc.Replacement || '', scope: rc.Scope || [],
257
- }))
258
- return { status: first.Status, reason: first.StatusReason || '', changes }
259
- }
260
- await sleep(pollMs)
261
- }
262
- throw new Error(`change set ${changeSetName} on ${target.stackName} did not finish creating`)
263
- }
264
-
265
220
  /**
266
221
  * Waits for the stack update to settle; returns the final stack status.
267
- * @param {ReturnType<typeof awsRunner>} aws
222
+ * @param {import('../foundation-change-set').AwsJson} aws
268
223
  * @param {Target} target
269
224
  * @param {Required<Pick<Deps, 'sleep'|'pollMs'|'maxPolls'>>} wait
270
225
  */
@@ -279,7 +234,7 @@ async function waitForUpdate(aws, target, { sleep, pollMs, maxPolls }) {
279
234
 
280
235
  /**
281
236
  * Failed resource events of the latest update (newest first, back to the stack's own UPDATE_IN_PROGRESS event).
282
- * @param {ReturnType<typeof awsRunner>} aws
237
+ * @param {import('../foundation-change-set').AwsJson} aws
283
238
  * @param {Target} target
284
239
  */
285
240
  function failedEvents(aws, target) {
@@ -292,16 +247,9 @@ function failedEvents(aws, target) {
292
247
  return failures
293
248
  }
294
249
 
295
- /** @param {Change[]} changes */
296
- function formatChanges(changes) {
297
- const w = (key) => Math.max(...changes.map((c) => String(c[key]).length))
298
- const [wa, wl, wt] = [w('action'), w('logicalId'), w('type')]
299
- return changes.map((c) => ` ${c.action.padEnd(wa)} ${c.logicalId.padEnd(wl)} ${c.type.padEnd(wt)} replacement=${c.replacement || '-'} scope=${c.scope.join(',') || '-'}`)
300
- }
301
-
302
250
  /**
303
251
  * After setting a sender domain: the DKIM records the stack now outputs, for the domain's DNS.
304
- * @param {ReturnType<typeof awsRunner>} aws @param {Target} target @param {string|undefined} domain @param {Function} log
252
+ * @param {import('../foundation-change-set').AwsJson} aws @param {Target} target @param {string|undefined} domain @param {Function} log
305
253
  */
306
254
  function logSenderRecords(aws, target, domain, log) {
307
255
  if (!domain) return
@@ -313,12 +261,13 @@ function logSenderRecords(aws, target, domain, log) {
313
261
  /**
314
262
  * Upgrades one foundation stack. Returns { stackName, result, ... } where result is upgraded | up to date | dry-run |
315
263
  * aborted | not installed. Throws on any refusal or failure.
264
+ * A conversion (account stack only) sets TrustEntries and ConnectionAuthorizerArns explicitly and drops ExternalId.
316
265
  * @param {Target} target
317
266
  * @param {object} flags
318
- * @param {{ aws: ReturnType<typeof awsRunner>, region: string, required: boolean, log: Function, confirm: Function, wait: object }} ctx
267
+ * @param {{ aws: import('../foundation-change-set').AwsJson, required: boolean, log: Function, confirm: Function, wait: object, conversion?: Conversion }} ctx
319
268
  */
320
- async function upgradeStack(target, flags, { aws, region, required, log, confirm, wait }) {
321
- const label = `${target.stackName} (${region})`
269
+ async function upgradeStack(target, flags, { aws, required, log, confirm, wait, conversion }) {
270
+ const label = `${target.stackName} (${target.region})`
322
271
  const installed = readStack(aws, target)
323
272
  if (!installed) {
324
273
  if (required) throw new Error(`${label} is not installed — onboard the account first (saaslayer aws connect / saaslayer init)`)
@@ -333,7 +282,10 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
333
282
  if (installed.version && compareVersions(installed.version, info.version) > 0) {
334
283
  throw new Error(`${label} runs ${installed.version}, newer than this CLI's bundled ${info.version}; update the saaslayer CLI instead of downgrading`)
335
284
  }
336
- const plan = upgradeParameters(info.parameters, installed.paramKeys)
285
+ const templateFile = target.kind === 'account' ? renderedAccountTemplate(target, installed, label, conversion) : writeDeployableTemplate(target.template)
286
+ const explicit = target.kind === 'account' && !installed.paramKeys.includes('TrustEntries') ? conversion : {}
287
+ const plan = upgradeParameters(info.parameters.filter((p) => !(p.name in explicit)), installed.paramKeys)
288
+ for (const [key, value] of Object.entries(explicit)) plan.parameters.push({ ParameterKey: key, ParameterValue: value })
337
289
  // --email-sender-domain sets the region stack's sender domain; every other parameter keeps its value.
338
290
  const senderDomain = target.kind === 'region' ? emailSenderDomainFlag(flags) : undefined
339
291
  if (senderDomain !== undefined) {
@@ -346,18 +298,19 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
346
298
 
347
299
  log(`\n${label}: ${from} -> ${info.version}`)
348
300
  log(` parameters kept (previous values): ${plan.parameters.filter((p) => p.UsePreviousValue).map((p) => p.ParameterKey).join(', ') || '-'}`)
301
+ if (Object.keys(explicit).length) log(' trust: converting the single ExternalId to per-control-plane TrustEntries (ConnectionAuthorizerArns: the deploying principal)')
349
302
  if (senderDomain !== undefined) log(` email sender domain: ${senderDomain || '(removed)'}`)
350
303
  if (plan.added.length) log(` new parameters (template default): ${plan.added.map((p) => `${p.name}='${p.default}'`).join(', ')}`)
351
304
  if (plan.removed.length) log(` parameters no longer in the template: ${plan.removed.join(', ')}`)
352
305
 
353
306
  aws([
354
307
  'cloudformation', 'create-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName,
355
- '--change-set-type', 'UPDATE', '--template-body', `file://${writeDeployableTemplate(target.template)}`,
308
+ '--change-set-type', 'UPDATE', '--template-body', `file://${templateFile}`,
356
309
  '--parameters', JSON.stringify(plan.parameters),
357
310
  ...(target.capabilities.length ? ['--capabilities', ...target.capabilities] : []),
358
311
  '--description', `saaslayer foundation upgrade ${from} -> ${info.version}`,
359
312
  ])
360
- const cs = await waitForChangeSet(aws, target, changeSetName, wait)
313
+ const cs = await waitForChangeSet(aws, target.stackName, changeSetName, wait)
361
314
  if (cs.status === 'FAILED') {
362
315
  del()
363
316
  if (NO_CHANGES.test(cs.reason)) {
@@ -371,6 +324,11 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
371
324
  log(` changes (${cs.changes.length}):`)
372
325
  for (const line of formatChanges(cs.changes)) log(line)
373
326
  for (const c of conditionalChanges(cs.changes)) log(` ! ${c.logicalId} may be replaced (Replacement=Conditional)`)
327
+ const smsRefusal = smsNumberRefusal(label, cs.changes)
328
+ if (smsRefusal) {
329
+ del()
330
+ throw smsRefusal
331
+ }
374
332
  const blocking = blockingChanges(cs.changes)
375
333
  if (blocking.length) {
376
334
  for (const c of blocking) log(` !! ${c.logicalId} (${c.type}): ${c.action === 'Remove' ? 'removed' : 'replaced'}`)
@@ -417,7 +375,7 @@ async function refreshFoundationRecord({ accountId, region }, flags) {
417
375
  * After a finished upgrade (or one with nothing to change), have the control plane re-read the account so the console
418
376
  * and deploys see the new version. Best effort: a failure is reported with how the record catches up, never thrown.
419
377
  * @param {object} flags
420
- * @param {{ aws: ReturnType<typeof awsRunner>, region: string, log: Function, refresh: Refresh }} ctx
378
+ * @param {{ aws: import('../foundation-change-set').AwsJson, region: string, log: Function, refresh: Refresh }} ctx
421
379
  */
422
380
  async function reportToControlPlane(flags, { aws, region, log, refresh }) {
423
381
  try {
@@ -438,19 +396,19 @@ async function reportToControlPlane(flags, { aws, region, log, refresh }) {
438
396
  */
439
397
  async function foundationUpgrade(flags, { exec = defaultExec, log = console.log, confirm = promptConfirm, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), pollMs = 5000, maxPolls = 720, refresh = refreshFoundationRecord } = {}) {
440
398
  emailSenderDomainFlag(flags) // refuse a malformed --email-sender-domain before touching AWS
441
- const { region, targets } = resolveTargets(flags)
442
- const aws = awsRunner(exec, flags, region)
399
+ const awsIn = (r) => awsRunner(exec, { region: r, profile: flags.profile })
400
+ const { region, targets } = resolveTargets(flags, awsIn)
443
401
  const results = []
444
402
  for (const t of targets) {
445
403
  // The account stack must exist; the region stack is optional unless it was asked for by --only.
446
404
  const required = t.kind === 'account' || flags.only === 'region'
447
- results.push(await upgradeStack(t, flags, { aws, region, required, log, confirm, wait: { sleep, pollMs, maxPolls } }))
405
+ results.push(await upgradeStack(t, flags, { aws: awsIn(t.region), required, log, confirm, wait: { sleep, pollMs, maxPolls } }))
448
406
  }
449
- if (results.some((r) => r.result === 'upgraded' || r.result === 'up to date')) await reportToControlPlane(flags, { aws, region, log, refresh })
407
+ if (results.some((r) => r.result === 'upgraded' || r.result === 'up to date')) await reportToControlPlane(flags, { aws: awsIn(region), region, log, refresh })
450
408
  return results
451
409
  }
452
410
 
453
411
  module.exports = {
454
412
  foundationStatus, foundationUpgrade, refreshFoundationRecord, templateInfo, upgradeParameters, compareVersions, blockingChanges, conditionalChanges,
455
- STABLE_STATUSES,
413
+ accountTarget, readStack, upgradeStack, STABLE_STATUSES,
456
414
  }
@@ -0,0 +1,271 @@
1
+ // `saaslayer hooks status|set|unset|grants set|rotate-secret|test|claims-cache invalidate`: read, change or test one user-service
2
+ // instance's lifecycle hooks through the control plane's instance hooks proxy (/api/deployments/{id}/services/{ref}/hooks). The
3
+ // new signing secret is printed once.
4
+ 'use strict'
5
+ const { apiCall } = require('../api-client')
6
+ const { resolveDeployment } = require('../deployments')
7
+ const { PROTECTED_ENVS } = require('../settings')
8
+ const { chooseInstance, refOf } = require('../user-service-instance')
9
+
10
+ const USAGE = 'usage: saaslayer hooks <status|set|unset|grants set|rotate-secret|test|claims-cache invalidate|logs> [--env E] [--service REF] … (see saaslayer --help)'
11
+ const CLAIMS_CACHE_USAGE = 'usage: saaslayer hooks claims-cache invalidate [--env E] [--service REF] [--json]'
12
+ const GRANTS_USAGE = 'usage: saaslayer hooks grants set --org <orgId> --role <roleId> [--org <orgId> --role <roleId> …] [--env E] [--service REF]'
13
+ // The hook points user-service runs, in the order a sign-up meets them.
14
+ const HOOK_POINTS = ['beforeSignUp', 'afterUserCreated', 'beforeTokenIssue', 'afterSignIn', 'message']
15
+
16
+ /** @param {unknown} value a repeatable flag @returns {string[]} */
17
+ const list = (value) => (value === undefined ? [] : (Array.isArray(value) ? value : [value]).map(String))
18
+
19
+ /**
20
+ * One point's target and delivery rules as one line.
21
+ * @param {Record<string, unknown>|undefined} entry
22
+ */
23
+ function describePoint(entry) {
24
+ if (!entry) return '—'
25
+ const parts = [entry.lambdaArn ? `lambda ${entry.lambdaArn}` : `url ${entry.url}`]
26
+ if (entry.onFailure) parts.push(`on failure ${entry.onFailure}`)
27
+ if (entry.timeoutMs !== undefined) parts.push(`timeout ${entry.timeoutMs} ms`)
28
+ if (entry.claimsTtlSeconds !== undefined) parts.push(`claims cached ${entry.claimsTtlSeconds} s`)
29
+ return parts.join(', ')
30
+ }
31
+
32
+ /** @param {Array<{ org: string, role: string }>} grants */
33
+ const describeGrants = (grants) => (grants.length ? grants.map((g) => `${g.org} → ${g.role}`).join(', ') : '—')
34
+
35
+ /** @param {Record<string, any>} secret the signing-secret status */
36
+ function describeSecret(secret) {
37
+ if (!secret || !secret.configured) return 'none yet (saaslayer hooks rotate-secret creates one)'
38
+ const previous = secret.previous ? `; key ${secret.previous.id} keeps signing until ${secret.previous.expiresAt}` : ''
39
+ return `key ${secret.current.id} since ${secret.current.createdAt}${previous}`
40
+ }
41
+
42
+ /**
43
+ * The deployment and chosen instance, and the proxy path for its hooks.
44
+ * @param {Record<string, any>} flags
45
+ */
46
+ async function resolveHooks(flags) {
47
+ const deployment = await resolveDeployment(flags)
48
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}`, undefined, flags)
49
+ const service = refOf(/** @type {any} */ (chooseInstance({ deploymentId: deployment.deploymentId, ...doc.data.attributes }, flags)))
50
+ const path = `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/services/${encodeURIComponent(service)}/hooks`
51
+ return { deployment, service, path }
52
+ }
53
+
54
+ /**
55
+ * A refusal as `<code>: <reason>` plus the next step it needs.
56
+ * @param {any} err @param {{ deployment: { env: string }, service: string }} scope
57
+ */
58
+ function refusalOf(err, { deployment, service }) {
59
+ const first = err && err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
60
+ if (!first) return err
61
+ let message = `${first.code || err.status}: ${first.detail || first.title || 'request refused'}`
62
+ if (first.code === 'CONFLICT' && err.status === 409 && /reload and retry/.test(message)) message += ' (saaslayer hooks status shows the current one)'
63
+ if (/HookLambdaArns/.test(String(first.detail))) {
64
+ const reason = PROTECTED_ENVS.has(deployment.env) ? ' --reason <text>' : ''
65
+ message += `\nlist the function first: saaslayer settings set --env ${deployment.env} --set ${service}.HookLambdaArns=<every allowed ARN, comma-separated>${reason}`
66
+ }
67
+ return Object.assign(new Error(message), { status: err.status, body: err.body })
68
+ }
69
+
70
+ /**
71
+ * Send one hooks request; a refusal becomes its reason.
72
+ * @param {'PUT'|'DELETE'|'POST'} method @param {string} path @param {unknown} body
73
+ * @param {Record<string, any>} flags @param {Parameters<typeof refusalOf>[1]} scope
74
+ */
75
+ async function send(method, path, body, flags, scope) {
76
+ try {
77
+ return await apiCall(method, path, body, flags)
78
+ } catch (err) {
79
+ throw refusalOf(err, scope)
80
+ }
81
+ }
82
+
83
+ /** @param {string|undefined} point @param {string} sub */
84
+ function checkPoint(point, sub) {
85
+ if (!point) throw new Error(`hooks ${sub} needs a hook point: ${HOOK_POINTS.join(', ')}`)
86
+ if (!HOOK_POINTS.includes(point)) throw new Error(`${point} is not a hook point: ${HOOK_POINTS.join(', ')}`)
87
+ }
88
+
89
+ /**
90
+ * The point's whole configuration from the flags; refusals happen before anything is sent.
91
+ * @param {string} point @param {Record<string, any>} flags
92
+ */
93
+ function pointTarget(point, flags) {
94
+ const url = typeof flags.url === 'string' ? flags.url : undefined
95
+ const lambdaArn = typeof flags.lambda === 'string' ? flags.lambda : undefined
96
+ if (Boolean(url) === Boolean(lambdaArn)) throw new Error('hooks set needs exactly one target: --url <https url> or --lambda <function arn>')
97
+ /** @type {Record<string, unknown>} */
98
+ const target = url ? { url } : { lambdaArn }
99
+ if (flags['on-failure'] !== undefined) {
100
+ if (flags['on-failure'] !== 'allow' && flags['on-failure'] !== 'deny') throw new Error('--on-failure must be allow or deny')
101
+ target.onFailure = flags['on-failure']
102
+ }
103
+ if (flags['timeout-ms'] !== undefined) {
104
+ if (!/^\d+$/.test(String(flags['timeout-ms']))) throw new Error('--timeout-ms must be a whole number of milliseconds')
105
+ target.timeoutMs = Number(flags['timeout-ms'])
106
+ }
107
+ // How long beforeTokenIssue's app: claims are reused before the hook is asked again (0 = every issuance).
108
+ if (flags['claims-ttl-seconds'] !== undefined) {
109
+ if (point !== 'beforeTokenIssue') throw new Error('--claims-ttl-seconds applies only to beforeTokenIssue')
110
+ if (!/^\d+$/.test(String(flags['claims-ttl-seconds']))) throw new Error('--claims-ttl-seconds must be a whole number of seconds')
111
+ target.claimsTtlSeconds = Number(flags['claims-ttl-seconds'])
112
+ }
113
+ return target
114
+ }
115
+
116
+ /** @param {Record<string, any>} flags @returns {Array<{ org: string, role: string }>} */
117
+ function grantPairs(flags) {
118
+ const orgs = list(flags.org)
119
+ const roles = list(flags.role)
120
+ if (orgs.length === 0 && roles.length === 0) throw new Error('hooks grants set needs one --org <orgId> --role <roleId> pair or more')
121
+ if (orgs.length !== roles.length) throw new Error(`hooks grants set pairs each --org with one --role: got ${orgs.length} --org and ${roles.length} --role`)
122
+ return orgs.map((org, i) => ({ org, role: roles[i] }))
123
+ }
124
+
125
+ /** `hooks status`. @param {Record<string, any>} flags */
126
+ async function showStatus(flags) {
127
+ const { deployment, service, path } = await resolveHooks(flags)
128
+ const { version, hooks, signingSecret } = (await apiCall('GET', path, undefined, flags)).data.attributes
129
+ const status = { deploymentId: deployment.deploymentId, service, version, hooks, signingSecret }
130
+ if (flags.json) {
131
+ console.log(JSON.stringify(status, null, 2))
132
+ return status
133
+ }
134
+ const lines = [`hooks of ${service} on deployment ${deployment.deploymentId} (config version ${version})`]
135
+ for (const point of HOOK_POINTS) lines.push(` ${point}: ${describePoint(hooks[point])}`)
136
+ lines.push(` grants: ${describeGrants(hooks.grants || [])}`, ` signing secret: ${describeSecret(signingSecret)}`)
137
+ console.log(lines.join('\n'))
138
+ return status
139
+ }
140
+
141
+ /**
142
+ * `hooks set|unset <point>` and `hooks grants set`: one write, then what the instance stored.
143
+ * @param {string} sub @param {string[]} args @param {Record<string, any>} flags
144
+ */
145
+ async function changeHooks(sub, args, flags) {
146
+ if (sub === 'grants' && args[0] !== 'set') throw new Error(GRANTS_USAGE)
147
+ const point = sub === 'grants' ? undefined : args[0]
148
+ if (sub !== 'grants') checkPoint(point, sub)
149
+ const target = sub === 'set' ? pointTarget(/** @type {string} */ (point), flags) : undefined
150
+ const grants = sub === 'grants' ? grantPairs(flags) : undefined
151
+ const scope = await resolveHooks(flags)
152
+ const where = `${scope.service} of ${scope.deployment.deploymentId}`
153
+ let doc
154
+ if (sub === 'grants') doc = await send('PUT', `${scope.path}/grants`, { data: { type: 'hooks', attributes: { grants } } }, flags, scope)
155
+ else if (sub === 'set') doc = await send('PUT', `${scope.path}/${point}`, { data: { type: 'hooks', attributes: target } }, flags, scope)
156
+ else doc = await send('DELETE', `${scope.path}/${point}`, undefined, flags, scope)
157
+ const { version, hooks } = doc.data.attributes
158
+ if (sub === 'grants') console.log(`grants set on ${where} (config version ${version}): ${describeGrants(hooks.grants || [])}`)
159
+ else if (sub === 'set') console.log(`${point} set on ${where} (config version ${version}): ${describePoint(hooks[point])}`)
160
+ else console.log(`${point} unset on ${where} (config version ${version})`)
161
+ return doc.data.attributes
162
+ }
163
+
164
+ /** `hooks rotate-secret`: the new secret goes to stdout once and nowhere else. @param {Record<string, any>} flags */
165
+ async function rotateSecret(flags) {
166
+ const scope = await resolveHooks(flags)
167
+ const doc = await send('POST', `${scope.path}/signing-secrets`, undefined, flags, scope)
168
+ const rotated = { id: doc.data.id, ...doc.data.attributes }
169
+ if (flags.json) {
170
+ console.log(JSON.stringify(rotated, null, 2))
171
+ return { id: rotated.id }
172
+ }
173
+ const lines = [`signing secret key ${rotated.id} for ${scope.service} of ${scope.deployment.deploymentId} (shown once; store it in your receiver now):`, rotated.secret]
174
+ if (rotated.previous) lines.push(`key ${rotated.previous.id} keeps signing until ${rotated.previous.expiresAt}: verify with both until then`)
175
+ console.log(lines.join('\n'))
176
+ return { id: rotated.id }
177
+ }
178
+
179
+ /**
180
+ * `hooks test <point>`: the instance sends the point a signed synthetic event and reports what came back. Nothing is applied.
181
+ * @param {string|undefined} point @param {Record<string, any>} flags
182
+ */
183
+ async function testPoint(point, flags) {
184
+ checkPoint(point, 'test')
185
+ const scope = await resolveHooks(flags)
186
+ const result = (await send('POST', `${scope.path}/${point}/test`, undefined, flags, scope)).data.attributes
187
+ if (flags.json) {
188
+ console.log(JSON.stringify(result, null, 2))
189
+ return result
190
+ }
191
+ const where = `${point} test event on ${scope.service} of ${scope.deployment.deploymentId}`
192
+ if (result.ok) {
193
+ const proposed = Object.keys(result.actions || {}).length ? JSON.stringify(result.actions, null, 2) : 'none'
194
+ console.log([`${where}: answered in ${result.durationMs} ms (${result.kind})`, `proposed actions (test only, nothing applied): ${proposed}`].join('\n'))
195
+ } else {
196
+ const status = result.status ? ` ${result.status}` : ''
197
+ const policy = result.onFailure ? `; a real call would ${result.onFailure}` : ''
198
+ console.log(`${where} failed after ${result.durationMs} ms (${result.kind}): ${result.reason}${status}${policy}`)
199
+ }
200
+ return result
201
+ }
202
+
203
+ /**
204
+ * `hooks claims-cache invalidate`: every cached beforeTokenIssue claim is dropped, so the next sign-in asks the hook again.
205
+ * @param {string[]} args @param {Record<string, any>} flags
206
+ */
207
+ async function invalidateClaims(args, flags) {
208
+ if (args[0] !== 'invalidate') throw new Error(CLAIMS_CACHE_USAGE)
209
+ const scope = await resolveHooks(flags)
210
+ const { version } = (await send('POST', `${scope.path}/claims-cache/invalidate`, undefined, flags, scope)).data.attributes
211
+ const result = { deploymentId: scope.deployment.deploymentId, service: scope.service, version }
212
+ if (flags.json) console.log(JSON.stringify(result, null, 2))
213
+ else console.log(`claims cache invalidated on ${scope.service} of ${scope.deployment.deploymentId} (config version ${version}): the next sign-in asks beforeTokenIssue again`)
214
+ return result
215
+ }
216
+
217
+ /**
218
+ * One delivery-log entry as a line: when, point, event and attempt, then what is known about the call.
219
+ * @param {Record<string, any>} entry
220
+ */
221
+ function describeDelivery(entry) {
222
+ const parts = [entry.at, entry.point, `${entry.eventId} #${entry.attempt}`]
223
+ if (entry.kind) parts.push(entry.kind)
224
+ parts.push(entry.outcome)
225
+ if (entry.status !== undefined) parts.push(String(entry.status))
226
+ if (entry.durationMs !== undefined) parts.push(`${entry.durationMs} ms`)
227
+ if (entry.reason) parts.push(`reason: ${entry.reason}`)
228
+ if (entry.actions && entry.actions.length) parts.push(`actions: ${entry.actions.join(', ')}`)
229
+ return ` ${parts.join(' ')}`
230
+ }
231
+
232
+ /**
233
+ * `hooks logs [--point P]`: the newest page of the instance's delivery log (metadata only, 14 days).
234
+ * @param {Record<string, any>} flags
235
+ */
236
+ async function showLogs(flags) {
237
+ const point = flags.point === undefined ? undefined : String(flags.point)
238
+ if (point !== undefined) checkPoint(point, 'logs')
239
+ const scope = await resolveHooks(flags)
240
+ const doc = await apiCall('GET', `${scope.path}/deliveries${point ? `?point=${encodeURIComponent(point)}` : ''}`, undefined, flags)
241
+ const entries = doc.data.map((/** @type {{ attributes: Record<string, any> }} */ item) => item.attributes)
242
+ if (flags.json) {
243
+ console.log(JSON.stringify(entries, null, 2))
244
+ return entries
245
+ }
246
+ if (entries.length === 0) {
247
+ console.log(`no hook calls recorded${point ? ` for ${point}` : ''} in the last 14 days on ${scope.service} of ${scope.deployment.deploymentId}`)
248
+ return entries
249
+ }
250
+ const lines = [`delivery log of ${scope.service} on deployment ${scope.deployment.deploymentId} (newest first)`, ...entries.map(describeDelivery)]
251
+ if (doc.meta && doc.meta.hasMore) lines.push('older calls are not shown: the console\'s Hooks page pages through them')
252
+ console.log(lines.join('\n'))
253
+ return entries
254
+ }
255
+
256
+ /**
257
+ * @param {string|undefined} sub status | set | unset | grants | rotate-secret | test | logs | claims-cache
258
+ * @param {string[]} args the positionals after the subcommand (the point, or `set` for grants)
259
+ * @param {Record<string, any>} flags
260
+ */
261
+ async function hooksCommand(sub, args, flags) {
262
+ if (sub === 'status') return showStatus(flags)
263
+ if (sub === 'set' || sub === 'unset' || sub === 'grants') return changeHooks(sub, args, flags)
264
+ if (sub === 'rotate-secret') return rotateSecret(flags)
265
+ if (sub === 'test') return testPoint(args[0], flags)
266
+ if (sub === 'claims-cache') return invalidateClaims(args, flags)
267
+ if (sub === 'logs') return showLogs(flags)
268
+ throw new Error(USAGE)
269
+ }
270
+
271
+ module.exports = { hooksCommand }
@@ -4,7 +4,7 @@
4
4
  const crypto = require('crypto')
5
5
  const { apiCall } = require('../api-client')
6
6
 
7
- const KINDS = ['email-authoring', 'config']
7
+ const KINDS = ['email-authoring', 'config', 'hooks']
8
8
 
9
9
  /** @param {object} flags @param {string} name */
10
10
  const required = (flags, name) => {