saaslayer 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/saaslayer.js CHANGED
@@ -190,6 +190,19 @@ Usage:
190
190
  For a user who lost every MFA factor: removes their passkeys and authenticator-app MFA and signs them out
191
191
  everywhere, so they can enroll a new factor. Access admins only (never --iam); the reason
192
192
  goes to the audit line. Resetting your own MFA needs a fresh MFA sign-in.
193
+ saaslayer users admin bootstrap|keys|grants --deployment <id> --service <ref> --account-id <id> --region <r>
194
+ [--profile <p> --manifest <file>] [--wait]
195
+ Opt-in local management of one user-service instance (off by default): owners, machine keys and human grants
196
+ with fixed purposes, usable without the control plane or permissions-service. Standalone (--manifest, your
197
+ target-account IAM; the manifest is checked against the stack before any write) or managed (an owner of the
198
+ deployment's owning org, through the control plane).
199
+ bootstrap --owner-suid <suid> --owner-email <email> [repeat] --purpose <p> [repeat] [--reason <text>]
200
+ keys --caller <id> --purpose <p> --phase introduce --output <private-file>
201
+ keys --caller <id> --phase activate|retire|revoke --key-id <id> [--reason <text>] | keys --phase status
202
+ grants --principal <suid> [repeat] --purpose <p> --phase grant|revoke|status [--reason <text>]
203
+ Purposes: account-read, account-provisioning, account-import, account-administration, account-deletion,
204
+ account-sensitive, account-recovery (humans only), reconciliation, config, email-authoring. A raw key is written
205
+ only to --output (0600); revoke needs --reason; a revoked grant or root comes back only with --reason.
193
206
 
194
207
  Deploy & lifecycle (requires login + a connected AWS account):
195
208
  saaslayer aws connect --aws-account <id> [--region R] [--org ID] [--org-wide]
@@ -279,6 +292,11 @@ Deploy & lifecycle (requires login + a connected AWS account):
279
292
  saaslayer activity --env E [--region R | --deployment ID] [--limit N] [--json]
280
293
  A deployment's activity, newest first: every change — yours and any SaaSLayer operator's — with who made it
281
294
  (customer:<id> | operator:<id>), the action, what it touched, the reason and its operation id.
295
+ saaslayer credentials status --deployment <id> --service <ref> [--json]
296
+ saaslayer credentials revoke --deployment <id> --service <ref> --kind email-authoring|config --key-id <id> --reason <text> [--json]
297
+ Org owners: a user-service instance's console integration credentials (key ids, state, age; never a value), and an
298
+ emergency revoke of one key (no delay). The revoke answers its pending operation; the key stops working once every
299
+ verifier holds the replacement.
282
300
 
283
301
  Data migrations you run yourself (a deployment with migrationRunner self):
284
302
  saaslayer migrate status --deployment <id> [--service <ref>]
@@ -383,6 +401,7 @@ async function main() {
383
401
  const users = require('../src/commands/users')
384
402
  if (sub === 'export') { await users.usersExport(flags); return }
385
403
  if (sub === 'import') { await users.usersImport(flags); return }
404
+ if (sub === 'admin') { await require('../src/commands/users-management').usersManagement(positional[2], flags); return }
386
405
  if (users.ADMIN_COMMANDS.includes(sub)) { await users.usersAdmin(sub, positional.slice(2), flags); return }
387
406
  console.error(users.USAGE); process.exit(1)
388
407
  }
@@ -508,6 +527,8 @@ async function main() {
508
527
  if (cmd === 'settings') { const { settingsCommand } = require('../src/commands/settings'); await settingsCommand(sub, flags); return }
509
528
  if (cmd === 'first-admin') { const { firstAdminCommand } = require('../src/commands/first-admin'); await firstAdminCommand(sub, flags); return }
510
529
  if (cmd === 'activity') { const { activityCommand } = require('../src/commands/activity'); await activityCommand(flags); return }
530
+ if (cmd === 'credentials' && sub === 'status') { await require('../src/commands/integration-credentials').credentialsStatus(flags); return }
531
+ if (cmd === 'credentials' && sub === 'revoke') { await require('../src/commands/integration-credentials').credentialsRevoke(flags); return }
511
532
  if (cmd === 'operations' || cmd === 'operation') { const { operationsCommand } = require('../src/commands/operations'); await operationsCommand(sub, positional[2], flags); return }
512
533
  if (cmd === 'service') {
513
534
  const lc = require('../src/commands/lifecycle')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "saaslayer",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "SaaSLayer CLI — onboard an account (init) and register a service's permissions manifest.",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -41,7 +41,7 @@
41
41
  "access": "public"
42
42
  },
43
43
  "scripts": {
44
- "test": "node scripts/sync-template.js --check && node scripts/sync-vendor.js --check && node bin/saaslayer.js --help >/dev/null && node test/credentials.test.js && node test/multi-account.test.js && node test/aws.test.js && node test/api-client-refresh.test.js && node test/update.test.js && node test/migrations-approve.test.js && node test/service-remove.test.js && node test/settings.test.js && node test/env-compare.test.js && node test/release-manifest.test.js && node test/operations.test.js && node test/projects.test.js && node test/activity.test.js && node test/deploy.test.js && node test/module-catalog.test.js && node test/stacks.test.js && node test/catalog.test.js && node test/catalog-registry.test.js && node test/permissions-inspect.test.js && node test/permissions-commands.test.js && node test/iam.test.js && node test/machine-trust.test.js && node test/access-admins.test.js && node test/first-admin.test.js && node test/service-principals.test.js && node test/package-files.test.js && node test/users-export.test.js && node test/users-import.test.js && node test/users.test.js && node test/migrate.test.js && node test/foundation-template.test.js && node test/foundation.test.js && node test/scope.test.js && node test/discovery.test.js && node test/credential-profiles.test.js && node test/login-challenges.test.js && node test/login-prompt.test.js && node test/control-plane-url.test.js && echo ok",
44
+ "test": "node scripts/sync-template.js --check && node scripts/sync-vendor.js --check && node bin/saaslayer.js --help >/dev/null && node test/credentials.test.js && node test/multi-account.test.js && node test/aws.test.js && node test/api-client-refresh.test.js && node test/update.test.js && node test/migrations-approve.test.js && node test/service-remove.test.js && node test/settings.test.js && node test/env-compare.test.js && node test/release-manifest.test.js && node test/operations.test.js && node test/projects.test.js && node test/activity.test.js && node test/integration-credentials.test.js && node test/users-management.test.js && node test/deploy.test.js && node test/module-catalog.test.js && node test/stacks.test.js && node test/catalog.test.js && node test/catalog-registry.test.js && node test/permissions-inspect.test.js && node test/permissions-commands.test.js && node test/iam.test.js && node test/machine-trust.test.js && node test/access-admins.test.js && node test/first-admin.test.js && node test/service-principals.test.js && node test/package-files.test.js && node test/users-export.test.js && node test/users-import.test.js && node test/users.test.js && node test/migrate.test.js && node test/foundation-template.test.js && node test/foundation.test.js && node test/scope.test.js && node test/discovery.test.js && node test/credential-profiles.test.js && node test/login-challenges.test.js && node test/login-prompt.test.js && node test/control-plane-url.test.js && echo ok",
45
45
  "sync-template": "node scripts/sync-template.js",
46
46
  "sync-template:check": "node scripts/sync-template.js --check",
47
47
  "prepublishOnly": "node scripts/sync-template.js",
@@ -80,9 +80,49 @@ function artifactsBucketName(accountId, region) {
80
80
  return `sl-artifacts-${region}-${opaqueAccountToken(accountId, 'artifacts').slice(0, 12)}`
81
81
  }
82
82
 
83
+ // The account's email sender domain, as the region template's EmailSenderDomain AllowedPattern takes it (or '' = none).
84
+ const EMAIL_SENDER_DOMAIN_PATTERN = /^(([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63})?$/
85
+
86
+ /**
87
+ * The --email-sender-domain flag, lowercased and checked before anything touches AWS; undefined when not passed.
88
+ * @param {Record<string, unknown>} flags
89
+ * @returns {string|undefined}
90
+ */
91
+ function emailSenderDomainFlag(flags) {
92
+ const raw = flags['email-sender-domain']
93
+ if (raw === undefined) return undefined
94
+ const domain = String(raw === true ? '' : raw).trim().toLowerCase()
95
+ if (!EMAIL_SENDER_DOMAIN_PATTERN.test(domain)) throw new Error(`--email-sender-domain expects a domain like acme.com ('' removes it), got '${raw}'`)
96
+ return domain
97
+ }
98
+
99
+ /**
100
+ * The region stack's email sender outputs: the SES identity ARN and the DKIM CNAME records for the domain's DNS.
101
+ * @param {Array<{ OutputKey: string, OutputValue: string }>} outputs
102
+ * @returns {{ identityArn: string, records: string[] }|null}
103
+ */
104
+ function emailSenderOutputs(outputs) {
105
+ const value = (key) => ((outputs || []).find((o) => o.OutputKey === key) || {}).OutputValue
106
+ const records = value('EmailSenderDkimRecords')
107
+ if (!records) return null
108
+ return { identityArn: value('EmailSenderIdentityArn') || '', records: records.split('\n').filter(Boolean) }
109
+ }
110
+
111
+ /**
112
+ * Prints what the customer's DNS admin adds, and the setting that sends through the domain once verified.
113
+ * @param {(...a: unknown[]) => void} log @param {string} domain @param {{ identityArn: string, records: string[] }} sender
114
+ */
115
+ function logEmailSenderRecords(log, domain, sender) {
116
+ log(` email sender domain ${domain}: add these DKIM records to its DNS (CNAME, TTL 300 or the default):`)
117
+ for (const record of sender.records) log(` ${record}`)
118
+ log(' once verified (saaslayer foundation status), send through it with:')
119
+ log(` saaslayer settings set CognitoEmailSenderArn=${sender.identityArn} CognitoEmailFromAddress='<Name> <no-reply@${domain}>'`)
120
+ }
121
+
83
122
  // Build the `aws cloudformation deploy` argv for the per-region foundation stack. Pure — unit-testable.
84
- // No IAM in this stack, so no CAPABILITY_NAMED_IAM; a no-op re-deploy must be clean, not a failure.
85
- function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templateFile = FOUNDATION_REGION_TEMPLATE }) {
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 }) {
86
126
  return [
87
127
  'cloudformation', 'deploy',
88
128
  '--template-file', templateFile,
@@ -91,13 +131,15 @@ function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templ
91
131
  '--no-fail-on-empty-changeset',
92
132
  '--parameter-overrides',
93
133
  `ArtifactsBucketName=${bucket}`,
134
+ ...(emailSenderDomain !== undefined ? [`EmailSenderDomain=${emailSenderDomain}`] : []),
94
135
  ]
95
136
  }
96
137
 
97
- // Deploy the per-region foundation stack (shared artifact bucket) with the caller's creds (or injected `env`).
98
- function deployFoundationRegion({ accountId, region, env }) {
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 }) {
99
141
  const bucket = artifactsBucketName(accountId, region)
100
- execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket }),
142
+ execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket, emailSenderDomain }),
101
143
  { stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
102
144
  return bucket
103
145
  }
@@ -107,6 +149,7 @@ async function awsConnect(flags) {
107
149
  const region = flags.region || 'us-east-1'
108
150
  const orgId = flags.org || context.get('org')
109
151
  if (!accountId) throw new Error('aws connect requires --aws-account <12-digit id>')
152
+ const emailSenderDomain = emailSenderDomainFlag(flags)
110
153
  if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
111
154
  // D5: bind the account to the active project by default; --org-wide opens it to all org projects.
112
155
  const orgWide = flags['org-wide'] === true || flags['org-wide'] === 'true'
@@ -118,8 +161,13 @@ async function awsConnect(flags) {
118
161
  console.log(` registered (trust secret minted); deploying the account-global foundation stack into ${accountId} with your AWS creds…`)
119
162
  deployFoundation({ controlPlaneAccount: conn.controlPlaneAccountId, externalId: conn.externalId, region, stackNamePrefix: conn.stackNamePrefix, orgId })
120
163
  console.log(` global foundation deployed; deploying the per-region foundation (shared artifact bucket) into ${region}…`)
121
- const bucket = deployFoundationRegion({ accountId, region })
164
+ const bucket = deployFoundationRegion({ accountId, region, emailSenderDomain })
122
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)
170
+ }
123
171
  const v = await apiCall('POST', '/api/aws/connect/verify', { accountId, region }, flags)
124
172
  console.log(`✅ AWS account ${accountId} connected to org ${orgId} (${v.bootstrapStatus})`)
125
173
  return v
@@ -128,5 +176,6 @@ async function awsConnect(flags) {
128
176
  module.exports = {
129
177
  awsConnect, deployFoundation, foundationDeployArgs, FOUNDATION_TEMPLATE,
130
178
  deployFoundationRegion, foundationRegionDeployArgs, foundationRegionStackName, artifactsBucketName,
179
+ emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords,
131
180
  FOUNDATION_REGION_TEMPLATE,
132
181
  }
@@ -3,7 +3,7 @@
3
3
  'use strict'
4
4
  const fs = require('fs')
5
5
  const { execFileSync } = require('child_process')
6
- const { FOUNDATION_TEMPLATE, FOUNDATION_REGION_TEMPLATE, foundationRegionStackName } = require('./aws')
6
+ const { FOUNDATION_TEMPLATE, FOUNDATION_REGION_TEMPLATE, foundationRegionStackName, emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords } = require('./aws')
7
7
  const { stripComments, writeDeployableTemplate } = require('../foundation-template')
8
8
  const { confirm: promptConfirm } = require('../prompt')
9
9
  const { apiCall } = require('../api-client')
@@ -16,7 +16,7 @@ const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', s
16
16
  * @typedef {{ exec?: typeof defaultExec, log?: (...a: unknown[]) => void, confirm?: (q: string) => Promise<boolean>,
17
17
  * sleep?: (ms: number) => Promise<void>, pollMs?: number, maxPolls?: number, refresh?: Refresh }} Deps
18
18
  * @typedef {{ kind: 'account'|'region', stackName: string, template: string, outputKey: string, capabilities: string[] }} Target
19
- * @typedef {{ status: string, version: string|null, paramKeys: string[], lastUpdated: string|null }} InstalledStack
19
+ * @typedef {{ status: string, version: string|null, paramKeys: string[], params: Record<string, string>, outputs: Array<{ OutputKey: string, OutputValue: string }>, lastUpdated: string|null }} InstalledStack
20
20
  * @typedef {{ action: string, logicalId: string, type: string, replacement: string, scope: string[] }} Change
21
21
  */
22
22
 
@@ -159,6 +159,8 @@ function readStack(aws, target) {
159
159
  status: s.StackStatus,
160
160
  version: output ? output.OutputValue : null,
161
161
  paramKeys: (s.Parameters || []).map((p) => p.ParameterKey),
162
+ params: Object.fromEntries((s.Parameters || []).map((p) => [p.ParameterKey, p.ParameterValue])),
163
+ outputs: s.Outputs || [],
162
164
  lastUpdated: s.LastUpdatedTime || s.CreationTime || null,
163
165
  }
164
166
  }
@@ -184,6 +186,27 @@ function versionState(installed, bundledVersion) {
184
186
  * @param {object} flags
185
187
  * @param {Deps} [deps]
186
188
  */
189
+ /**
190
+ * The region stack's email sender domain and its SES verification, when one is set.
191
+ * @param {ReturnType<typeof awsRunner>} aws @param {InstalledStack} installed
192
+ * @returns {{ emailSender?: { domain: string, verified: boolean, dkimStatus: string|null, records: string[] } }}
193
+ */
194
+ function emailSenderStatus(aws, installed) {
195
+ const domain = installed.params.EmailSenderDomain
196
+ if (!domain) return {}
197
+ const sender = emailSenderOutputs(installed.outputs)
198
+ let identity = {}
199
+ try { identity = aws(['sesv2', 'get-email-identity', '--email-identity', domain]) } catch { identity = {} }
200
+ return {
201
+ emailSender: {
202
+ domain,
203
+ verified: identity.VerifiedForSendingStatus === true,
204
+ dkimStatus: (identity.DkimAttributes && identity.DkimAttributes.Status) || null,
205
+ records: sender ? sender.records : [],
206
+ },
207
+ }
208
+ }
209
+
187
210
  async function foundationStatus(flags, { exec = defaultExec, log = console.log } = {}) {
188
211
  const { region, targets } = resolveTargets(flags)
189
212
  const aws = awsRunner(exec, flags, region)
@@ -196,6 +219,7 @@ async function foundationStatus(flags, { exec = defaultExec, log = console.log }
196
219
  installedVersion: installed ? installed.version || 'unknown' : null,
197
220
  bundledVersion,
198
221
  state: versionState(installed, bundledVersion),
222
+ ...(t.kind === 'region' && installed ? emailSenderStatus(aws, installed) : {}),
199
223
  }
200
224
  })
201
225
  for (const r of rows) {
@@ -204,6 +228,11 @@ async function foundationStatus(flags, { exec = defaultExec, log = console.log }
204
228
  log(` installed ${r.installedVersion || '-'}`)
205
229
  log(` bundled ${r.bundledVersion}`)
206
230
  log(` ${r.state}`)
231
+ if (r.emailSender) {
232
+ const e = r.emailSender
233
+ log(` email sender ${e.domain}: ${e.verified ? 'verified' : `not verified yet (DKIM ${e.dkimStatus || 'unknown'})`}`)
234
+ if (!e.verified) for (const record of e.records) log(` ${record}`)
235
+ }
207
236
  }
208
237
  if (rows.some((r) => r.state === 'upgrade available')) log('\nRun `saaslayer foundation upgrade` to review and apply the upgrade.')
209
238
  return rows
@@ -270,6 +299,17 @@ function formatChanges(changes) {
270
299
  return changes.map((c) => ` ${c.action.padEnd(wa)} ${c.logicalId.padEnd(wl)} ${c.type.padEnd(wt)} replacement=${c.replacement || '-'} scope=${c.scope.join(',') || '-'}`)
271
300
  }
272
301
 
302
+ /**
303
+ * 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
305
+ */
306
+ function logSenderRecords(aws, target, domain, log) {
307
+ if (!domain) return
308
+ const after = readStack(aws, target)
309
+ const sender = after && emailSenderOutputs(after.outputs)
310
+ if (sender) logEmailSenderRecords(log, domain, sender)
311
+ }
312
+
273
313
  /**
274
314
  * Upgrades one foundation stack. Returns { stackName, result, ... } where result is upgraded | up to date | dry-run |
275
315
  * aborted | not installed. Throws on any refusal or failure.
@@ -294,11 +334,19 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
294
334
  throw new Error(`${label} runs ${installed.version}, newer than this CLI's bundled ${info.version}; update the saaslayer CLI instead of downgrading`)
295
335
  }
296
336
  const plan = upgradeParameters(info.parameters, installed.paramKeys)
337
+ // --email-sender-domain sets the region stack's sender domain; every other parameter keeps its value.
338
+ const senderDomain = target.kind === 'region' ? emailSenderDomainFlag(flags) : undefined
339
+ if (senderDomain !== undefined) {
340
+ plan.parameters = plan.parameters.filter((p) => p.ParameterKey !== 'EmailSenderDomain')
341
+ plan.added = plan.added.filter((p) => p.name !== 'EmailSenderDomain')
342
+ plan.parameters.push({ ParameterKey: 'EmailSenderDomain', ParameterValue: senderDomain })
343
+ }
297
344
  const changeSetName = `saaslayer-upgrade-${Date.now()}`
298
345
  const del = () => aws(['cloudformation', 'delete-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName])
299
346
 
300
347
  log(`\n${label}: ${from} -> ${info.version}`)
301
- log(` parameters kept (previous values): ${plan.parameters.map((p) => p.ParameterKey).join(', ') || '-'}`)
348
+ log(` parameters kept (previous values): ${plan.parameters.filter((p) => p.UsePreviousValue).map((p) => p.ParameterKey).join(', ') || '-'}`)
349
+ if (senderDomain !== undefined) log(` email sender domain: ${senderDomain || '(removed)'}`)
302
350
  if (plan.added.length) log(` new parameters (template default): ${plan.added.map((p) => `${p.name}='${p.default}'`).join(', ')}`)
303
351
  if (plan.removed.length) log(` parameters no longer in the template: ${plan.removed.join(', ')}`)
304
352
 
@@ -314,6 +362,7 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
314
362
  del()
315
363
  if (NO_CHANGES.test(cs.reason)) {
316
364
  log(` no changes — already up to date (${from})`)
365
+ logSenderRecords(aws, target, senderDomain, log)
317
366
  return { stackName: target.stackName, result: 'up to date', installedVersion: installed.version }
318
367
  }
319
368
  throw new Error(`${label}: change set failed: ${cs.reason}`)
@@ -350,6 +399,7 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
350
399
  }
351
400
  if (done.version !== info.version) throw new Error(`${label} updated but reports version ${done.version}, expected ${info.version}`)
352
401
  log(` ✅ ${label} upgraded ${from} -> ${done.version}`)
402
+ logSenderRecords(aws, target, senderDomain, log)
353
403
  return { stackName: target.stackName, result: 'upgraded', from, installedVersion: done.version }
354
404
  }
355
405
 
@@ -387,6 +437,7 @@ async function reportToControlPlane(flags, { aws, region, log, refresh }) {
387
437
  * @param {Deps} [deps]
388
438
  */
389
439
  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
+ emailSenderDomainFlag(flags) // refuse a malformed --email-sender-domain before touching AWS
390
441
  const { region, targets } = resolveTargets(flags)
391
442
  const aws = awsRunner(exec, flags, region)
392
443
  const results = []
@@ -0,0 +1,66 @@
1
+ // `saaslayer credentials status|revoke --deployment <id> --service <ref>`: an org owner reads a user-service instance's
2
+ // integration credentials (key ids, state, age; never a value) or revokes one key (reason required) through the console.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { apiCall } = require('../api-client')
6
+
7
+ const KINDS = ['email-authoring', 'config']
8
+
9
+ /** @param {object} flags @param {string} name */
10
+ const required = (flags, name) => {
11
+ const value = flags[name]
12
+ if (typeof value !== 'string' || !value.trim()) throw new Error(`--${name} is required`)
13
+ return value.trim()
14
+ }
15
+
16
+ /** @param {object} flags */
17
+ function basePath(flags) {
18
+ return `/api/deployments/${encodeURIComponent(required(flags, 'deployment'))}/services/${encodeURIComponent(required(flags, 'service'))}/credentials`
19
+ }
20
+
21
+ /**
22
+ * One line per key and the pending operation, from a status document.
23
+ * @param {Record<string, any>} attrs
24
+ * @returns {string[]}
25
+ */
26
+ function formatStatus(attrs) {
27
+ const lines = []
28
+ for (const [kind, keys] of Object.entries(attrs.kinds || {})) {
29
+ for (const k of keys) lines.push(`${kind} ${k.keyId} ${k.state} age ${k.ageDays}d ${k.accepted ? 'accepted' : 'pending acceptance'}`)
30
+ }
31
+ const op = attrs.operation
32
+ if (op && op.operationId) lines.push(`operation ${op.operationId} ${op.phase} ${op.status}${op.detail ? ` — ${op.detail}` : ''}`)
33
+ return lines.length ? lines : ['no integration credentials']
34
+ }
35
+
36
+ /**
37
+ * Print the instance's integration credentials (or the document with --json) and return its attributes.
38
+ * @param {object} flags
39
+ */
40
+ async function credentialsStatus(flags) {
41
+ const doc = await apiCall('GET', basePath(flags), undefined, flags)
42
+ const attrs = (doc && doc.data && doc.data.attributes) || {}
43
+ console.log(flags.json ? JSON.stringify(attrs, null, 2) : formatStatus(attrs).join('\n'))
44
+ return attrs
45
+ }
46
+
47
+ /**
48
+ * Revoke one key now (no delay). The answer is the pending operation: the old key stops working once every verifier
49
+ * has the replacement; the console sends the replacement only then.
50
+ * @param {object} flags
51
+ */
52
+ async function credentialsRevoke(flags) {
53
+ const kind = required(flags, 'kind')
54
+ if (!KINDS.includes(kind)) throw new Error(`--kind must be one of ${KINDS.join(', ')}`)
55
+ const keyId = required(flags, 'key-id')
56
+ const reason = required(flags, 'reason')
57
+ const path = `${basePath(flags)}/revoke`
58
+ const doc = await apiCall('POST', path, { data: { type: 'credential-revocations', attributes: { kind, keyId, reason } } }, flags, { headers: { 'Idempotency-Key': `cli-${crypto.randomUUID()}` } })
59
+ const attrs = (doc && doc.data && doc.data.attributes) || {}
60
+ console.log(flags.json
61
+ ? JSON.stringify(attrs, null, 2)
62
+ : `revoke of ${keyId}: operation ${attrs.operationId} ${attrs.status}${attrs.replacementKeyId ? ` (replacement ${attrs.replacementKeyId})` : ''}; check with \`saaslayer credentials status\``)
63
+ return attrs
64
+ }
65
+
66
+ module.exports = { credentialsStatus, credentialsRevoke, formatStatus }
@@ -29,7 +29,11 @@ async function status(flags) {
29
29
  for (const g of groups) {
30
30
  for (const i of g.instances || []) {
31
31
  const inst = i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''
32
- console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst}`)
32
+ // release = the commit the instance was last deployed at; a fleet state other than ACTIVE (e.g. migrations
33
+ // awaiting approval) is shown because the deployment status alone reads ACTIVE.
34
+ const release = i.commitSha ? String(i.commitSha).slice(0, 8) : '—'
35
+ const fleet = i.fleetState && i.fleetState !== 'ACTIVE' ? ` ${i.fleetState}` : ''
36
+ console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst} release ${release}${fleet}`)
33
37
  }
34
38
  }
35
39
  return view
@@ -0,0 +1,401 @@
1
+ // `saaslayer users admin bootstrap|keys|grants`: opt-in local management of one user-service instance. Standalone, with the
2
+ // owner's target-account IAM against a checked manifest; managed, through the control plane as an owner of the owning org.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const crypto = require('crypto')
7
+ const { execFileSync } = require('child_process')
8
+ const { apiCall } = require('../api-client')
9
+ const { signRequest } = require('../aws-sigv4')
10
+ const { awsCredentials } = require('../iam-session')
11
+
12
+ // The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
13
+ // vendor/user-management, synced on prepack).
14
+ const MONOREPO_MANAGEMENT = path.join(__dirname, '../../../../services/user-service/src/management')
15
+
16
+ /** The user-service management package: registry, purposes and the request flow its seed also runs. */
17
+ function loadManagement() {
18
+ try {
19
+ return require('../../vendor/user-management')
20
+ } catch (err) {
21
+ if (err && err.code !== 'MODULE_NOT_FOUND') throw err
22
+ return require(MONOREPO_MANAGEMENT)
23
+ }
24
+ }
25
+
26
+ const SUBCOMMANDS = ['bootstrap', 'keys', 'grants']
27
+ const KEY_PHASES = ['introduce', 'activate', 'retire', 'revoke', 'status']
28
+ const GRANT_PHASES = ['grant', 'revoke', 'status']
29
+ const MANIFEST_FIELDS = ['deploymentId', 'serviceRef', 'accountId', 'region', 'stackName', 'userPoolId', 'managementTableName', 'managementMaterialPath']
30
+
31
+ const USAGE = `usage: saaslayer users admin <bootstrap|keys|grants> --deployment <id> --service <ref> --account-id <id> --region <r>
32
+ [--profile <p> --manifest <file>] (standalone: your target-account IAM; otherwise through the control plane)
33
+ bootstrap --owner-suid <suid> --owner-email <email> [repeat the pair] --purpose <purpose> [repeatable] [--reason <text>]
34
+ keys --caller <id> --purpose <purpose> --phase introduce --output <private-file>
35
+ keys --caller <id> --phase activate|retire|revoke --key-id <id> [--reason <text>] | keys --phase status
36
+ grants --principal <suid> [repeatable] --purpose <purpose> --phase grant|revoke|status [--reason <text>]`
37
+
38
+ /** @param {unknown} value @returns {string[]} */
39
+ const listOf = (value) => (value === undefined || value === true ? [] : Array.isArray(value) ? value.map(String) : [String(value)])
40
+
41
+ /** @param {Record<string, any>} flags @param {string} name */
42
+ function required(flags, name) {
43
+ const value = flags[name]
44
+ if (typeof value !== 'string' || !value.trim()) throw new Error(`--${name} is required\n${USAGE}`)
45
+ return value.trim()
46
+ }
47
+
48
+ /** @param {Record<string, any>} flags @param {string} name */
49
+ const optional = (flags, name) => (typeof flags[name] === 'string' && flags[name].trim() ? flags[name].trim() : undefined)
50
+
51
+ /**
52
+ * The instance every subcommand names: deployment, service ref, account and region.
53
+ * @param {Record<string, any>} flags
54
+ */
55
+ function instanceOf(flags) {
56
+ const deploymentId = required(flags, 'deployment')
57
+ const serviceRef = required(flags, 'service')
58
+ const accountId = required(flags, 'account-id')
59
+ const region = required(flags, 'region')
60
+ if (!/^[0-9]{12}$/.test(accountId)) throw new Error('--account-id must be a 12-digit AWS account id')
61
+ if (!/^user-service(@[a-z][a-z0-9]{0,11})?$/.test(serviceRef)) throw new Error('--service must be user-service or user-service@<instance>')
62
+ return { deploymentId, serviceRef, accountId, region }
63
+ }
64
+
65
+ /**
66
+ * The checked request(s) of a subcommand, before any I/O. A grants run carries one request per --principal.
67
+ * @param {string} sub @param {Record<string, any>} flags
68
+ * @returns {Array<Record<string, any>>}
69
+ */
70
+ function requestsOf(sub, flags) {
71
+ const reason = optional(flags, 'reason')
72
+ const purposes = listOf(flags.purpose)
73
+ if (sub === 'bootstrap') {
74
+ const suids = listOf(flags['owner-suid'])
75
+ const emails = listOf(flags['owner-email'])
76
+ if (suids.length === 0) throw new Error(`--owner-suid is required\n${USAGE}`)
77
+ if (suids.length !== emails.length) throw new Error('pair every --owner-suid with an --owner-email, in the same order')
78
+ if (purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
79
+ // A reason makes this an explicit, audited owner action: adding a root to an initialized instance, or recovering one.
80
+ return [{ action: 'bootstrap', owners: suids.map((suid, i) => ({ suid, email: emails[i], purposes })), ...(reason ? { reason, recover: true } : {}) }]
81
+ }
82
+ const phase = required(flags, 'phase')
83
+ if (sub === 'keys') {
84
+ if (!KEY_PHASES.includes(phase)) throw new Error(`--phase must be one of ${KEY_PHASES.join(', ')}`)
85
+ if (phase === 'status') return [{ action: 'key', phase }]
86
+ const callerId = required(flags, 'caller')
87
+ if (phase === 'introduce') {
88
+ required(flags, 'output')
89
+ if (purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
90
+ return [{ action: 'key', phase, callerId, purposes }]
91
+ }
92
+ const keyId = required(flags, 'key-id')
93
+ if (phase === 'revoke' && !reason) throw new Error('--reason is required to revoke a key')
94
+ return [{ action: 'key', phase, callerId, keyId, ...(reason ? { reason } : {}) }]
95
+ }
96
+ if (!GRANT_PHASES.includes(phase)) throw new Error(`--phase must be one of ${GRANT_PHASES.join(', ')}`)
97
+ if (phase === 'status') return [{ action: 'grant', phase }]
98
+ const principals = listOf(flags.principal)
99
+ if (principals.length === 0) throw new Error(`--principal is required (repeatable)\n${USAGE}`)
100
+ if (phase === 'grant' && purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
101
+ if (phase === 'revoke' && !reason) throw new Error('--reason is required to revoke a grant')
102
+ return principals.map((principal) => ({ action: 'grant', phase, principal, ...(phase === 'grant' ? { purposes } : {}), ...(reason ? { reason } : {}) }))
103
+ }
104
+
105
+ /**
106
+ * Write an issued raw key to the caller's private file (0600, never overwritten). A retry re-outputting the same key is
107
+ * fine; a file holding anything else is refused.
108
+ * @param {string} file @param {string} key
109
+ */
110
+ function writeKeyFile(file, key) {
111
+ try {
112
+ fs.writeFileSync(file, `${key}\n`, { mode: 0o600, flag: 'wx' })
113
+ } catch (err) {
114
+ if (!err || /** @type {{ code?: string }} */ (err).code !== 'EEXIST') throw err
115
+ if (fs.readFileSync(file, 'utf8').trim() !== key) throw new Error(`--output ${file} already exists and holds something else; choose a new file`)
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Claim --output for a key the control plane returns once: a new private file (0600), created exclusively, so an existing
121
+ * file or a symlink is refused before anything is requested.
122
+ * @param {string} file
123
+ * @returns {number} the open file descriptor
124
+ */
125
+ function claimKeyFile(file) {
126
+ try {
127
+ return fs.openSync(file, 'wx', 0o600)
128
+ } catch (err) {
129
+ const code = /** @type {{ code?: string }} */ (err).code
130
+ if (code === 'EEXIST') throw new Error(`--output ${file} already exists (or is a link); a managed key is returned once, so choose a new file`)
131
+ throw new Error(`--output ${file} cannot be created: ${/** @type {Error} */ (err).message}`)
132
+ }
133
+ }
134
+
135
+ // ---- standalone: the owner's target-account IAM ------------------------------------------------------------------
136
+
137
+ /** @param {string} cmd @param {string[]} args */
138
+ const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] })
139
+
140
+ /**
141
+ * The manifest, checked against the flags and its own derivations before anything is called.
142
+ * @param {string} file @param {ReturnType<typeof instanceOf>} instance @param {ReturnType<typeof loadManagement>} management
143
+ */
144
+ function checkedManifest(file, instance, management) {
145
+ let manifest
146
+ try {
147
+ manifest = JSON.parse(fs.readFileSync(file, 'utf8'))
148
+ } catch (err) {
149
+ throw new Error(`--manifest ${file} is not a readable JSON file: ${/** @type {Error} */ (err).message}`)
150
+ }
151
+ const missing = MANIFEST_FIELDS.filter((f) => typeof manifest[f] !== 'string' || !manifest[f])
152
+ if (missing.length) throw new Error(`the manifest lacks ${missing.join(', ')}`)
153
+ for (const [field, flag] of [['deploymentId', 'deploymentId'], ['serviceRef', 'serviceRef'], ['accountId', 'accountId'], ['region', 'region']]) {
154
+ if (manifest[field] !== instance[/** @type {keyof typeof instance} */ (flag)]) throw new Error(`the manifest names ${field} ${manifest[field]}, not ${instance[/** @type {keyof typeof instance} */ (flag)]}; refusing a write to another target`)
155
+ }
156
+ const materialPath = management.managementMaterialPath(manifest.deploymentId, manifest.serviceRef)
157
+ if (manifest.managementMaterialPath !== materialPath) throw new Error(`the manifest's managementMaterialPath is not this instance's (${materialPath})`)
158
+ return manifest
159
+ }
160
+
161
+ /**
162
+ * The instance's pending key material in the owner-only SSM path: create-only SecureStrings, read back for a retry,
163
+ * removed once the key is no longer pending. Signed with the owner's credentials (no SDK; the raw value never reaches a
164
+ * process argument).
165
+ * @param {{ region: string, credentials: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, basePath: string, fetchImpl: typeof fetch }} deps
166
+ */
167
+ function ssmMaterial({ region, credentials, basePath, fetchImpl }) {
168
+ const host = `ssm.${region}.amazonaws.com`
169
+ /** @param {string} action @param {Record<string, unknown>} input */
170
+ async function call(action, input) {
171
+ const body = JSON.stringify(input)
172
+ const { headers } = signRequest({
173
+ method: 'POST',
174
+ url: `https://${host}/`,
175
+ body,
176
+ region,
177
+ service: 'ssm',
178
+ credentials: credentials(),
179
+ headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': `AmazonSSM.${action}`, Host: host },
180
+ })
181
+ const res = await fetchImpl(`https://${host}/`, { method: 'POST', headers, body })
182
+ const doc = await res.json().catch(() => ({}))
183
+ if (res.ok) return doc
184
+ const type = String((doc && (doc.__type || doc.code)) || '').split('#').pop()
185
+ throw Object.assign(new Error(`SSM ${action} failed (${res.status}${type ? ` ${type}` : ''})`), { name: type || 'SsmError' })
186
+ }
187
+ const name = (/** @type {string} */ keyId) => `${basePath}/${keyId}`
188
+ return {
189
+ async put(/** @type {string} */ keyId, /** @type {string} */ raw) {
190
+ await call('PutParameter', { Name: name(keyId), Value: raw, Type: 'SecureString', Overwrite: false, Description: 'pending local management key (owner only)' })
191
+ },
192
+ async get(/** @type {string} */ keyId) {
193
+ try {
194
+ const doc = await call('GetParameter', { Name: name(keyId), WithDecryption: true })
195
+ return doc.Parameter ? String(doc.Parameter.Value) : null
196
+ } catch (err) {
197
+ if (/** @type {{ name?: string }} */ (err).name === 'ParameterNotFound') return null
198
+ throw err
199
+ }
200
+ },
201
+ async remove(/** @type {string} */ keyId) {
202
+ try {
203
+ await call('DeleteParameter', { Name: name(keyId) })
204
+ } catch (err) {
205
+ if (/** @type {{ name?: string }} */ (err).name !== 'ParameterNotFound') throw err
206
+ }
207
+ },
208
+ }
209
+ }
210
+
211
+ /**
212
+ * The own pool through the aws CLI with the owner's credentials: the account holding an email (its custom:suid and sub),
213
+ * and an invitation creating one at a suid (its sub).
214
+ * @param {{ exec: typeof defaultExec, awsArgs: string[], userPoolId: string }} deps
215
+ */
216
+ function poolAccounts({ exec, awsArgs, userPoolId }) {
217
+ return {
218
+ async get(/** @type {string} */ email) {
219
+ let out
220
+ try {
221
+ out = JSON.parse(exec('aws', ['cognito-idp', 'admin-get-user', '--user-pool-id', userPoolId, '--username', email, '--output', 'json', ...awsArgs]))
222
+ } catch (err) {
223
+ if (String(/** @type {{ stderr?: unknown }} */ (err).stderr || '').includes('UserNotFoundException')) return null
224
+ throw new Error('reading the owner account failed (aws cognito-idp admin-get-user)')
225
+ }
226
+ return { suid: attributeOf(out.UserAttributes, 'custom:suid'), sub: attributeOf(out.UserAttributes, 'sub') }
227
+ },
228
+ async invite(/** @type {{ email: string, suid: string }} */ { email, suid }) {
229
+ const out = JSON.parse(exec('aws', ['cognito-idp', 'admin-create-user', '--user-pool-id', userPoolId, '--username', email, '--desired-delivery-mediums', 'EMAIL',
230
+ '--user-attributes', `Name=email,Value=${email}`, 'Name=email_verified,Value=true', `Name=custom:suid,Value=${suid}`, '--output', 'json', ...awsArgs]))
231
+ return { sub: attributeOf(out.User && out.User.Attributes, 'sub') }
232
+ },
233
+ }
234
+ }
235
+
236
+ /**
237
+ * A Cognito attribute's value from an aws CLI attribute list, or null.
238
+ * @param {unknown} attributes @param {string} name
239
+ * @returns {string|null}
240
+ */
241
+ function attributeOf(attributes, name) {
242
+ const found = (Array.isArray(attributes) ? attributes : []).find((/** @type {{ Name?: string }} */ a) => a && a.Name === name)
243
+ return found && found.Value ? String(found.Value) : null
244
+ }
245
+
246
+ /**
247
+ * Check the target (manifest vs flags, the caller's account, the stack's outputs) and build the registry and its ports
248
+ * with the owner's credentials. Nothing is written until every check passed.
249
+ * @param {Record<string, any>} flags @param {ReturnType<typeof instanceOf>} instance @param {Record<string, any>} deps
250
+ */
251
+ async function standaloneTarget(flags, instance, deps) {
252
+ const management = loadManagement()
253
+ const manifest = checkedManifest(required(flags, 'manifest'), instance, management)
254
+ const exec = deps.exec || defaultExec
255
+ const awsArgs = ['--region', manifest.region, ...(flags.profile ? ['--profile', String(flags.profile)] : [])]
256
+ const identity = JSON.parse(exec('aws', ['sts', 'get-caller-identity', '--output', 'json', ...awsArgs]))
257
+ if (identity.Account !== manifest.accountId) throw new Error(`your credentials are for account ${identity.Account}, not the manifest's ${manifest.accountId}`)
258
+ const outputs = Object.fromEntries((JSON.parse(exec('aws', ['cloudformation', 'describe-stacks', '--stack-name', manifest.stackName, '--query', 'Stacks[0].Outputs', '--output', 'json', ...awsArgs])) || [])
259
+ .map((/** @type {{ OutputKey: string, OutputValue: string }} */ o) => [o.OutputKey, o.OutputValue]))
260
+ if (outputs.UserPoolId !== manifest.userPoolId) throw new Error(`stack ${manifest.stackName} reports UserPoolId ${outputs.UserPoolId || '(none)'}, not the manifest's`)
261
+ if (outputs.ManagementTableName !== manifest.managementTableName) throw new Error(`stack ${manifest.stackName} reports ManagementTableName ${outputs.ManagementTableName || '(none)'}, not the manifest's`)
262
+ const credentials = deps.credentials || (() => awsCredentials({ profile: flags.profile }))
263
+ const doc = deps.doc || standaloneDocumentClient(manifest.region, credentials)
264
+ return {
265
+ management,
266
+ actor: { kind: 'aws-principal', id: identity.Arn },
267
+ registry: management.createManagementRegistry({ doc, tableName: manifest.managementTableName, serviceRef: manifest.serviceRef }),
268
+ accounts: poolAccounts({ exec, awsArgs, userPoolId: manifest.userPoolId }),
269
+ // The stack's own core table: an owner invitation claims its suid's onboarding marker there first, and a grant finds
270
+ // its grantee's account there.
271
+ coreTableName: outputs.CoreTableName || null,
272
+ identity: outputs.CoreTableName ? management.coreIdentity({ doc, tableName: outputs.CoreTableName }) : undefined,
273
+ material: ssmMaterial({ region: manifest.region, credentials, basePath: manifest.managementMaterialPath, fetchImpl: deps.fetch || fetch }),
274
+ }
275
+ }
276
+
277
+ /**
278
+ * DynamoDB with the owner's credentials (the registry's conditional writes are the authorization: no IAM write, no change).
279
+ * @param {string} region @param {() => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }} credentials
280
+ */
281
+ function standaloneDocumentClient(region, credentials) {
282
+ const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
283
+ const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
284
+ return DynamoDBDocumentClient.from(new DynamoDBClient({ region, credentials: async () => credentials() }), { marshallOptions: { removeUndefinedValues: true } })
285
+ }
286
+
287
+ // ---- output -------------------------------------------------------------------------------------------------------
288
+
289
+ /**
290
+ * The lines a result prints: owners and outcomes, key ids and states with age, grants; never an email, hash or raw key.
291
+ * @param {Record<string, any>} result
292
+ * @returns {string[]}
293
+ */
294
+ function formatResult(result) {
295
+ if (Array.isArray(result.owners)) return result.owners.map((o) => `${o.suid} ${o.account || ''} ${o.outcome}`.replace(/\s{3,}/g, ' '))
296
+ if (Array.isArray(result.callers)) {
297
+ const lines = []
298
+ for (const c of result.callers) {
299
+ const keys = c.keys || []
300
+ if (c.callerType === 'machine') {
301
+ if (keys.length === 0) lines.push(`${c.callerId} (no keys) ${c.purposes.join(',')}`)
302
+ for (const k of keys) lines.push(`${c.callerId} ${k.keyId} ${k.state} age ${k.ageDays}d ${c.purposes.join(',')}`)
303
+ } else {
304
+ lines.push(`${c.callerId} grant ${c.status} ${c.purposes.join(',')}`)
305
+ }
306
+ }
307
+ return lines.length ? lines : ['no local management callers']
308
+ }
309
+ if (result.principal) return [`${result.principal} ${result.outcome}`]
310
+ if (result.keyId) return [`${result.callerId} ${result.keyId} ${result.state || (result.phase === 'introduce' ? 'next (pending)' : '')}${result.reused ? ' (pending key re-issued)' : ''}`]
311
+ return [JSON.stringify(result)]
312
+ }
313
+
314
+ // ---- managed: through the control plane ---------------------------------------------------------------------------
315
+
316
+ const ROUTE = { bootstrap: 'bootstrap', keys: 'keys', grants: 'grants' }
317
+
318
+ /**
319
+ * One managed request: the deployment must be the named target; the owner route starts the operation; an issued key goes
320
+ * only to --output.
321
+ * @param {string} sub @param {Record<string, any>} request @param {ReturnType<typeof instanceOf>} instance @param {Record<string, any>} flags
322
+ * @param {(line: string) => void} log
323
+ */
324
+ async function managedRequest(sub, request, instance, flags, log) {
325
+ const { action, ...attributes } = request
326
+ if (attributes.recover) delete attributes.recover
327
+ const file = String(flags.output)
328
+ const fd = action === 'key' && request.phase === 'introduce' ? claimKeyFile(file) : null
329
+ let attrs
330
+ try {
331
+ const doc = await apiCall('POST', `/api/deployments/${encodeURIComponent(instance.deploymentId)}/services/${encodeURIComponent(instance.serviceRef)}/admin/${ROUTE[/** @type {keyof typeof ROUTE} */ (sub)]}`,
332
+ { data: { type: 'management-requests', attributes } }, flags, { headers: { 'Idempotency-Key': `cli-${crypto.randomUUID()}` } })
333
+ attrs = (doc && doc.data && doc.data.attributes) || {}
334
+ if (fd !== null && attrs.key) fs.writeSync(fd, `${attrs.key}\n`)
335
+ } catch (err) {
336
+ if (fd !== null) {
337
+ fs.closeSync(fd)
338
+ fs.rmSync(file, { force: true })
339
+ }
340
+ throw err
341
+ }
342
+ if (fd !== null) {
343
+ fs.closeSync(fd)
344
+ if (!attrs.key) fs.rmSync(file, { force: true })
345
+ }
346
+ if (attrs.key) log(`key ${attrs.keyId} for ${request.callerId} written to ${file} (pending until activated)`)
347
+ log(`operation ${attrs.operationId} ${attrs.status || 'started'} — follow with \`saaslayer operations watch ${attrs.operationId} --deployment ${instance.deploymentId}\``)
348
+ if (flags.wait) {
349
+ const { followOperation } = require('./operations')
350
+ const final = await followOperation({ deploymentId: instance.deploymentId, operationId: attrs.operationId, flags })
351
+ const component = (final.components || []).find((c) => c.name === 'management')
352
+ const result = component && component.detail && component.detail.request && component.detail.request.result
353
+ if (result) for (const line of formatResult(result)) log(line)
354
+ }
355
+ return attrs
356
+ }
357
+
358
+ /**
359
+ * Run `saaslayer users admin <sub>`. deps (tests): exec, fetch, doc, credentials, log.
360
+ * @param {string} sub @param {Record<string, any>} flags @param {Record<string, any>} [deps]
361
+ */
362
+ async function usersManagement(sub, flags, deps = {}) {
363
+ if (!SUBCOMMANDS.includes(sub)) throw new Error(USAGE)
364
+ const log = deps.log || ((/** @type {string} */ line) => console.log(line))
365
+ const instance = instanceOf(flags)
366
+ const requests = requestsOf(sub, flags)
367
+ if (!flags.manifest) {
368
+ const deployment = await apiCall('GET', `/api/deployments/${encodeURIComponent(instance.deploymentId)}`, undefined, flags)
369
+ const d = (deployment && deployment.data && deployment.data.attributes) || {}
370
+ if (d.accountId !== instance.accountId) throw new Error(`deployment ${instance.deploymentId} is in account ${d.accountId}, not ${instance.accountId}`)
371
+ if (d.region !== instance.region) throw new Error(`deployment ${instance.deploymentId} is in region ${d.region}, not ${instance.region}`)
372
+ const results = []
373
+ for (const request of requests) results.push(await managedRequest(sub, request, instance, flags, log))
374
+ return results
375
+ }
376
+ const target = await standaloneTarget(flags, instance, deps)
377
+ if (requests.some((r) => r.action === 'bootstrap' || (r.action === 'grant' && r.phase === 'grant')) && !target.coreTableName) {
378
+ throw new Error('the stack reports no CoreTableName output: deploy the release that adds it before bootstrapping or granting')
379
+ }
380
+ const results = []
381
+ for (const request of requests) {
382
+ const { management, registry, accounts, identity, material, actor } = target
383
+ let result
384
+ try {
385
+ result = await management.applyManagementRequest({ registry, accounts, identity, request, actor, material })
386
+ } catch (err) {
387
+ const e = /** @type {Error & { code?: string }} */ (err)
388
+ throw new Error(e.code ? `${e.code}: ${e.message}` : e.message)
389
+ }
390
+ if (result.key) {
391
+ writeKeyFile(String(flags.output), String(result.key))
392
+ log(`key ${result.keyId} for ${result.callerId} written to ${flags.output} (pending until activated)`)
393
+ delete result.key
394
+ }
395
+ for (const line of formatResult(result)) log(line)
396
+ results.push(result)
397
+ }
398
+ return results
399
+ }
400
+
401
+ module.exports = { usersManagement, requestsOf, formatResult, ssmMaterial, loadManagement, USAGE, SUBCOMMANDS }
@@ -16,6 +16,12 @@
16
16
  # it is the deployment-artifact spine that rollback, provenance, supply-chain scanning, and audit hang off.
17
17
  # Likely future occupants (not built yet — this stack is designed to hold them): a per-region KMS key, an
18
18
  # access-log bucket, an ops-alert SNS topic, deploy-notification queues, VPC endpoints.
19
+ #
20
+ # OPTIONAL — the account's email sender domain (EmailSenderDomain). An SES identity belongs to an account+region,
21
+ # not to one deployment, so it lives here. This stack is installed with the CUSTOMER's own credentials
22
+ # (`saaslayer aws connect` / `saaslayer foundation upgrade --email-sender-domain`), so SaaSLayer's deploy role never
23
+ # creates or verifies identities (tests/bootstrap.test.js). The DKIM records it outputs go into the customer's DNS;
24
+ # once verified, deployments send through it via the user-service CognitoEmailSenderArn setting.
19
25
  AWSTemplateFormatVersion: '2010-09-09'
20
26
  Description: >-
21
27
  SaaSLayer per-region foundation stack: region-bound resources for a SaaSLayer host account, starting
@@ -33,6 +39,16 @@ Parameters:
33
39
  deployer refs.ts) and passes it, guaranteeing the bucket and the injected SERVERLESS_DEPLOYMENT_BUCKET
34
40
  agree byte-for-byte. Opaque (no raw account id) so a globally-probeable S3 name never confirms the
35
41
  account is SaaSLayer-managed.
42
+ EmailSenderDomain:
43
+ Type: String
44
+ Default: ''
45
+ AllowedPattern: '^(([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63})?$'
46
+ Description: >-
47
+ Optional domain this account sends email from (e.g. acme.com). When set, an SES identity with Easy DKIM is
48
+ created and its three DKIM CNAME records are output for the domain's DNS. Empty = no sender domain.
49
+
50
+ Conditions:
51
+ HasEmailSenderDomain: !Not [!Equals [!Ref EmailSenderDomain, '']]
36
52
 
37
53
  Mappings:
38
54
  # Per-region foundation template version (semver). BUMP on every change so ops can tell which regional
@@ -40,7 +56,7 @@ Mappings:
40
56
  # saaslayer-foundation: major = breaking change (resource replaced/removed), minor = additive, patch = docs.
41
57
  Meta:
42
58
  FoundationRegion:
43
- Version: '1.0.0'
59
+ Version: '1.1.0'
44
60
 
45
61
  Resources:
46
62
  # Shared deployment-artifact bucket. Serverless namespaces every deploy under
@@ -100,7 +116,27 @@ Resources:
100
116
  Bool:
101
117
  aws:SecureTransport: 'false'
102
118
 
119
+ # The account's email sender domain (see the header). Easy DKIM: SES generates the keys and rotates them; the
120
+ # customer adds the three CNAMEs in EmailSenderDkimRecords to the domain's DNS to verify it.
121
+ EmailSenderIdentity:
122
+ Type: AWS::SES::EmailIdentity
123
+ Condition: HasEmailSenderDomain
124
+ Properties:
125
+ EmailIdentity: !Ref EmailSenderDomain
126
+
103
127
  Outputs:
128
+ EmailSenderIdentityArn:
129
+ Condition: HasEmailSenderDomain
130
+ Description: SES identity ARN of the account's email sender domain (the user-service CognitoEmailSenderArn setting).
131
+ Value: !Sub arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${EmailSenderDomain}
132
+ EmailSenderDkimRecords:
133
+ Condition: HasEmailSenderDomain
134
+ Description: The three DKIM CNAME records ('name CNAME value', one per line) to add to the sender domain's DNS.
135
+ Value: !Join
136
+ - "\n"
137
+ - - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName1, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue1]]
138
+ - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName2, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue2]]
139
+ - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName3, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue3]]
104
140
  ArtifactsBucketName:
105
141
  Description: Shared deployment-artifact bucket every SaaSLayer service in this account+region deploys into.
106
142
  Value: !Ref DeploymentArtifactBucket
@@ -15,7 +15,8 @@
15
15
  # 1. SaaSLayerDeploymentRole — the only cross-account WRITE entry point. Assumable solely by the
16
16
  # SaaSLayer control-plane account (ControlPlaneAccountId parameter) and only with the shared
17
17
  # ExternalId. It can drive the CloudFormation lifecycle of stacks whose names start with
18
- # StackNamePrefix (default "sl-"), read/write the deployment artifact buckets, and pass exactly
18
+ # StackNamePrefix (default "sl-"), read/write the deployment artifact buckets, update the
19
+ # configuration of StackNamePrefix functions (credential hot-swap), and pass exactly
19
20
  # one role (SaaSLayerCloudFormationExecutionRole) to CloudFormation. It cannot create IAM
20
21
  # resources or touch anything outside the managed stack namespace directly. Its only
21
22
  # sts:AssumeRole grant is into a module stack's own data-migration role
@@ -34,7 +35,8 @@
34
35
  # It carries only Get/List/Describe verbs, is tag-scoped to resources carrying
35
36
  # managed-by=saaslayer-deployer where IAM supports resource-tag conditions, and deliberately
36
37
  # excludes all data-plane reads (no S3 object reads, no DynamoDB item reads, no SSM parameter
37
- # values, no Secrets Manager secret values).
38
+ # values, no Secrets Manager secret values, no function code downloads). An explicit Deny
39
+ # (DenySecretValueReads) covers the /saaslayer/deployment/* SecureStrings and their KMS decrypt.
38
40
  #
39
41
  # SaaSLayerManagedResourceBoundary is a permissions boundary attached to every IAM role that
40
42
  # SaaSLayer module templates create: whatever a module role's own policy says, its effective
@@ -113,7 +115,7 @@ Mappings:
113
115
  # patch = comments/docs/no behavior change
114
116
  Meta:
115
117
  Foundation:
116
- Version: '5.12.0'
118
+ Version: '6.0.0'
117
119
 
118
120
  Resources:
119
121
  # The shared deployment-artifact bucket moved OUT of this account-global stack into the per-region
@@ -640,6 +642,12 @@ Resources:
640
642
  # secret from an SSM SecureString (/saaslayer/deployment/*); kms:Decrypt above covers the
641
643
  # SecureString's aws/ssm key.
642
644
  - ssm:GetParameter
645
+ # ssm SecretDelivery: user-service reads its create-only integration-credential generations by path
646
+ # (/saaslayer/deployment/<dep>/<inst>/users/integration-credentials); its role scopes the path.
647
+ - ssm:GetParametersByPath
648
+ # ssm SecretDelivery: user-service reads its permissions handoff parameters in one batch call; its role
649
+ # names the exact parameters.
650
+ - ssm:GetParameters
643
651
  Resource: '*'
644
652
  # PITR check + opt-in on-demand backup for per-service migrate roles (@saaslayer/migrations).
645
653
  # Managed-prefix tables only. The boundary is account-global and the role policies do the
@@ -779,6 +787,14 @@ Resources:
779
787
  - lambda:ListTags
780
788
  - lambda:ListVersionsByFunction
781
789
  Resource: '*'
790
+ # Env-mode credential hot-swap: revoke/rotate updates a managed function's environment directly
791
+ # (UpdateFunctionConfiguration with RevisionId, read back with GetFunctionConfiguration above) instead
792
+ # of a stack deploy. Managed-prefix functions only.
793
+ - Sid: HotSwapFunctionConfiguration
794
+ Effect: Allow
795
+ Action:
796
+ - lambda:UpdateFunctionConfiguration
797
+ Resource: !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${StackNamePrefix}*
782
798
  # Post-deploy SEED data-plane: after a module deploys, the deployer runs its seed
783
799
  # script under this role to make the deployment usable — bootstrap the tenant, the
784
800
  # designated first admin's deployment-administrator binding (and an explicit recovery's
@@ -937,7 +953,11 @@ Resources:
937
953
  # account + external ID) and additionally pins the session name to saaslayer-support-* so each
938
954
  # assumption is attributable in CloudTrail. Grants carry only Get/List/Describe verbs — enforced
939
955
  # by tests/bootstrap.test.js — and exclude all data-plane reads: no S3 object reads, no DynamoDB
940
- # item reads, no SSM parameter values, no Secrets Manager secret values.
956
+ # item reads, no SSM parameter values, no Secrets Manager secret values, no function code downloads.
957
+ # Function configuration and stack templates stay readable: with SecretDelivery=env (the default) they
958
+ # carry the deployment's generated secrets (an accepted risk; this role trusts the same principals as the
959
+ # deployment role). With SecretDelivery=ssm they carry only parameter paths, and DenySecretValueReads
960
+ # blocks the values.
941
961
  SaaSLayerSupportReadOnlyRole:
942
962
  Type: AWS::IAM::Role
943
963
  Properties:
@@ -993,8 +1013,8 @@ Resources:
993
1013
  - dynamodb:ListTagsOfResource
994
1014
  - events:DescribeEventBus
995
1015
  - events:ListTagsForResource
1016
+ # No lambda:GetFunction: it returns a presigned code download URL. Configuration reads stay.
996
1017
  - lambda:GetAlias
997
- - lambda:GetFunction
998
1018
  - lambda:GetFunctionConfiguration
999
1019
  - lambda:GetFunctionEventInvokeConfig
1000
1020
  - lambda:GetPolicy
@@ -1031,6 +1051,22 @@ Resources:
1031
1051
  - cloudwatch:GetDashboard
1032
1052
  - cloudwatch:ListDashboards
1033
1053
  Resource: '*'
1054
+ # DenySecretValueReads: deployments with SecretDelivery=ssm keep generated secrets as SecureStrings
1055
+ # under /saaslayer/deployment/*. The role has no Allow for them; these Denies make that explicit, in
1056
+ # every region, so no later Allow (here or attached out of band) can read a secret value.
1057
+ - Sid: DenySecretValueReads
1058
+ Effect: Deny
1059
+ Action:
1060
+ - ssm:GetParameter*
1061
+ Resource: !Sub arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:parameter/saaslayer/deployment/*
1062
+ - Effect: Deny
1063
+ Action:
1064
+ - kms:Decrypt
1065
+ Resource: '*'
1066
+ Condition:
1067
+ StringLike:
1068
+ kms:ViaService: ssm.*.amazonaws.com
1069
+ kms:EncryptionContext:PARAMETER_ARN: !Sub arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:parameter/saaslayer/deployment/*
1034
1070
 
1035
1071
  Outputs:
1036
1072
  DeploymentRoleArn: