saaslayer 0.0.7 → 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/README.md +150 -13
- package/bin/saaslayer.js +318 -66
- package/package.json +4 -3
- package/src/api-client.js +48 -28
- package/src/aws-sigv4.js +1 -1
- package/src/commands/access-admins.js +73 -0
- package/src/commands/accounts.js +32 -3
- package/src/commands/activity.js +33 -0
- package/src/commands/aws.js +55 -6
- package/src/commands/catalog.js +30 -29
- package/src/commands/context.js +64 -0
- package/src/commands/deploy.js +79 -10
- package/src/commands/first-admin.js +42 -0
- package/src/commands/foundation.js +456 -0
- package/src/commands/integration-credentials.js +66 -0
- package/src/commands/lifecycle.js +77 -40
- package/src/commands/login.js +200 -26
- package/src/commands/machine-trust.js +96 -0
- package/src/commands/operations.js +140 -0
- package/src/commands/orgs.js +29 -4
- package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
- package/src/commands/release-manifest.js +138 -0
- package/src/commands/service-principals.js +81 -0
- package/src/commands/settings.js +140 -0
- package/src/commands/stacks.js +12 -7
- package/src/commands/users-management.js +401 -0
- package/src/commands/users.js +192 -4
- package/src/config.js +20 -7
- package/src/credentials.js +221 -34
- package/src/deployment-api-auth.js +61 -0
- package/src/deployment-auth.js +38 -0
- package/src/deployments.js +12 -13
- package/src/discovery.js +66 -0
- package/src/env-compare.js +143 -0
- package/src/iam-session.js +4 -30
- package/src/module-catalog.js +66 -0
- package/src/permissions-request.js +43 -0
- package/src/release-manifest.js +334 -0
- package/src/scope.js +114 -0
- package/src/settings.js +272 -0
- package/src/users-api.js +165 -0
- package/src/users-import/import.js +10 -10
- package/templates/saaslayer-foundation-region.yml +37 -1
- package/templates/saaslayer-foundation.yml +63 -10
- package/src/commands/iam-principals.js +0 -53
- package/src/rbac-auth.js +0 -25
- package/vendor/ids/index.d.ts +0 -21
- package/vendor/ids/index.js +0 -237
package/src/commands/deploy.js
CHANGED
|
@@ -1,20 +1,80 @@
|
|
|
1
1
|
// `saaslayer deploy` (swf2.7) — self-serve deploy of the customer's project into their connected account.
|
|
2
2
|
// POSTs to the BFF (Bearer id token); the BFF authorizes the caller, resolves the target, and calls the
|
|
3
3
|
// deployer. Handles the two-step cost-confirm (D14): the first call returns NEEDS_CONFIRMATION with an
|
|
4
|
-
// estimate; on y (or --yes) we re-send confirmCost:true.
|
|
4
|
+
// estimate; on y (or --yes) we re-send confirmCost:true. Then waits for the deploy operation unless --no-wait.
|
|
5
5
|
'use strict'
|
|
6
|
-
const
|
|
6
|
+
const { resolveScope, printScope } = require('../scope')
|
|
7
7
|
const { apiCall } = require('../api-client')
|
|
8
8
|
const { confirm } = require('../prompt')
|
|
9
|
+
const { finishMutation } = require('./operations')
|
|
10
|
+
const { fetchModuleCatalog, checkModuleIds, checkDependencies, checkParamModules } = require('../module-catalog')
|
|
11
|
+
const { parseSetFlags, readSettingsFile, mergePatches, checkPatch } = require('../settings')
|
|
12
|
+
const { fetchSchema } = require('./settings')
|
|
9
13
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Module ids from --services a,b and --module (repeatable, comma-separated).
|
|
16
|
+
* @param {object} flags
|
|
17
|
+
* @returns {string[]|undefined}
|
|
18
|
+
*/
|
|
19
|
+
function selectedModules(flags) {
|
|
20
|
+
const raw = [flags.services, flags.module].flat().filter((v) => typeof v === 'string')
|
|
21
|
+
const ids = [...new Set(raw.flatMap((v) => v.split(',')).map((s) => s.trim()).filter(Boolean))]
|
|
22
|
+
return ids.length ? ids : undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Check create settings against each module's schema at the revision being deployed (--commit-sha, else the default
|
|
27
|
+
* release the catalog reports) and name the create-only ones. With no known revision the control plane checks them.
|
|
28
|
+
* @param {Record<string, Record<string, unknown>>} parameters
|
|
29
|
+
* @param {string|undefined} commitSha
|
|
30
|
+
* @param {import('../module-catalog').CatalogModule[]} modules
|
|
31
|
+
* @param {object} flags
|
|
32
|
+
*/
|
|
33
|
+
async function checkCreateSettings(parameters, commitSha, modules, flags) {
|
|
34
|
+
/** @param {string} id */
|
|
35
|
+
const revisionOf = (id) => commitSha || (modules.find((m) => m.id === id) || { attributes: {} }).attributes.revision
|
|
36
|
+
const ids = Object.keys(parameters)
|
|
37
|
+
if (ids.some((id) => !revisionOf(id))) {
|
|
38
|
+
console.log(' the control plane reports no default release, so settings are checked by the control plane only (pass --commit-sha to check them here first)')
|
|
39
|
+
return parameters
|
|
40
|
+
}
|
|
41
|
+
const schemas = Object.fromEntries(await Promise.all(ids.map(async (id) => [id, await fetchSchema(id, String(revisionOf(id)), flags)])))
|
|
42
|
+
const { patch, createOnly } = checkPatch(parameters, schemas, { op: 'create' })
|
|
43
|
+
if (createOnly.length) console.log(` create-only (fixed once deployed): ${createOnly.join(', ')}`)
|
|
44
|
+
return patch
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {Record<string, any>} flags
|
|
49
|
+
* @param {{ interactive?: boolean, confirm?: (question: string) => Promise<boolean> }} [io] test seams: whether a person can
|
|
50
|
+
* answer (default: stdin is a terminal) and how they are asked
|
|
51
|
+
*/
|
|
52
|
+
async function deploy(flags, io = {}) {
|
|
53
|
+
const interactive = io.interactive === undefined ? Boolean(process.stdin.isTTY) : io.interactive
|
|
54
|
+
const ask = io.confirm || confirm
|
|
55
|
+
const yes = flags.yes === true || flags.yes === 'true'
|
|
56
|
+
const scope = resolveScope(flags, { env: 'prod' })
|
|
57
|
+
printScope(scope, flags)
|
|
58
|
+
const project = scope.project.value
|
|
59
|
+
const environment = scope.env.value
|
|
60
|
+
const services = selectedModules(flags)
|
|
15
61
|
// Accept the documented kebab flag (--commit-sha) as well as the camelCase form; parseArgs keys by the
|
|
16
62
|
// literal flag, so --commit-sha lands in flags['commit-sha'].
|
|
17
63
|
const commitSha = flags['commit-sha'] || flags.commitSha
|
|
64
|
+
// A settings file is input to this deploy; --set / --param values override it.
|
|
65
|
+
let parameters = mergePatches(typeof flags.settings === 'string' ? readSettingsFile(flags.settings) : undefined, parseSetFlags(flags.param, '--param'), parseSetFlags(flags.set, '--set'))
|
|
66
|
+
// Module ids, dependencies and --param module keys are checked against the catalog before anything is sent.
|
|
67
|
+
if (services || parameters) {
|
|
68
|
+
const modules = await fetchModuleCatalog(flags)
|
|
69
|
+
if (services) {
|
|
70
|
+
checkModuleIds(services, modules)
|
|
71
|
+
checkDependencies(services, modules)
|
|
72
|
+
}
|
|
73
|
+
if (parameters) {
|
|
74
|
+
checkParamModules(parameters, modules)
|
|
75
|
+
parameters = await checkCreateSettings(parameters, commitSha, modules, flags)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
18
78
|
|
|
19
79
|
const attributes = {
|
|
20
80
|
customerId: project,
|
|
@@ -24,9 +84,16 @@ async function deploy(flags) {
|
|
|
24
84
|
...(flags.target ? { targetAccountId: flags.target } : {}),
|
|
25
85
|
...(commitSha ? { commitSha } : {}),
|
|
26
86
|
...(flags['admin-email'] ? { adminEmail: flags['admin-email'] } : {}),
|
|
87
|
+
...(parameters ? { parameters } : {}),
|
|
27
88
|
}
|
|
28
89
|
|
|
29
|
-
|
|
90
|
+
// Creating a deployment is never implicit: --yes, or a person confirms before the first create request is sent.
|
|
91
|
+
const what = `${services ? services.join(' + ') : 'the default services'} to ${project}/${environment}${flags.region ? '/' + flags.region : ''}`
|
|
92
|
+
if (!yes) {
|
|
93
|
+
if (!interactive) throw new Error(`deploy creates a deployment (${what}); pass --yes to confirm when running non-interactively`)
|
|
94
|
+
if (!(await ask(`Create a deployment: ${what}${flags.target ? ` in account ${flags.target}` : ''}?`))) { console.log('Aborted.'); return null }
|
|
95
|
+
}
|
|
96
|
+
console.log(`Deploying ${what}…`)
|
|
30
97
|
let res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes }, }, flags)
|
|
31
98
|
|
|
32
99
|
// Cost-confirm (D14): the BFF returns a deployment-estimate with status NEEDS_CONFIRMATION.
|
|
@@ -34,7 +101,7 @@ async function deploy(flags) {
|
|
|
34
101
|
const est = res.data.attributes.estimate || {}
|
|
35
102
|
const monthly = est.monthlyUsd != null ? `$${est.monthlyUsd}/mo` : 'an unknown monthly cost'
|
|
36
103
|
console.log(` Estimated cost: ${monthly}.`)
|
|
37
|
-
const ok =
|
|
104
|
+
const ok = yes || (interactive && (await ask('Proceed with the deploy?')))
|
|
38
105
|
if (!ok) { console.log('Aborted.'); return null }
|
|
39
106
|
res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes: { ...attributes, confirmCost: true } } }, flags)
|
|
40
107
|
}
|
|
@@ -42,7 +109,9 @@ async function deploy(flags) {
|
|
|
42
109
|
const dep = res.data || {}
|
|
43
110
|
const run = dep.attributes && dep.attributes.run
|
|
44
111
|
console.log(`✅ deploy started: deployment ${dep.id}${run && run.runId ? ` (run ${run.runId})` : ''}`)
|
|
45
|
-
console.log(`
|
|
112
|
+
console.log(` status: saaslayer status --project ${project}${flags.region ? ' --region ' + flags.region : ''}`)
|
|
113
|
+
await finishMutation({ response: res, deploymentId: dep.id, flags })
|
|
114
|
+
if (res.operation) dep.operation = res.operation
|
|
46
115
|
return dep
|
|
47
116
|
}
|
|
48
117
|
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// `saaslayer first-admin resend|recover` (authorization matrix B2/B3): resend the designated first admin's first sign-in,
|
|
2
|
+
// or designate a new first admin when no usable access admin remains; waits for the operation that does it.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { apiCall } = require('../api-client')
|
|
5
|
+
const { resolveDeployment } = require('../deployments')
|
|
6
|
+
const { finishMutation, requestKeyHeaders } = require('./operations')
|
|
7
|
+
|
|
8
|
+
const USAGE = 'usage: saaslayer first-admin <resend|recover> [--deployment ID | --project P --env E --region R] [--email E --reason TEXT] [--suid ID] [--no-wait]'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The request attributes for a subcommand; refusals happen before anything is sent.
|
|
12
|
+
* @param {string|undefined} sub
|
|
13
|
+
* @param {Record<string, unknown>} flags
|
|
14
|
+
* @returns {{ action: 'resend'|'recover', adminEmail?: string, adminSuid?: string, reason?: string }}
|
|
15
|
+
*/
|
|
16
|
+
function requestOf(sub, flags) {
|
|
17
|
+
/** @param {unknown} v */
|
|
18
|
+
const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
|
|
19
|
+
const reason = text(flags.reason)
|
|
20
|
+
if (sub === 'resend') return { action: 'resend', ...(reason ? { reason } : {}) }
|
|
21
|
+
if (sub !== 'recover') throw new Error(USAGE)
|
|
22
|
+
const adminEmail = text(flags.email)
|
|
23
|
+
if (!adminEmail) throw new Error('first-admin recover needs --email <new admin email>')
|
|
24
|
+
if (!reason) throw new Error('first-admin recover needs --reason <text> (recorded in the deployment activity)')
|
|
25
|
+
const adminSuid = text(flags.suid)
|
|
26
|
+
return { action: 'recover', adminEmail, ...(adminSuid ? { adminSuid } : {}), reason }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {string|undefined} sub resend | recover
|
|
31
|
+
* @param {Record<string, unknown>} flags
|
|
32
|
+
*/
|
|
33
|
+
async function firstAdminCommand(sub, flags) {
|
|
34
|
+
const attributes = requestOf(sub, flags)
|
|
35
|
+
const deploymentId = typeof flags.deployment === 'string' ? flags.deployment : (await resolveDeployment(flags)).deploymentId
|
|
36
|
+
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/admin-bootstrap`, { data: { type: 'admin-bootstrap-requests', attributes } }, flags, { headers: requestKeyHeaders() })
|
|
37
|
+
const attrs = (res.data && res.data.attributes) || {}
|
|
38
|
+
console.log(`first-admin ${attributes.action} started: operation ${attrs.operationId || '—'} on deployment ${deploymentId}`)
|
|
39
|
+
return finishMutation({ response: res, deploymentId, flags })
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { firstAdminCommand }
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
// `saaslayer foundation status|upgrade`: compare the installed foundation stacks with this CLI's bundled templates, upgrade
|
|
2
|
+
// them in place via a reviewed change set keeping every parameter value, then have the control plane re-read the account.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const { execFileSync } = require('child_process')
|
|
6
|
+
const { FOUNDATION_TEMPLATE, FOUNDATION_REGION_TEMPLATE, foundationRegionStackName, emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords } = require('./aws')
|
|
7
|
+
const { stripComments, writeDeployableTemplate } = require('../foundation-template')
|
|
8
|
+
const { confirm: promptConfirm } = require('../prompt')
|
|
9
|
+
const { apiCall } = require('../api-client')
|
|
10
|
+
|
|
11
|
+
/** @param {string} cmd @param {string[]} args */
|
|
12
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 })
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {(input: { accountId: string, region: string }, flags: object) => Promise<{ foundationVersion?: string|null }>} Refresh
|
|
16
|
+
* @typedef {{ exec?: typeof defaultExec, log?: (...a: unknown[]) => void, confirm?: (q: string) => Promise<boolean>,
|
|
17
|
+
* sleep?: (ms: number) => Promise<void>, pollMs?: number, maxPolls?: number, refresh?: Refresh }} Deps
|
|
18
|
+
* @typedef {{ kind: 'account'|'region', stackName: string, template: string, outputKey: string, capabilities: string[] }} Target
|
|
19
|
+
* @typedef {{ status: string, version: string|null, paramKeys: string[], params: Record<string, string>, outputs: Array<{ OutputKey: string, OutputValue: string }>, lastUpdated: string|null }} InstalledStack
|
|
20
|
+
* @typedef {{ action: string, logicalId: string, type: string, replacement: string, scope: string[] }} Change
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Stack states a change set can be created and executed from. */
|
|
24
|
+
const STABLE_STATUSES = ['CREATE_COMPLETE', 'UPDATE_COMPLETE', 'UPDATE_ROLLBACK_COMPLETE', 'IMPORT_COMPLETE', 'IMPORT_ROLLBACK_COMPLETE']
|
|
25
|
+
|
|
26
|
+
/** Resource types whose removal would cut the control plane's access or the account's deploy spine. */
|
|
27
|
+
const PROTECTED_REMOVE_TYPES = ['AWS::IAM::Role', 'AWS::IAM::ManagedPolicy', 'AWS::IAM::Policy', 'AWS::S3::Bucket']
|
|
28
|
+
|
|
29
|
+
/** CloudFormation's change-set status reasons when the template + params match what is installed. */
|
|
30
|
+
const NO_CHANGES = /didn't contain changes|No updates are to be performed/i
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The bundled template's version (Mappings.Meta.<name>.Version) and its parameters with their defaults.
|
|
34
|
+
* @param {string} text template YAML
|
|
35
|
+
* @returns {{ version: string|null, parameters: { name: string, hasDefault: boolean, default?: string }[] }}
|
|
36
|
+
*/
|
|
37
|
+
function templateInfo(text) {
|
|
38
|
+
const lines = stripComments(text).split('\n')
|
|
39
|
+
const versionMatch = /^ {2}Meta:\s*\n {4}\w+:\s*\n {6}Version:\s*'?([^'\s]+)'?/m.exec(lines.join('\n'))
|
|
40
|
+
const parameters = []
|
|
41
|
+
const start = lines.indexOf('Parameters:')
|
|
42
|
+
if (start !== -1) {
|
|
43
|
+
for (let i = start + 1; i < lines.length && !/^\S/.test(lines[i]); i++) {
|
|
44
|
+
const name = /^ {2}(\w+):\s*$/.exec(lines[i])
|
|
45
|
+
if (name) { parameters.push({ name: name[1], hasDefault: false }); continue }
|
|
46
|
+
const def = /^ {4}Default:\s*(.*)$/.exec(lines[i])
|
|
47
|
+
if (def && parameters.length) {
|
|
48
|
+
const current = parameters[parameters.length - 1]
|
|
49
|
+
current.hasDefault = true
|
|
50
|
+
current.default = def[1].trim().replace(/^'(.*)'$/, '$1').replace(/^"(.*)"$/, '$1')
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return { version: versionMatch ? versionMatch[1] : null, parameters }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Change-set parameters for an upgrade: every parameter the stack already has keeps its previous value (no value is
|
|
59
|
+
* ever passed), a parameter new in the template takes its default, and one the template dropped is left out.
|
|
60
|
+
* @param {{ name: string, hasDefault: boolean, default?: string }[]} templateParams
|
|
61
|
+
* @param {string[]} installedKeys
|
|
62
|
+
*/
|
|
63
|
+
function upgradeParameters(templateParams, installedKeys) {
|
|
64
|
+
const parameters = []
|
|
65
|
+
const added = []
|
|
66
|
+
const missing = []
|
|
67
|
+
for (const p of templateParams) {
|
|
68
|
+
if (installedKeys.includes(p.name)) parameters.push({ ParameterKey: p.name, UsePreviousValue: true })
|
|
69
|
+
else if (p.hasDefault) added.push({ name: p.name, default: p.default })
|
|
70
|
+
else missing.push(p.name)
|
|
71
|
+
}
|
|
72
|
+
if (missing.length) {
|
|
73
|
+
throw new Error(`the bundled template needs new parameter(s) ${missing.join(', ')} with no default; this upgrade cannot supply them`)
|
|
74
|
+
}
|
|
75
|
+
const removed = installedKeys.filter((k) => !templateParams.some((p) => p.name === k))
|
|
76
|
+
return { parameters, added, removed }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Numeric semver comparison (major.minor.patch).
|
|
81
|
+
* @param {string} a
|
|
82
|
+
* @param {string} b
|
|
83
|
+
* @returns {-1|0|1}
|
|
84
|
+
*/
|
|
85
|
+
function compareVersions(a, b) {
|
|
86
|
+
const pa = String(a).split('.').map(Number)
|
|
87
|
+
const pb = String(b).split('.').map(Number)
|
|
88
|
+
for (let i = 0; i < 3; i++) {
|
|
89
|
+
if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0) ? 1 : -1
|
|
90
|
+
}
|
|
91
|
+
return 0
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @param {Change[]} changes */
|
|
95
|
+
function blockingChanges(changes) {
|
|
96
|
+
return changes.filter((c) => c.replacement === 'True' || (c.action === 'Remove' && PROTECTED_REMOVE_TYPES.includes(c.type)))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** @param {Change[]} changes */
|
|
100
|
+
function conditionalChanges(changes) {
|
|
101
|
+
return changes.filter((c) => c.replacement === 'Conditional')
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The foundation stacks a command acts on: the account-global IAM stack and the per-region stack.
|
|
106
|
+
* @param {object} flags
|
|
107
|
+
* @returns {{ region: string, targets: Target[] }}
|
|
108
|
+
*/
|
|
109
|
+
function resolveTargets(flags) {
|
|
110
|
+
const region = flags.region || process.env.AWS_REGION || 'us-east-1'
|
|
111
|
+
const only = flags.only
|
|
112
|
+
if (only !== undefined && only !== 'account' && only !== 'region') throw new Error('--only expects account or region')
|
|
113
|
+
/** @type {Target[]} */
|
|
114
|
+
const all = [
|
|
115
|
+
{ kind: 'account', stackName: flags['stack-name'] || 'saaslayer-foundation', template: FOUNDATION_TEMPLATE, outputKey: 'FoundationVersion', capabilities: ['CAPABILITY_NAMED_IAM'] },
|
|
116
|
+
{ kind: 'region', stackName: foundationRegionStackName(region), template: FOUNDATION_REGION_TEMPLATE, outputKey: 'FoundationRegionVersion', capabilities: [] },
|
|
117
|
+
]
|
|
118
|
+
return { region, targets: only ? all.filter((t) => t.kind === only) : all }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Runs `aws <args>` with the caller's region/profile and parses the JSON reply.
|
|
123
|
+
* @param {typeof defaultExec} exec
|
|
124
|
+
* @param {object} flags
|
|
125
|
+
* @param {string} region
|
|
126
|
+
*/
|
|
127
|
+
function awsRunner(exec, flags, region) {
|
|
128
|
+
return (args) => {
|
|
129
|
+
const full = [...args, '--region', region, ...(flags.profile ? ['--profile', flags.profile] : []), '--output', 'json']
|
|
130
|
+
let out
|
|
131
|
+
try {
|
|
132
|
+
out = exec('aws', full)
|
|
133
|
+
} catch (err) {
|
|
134
|
+
const detail = String(err.stderr || err.message || '').trim()
|
|
135
|
+
const e = new Error(`aws ${args.slice(0, 2).join(' ')} failed: ${detail}`)
|
|
136
|
+
e.stderr = detail
|
|
137
|
+
throw e
|
|
138
|
+
}
|
|
139
|
+
return out && String(out).trim() ? JSON.parse(out) : {}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* @param {ReturnType<typeof awsRunner>} aws
|
|
145
|
+
* @param {Target} target
|
|
146
|
+
* @returns {InstalledStack|null}
|
|
147
|
+
*/
|
|
148
|
+
function readStack(aws, target) {
|
|
149
|
+
let res
|
|
150
|
+
try {
|
|
151
|
+
res = aws(['cloudformation', 'describe-stacks', '--stack-name', target.stackName])
|
|
152
|
+
} catch (err) {
|
|
153
|
+
if (/does not exist/.test(err.stderr || err.message)) return null
|
|
154
|
+
throw err
|
|
155
|
+
}
|
|
156
|
+
const s = res.Stacks[0]
|
|
157
|
+
const output = (s.Outputs || []).find((o) => o.OutputKey === target.outputKey)
|
|
158
|
+
return {
|
|
159
|
+
status: s.StackStatus,
|
|
160
|
+
version: output ? output.OutputValue : null,
|
|
161
|
+
paramKeys: (s.Parameters || []).map((p) => p.ParameterKey),
|
|
162
|
+
params: Object.fromEntries((s.Parameters || []).map((p) => [p.ParameterKey, p.ParameterValue])),
|
|
163
|
+
outputs: s.Outputs || [],
|
|
164
|
+
lastUpdated: s.LastUpdatedTime || s.CreationTime || null,
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** @param {Target} target */
|
|
169
|
+
function bundled(target) {
|
|
170
|
+
return templateInfo(fs.readFileSync(target.template, 'utf8'))
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @param {InstalledStack|null} installed
|
|
175
|
+
* @param {string|null} bundledVersion
|
|
176
|
+
*/
|
|
177
|
+
function versionState(installed, bundledVersion) {
|
|
178
|
+
if (!installed) return 'not installed'
|
|
179
|
+
if (!installed.version) return 'upgrade available'
|
|
180
|
+
const cmp = compareVersions(installed.version, bundledVersion)
|
|
181
|
+
return cmp < 0 ? 'upgrade available' : cmp > 0 ? 'newer than this CLI' : 'up to date'
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* `saaslayer foundation status`: installed vs bundled version of each foundation stack.
|
|
186
|
+
* @param {object} flags
|
|
187
|
+
* @param {Deps} [deps]
|
|
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
|
+
|
|
210
|
+
async function foundationStatus(flags, { exec = defaultExec, log = console.log } = {}) {
|
|
211
|
+
const { region, targets } = resolveTargets(flags)
|
|
212
|
+
const aws = awsRunner(exec, flags, region)
|
|
213
|
+
const rows = targets.map((t) => {
|
|
214
|
+
const installed = readStack(aws, t)
|
|
215
|
+
const bundledVersion = bundled(t).version
|
|
216
|
+
return {
|
|
217
|
+
stackName: t.stackName,
|
|
218
|
+
stackStatus: installed ? installed.status : null,
|
|
219
|
+
installedVersion: installed ? installed.version || 'unknown' : null,
|
|
220
|
+
bundledVersion,
|
|
221
|
+
state: versionState(installed, bundledVersion),
|
|
222
|
+
...(t.kind === 'region' && installed ? emailSenderStatus(aws, installed) : {}),
|
|
223
|
+
}
|
|
224
|
+
})
|
|
225
|
+
for (const r of rows) {
|
|
226
|
+
log(`${r.stackName} (${region})`)
|
|
227
|
+
log(` status ${r.stackStatus || '-'}`)
|
|
228
|
+
log(` installed ${r.installedVersion || '-'}`)
|
|
229
|
+
log(` bundled ${r.bundledVersion}`)
|
|
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
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (rows.some((r) => r.state === 'upgrade available')) log('\nRun `saaslayer foundation upgrade` to review and apply the upgrade.')
|
|
238
|
+
return rows
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Waits for a change set to finish creating and returns its status + every resource change.
|
|
243
|
+
* @param {ReturnType<typeof awsRunner>} aws
|
|
244
|
+
* @param {Target} target
|
|
245
|
+
* @param {string} changeSetName
|
|
246
|
+
* @param {Required<Pick<Deps, 'sleep'|'pollMs'|'maxPolls'>>} wait
|
|
247
|
+
*/
|
|
248
|
+
async function waitForChangeSet(aws, target, changeSetName, { sleep, pollMs, maxPolls }) {
|
|
249
|
+
const base = ['cloudformation', 'describe-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName]
|
|
250
|
+
for (let i = 0; i < maxPolls; i++) {
|
|
251
|
+
const first = aws(base)
|
|
252
|
+
if (first.Status === 'CREATE_COMPLETE' || first.Status === 'FAILED') {
|
|
253
|
+
// The aws CLI auto-paginates describe-change-set, so Changes holds every page.
|
|
254
|
+
/** @type {Change[]} */
|
|
255
|
+
const changes = (first.Changes || []).filter((c) => c.Type === 'Resource').map(({ ResourceChange: rc }) => ({
|
|
256
|
+
action: rc.Action, logicalId: rc.LogicalResourceId, type: rc.ResourceType, replacement: rc.Replacement || '', scope: rc.Scope || [],
|
|
257
|
+
}))
|
|
258
|
+
return { status: first.Status, reason: first.StatusReason || '', changes }
|
|
259
|
+
}
|
|
260
|
+
await sleep(pollMs)
|
|
261
|
+
}
|
|
262
|
+
throw new Error(`change set ${changeSetName} on ${target.stackName} did not finish creating`)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Waits for the stack update to settle; returns the final stack status.
|
|
267
|
+
* @param {ReturnType<typeof awsRunner>} aws
|
|
268
|
+
* @param {Target} target
|
|
269
|
+
* @param {Required<Pick<Deps, 'sleep'|'pollMs'|'maxPolls'>>} wait
|
|
270
|
+
*/
|
|
271
|
+
async function waitForUpdate(aws, target, { sleep, pollMs, maxPolls }) {
|
|
272
|
+
for (let i = 0; i < maxPolls; i++) {
|
|
273
|
+
const s = readStack(aws, target)
|
|
274
|
+
if (!/_IN_PROGRESS$/.test(s.status)) return s
|
|
275
|
+
await sleep(pollMs)
|
|
276
|
+
}
|
|
277
|
+
throw new Error(`${target.stackName} update did not finish; check it in the CloudFormation console`)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Failed resource events of the latest update (newest first, back to the stack's own UPDATE_IN_PROGRESS event).
|
|
282
|
+
* @param {ReturnType<typeof awsRunner>} aws
|
|
283
|
+
* @param {Target} target
|
|
284
|
+
*/
|
|
285
|
+
function failedEvents(aws, target) {
|
|
286
|
+
const { StackEvents = [] } = aws(['cloudformation', 'describe-stack-events', '--stack-name', target.stackName, '--max-items', '100'])
|
|
287
|
+
const failures = []
|
|
288
|
+
for (const e of StackEvents) {
|
|
289
|
+
if (e.LogicalResourceId === target.stackName && e.ResourceStatus === 'UPDATE_IN_PROGRESS') break
|
|
290
|
+
if (/_FAILED$/.test(e.ResourceStatus)) failures.push(`${e.LogicalResourceId}: ${e.ResourceStatusReason || e.ResourceStatus}`)
|
|
291
|
+
}
|
|
292
|
+
return failures
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** @param {Change[]} changes */
|
|
296
|
+
function formatChanges(changes) {
|
|
297
|
+
const w = (key) => Math.max(...changes.map((c) => String(c[key]).length))
|
|
298
|
+
const [wa, wl, wt] = [w('action'), w('logicalId'), w('type')]
|
|
299
|
+
return changes.map((c) => ` ${c.action.padEnd(wa)} ${c.logicalId.padEnd(wl)} ${c.type.padEnd(wt)} replacement=${c.replacement || '-'} scope=${c.scope.join(',') || '-'}`)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
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
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Upgrades one foundation stack. Returns { stackName, result, ... } where result is upgraded | up to date | dry-run |
|
|
315
|
+
* aborted | not installed. Throws on any refusal or failure.
|
|
316
|
+
* @param {Target} target
|
|
317
|
+
* @param {object} flags
|
|
318
|
+
* @param {{ aws: ReturnType<typeof awsRunner>, region: string, required: boolean, log: Function, confirm: Function, wait: object }} ctx
|
|
319
|
+
*/
|
|
320
|
+
async function upgradeStack(target, flags, { aws, region, required, log, confirm, wait }) {
|
|
321
|
+
const label = `${target.stackName} (${region})`
|
|
322
|
+
const installed = readStack(aws, target)
|
|
323
|
+
if (!installed) {
|
|
324
|
+
if (required) throw new Error(`${label} is not installed — onboard the account first (saaslayer aws connect / saaslayer init)`)
|
|
325
|
+
log(`${label}: not installed, skipped`)
|
|
326
|
+
return { stackName: target.stackName, result: 'not installed' }
|
|
327
|
+
}
|
|
328
|
+
if (!STABLE_STATUSES.includes(installed.status)) {
|
|
329
|
+
throw new Error(`${label} is ${installed.status}; upgrade needs one of ${STABLE_STATUSES.join(', ')}. Resolve it in CloudFormation first.`)
|
|
330
|
+
}
|
|
331
|
+
const info = bundled(target)
|
|
332
|
+
const from = installed.version || 'unknown'
|
|
333
|
+
if (installed.version && compareVersions(installed.version, info.version) > 0) {
|
|
334
|
+
throw new Error(`${label} runs ${installed.version}, newer than this CLI's bundled ${info.version}; update the saaslayer CLI instead of downgrading`)
|
|
335
|
+
}
|
|
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
|
+
}
|
|
344
|
+
const changeSetName = `saaslayer-upgrade-${Date.now()}`
|
|
345
|
+
const del = () => aws(['cloudformation', 'delete-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName])
|
|
346
|
+
|
|
347
|
+
log(`\n${label}: ${from} -> ${info.version}`)
|
|
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)'}`)
|
|
350
|
+
if (plan.added.length) log(` new parameters (template default): ${plan.added.map((p) => `${p.name}='${p.default}'`).join(', ')}`)
|
|
351
|
+
if (plan.removed.length) log(` parameters no longer in the template: ${plan.removed.join(', ')}`)
|
|
352
|
+
|
|
353
|
+
aws([
|
|
354
|
+
'cloudformation', 'create-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName,
|
|
355
|
+
'--change-set-type', 'UPDATE', '--template-body', `file://${writeDeployableTemplate(target.template)}`,
|
|
356
|
+
'--parameters', JSON.stringify(plan.parameters),
|
|
357
|
+
...(target.capabilities.length ? ['--capabilities', ...target.capabilities] : []),
|
|
358
|
+
'--description', `saaslayer foundation upgrade ${from} -> ${info.version}`,
|
|
359
|
+
])
|
|
360
|
+
const cs = await waitForChangeSet(aws, target, changeSetName, wait)
|
|
361
|
+
if (cs.status === 'FAILED') {
|
|
362
|
+
del()
|
|
363
|
+
if (NO_CHANGES.test(cs.reason)) {
|
|
364
|
+
log(` no changes — already up to date (${from})`)
|
|
365
|
+
logSenderRecords(aws, target, senderDomain, log)
|
|
366
|
+
return { stackName: target.stackName, result: 'up to date', installedVersion: installed.version }
|
|
367
|
+
}
|
|
368
|
+
throw new Error(`${label}: change set failed: ${cs.reason}`)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
log(` changes (${cs.changes.length}):`)
|
|
372
|
+
for (const line of formatChanges(cs.changes)) log(line)
|
|
373
|
+
for (const c of conditionalChanges(cs.changes)) log(` ! ${c.logicalId} may be replaced (Replacement=Conditional)`)
|
|
374
|
+
const blocking = blockingChanges(cs.changes)
|
|
375
|
+
if (blocking.length) {
|
|
376
|
+
for (const c of blocking) log(` !! ${c.logicalId} (${c.type}): ${c.action === 'Remove' ? 'removed' : 'replaced'}`)
|
|
377
|
+
if (!flags['allow-replacement']) {
|
|
378
|
+
del()
|
|
379
|
+
throw new Error(`${label}: the upgrade replaces or removes ${blocking.map((c) => c.logicalId).join(', ')}; re-run with --allow-replacement after reviewing`)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (flags['dry-run']) {
|
|
383
|
+
del()
|
|
384
|
+
log(' dry run: change set deleted, nothing executed')
|
|
385
|
+
return { stackName: target.stackName, result: 'dry-run', from, to: info.version, changes: cs.changes }
|
|
386
|
+
}
|
|
387
|
+
if (!flags.yes && !(await confirm(`Execute this change set on ${label}?`))) {
|
|
388
|
+
del()
|
|
389
|
+
log(' aborted: change set deleted, nothing executed')
|
|
390
|
+
return { stackName: target.stackName, result: 'aborted' }
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
aws(['cloudformation', 'execute-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName])
|
|
394
|
+
log(' executing, waiting for UPDATE_COMPLETE…')
|
|
395
|
+
const done = await waitForUpdate(aws, target, wait)
|
|
396
|
+
if (done.status !== 'UPDATE_COMPLETE') {
|
|
397
|
+
const failures = failedEvents(aws, target)
|
|
398
|
+
throw new Error(`${label} ended ${done.status}${failures.length ? `:\n ${failures.join('\n ')}` : ''}`)
|
|
399
|
+
}
|
|
400
|
+
if (done.version !== info.version) throw new Error(`${label} updated but reports version ${done.version}, expected ${info.version}`)
|
|
401
|
+
log(` ✅ ${label} upgraded ${from} -> ${done.version}`)
|
|
402
|
+
logSenderRecords(aws, target, senderDomain, log)
|
|
403
|
+
return { stackName: target.stackName, result: 'upgraded', from, installedVersion: done.version }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Has the control plane re-read one connected account's foundation (POST /api/accounts/{id}/foundation/refresh, as the
|
|
408
|
+
* logged-in customer). The control plane reads it through its own trust into the account; no AWS credentials are sent.
|
|
409
|
+
* @type {Refresh}
|
|
410
|
+
*/
|
|
411
|
+
async function refreshFoundationRecord({ accountId, region }, flags) {
|
|
412
|
+
const doc = await apiCall('POST', `/api/accounts/${encodeURIComponent(accountId)}/foundation/refresh`, { data: { type: 'foundation-refreshes', attributes: { region } } }, flags)
|
|
413
|
+
return doc.data.attributes
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* After a finished upgrade (or one with nothing to change), have the control plane re-read the account so the console
|
|
418
|
+
* and deploys see the new version. Best effort: a failure is reported with how the record catches up, never thrown.
|
|
419
|
+
* @param {object} flags
|
|
420
|
+
* @param {{ aws: ReturnType<typeof awsRunner>, region: string, log: Function, refresh: Refresh }} ctx
|
|
421
|
+
*/
|
|
422
|
+
async function reportToControlPlane(flags, { aws, region, log, refresh }) {
|
|
423
|
+
try {
|
|
424
|
+
const accountId = String(aws(['sts', 'get-caller-identity']).Account)
|
|
425
|
+
const recorded = await refresh({ accountId, region }, flags)
|
|
426
|
+
log(`control plane: recorded foundation ${recorded.foundationVersion || 'unknown'} for ${accountId} (${region})`)
|
|
427
|
+
} catch (err) {
|
|
428
|
+
log(`! control plane not updated yet: ${err.message}`)
|
|
429
|
+
log(' "check again" on the console Accounts page re-reads it, or run this command again (an up-to-date foundation changes nothing).')
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* `saaslayer foundation upgrade`: upgrade the account stack, then the region stack (skipped when absent), then have the
|
|
435
|
+
* control plane re-read the account.
|
|
436
|
+
* @param {object} flags
|
|
437
|
+
* @param {Deps} [deps]
|
|
438
|
+
*/
|
|
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
|
|
441
|
+
const { region, targets } = resolveTargets(flags)
|
|
442
|
+
const aws = awsRunner(exec, flags, region)
|
|
443
|
+
const results = []
|
|
444
|
+
for (const t of targets) {
|
|
445
|
+
// The account stack must exist; the region stack is optional unless it was asked for by --only.
|
|
446
|
+
const required = t.kind === 'account' || flags.only === 'region'
|
|
447
|
+
results.push(await upgradeStack(t, flags, { aws, region, required, log, confirm, wait: { sleep, pollMs, maxPolls } }))
|
|
448
|
+
}
|
|
449
|
+
if (results.some((r) => r.result === 'upgraded' || r.result === 'up to date')) await reportToControlPlane(flags, { aws, region, log, refresh })
|
|
450
|
+
return results
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
module.exports = {
|
|
454
|
+
foundationStatus, foundationUpgrade, refreshFoundationRecord, templateInfo, upgradeParameters, compareVersions, blockingChanges, conditionalChanges,
|
|
455
|
+
STABLE_STATUSES,
|
|
456
|
+
}
|