saaslayer 0.0.2 → 0.1.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 +195 -8
- package/bin/saaslayer.js +454 -38
- package/package.json +19 -4
- package/src/api-client.js +91 -0
- package/src/aws-sigv4.js +47 -0
- package/src/commands/access-admins.js +73 -0
- package/src/commands/accounts.js +54 -0
- package/src/commands/activity.js +33 -0
- package/src/commands/aws.js +132 -0
- package/src/commands/catalog.js +246 -0
- package/src/commands/context.js +64 -0
- package/src/commands/deploy.js +118 -0
- package/src/commands/first-admin.js +42 -0
- package/src/commands/foundation.js +405 -0
- package/src/commands/lifecycle.js +124 -0
- package/src/commands/login.js +261 -0
- package/src/commands/machine-trust.js +96 -0
- package/src/commands/migrate.js +290 -0
- package/src/commands/operations.js +140 -0
- package/src/commands/orgs.js +81 -0
- package/src/commands/permissions-inspect.js +228 -0
- 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 +22 -0
- package/src/commands/users.js +269 -0
- package/src/config.js +49 -0
- package/src/context-store.js +37 -0
- package/src/credentials.js +285 -0
- package/src/deployment-api-auth.js +61 -0
- package/src/deployment-auth.js +38 -0
- package/src/deployments.js +26 -0
- package/src/discovery.js +66 -0
- package/src/env-compare.js +143 -0
- package/src/foundation-template.js +57 -0
- package/src/iam-session.js +67 -0
- package/src/migrations-lib.js +15 -0
- package/src/module-catalog.js +66 -0
- package/src/permissions-request.js +43 -0
- package/src/prompt.js +19 -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/ids.js +24 -0
- package/src/users-import/import.js +292 -0
- package/src/users-import/manifest.js +90 -0
- package/src/users-import/providers/cognito.js +61 -0
- package/src/users-import/providers/index.js +24 -0
- package/templates/saaslayer-foundation-region.yml +109 -0
- package/templates/{host-account.yml → saaslayer-foundation.yml} +381 -87
|
@@ -0,0 +1,405 @@
|
|
|
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 } = 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[], 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
|
+
lastUpdated: s.LastUpdatedTime || s.CreationTime || null,
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** @param {Target} target */
|
|
167
|
+
function bundled(target) {
|
|
168
|
+
return templateInfo(fs.readFileSync(target.template, 'utf8'))
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* @param {InstalledStack|null} installed
|
|
173
|
+
* @param {string|null} bundledVersion
|
|
174
|
+
*/
|
|
175
|
+
function versionState(installed, bundledVersion) {
|
|
176
|
+
if (!installed) return 'not installed'
|
|
177
|
+
if (!installed.version) return 'upgrade available'
|
|
178
|
+
const cmp = compareVersions(installed.version, bundledVersion)
|
|
179
|
+
return cmp < 0 ? 'upgrade available' : cmp > 0 ? 'newer than this CLI' : 'up to date'
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* `saaslayer foundation status`: installed vs bundled version of each foundation stack.
|
|
184
|
+
* @param {object} flags
|
|
185
|
+
* @param {Deps} [deps]
|
|
186
|
+
*/
|
|
187
|
+
async function foundationStatus(flags, { exec = defaultExec, log = console.log } = {}) {
|
|
188
|
+
const { region, targets } = resolveTargets(flags)
|
|
189
|
+
const aws = awsRunner(exec, flags, region)
|
|
190
|
+
const rows = targets.map((t) => {
|
|
191
|
+
const installed = readStack(aws, t)
|
|
192
|
+
const bundledVersion = bundled(t).version
|
|
193
|
+
return {
|
|
194
|
+
stackName: t.stackName,
|
|
195
|
+
stackStatus: installed ? installed.status : null,
|
|
196
|
+
installedVersion: installed ? installed.version || 'unknown' : null,
|
|
197
|
+
bundledVersion,
|
|
198
|
+
state: versionState(installed, bundledVersion),
|
|
199
|
+
}
|
|
200
|
+
})
|
|
201
|
+
for (const r of rows) {
|
|
202
|
+
log(`${r.stackName} (${region})`)
|
|
203
|
+
log(` status ${r.stackStatus || '-'}`)
|
|
204
|
+
log(` installed ${r.installedVersion || '-'}`)
|
|
205
|
+
log(` bundled ${r.bundledVersion}`)
|
|
206
|
+
log(` ${r.state}`)
|
|
207
|
+
}
|
|
208
|
+
if (rows.some((r) => r.state === 'upgrade available')) log('\nRun `saaslayer foundation upgrade` to review and apply the upgrade.')
|
|
209
|
+
return rows
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Waits for a change set to finish creating and returns its status + every resource change.
|
|
214
|
+
* @param {ReturnType<typeof awsRunner>} aws
|
|
215
|
+
* @param {Target} target
|
|
216
|
+
* @param {string} changeSetName
|
|
217
|
+
* @param {Required<Pick<Deps, 'sleep'|'pollMs'|'maxPolls'>>} wait
|
|
218
|
+
*/
|
|
219
|
+
async function waitForChangeSet(aws, target, changeSetName, { sleep, pollMs, maxPolls }) {
|
|
220
|
+
const base = ['cloudformation', 'describe-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName]
|
|
221
|
+
for (let i = 0; i < maxPolls; i++) {
|
|
222
|
+
const first = aws(base)
|
|
223
|
+
if (first.Status === 'CREATE_COMPLETE' || first.Status === 'FAILED') {
|
|
224
|
+
// The aws CLI auto-paginates describe-change-set, so Changes holds every page.
|
|
225
|
+
/** @type {Change[]} */
|
|
226
|
+
const changes = (first.Changes || []).filter((c) => c.Type === 'Resource').map(({ ResourceChange: rc }) => ({
|
|
227
|
+
action: rc.Action, logicalId: rc.LogicalResourceId, type: rc.ResourceType, replacement: rc.Replacement || '', scope: rc.Scope || [],
|
|
228
|
+
}))
|
|
229
|
+
return { status: first.Status, reason: first.StatusReason || '', changes }
|
|
230
|
+
}
|
|
231
|
+
await sleep(pollMs)
|
|
232
|
+
}
|
|
233
|
+
throw new Error(`change set ${changeSetName} on ${target.stackName} did not finish creating`)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Waits for the stack update to settle; returns the final stack status.
|
|
238
|
+
* @param {ReturnType<typeof awsRunner>} aws
|
|
239
|
+
* @param {Target} target
|
|
240
|
+
* @param {Required<Pick<Deps, 'sleep'|'pollMs'|'maxPolls'>>} wait
|
|
241
|
+
*/
|
|
242
|
+
async function waitForUpdate(aws, target, { sleep, pollMs, maxPolls }) {
|
|
243
|
+
for (let i = 0; i < maxPolls; i++) {
|
|
244
|
+
const s = readStack(aws, target)
|
|
245
|
+
if (!/_IN_PROGRESS$/.test(s.status)) return s
|
|
246
|
+
await sleep(pollMs)
|
|
247
|
+
}
|
|
248
|
+
throw new Error(`${target.stackName} update did not finish; check it in the CloudFormation console`)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Failed resource events of the latest update (newest first, back to the stack's own UPDATE_IN_PROGRESS event).
|
|
253
|
+
* @param {ReturnType<typeof awsRunner>} aws
|
|
254
|
+
* @param {Target} target
|
|
255
|
+
*/
|
|
256
|
+
function failedEvents(aws, target) {
|
|
257
|
+
const { StackEvents = [] } = aws(['cloudformation', 'describe-stack-events', '--stack-name', target.stackName, '--max-items', '100'])
|
|
258
|
+
const failures = []
|
|
259
|
+
for (const e of StackEvents) {
|
|
260
|
+
if (e.LogicalResourceId === target.stackName && e.ResourceStatus === 'UPDATE_IN_PROGRESS') break
|
|
261
|
+
if (/_FAILED$/.test(e.ResourceStatus)) failures.push(`${e.LogicalResourceId}: ${e.ResourceStatusReason || e.ResourceStatus}`)
|
|
262
|
+
}
|
|
263
|
+
return failures
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** @param {Change[]} changes */
|
|
267
|
+
function formatChanges(changes) {
|
|
268
|
+
const w = (key) => Math.max(...changes.map((c) => String(c[key]).length))
|
|
269
|
+
const [wa, wl, wt] = [w('action'), w('logicalId'), w('type')]
|
|
270
|
+
return changes.map((c) => ` ${c.action.padEnd(wa)} ${c.logicalId.padEnd(wl)} ${c.type.padEnd(wt)} replacement=${c.replacement || '-'} scope=${c.scope.join(',') || '-'}`)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Upgrades one foundation stack. Returns { stackName, result, ... } where result is upgraded | up to date | dry-run |
|
|
275
|
+
* aborted | not installed. Throws on any refusal or failure.
|
|
276
|
+
* @param {Target} target
|
|
277
|
+
* @param {object} flags
|
|
278
|
+
* @param {{ aws: ReturnType<typeof awsRunner>, region: string, required: boolean, log: Function, confirm: Function, wait: object }} ctx
|
|
279
|
+
*/
|
|
280
|
+
async function upgradeStack(target, flags, { aws, region, required, log, confirm, wait }) {
|
|
281
|
+
const label = `${target.stackName} (${region})`
|
|
282
|
+
const installed = readStack(aws, target)
|
|
283
|
+
if (!installed) {
|
|
284
|
+
if (required) throw new Error(`${label} is not installed — onboard the account first (saaslayer aws connect / saaslayer init)`)
|
|
285
|
+
log(`${label}: not installed, skipped`)
|
|
286
|
+
return { stackName: target.stackName, result: 'not installed' }
|
|
287
|
+
}
|
|
288
|
+
if (!STABLE_STATUSES.includes(installed.status)) {
|
|
289
|
+
throw new Error(`${label} is ${installed.status}; upgrade needs one of ${STABLE_STATUSES.join(', ')}. Resolve it in CloudFormation first.`)
|
|
290
|
+
}
|
|
291
|
+
const info = bundled(target)
|
|
292
|
+
const from = installed.version || 'unknown'
|
|
293
|
+
if (installed.version && compareVersions(installed.version, info.version) > 0) {
|
|
294
|
+
throw new Error(`${label} runs ${installed.version}, newer than this CLI's bundled ${info.version}; update the saaslayer CLI instead of downgrading`)
|
|
295
|
+
}
|
|
296
|
+
const plan = upgradeParameters(info.parameters, installed.paramKeys)
|
|
297
|
+
const changeSetName = `saaslayer-upgrade-${Date.now()}`
|
|
298
|
+
const del = () => aws(['cloudformation', 'delete-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName])
|
|
299
|
+
|
|
300
|
+
log(`\n${label}: ${from} -> ${info.version}`)
|
|
301
|
+
log(` parameters kept (previous values): ${plan.parameters.map((p) => p.ParameterKey).join(', ') || '-'}`)
|
|
302
|
+
if (plan.added.length) log(` new parameters (template default): ${plan.added.map((p) => `${p.name}='${p.default}'`).join(', ')}`)
|
|
303
|
+
if (plan.removed.length) log(` parameters no longer in the template: ${plan.removed.join(', ')}`)
|
|
304
|
+
|
|
305
|
+
aws([
|
|
306
|
+
'cloudformation', 'create-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName,
|
|
307
|
+
'--change-set-type', 'UPDATE', '--template-body', `file://${writeDeployableTemplate(target.template)}`,
|
|
308
|
+
'--parameters', JSON.stringify(plan.parameters),
|
|
309
|
+
...(target.capabilities.length ? ['--capabilities', ...target.capabilities] : []),
|
|
310
|
+
'--description', `saaslayer foundation upgrade ${from} -> ${info.version}`,
|
|
311
|
+
])
|
|
312
|
+
const cs = await waitForChangeSet(aws, target, changeSetName, wait)
|
|
313
|
+
if (cs.status === 'FAILED') {
|
|
314
|
+
del()
|
|
315
|
+
if (NO_CHANGES.test(cs.reason)) {
|
|
316
|
+
log(` no changes — already up to date (${from})`)
|
|
317
|
+
return { stackName: target.stackName, result: 'up to date', installedVersion: installed.version }
|
|
318
|
+
}
|
|
319
|
+
throw new Error(`${label}: change set failed: ${cs.reason}`)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
log(` changes (${cs.changes.length}):`)
|
|
323
|
+
for (const line of formatChanges(cs.changes)) log(line)
|
|
324
|
+
for (const c of conditionalChanges(cs.changes)) log(` ! ${c.logicalId} may be replaced (Replacement=Conditional)`)
|
|
325
|
+
const blocking = blockingChanges(cs.changes)
|
|
326
|
+
if (blocking.length) {
|
|
327
|
+
for (const c of blocking) log(` !! ${c.logicalId} (${c.type}): ${c.action === 'Remove' ? 'removed' : 'replaced'}`)
|
|
328
|
+
if (!flags['allow-replacement']) {
|
|
329
|
+
del()
|
|
330
|
+
throw new Error(`${label}: the upgrade replaces or removes ${blocking.map((c) => c.logicalId).join(', ')}; re-run with --allow-replacement after reviewing`)
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (flags['dry-run']) {
|
|
334
|
+
del()
|
|
335
|
+
log(' dry run: change set deleted, nothing executed')
|
|
336
|
+
return { stackName: target.stackName, result: 'dry-run', from, to: info.version, changes: cs.changes }
|
|
337
|
+
}
|
|
338
|
+
if (!flags.yes && !(await confirm(`Execute this change set on ${label}?`))) {
|
|
339
|
+
del()
|
|
340
|
+
log(' aborted: change set deleted, nothing executed')
|
|
341
|
+
return { stackName: target.stackName, result: 'aborted' }
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
aws(['cloudformation', 'execute-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName])
|
|
345
|
+
log(' executing, waiting for UPDATE_COMPLETE…')
|
|
346
|
+
const done = await waitForUpdate(aws, target, wait)
|
|
347
|
+
if (done.status !== 'UPDATE_COMPLETE') {
|
|
348
|
+
const failures = failedEvents(aws, target)
|
|
349
|
+
throw new Error(`${label} ended ${done.status}${failures.length ? `:\n ${failures.join('\n ')}` : ''}`)
|
|
350
|
+
}
|
|
351
|
+
if (done.version !== info.version) throw new Error(`${label} updated but reports version ${done.version}, expected ${info.version}`)
|
|
352
|
+
log(` ✅ ${label} upgraded ${from} -> ${done.version}`)
|
|
353
|
+
return { stackName: target.stackName, result: 'upgraded', from, installedVersion: done.version }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Has the control plane re-read one connected account's foundation (POST /api/accounts/{id}/foundation/refresh, as the
|
|
358
|
+
* logged-in customer). The control plane reads it through its own trust into the account; no AWS credentials are sent.
|
|
359
|
+
* @type {Refresh}
|
|
360
|
+
*/
|
|
361
|
+
async function refreshFoundationRecord({ accountId, region }, flags) {
|
|
362
|
+
const doc = await apiCall('POST', `/api/accounts/${encodeURIComponent(accountId)}/foundation/refresh`, { data: { type: 'foundation-refreshes', attributes: { region } } }, flags)
|
|
363
|
+
return doc.data.attributes
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* After a finished upgrade (or one with nothing to change), have the control plane re-read the account so the console
|
|
368
|
+
* and deploys see the new version. Best effort: a failure is reported with how the record catches up, never thrown.
|
|
369
|
+
* @param {object} flags
|
|
370
|
+
* @param {{ aws: ReturnType<typeof awsRunner>, region: string, log: Function, refresh: Refresh }} ctx
|
|
371
|
+
*/
|
|
372
|
+
async function reportToControlPlane(flags, { aws, region, log, refresh }) {
|
|
373
|
+
try {
|
|
374
|
+
const accountId = String(aws(['sts', 'get-caller-identity']).Account)
|
|
375
|
+
const recorded = await refresh({ accountId, region }, flags)
|
|
376
|
+
log(`control plane: recorded foundation ${recorded.foundationVersion || 'unknown'} for ${accountId} (${region})`)
|
|
377
|
+
} catch (err) {
|
|
378
|
+
log(`! control plane not updated yet: ${err.message}`)
|
|
379
|
+
log(' "check again" on the console Accounts page re-reads it, or run this command again (an up-to-date foundation changes nothing).')
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* `saaslayer foundation upgrade`: upgrade the account stack, then the region stack (skipped when absent), then have the
|
|
385
|
+
* control plane re-read the account.
|
|
386
|
+
* @param {object} flags
|
|
387
|
+
* @param {Deps} [deps]
|
|
388
|
+
*/
|
|
389
|
+
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 } = {}) {
|
|
390
|
+
const { region, targets } = resolveTargets(flags)
|
|
391
|
+
const aws = awsRunner(exec, flags, region)
|
|
392
|
+
const results = []
|
|
393
|
+
for (const t of targets) {
|
|
394
|
+
// The account stack must exist; the region stack is optional unless it was asked for by --only.
|
|
395
|
+
const required = t.kind === 'account' || flags.only === 'region'
|
|
396
|
+
results.push(await upgradeStack(t, flags, { aws, region, required, log, confirm, wait: { sleep, pollMs, maxPolls } }))
|
|
397
|
+
}
|
|
398
|
+
if (results.some((r) => r.result === 'upgraded' || r.result === 'up to date')) await reportToControlPlane(flags, { aws, region, log, refresh })
|
|
399
|
+
return results
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
module.exports = {
|
|
403
|
+
foundationStatus, foundationUpgrade, refreshFoundationRecord, templateInfo, upgradeParameters, compareVersions, blockingChanges, conditionalChanges,
|
|
404
|
+
STABLE_STATUSES,
|
|
405
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// `saaslayer status | update | destroy | service add|remove` (swf2.8) — lifecycle over a deployed project.
|
|
2
|
+
// Each resolves the deployment id from (project, env, region) then calls the guarded BFF route and, unless --no-wait,
|
|
3
|
+
// waits for the resulting operation. destroy + service-remove (delete custody) are guarded: destroy needs a typed
|
|
4
|
+
// project-name confirmation; a protected-env service removal needs --reason and the typed service name.
|
|
5
|
+
'use strict'
|
|
6
|
+
const { apiCall } = require('../api-client')
|
|
7
|
+
const { resolveDeployment } = require('../deployments')
|
|
8
|
+
const { resolveScope, printScope, deployedProjectsHint } = require('../scope')
|
|
9
|
+
const { ask } = require('../prompt')
|
|
10
|
+
const { finishMutation, requestKeyHeaders } = require('./operations')
|
|
11
|
+
const { fetchModuleCatalog, checkParamModules } = require('../module-catalog')
|
|
12
|
+
const { PROTECTED_ENVS, parseSetFlags } = require('../settings')
|
|
13
|
+
const { applySettings } = require('./settings')
|
|
14
|
+
|
|
15
|
+
async function status(flags) {
|
|
16
|
+
const scope = resolveScope(flags, { env: 'all' })
|
|
17
|
+
printScope(scope, flags)
|
|
18
|
+
const project = scope.project.value
|
|
19
|
+
const view = await apiCall('GET', `/api/projects/${encodeURIComponent(project)}/deployments`, undefined, flags)
|
|
20
|
+
// --env narrows the listing to one deploy env; without it every live env is shown.
|
|
21
|
+
const groups = (view.environments || []).filter((g) => scope.env.value === 'all' || g.environment === scope.env.value)
|
|
22
|
+
const count = groups.reduce((n, g) => n + (g.instances || []).length, 0)
|
|
23
|
+
console.log(`Project ${project} (${scope.project.kind}): ${count} deployment(s)`)
|
|
24
|
+
if (!count) {
|
|
25
|
+
console.log(`no deployments for project ${project} (${scope.project.kind}) in org=${scope.org.value || '—'} env=${scope.env.value}`)
|
|
26
|
+
for (const line of await deployedProjectsHint(scope, flags)) console.log(line)
|
|
27
|
+
return view
|
|
28
|
+
}
|
|
29
|
+
for (const g of groups) {
|
|
30
|
+
for (const i of g.instances || []) {
|
|
31
|
+
const inst = i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''
|
|
32
|
+
console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst}`)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return view
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Roll an existing deployment's modules to a new commit (the upgrade path; `deploy` only creates). --param changes
|
|
39
|
+
// settings instead, through the settings route (`saaslayer settings set`), keeping the current commit. --manifest
|
|
40
|
+
// applies a tested release manifest (commands/release-manifest.js).
|
|
41
|
+
async function update(flags) {
|
|
42
|
+
if (flags.manifest !== undefined) return require('./release-manifest').updateFromManifest(flags)
|
|
43
|
+
const commitSha = flags['commit-sha'] || flags.commitSha
|
|
44
|
+
const parameters = parseSetFlags(flags.param, '--param')
|
|
45
|
+
if (!commitSha && !parameters) throw new Error('update requires --commit-sha <sha> (or --param <module>.<Setting>=<value> to change settings)')
|
|
46
|
+
if (commitSha && parameters) {
|
|
47
|
+
throw new Error('update moves a release (--commit-sha) or changes settings (--param), not both: run `saaslayer update --commit-sha <sha>`, then `saaslayer settings set --set <module>.<Setting>=<value>`')
|
|
48
|
+
}
|
|
49
|
+
if (parameters) {
|
|
50
|
+
checkParamModules(parameters, await fetchModuleCatalog(flags))
|
|
51
|
+
return applySettings(parameters, flags)
|
|
52
|
+
}
|
|
53
|
+
const d = await resolveDeployment(flags)
|
|
54
|
+
console.log(`Updating ${d.project}/${d.env}/${d.region} (${d.deploymentId}) to ${commitSha}…`)
|
|
55
|
+
// Protected envs (staging/prod) require --reason; --force passes the drift gate (audited with the reason).
|
|
56
|
+
const attributes = { commitSha }
|
|
57
|
+
if (flags.reason) attributes.reason = flags.reason
|
|
58
|
+
if (flags.force === true || flags.force === 'true') attributes.force = true
|
|
59
|
+
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
|
|
60
|
+
const status = res && res.data && res.data.attributes && res.data.attributes.status
|
|
61
|
+
console.log(`✅ update started for ${d.deploymentId}${status ? ` (${status})` : ''}`)
|
|
62
|
+
return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Approve the migrations one run left awaiting approval (a protected env's destructive/contract migrations): the control
|
|
67
|
+
* plane starts the run that applies them, recording you and the reason. `saaslayer update` prints the run id.
|
|
68
|
+
* @param {Record<string, any>} flags --run <runId>, --reason <text>, plus the usual scope flags
|
|
69
|
+
*/
|
|
70
|
+
async function approveMigrations(flags) {
|
|
71
|
+
const runId = typeof flags.run === 'string' ? flags.run.trim() : ''
|
|
72
|
+
if (!runId) throw new Error('migrations approve requires --run <runId> (the update run that left migrations awaiting approval)')
|
|
73
|
+
const reason = typeof flags.reason === 'string' ? flags.reason.trim() : ''
|
|
74
|
+
if (!reason) throw new Error('migrations approve requires --reason <text> (recorded with the approval)')
|
|
75
|
+
const d = await resolveDeployment(flags)
|
|
76
|
+
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/migrations/approvals`, { data: { type: 'migration-approvals', attributes: { runId, reason } } }, flags, { headers: requestKeyHeaders() })
|
|
77
|
+
console.log(`✅ approved the migrations ${runId} left awaiting approval on ${d.deploymentId}`)
|
|
78
|
+
return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function destroy(flags) {
|
|
82
|
+
const dataCustody = flags['data-custody']
|
|
83
|
+
if (dataCustody !== 'delete' && dataCustody !== 'retain') throw new Error('destroy requires --data-custody delete|retain')
|
|
84
|
+
// Prod destroy is audited: the deployer requires an explicit reason. Default a sensible one when --reason is omitted.
|
|
85
|
+
const reason = flags.reason || 'destroyed via saaslayer CLI'
|
|
86
|
+
const d = await resolveDeployment(flags)
|
|
87
|
+
console.log(`⚠ This will DESTROY ${d.project}/${d.env}/${d.region} (${d.deploymentId}), data-custody=${dataCustody}.`)
|
|
88
|
+
const typed = flags.yes ? d.project : await ask(`Type the project name "${d.project}" to confirm: `)
|
|
89
|
+
if (typed !== d.project) { console.log('Aborted (name did not match).'); return null }
|
|
90
|
+
const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}?dataCustody=${dataCustody}&reason=${encodeURIComponent(reason)}`, undefined, flags)
|
|
91
|
+
console.log(`✅ destroy started for ${d.deploymentId}`)
|
|
92
|
+
return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function serviceAdd(service, flags) {
|
|
96
|
+
if (!service) throw new Error('`service add` requires a service name')
|
|
97
|
+
const d = await resolveDeployment(flags)
|
|
98
|
+
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services`, { data: { type: 'service', attributes: { service } } }, flags, { headers: requestKeyHeaders() })
|
|
99
|
+
console.log(`✅ adding ${service} to ${d.deploymentId}`)
|
|
100
|
+
return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function serviceRemove(service, flags) {
|
|
104
|
+
if (!service) throw new Error('`service remove` requires a service name')
|
|
105
|
+
const dataCustody = flags['data-custody']
|
|
106
|
+
if (dataCustody !== 'delete' && dataCustody !== 'retain') throw new Error('`service remove` requires --data-custody delete|retain')
|
|
107
|
+
const d = await resolveDeployment(flags)
|
|
108
|
+
// A protected env (staging, prod) removal is audited and confirmed: --reason, then the typed service name (--yes supplies it).
|
|
109
|
+
const isProtected = PROTECTED_ENVS.has(d.env)
|
|
110
|
+
if (isProtected && !flags.reason) throw new Error(`\`service remove\` on ${d.env} (protected) requires --reason <text>`)
|
|
111
|
+
const query = new URLSearchParams({ dataCustody })
|
|
112
|
+
if (flags.reason) query.set('reason', flags.reason)
|
|
113
|
+
if (isProtected) {
|
|
114
|
+
console.log(`⚠ This will REMOVE ${service} from ${d.project}/${d.env}/${d.region} (${d.deploymentId}), data-custody=${dataCustody}.`)
|
|
115
|
+
const typed = flags.yes ? service : await ask(`Type the service name "${service}" to confirm: `)
|
|
116
|
+
if (typed !== service) { console.log('Aborted (name did not match).'); return null }
|
|
117
|
+
query.set('confirmation', typed)
|
|
118
|
+
}
|
|
119
|
+
const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services/${encodeURIComponent(service)}?${query}`, undefined, flags, { headers: requestKeyHeaders() })
|
|
120
|
+
console.log(`✅ removing ${service} from ${d.deploymentId} (data-custody=${dataCustody})`)
|
|
121
|
+
return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
module.exports = { status, update, approveMigrations, destroy, serviceAdd, serviceRemove }
|