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,57 +1,119 @@
1
- // `saaslayer aws connect` — connect the caller's own AWS account (cloud-prem) to an org. Mints a
2
- // per-host-account trust secret via the control-plane API, deploys the SaaSLayer foundation stack into
3
- // that account using the operator's AMBIENT AWS creds, then verifies the cross-account trust.
1
+ // `saaslayer aws connect` — connect the caller's own AWS account (cloud-prem) to an org with an AWS-verified connection
2
+ // proof (ADR 0005 §4). Registers the account with the control plane, makes sure the account foundation (one stack in its home
3
+ // region) carries this control plane's trust entry, deploys the requested region's foundation stack with the caller's AMBIENT
4
+ // AWS creds, verifies the cross-account trust and activates the org connection. `saaslayer aws authorizers add|remove`
5
+ // changes who may authorize those connections; `saaslayer aws rotate-trust` rotates the account's trust identifier (D7).
4
6
  'use strict'
5
7
  const fs = require('fs')
6
- const os = require('os')
7
8
  const path = require('path')
8
9
  const crypto = require('crypto')
9
10
  const { execFileSync } = require('child_process')
10
11
  const context = require('../context-store')
11
- const { apiCall } = require('../api-client')
12
-
13
- // CloudFormation's inline template limit is 51,200 bytes. The foundation template exceeds it with its
14
- // comments (~40% of the file), so `aws cloudformation deploy --template-file` would demand --s3-bucket.
15
- // Strip full-line comments + blank lines into a temp file for the deploy — the SOURCE keeps every comment.
16
- // Safe: the foundation template has no inline `#` inside quoted values (only full-line comments).
17
- function strippedTemplate(templateFile) {
18
- const out = fs.readFileSync(templateFile, 'utf8')
19
- .split('\n')
20
- .filter((l) => { const t = l.trim(); return t !== '' && !t.startsWith('#') })
21
- .join('\n')
22
- const tmp = path.join(os.tmpdir(), `saaslayer-foundation-${process.pid}.yml`)
23
- fs.writeFileSync(tmp, out)
24
- return tmp
25
- }
12
+ const { apiCall, jsonApiCall } = require('../api-client')
13
+ const { applyRegionFoundation, awsRunner } = require('../foundation-change-set')
14
+ const { writeParameterOverridesFile, writeDeployableTemplate, stripComments } = require('../foundation-template')
15
+ const { controlPlaneEntry, mergeTrustEntry, parseTrustEntries, renderFoundationTemplate, canonicalRoleArn } = require('../trust-entries')
16
+ const { resolveFoundationHome, FOUNDATION_STACK } = require('../foundation-home')
17
+ const { writeTrustEntries, writeConnectionAuthorizers, AUTHORIZERS_SSM_NAME } = require('../foundation-trust-write')
18
+ const { buildConnectionProof, proofScope } = require('../connection-proof')
19
+ const { awsCredentials } = require('../iam-session')
20
+ const { confirm: promptConfirm } = require('../prompt')
21
+ const { SMS_NUMBER_COST, smsNumberOf, logSmsNextSteps } = require('../sms/number')
22
+
23
+ /** Change-set and stack polling for the region foundation deploy. */
24
+ const DEFAULT_WAIT = { sleep: (ms) => new Promise((r) => setTimeout(r, ms)), pollMs: 5000, maxPolls: 720 }
25
+
26
+ /** @param {string} cmd @param {string[]} args */
27
+ const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 })
26
28
 
27
29
  // Absolute path to the bundled foundation template. This template file is the SHARED contract between
28
30
  // `saaslayer aws connect` (customer BYO, ambient creds) and cplane account-vending (assumed-role creds) —
29
31
  // see control-plane/cli/src/accounts/foundation.ts, which deploys this same template + param contract.
30
32
  const FOUNDATION_TEMPLATE = path.join(__dirname, '..', '..', 'templates', 'saaslayer-foundation.yml')
31
33
 
32
- // Build the `aws cloudformation deploy` argv for the foundation stack. Pure — unit-testable, and shared
33
- // so the stack name + param contract live in one place.
34
- function foundationDeployArgs({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId = '', templateFile = FOUNDATION_TEMPLATE }) {
35
- return [
36
- 'cloudformation', 'deploy',
37
- '--template-file', templateFile,
38
- '--stack-name', 'saaslayer-foundation',
39
- '--region', region,
40
- '--capabilities', 'CAPABILITY_NAMED_IAM',
41
- '--parameter-overrides',
42
- `ControlPlaneAccountId=${controlPlaneAccount}`,
43
- `ExternalId=${externalId}`,
44
- `StackNamePrefix=${stackNamePrefix}`,
45
- `OrgId=${orgId}`,
46
- ]
47
- }
48
-
49
- // Deploy the bundled foundation template into the target account. `env` lets a caller inject ASSUMED
50
- // role creds (AWS_ACCESS_KEY_ID/SECRET/SESSION_TOKEN); omit to use the caller's ambient creds.
51
- function deployFoundation({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId, env }) {
52
- const templateFile = strippedTemplate(FOUNDATION_TEMPLATE)
53
- execFileSync('aws', foundationDeployArgs({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId, templateFile }),
54
- { stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
34
+ /**
35
+ * Text with every given value masked (trust identifiers never reach a terminal or log).
36
+ * @param {string} text @param {string[]} values
37
+ * @returns {string}
38
+ */
39
+ function redactValues(text, values) {
40
+ return values.filter(Boolean).reduce((out, value) => out.split(value).join('<redacted>'), String(text))
41
+ }
42
+
43
+ /**
44
+ * Creates the account foundation stack (create-only: never over an installed one) with its trust rendered from
45
+ * `trustEntries`. Parameters travel in a 0600 file, never argv; a failure's message never carries a trust identifier.
46
+ * @param {{ aws: import('../foundation-change-set').AwsJson, trustEntries: string, connectionAuthorizerArns: string,
47
+ * controlPlaneAccount: string, stackNamePrefix: string, orgId?: string, stackName?: string, templatePath?: string }} o
48
+ */
49
+ function createAccountFoundation({ aws, trustEntries, connectionAuthorizerArns, controlPlaneAccount, stackNamePrefix, orgId = '', stackName = FOUNDATION_STACK, templatePath = FOUNDATION_TEMPLATE }) {
50
+ const templateFile = writeDeployableTemplate(templatePath, renderFoundationTemplate(stripComments(fs.readFileSync(templatePath, 'utf8')), trustEntries))
51
+ const params = writeParameterOverridesFile({
52
+ ControlPlaneAccountId: controlPlaneAccount, TrustEntries: trustEntries, ConnectionAuthorizerArns: connectionAuthorizerArns,
53
+ StackNamePrefix: stackNamePrefix, OrgId: orgId,
54
+ })
55
+ try {
56
+ aws(['cloudformation', 'create-stack', '--stack-name', stackName, '--template-body', `file://${templateFile}`,
57
+ '--parameters', `file://${params.file}`, '--capabilities', 'CAPABILITY_NAMED_IAM'])
58
+ aws(['cloudformation', 'wait', 'stack-create-complete', '--stack-name', stackName])
59
+ } catch (err) {
60
+ const identifiers = parseTrustEntries(trustEntries).flatMap((p) => p.entry.trustIdentifiers)
61
+ throw new Error(`foundation stack create failed: ${redactValues(err.message, identifiers)}`)
62
+ } finally {
63
+ params.remove()
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Makes sure the account foundation carries this control plane's trust entry, acting only on the home stack:
69
+ * - no foundation yet: creates it in the requested region (that becomes its home), the caller as its only authorizer;
70
+ * - a foundation that still trusts a single ExternalId: converts it through the reviewed upgrade change set, from its
71
+ * home region only (the control plane's identifier for another region may not be the installed one);
72
+ * - an installed TrustEntries already holding this entry: nothing to write;
73
+ * - an installed TrustEntries without it: adds it through the trust write loop (only the entry roles' trust statements
74
+ * change, every other entry and parameter is kept; a newer foundation is refused, never downgraded);
75
+ * - a different entry for this control plane is refused: changing its identifier or callers is a rotation or handoff.
76
+ * @param {{ accountId: string, region: string, entry: import('../trust-entries').TrustEntry, controlPlaneAccount: string,
77
+ * stackNamePrefix: string, orgId?: string, flags: Record<string, any>, exec?: (cmd: string, args: string[]) => string,
78
+ * wait?: import('../foundation-change-set').Wait, log?: (...a: unknown[]) => void, confirm?: (q: string) => Promise<boolean> }} o
79
+ * @returns {Promise<{ result: 'created'|'unchanged'|'upgraded'|'up to date'|'entry added', homeRegion: string }>}
80
+ */
81
+ async function ensureAccountFoundation({ accountId, region, entry, controlPlaneAccount, stackNamePrefix, orgId, flags, exec = defaultExec, wait = DEFAULT_WAIT, log = console.log, confirm = promptConfirm }) {
82
+ const awsIn = (r) => awsRunner(exec, { region: r, profile: flags.profile })
83
+ const home = resolveFoundationHome({ awsIn, requestedRegion: region })
84
+ const authorizer = () => canonicalRoleArn(awsIn(region)(['sts', 'get-caller-identity']).Arn)
85
+ if (home.state === 'absent') {
86
+ log(` creating the account foundation ${FOUNDATION_STACK} in ${region} (its home region)…`)
87
+ try {
88
+ createAccountFoundation({ aws: awsIn(region), trustEntries: mergeTrustEntry('', entry), connectionAuthorizerArns: authorizer(), controlPlaneAccount, stackNamePrefix, orgId })
89
+ } catch (err) {
90
+ // The account is already registered with the control plane, so the failure says how to finish.
91
+ throw new Error(`aws connect: ${err.message}\nthe account is registered; rerun \`saaslayer aws connect --aws-account ${accountId} --region ${region}\` to finish`)
92
+ }
93
+ return { result: 'created', homeRegion: region }
94
+ }
95
+ const { accountTarget, readStack, upgradeStack } = require('./foundation')
96
+ const target = accountTarget({}, home.homeRegion)
97
+ const aws = awsIn(home.homeRegion)
98
+ const installed = readStack(aws, target)
99
+ if (!installed.paramKeys.includes('TrustEntries')) {
100
+ if (region !== home.homeRegion) {
101
+ throw new Error(`the account foundation in its home region ${home.homeRegion} still trusts a single ExternalId; convert it first with ` +
102
+ `\`saaslayer aws connect --aws-account ${accountId} --region ${home.homeRegion}\`, then connect ${region}. Nothing was changed.`)
103
+ }
104
+ const conversion = { TrustEntries: mergeTrustEntry('', entry), ConnectionAuthorizerArns: authorizer() }
105
+ const res = await upgradeStack(target, flags, { aws, required: true, log, confirm, wait, conversion })
106
+ if (res.result !== 'upgraded' && res.result !== 'up to date') throw new Error(`aws connect stopped: the account foundation conversion was ${res.result}; nothing was connected`)
107
+ return { result: res.result, homeRegion: home.homeRegion }
108
+ }
109
+ mergeTrustEntry(installed.params.TrustEntries, entry)
110
+ if (parseTrustEntries(installed.params.TrustEntries).some((p) => p.entry.controlPlaneId === entry.controlPlaneId)) {
111
+ log(` account foundation in ${home.homeRegion} already trusts ${entry.controlPlaneId}; unchanged`)
112
+ return { result: 'unchanged', homeRegion: home.homeRegion }
113
+ }
114
+ log(` adding the ${entry.controlPlaneId} trust entry to the account foundation in ${home.homeRegion}…`)
115
+ const res = await writeTrustEntries({ aws, stackName: target.stackName, homeRegion: home.homeRegion, controlPlaneId: entry.controlPlaneId, mutate: () => entry, wait, log })
116
+ return { result: res.result === 'updated' ? 'entry added' : 'unchanged', homeRegion: home.homeRegion }
55
117
  }
56
118
 
57
119
  // The account-global saaslayer-foundation stack holds IAM only (a role can't be created twice, so it's
@@ -96,6 +158,18 @@ function emailSenderDomainFlag(flags) {
96
158
  return domain
97
159
  }
98
160
 
161
+ /**
162
+ * The --sms-toll-free flag: install the toll-free SMS sending number with the region foundation; undefined when not passed.
163
+ * @param {Record<string, unknown>} flags
164
+ * @returns {'toll-free'|undefined}
165
+ */
166
+ function smsTollFreeFlag(flags) {
167
+ const raw = flags['sms-toll-free']
168
+ if (raw === undefined) return undefined
169
+ if (raw !== true) throw new Error(`--sms-toll-free takes no value, got '${raw}'`)
170
+ return 'toll-free'
171
+ }
172
+
99
173
  /**
100
174
  * The region stack's email sender outputs: the SES identity ARN and the DKIM CNAME records for the domain's DNS.
101
175
  * @param {Array<{ OutputKey: string, OutputValue: string }>} outputs
@@ -119,63 +193,262 @@ function logEmailSenderRecords(log, domain, sender) {
119
193
  log(` saaslayer settings set CognitoEmailSenderArn=${sender.identityArn} CognitoEmailFromAddress='<Name> <no-reply@${domain}>'`)
120
194
  }
121
195
 
122
- // Build the `aws cloudformation deploy` argv for the per-region foundation stack. Pure — unit-testable.
123
- // No IAM in this stack, so no CAPABILITY_NAMED_IAM; a no-op re-deploy must be clean, not a failure. Without
124
- // emailSenderDomain no override is passed, so a re-run keeps the sender domain the stack already has.
125
- function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templateFile = FOUNDATION_REGION_TEMPLATE, emailSenderDomain }) {
126
- return [
127
- 'cloudformation', 'deploy',
128
- '--template-file', templateFile,
129
- '--stack-name', foundationRegionStackName(region),
130
- '--region', region,
131
- '--no-fail-on-empty-changeset',
132
- '--parameter-overrides',
133
- `ArtifactsBucketName=${bucket}`,
134
- ...(emailSenderDomain !== undefined ? [`EmailSenderDomain=${emailSenderDomain}`] : []),
135
- ]
136
- }
137
-
138
- // Deploy the per-region foundation stack (shared artifact bucket, optional email sender domain) with the caller's
139
- // creds (or injected `env`).
140
- function deployFoundationRegion({ accountId, region, env, emailSenderDomain }) {
196
+ /**
197
+ * Deploy the per-region foundation stack (shared artifact bucket, optional email sender domain, optional SMS number) with
198
+ * the caller's creds (or injected `env`), through a reviewed change set: every installed value is kept unless passed, a
199
+ * change set that would replace or remove the SMS number is refused. Without emailSenderDomain the stack keeps its own;
200
+ * smsNumberType (only 'toll-free', from --sms-toll-free) installs the number.
201
+ * @param {{ accountId: string, region: string, profile?: string, env?: Record<string, string>, emailSenderDomain?: string, smsNumberType?: 'toll-free',
202
+ * exec?: (cmd: string, args: string[]) => string, wait?: import('../foundation-change-set').Wait, log?: (...a: unknown[]) => void }} o
203
+ * @returns {Promise<string>} the artifact bucket name
204
+ */
205
+ async function deployFoundationRegion({ accountId, region, profile, env, emailSenderDomain, smsNumberType, exec, wait = DEFAULT_WAIT, log = console.log }) {
141
206
  const bucket = artifactsBucketName(accountId, region)
142
- execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket, emailSenderDomain }),
143
- { stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
207
+ const run = exec || ((cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024, env: env ? { ...process.env, ...env } : process.env }))
208
+ await applyRegionFoundation({
209
+ aws: awsRunner(run, { region, profile }),
210
+ stackName: foundationRegionStackName(region),
211
+ templateFile: FOUNDATION_REGION_TEMPLATE,
212
+ overrides: {
213
+ ArtifactsBucketName: bucket,
214
+ ...(emailSenderDomain !== undefined ? { EmailSenderDomain: emailSenderDomain } : {}),
215
+ ...(smsNumberType ? { SmsOriginationNumberType: smsNumberType } : {}),
216
+ },
217
+ wait,
218
+ log,
219
+ })
144
220
  return bucket
145
221
  }
146
222
 
147
- async function awsConnect(flags) {
223
+ /**
224
+ * The caller's AWS identity, refusing credentials for another account than the one being connected (every write below
225
+ * runs with them).
226
+ * @param {import('../foundation-change-set').AwsJson} aws @param {string} accountId
227
+ * @returns {{ Account: string, Arn: string }}
228
+ */
229
+ function callerIn(aws, accountId) {
230
+ const caller = aws(['sts', 'get-caller-identity'])
231
+ if (caller.Account !== accountId) throw new Error(`your AWS credentials are for account ${caller.Account}, not ${accountId}; switch credentials (--profile) and rerun. Nothing was changed.`)
232
+ return caller
233
+ }
234
+
235
+ /**
236
+ * `saaslayer aws connect`: proves the caller may authorize this org's connection (ADR 0005 §4), makes sure the account
237
+ * foundation trusts this control plane, deploys the requested region's stack, and, when the first submission could not be
238
+ * checked yet (first-connect bootstrap), submits a fresh proof that activates the connection; then it verifies the trust
239
+ * (verify needs the org's connection ACTIVE).
240
+ * Every submission carries a new proof; the presigned URL and credentials are never logged.
241
+ * @param {Record<string, any>} flags
242
+ * @param {{ confirm?: (q: string) => Promise<boolean>, exec?: (cmd: string, args: string[]) => string,
243
+ * api?: (method: string, path: string, body?: unknown, flags?: object) => Promise<any>, wait?: import('../foundation-change-set').Wait,
244
+ * log?: (...a: unknown[]) => void }} [deps]
245
+ */
246
+ async function awsConnect(flags, { confirm = promptConfirm, exec = defaultExec, api = apiCall, wait = DEFAULT_WAIT, log = console.log } = {}) {
148
247
  const accountId = flags['aws-account']
149
248
  const region = flags.region || 'us-east-1'
150
249
  const orgId = flags.org || context.get('org')
151
250
  if (!accountId) throw new Error('aws connect requires --aws-account <12-digit id>')
152
251
  const emailSenderDomain = emailSenderDomainFlag(flags)
252
+ const smsNumberType = smsTollFreeFlag(flags)
153
253
  if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
254
+ if (smsNumberType && !flags.yes && !(await confirm(`--sms-toll-free installs a US toll-free SMS number in ${accountId} ${region}; AWS bills it ${SMS_NUMBER_COST} while it exists. Continue?`))) {
255
+ throw new Error('aws connect cancelled; nothing changed (drop --sms-toll-free to connect without an SMS number)')
256
+ }
154
257
  // D5: bind the account to the active project by default; --org-wide opens it to all org projects.
155
258
  const orgWide = flags['org-wide'] === true || flags['org-wide'] === 'true'
156
259
  const projectId = orgWide ? undefined : flags.project || context.get('project')
157
260
 
158
- const scope = orgWide ? 'all projects in the org' : projectId ? `project ${projectId}` : 'all projects in the org (no active project)'
159
- console.log(`Connecting AWS account ${accountId} (${region}) to org ${orgId} — deployable by ${scope}…`)
160
- const conn = await apiCall('POST', '/api/aws/connect', { accountId, region, orgId, projectId, orgWide }, flags)
161
- console.log(` registered (trust secret minted); deploying the account-global foundation stack into ${accountId} with your AWS creds…`)
162
- deployFoundation({ controlPlaneAccount: conn.controlPlaneAccountId, externalId: conn.externalId, region, stackNamePrefix: conn.stackNamePrefix, orgId })
163
- console.log(` global foundation deployed; deploying the per-region foundation (shared artifact bucket) into ${region}…`)
164
- const bucket = deployFoundationRegion({ accountId, region, emailSenderDomain })
165
- console.log(` per-region foundation deployed (bucket ${bucket}); verifying cross-account trust…`)
166
- if (emailSenderDomain) {
167
- const described = JSON.parse(execFileSync('aws', ['cloudformation', 'describe-stacks', '--stack-name', foundationRegionStackName(region), '--region', region, '--output', 'json'], { encoding: 'utf8' }))
168
- const sender = emailSenderOutputs(described.Stacks[0].Outputs)
169
- if (sender) logEmailSenderRecords(console.log, emailSenderDomain, sender)
261
+ const awsHere = awsRunner(exec, { region, profile: flags.profile })
262
+ callerIn(awsHere, accountId)
263
+ const { controlPlaneId } = await api('GET', '/api/config', undefined, flags)
264
+ if (!controlPlaneId) throw new Error('the control plane does not report its controlPlaneId (GET /api/config); it needs an update before aws connect can prove a connection. Nothing was changed.')
265
+ const credentials = awsCredentials({ profile: flags.profile, exec })
266
+ const scope = proofScope({ orgWide, projectId })
267
+ const submit = () => api('POST', '/api/aws/connect', {
268
+ accountId, region, orgId, projectId, orgWide,
269
+ connectionProof: buildConnectionProof({ orgId, controlPlaneId, scope, region, credentials }),
270
+ }, flags)
271
+
272
+ const audience = orgWide ? 'all projects in the org' : projectId ? `project ${projectId}` : 'all projects in the org (no active project)'
273
+ log(`Connecting AWS account ${accountId} (${region}) to org ${orgId} — deployable by ${audience}…`)
274
+ const conn = await submit()
275
+ if (conn.controlPlaneId !== controlPlaneId) throw new Error(`the control plane answered for control plane ${conn.controlPlaneId}, not ${controlPlaneId}; nothing was changed in AWS`)
276
+ const entry = controlPlaneEntry({ controlPlaneId, principalAccountId: conn.controlPlaneAccountId, trustIdentifiers: [conn.externalId] })
277
+ log(` registered (${conn.connectionStatus}); checking the account foundation of ${accountId} with your AWS creds…`)
278
+ await ensureAccountFoundation({ accountId, region, entry, controlPlaneAccount: conn.controlPlaneAccountId, stackNamePrefix: conn.stackNamePrefix, orgId, flags, exec, wait, log, confirm })
279
+ log(` deploying the per-region foundation (shared artifact bucket) into ${region}…`)
280
+ const bucket = await deployFoundationRegion({ accountId, region, profile: flags.profile, emailSenderDomain, smsNumberType, exec, wait, log })
281
+ log(` per-region foundation deployed (bucket ${bucket}); verifying cross-account trust…`)
282
+ if (emailSenderDomain || smsNumberType) {
283
+ const described = awsHere(['cloudformation', 'describe-stacks', '--stack-name', foundationRegionStackName(region)])
284
+ const sender = emailSenderDomain ? emailSenderOutputs(described.Stacks[0].Outputs) : null
285
+ if (sender) logEmailSenderRecords(log, emailSenderDomain, sender)
286
+ const number = smsNumberOf(described.Stacks[0])
287
+ if (smsNumberType && number.arn) logSmsNextSteps(log, { arn: number.arn, env: '<env>', numberType: number.numberType })
288
+ }
289
+ // Verify needs the org's connection ACTIVE: a first connect submits its fresh proof first, now that the foundation
290
+ // trusts this control plane.
291
+ let connectionStatus = conn.connectionStatus
292
+ if (connectionStatus !== 'ACTIVE') {
293
+ log(' submitting the connection proof now that the foundation trusts this control plane…')
294
+ connectionStatus = (await submit()).connectionStatus
295
+ if (connectionStatus !== 'ACTIVE') {
296
+ throw new Error(`the connection of org ${orgId} to ${accountId} is still ${connectionStatus}: the control plane could not read the account's ` +
297
+ 'connection authorizers yet. Rerun `saaslayer aws connect` to submit a new proof.')
298
+ }
299
+ }
300
+ const v = await api('POST', '/api/aws/connect/verify', { accountId, region }, flags)
301
+ log(`✅ AWS account ${accountId} connected to org ${orgId} (${v.bootstrapStatus}, ${connectionStatus})`)
302
+ return { ...v, connectionStatus }
303
+ }
304
+
305
+ /**
306
+ * `saaslayer aws authorizers add|remove <arn> --aws-account <id>`: changes who may authorize SaaSLayer org connections to
307
+ * the account (ConnectionAuthorizerArns), as a parameter-only update of the home foundation stack. Only a current
308
+ * authorizer may change it (checked here from the SSM parameter; IAM enforces the stack update on the customer side).
309
+ * @param {string} action add or remove
310
+ * @param {string} arn an IAM principal ARN (stored as its path-less role ARN)
311
+ * @param {Record<string, any>} flags
312
+ * @param {{ exec?: (cmd: string, args: string[]) => string, wait?: import('../foundation-change-set').Wait, log?: (...a: unknown[]) => void }} [deps]
313
+ */
314
+ async function awsAuthorizers(action, arn, flags, { exec = defaultExec, wait = DEFAULT_WAIT, log = console.log } = {}) {
315
+ const accountId = flags['aws-account']
316
+ if ((action !== 'add' && action !== 'remove') || !arn || !accountId) throw new Error('usage: saaslayer aws authorizers <add|remove> <arn> --aws-account <id> [--region R] [--profile P]')
317
+ const canonical = canonicalRoleArn(arn)
318
+ const region = flags.region || 'us-east-1'
319
+ const awsIn = (r) => awsRunner(exec, { region: r, profile: flags.profile })
320
+ const caller = canonicalRoleArn(callerIn(awsIn(region), accountId).Arn)
321
+ const home = resolveFoundationHome({ awsIn, requestedRegion: region })
322
+ if (home.state === 'absent') throw new Error(`${accountId} has no account foundation yet; connect it first with saaslayer aws connect. Nothing was changed.`)
323
+ const aws = awsIn(home.homeRegion)
324
+ const current = JSON.parse(aws(['ssm', 'get-parameter', '--name', AUTHORIZERS_SSM_NAME]).Parameter.Value).connectionAuthorizerArns || []
325
+ if (!current.includes(caller)) {
326
+ throw new Error(`${caller} is not a connection authorizer of ${accountId}; only a current authorizer can change ConnectionAuthorizerArns. Nothing was changed.`)
327
+ }
328
+ log(`${action === 'add' ? 'Adding' : 'Removing'} connection authorizer ${canonical} (${accountId}, home ${home.homeRegion})…`)
329
+ const res = await writeConnectionAuthorizers({ aws, homeRegion: home.homeRegion, [action]: canonical, wait, log })
330
+ log(res.result === 'updated' ? `✅ connection authorizers of ${accountId} updated` : `connection authorizers of ${accountId} unchanged`)
331
+ return res
332
+ }
333
+
334
+ const ROTATE_TRUST_STEPS = ['start', 'verify', 'switch', 'retire', 'rollback', 'status']
335
+ const ROTATE_TRUST_USAGE = 'usage: saaslayer aws rotate-trust <start|verify|switch|retire|rollback|status> --aws-account <id> ' +
336
+ '[--reason <text> (start)] [--region R] [--org ID] [--profile P]'
337
+
338
+ /**
339
+ * One line describing a rotation (never an identifier value).
340
+ * @param {{ rotationId: string|null, state: string, carriedBy: string[] }} r
341
+ */
342
+ function rotationLine(r) {
343
+ const carriers = r.carriedBy && r.carriedBy.length ? `; ${r.carriedBy.length} running operation(s) still carry the outgoing identifier: ${r.carriedBy.join(', ')}` : ''
344
+ return `trust rotation ${r.rotationId || '(none yet)'}: ${r.state}${carriers}`
345
+ }
346
+
347
+ /** What each state leads to next, for the step's closing line. */
348
+ const NEXT_STEP = {
349
+ next_added: 'next: saaslayer aws rotate-trust verify',
350
+ verified: 'next: saaslayer aws rotate-trust switch',
351
+ switched: 'next: saaslayer aws rotate-trust retire (once the running operations above finish)',
352
+ rolling_back: 'rerun saaslayer aws rotate-trust rollback once the running operations above finish',
353
+ idle: 'the account trusts a single identifier',
354
+ }
355
+
356
+ /**
357
+ * `saaslayer aws rotate-trust <step> --aws-account <id>` (ADR 0005 D7): rotates the trust identifier of the account's
358
+ * relationship with this control plane, with overlap and drain. The control plane holds the rotation state and mints next;
359
+ * every step carries a fresh connection proof (bound to `trust-rotation:<step>`) signed with the caller's AWS credentials,
360
+ * so only a connection authorizer of the account can rotate. The caller's credentials change the foundation trust entry
361
+ * through the trust write loop: start adds next, verify re-adds it when an interrupted start left it out, retire and a
362
+ * finished rollback leave the one remaining identifier. status reads the rotation only. Identifier values are never printed.
363
+ * @param {string} step start, verify, switch, retire, rollback or status
364
+ * @param {Record<string, any>} flags
365
+ * @param {{ exec?: (cmd: string, args: string[]) => string, api?: typeof jsonApiCall, wait?: import('../foundation-change-set').Wait,
366
+ * log?: (...a: unknown[]) => void }} [deps]
367
+ * @returns {Promise<{ accountId: string, controlPlaneId: string, rotationId: string|null, state: string, startedAt: string|null, carriedBy: string[] }>}
368
+ */
369
+ async function awsRotateTrust(step, flags, { exec = defaultExec, api = jsonApiCall, wait = DEFAULT_WAIT, log = console.log } = {}) {
370
+ const accountId = flags['aws-account']
371
+ if (!ROTATE_TRUST_STEPS.includes(step) || !accountId) throw new Error(ROTATE_TRUST_USAGE)
372
+ const path = `/api/accounts/${accountId}/trust-rotations`
373
+ /** @param {any} doc */
374
+ const statusOf = (doc) => {
375
+ const { trustIdentifiers, authorizedBy, verification, ...status } = doc.data.attributes
376
+ return status
377
+ }
378
+ if (step === 'status') {
379
+ const status = statusOf(await api('GET', path, undefined, flags))
380
+ log(rotationLine(status))
381
+ return status
382
+ }
383
+ const reason = typeof flags.reason === 'string' ? flags.reason.trim() : ''
384
+ if (step === 'start' && !reason) throw new Error('aws rotate-trust start needs --reason "<why>" (recorded in the audit log). Nothing was changed.')
385
+ const orgId = flags.org || context.get('org')
386
+ if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
387
+ const region = flags.region || 'us-east-1'
388
+ const awsIn = (r) => awsRunner(exec, { region: r, profile: flags.profile })
389
+ callerIn(awsIn(region), accountId)
390
+ const { controlPlaneId } = await api('GET', '/api/config', undefined, flags)
391
+ if (!controlPlaneId) throw new Error('the control plane does not report its controlPlaneId (GET /api/config); it needs an update first. Nothing was changed.')
392
+ const home = resolveFoundationHome({ awsIn, requestedRegion: region })
393
+ if (home.state === 'absent') throw new Error(`${accountId} has no account foundation; connect it first with saaslayer aws connect. Nothing was changed.`)
394
+ const credentials = awsCredentials({ profile: flags.profile, exec })
395
+ /** A step request with a fresh proof bound to this step. @param {string} s */
396
+ const request = (s) => ({
397
+ region, orgId, ...(reason ? { reason } : {}),
398
+ connectionProof: buildConnectionProof({ orgId, controlPlaneId, scope: `trust-rotation:${s}`, region, credentials }),
399
+ })
400
+ /**
401
+ * Makes this control plane's foundation entry trust exactly the identifiers the rotation needs now (current, plus next
402
+ * until it is retired or rolled back). Refuses an entry that does not hold current: the foundation drifted.
403
+ * @param {{ current: string, next: string|null }} ids
404
+ */
405
+ const trustEntryFor = async (ids) => {
406
+ const wanted = ids.next ? [ids.current, ids.next] : [ids.current]
407
+ const res = await writeTrustEntries({
408
+ aws: awsIn(home.homeRegion), homeRegion: home.homeRegion, controlPlaneId, mergeOptions: { identifierChange: true }, wait, log,
409
+ mutate: (own) => {
410
+ if (!own || !own.trustIdentifiers.includes(ids.current)) {
411
+ throw new Error(`the account foundation in ${home.homeRegion} does not hold this control plane's current trust identifier; ` +
412
+ 'it needs reconciliation before a rotation can change it (roll the rotation back with saaslayer aws rotate-trust rollback). Nothing was changed.')
413
+ }
414
+ return controlPlaneEntry({ controlPlaneId, principalAccountId: own.principalAccountId, trustIdentifiers: wanted })
415
+ },
416
+ })
417
+ log(res.result === 'updated' ? ` account foundation (${home.homeRegion}) now trusts ${wanted.length} identifier(s) for ${controlPlaneId}` : ` account foundation (${home.homeRegion}) already trusts the identifier(s) this step needs`)
418
+ }
419
+
420
+ let doc
421
+ if (step === 'start') {
422
+ log(`Starting a trust rotation of ${accountId} for ${controlPlaneId}…`)
423
+ doc = await api('POST', path, request('start'), flags)
424
+ log(` ${rotationLine(statusOf(doc))}; adding the next identifier to the account foundation…`)
425
+ await trustEntryFor(doc.data.attributes.trustIdentifiers)
426
+ } else {
427
+ const rotationId = statusOf(await api('GET', path, undefined, flags)).rotationId
428
+ if (!rotationId) throw new Error(`${accountId} has no trust rotation; start one with saaslayer aws rotate-trust start --reason "<why>". Nothing was changed.`)
429
+ const stepPath = `${path}/${rotationId}/${step}`
430
+ doc = await api('POST', stepPath, request(step), flags)
431
+ if (step === 'verify' && doc.data.attributes.state === 'next_added') {
432
+ log(' the next identifier does not verify yet; making sure the account foundation trusts it…')
433
+ await trustEntryFor(doc.data.attributes.trustIdentifiers)
434
+ doc = await api('POST', stepPath, request(step), flags)
435
+ const v = doc.data.attributes.verification || {}
436
+ if (doc.data.attributes.state === 'next_added') {
437
+ const failed = ['deploy', 'support', 'executionRole'].filter((k) => !v[k])
438
+ throw new Error(`the next trust identifier did not verify (${failed.join(', ') || 'unknown'}); IAM may still be propagating. Rerun saaslayer aws rotate-trust verify.`)
439
+ }
440
+ }
441
+ if ((step === 'retire' || step === 'rollback') && doc.data.attributes.state === 'idle') await trustEntryFor(doc.data.attributes.trustIdentifiers)
170
442
  }
171
- const v = await apiCall('POST', '/api/aws/connect/verify', { accountId, region }, flags)
172
- console.log(`✅ AWS account ${accountId} connected to org ${orgId} (${v.bootstrapStatus})`)
173
- return v
443
+ const status = statusOf(doc)
444
+ log(`${step === 'start' || status.state === 'idle' || status.state === 'verified' || status.state === 'switched' ? '✅ ' : ''}${rotationLine(status)}`)
445
+ log(` ${NEXT_STEP[status.state] || ''}`)
446
+ return status
174
447
  }
175
448
 
176
449
  module.exports = {
177
- awsConnect, deployFoundation, foundationDeployArgs, FOUNDATION_TEMPLATE,
178
- deployFoundationRegion, foundationRegionDeployArgs, foundationRegionStackName, artifactsBucketName,
179
- emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords,
450
+ awsConnect, awsAuthorizers, awsRotateTrust, ensureAccountFoundation, createAccountFoundation, FOUNDATION_TEMPLATE,
451
+ deployFoundationRegion, foundationRegionStackName, artifactsBucketName,
452
+ emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords, smsTollFreeFlag,
180
453
  FOUNDATION_REGION_TEMPLATE,
181
454
  }