saaslayer 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +199 -18
- package/bin/saaslayer.js +335 -62
- package/package.json +3 -2
- package/src/aws-sigv4.js +74 -26
- package/src/commands/access-admins.js +2 -2
- package/src/commands/admin-allowlist.js +23 -3
- package/src/commands/api-keys.js +83 -0
- package/src/commands/audit.js +77 -0
- package/src/commands/aws.js +355 -82
- package/src/commands/binding-handoff.js +174 -0
- package/src/commands/bindings.js +111 -0
- package/src/commands/catalog.js +30 -3
- package/src/commands/deploy.js +49 -11
- package/src/commands/env-export.js +58 -0
- package/src/commands/first-admin.js +15 -4
- package/src/commands/foundation.js +75 -117
- package/src/commands/hooks.js +271 -0
- package/src/commands/integration-credentials.js +1 -1
- package/src/commands/lifecycle.js +149 -24
- package/src/commands/login-domain.js +259 -0
- package/src/commands/permission-orgs.js +80 -0
- package/src/commands/release-manifest.js +17 -8
- package/src/commands/service-principals.js +42 -5
- package/src/commands/settings.js +21 -5
- package/src/commands/sms-registration.js +182 -0
- package/src/commands/sms.js +178 -0
- package/src/commands/social.js +265 -0
- package/src/commands/support-staff.js +72 -0
- package/src/commands/users-management.js +2 -20
- package/src/commands/users.js +56 -11
- package/src/commands/versions.js +61 -0
- package/src/connection-proof.js +41 -0
- package/src/deployments.js +14 -2
- package/src/foundation-change-set.js +180 -0
- package/src/foundation-home.js +121 -0
- package/src/foundation-template.js +51 -10
- package/src/foundation-trust-write.js +379 -0
- package/src/iam-session.js +14 -8
- package/src/login-domain.js +138 -0
- package/src/login-methods.js +118 -0
- package/src/module-catalog.js +3 -2
- package/src/release-manifest.js +11 -4
- package/src/scope.js +3 -1
- package/src/settings.js +85 -13
- package/src/sms/number.js +37 -0
- package/src/sms/registration-fields.js +167 -0
- package/src/sms/registration-validate.js +151 -0
- package/src/sms/registration.js +216 -0
- package/src/sms/release.js +55 -0
- package/src/sms/scope.js +86 -0
- package/src/sms/status.js +181 -0
- package/src/ssm-api.js +31 -0
- package/src/trust-entries.js +350 -0
- package/src/user-service-instance.js +27 -0
- package/src/users-api.js +55 -8
- package/src/users-import/checkpoint.js +76 -0
- package/src/users-import/import.js +233 -24
- package/src/versions.js +80 -0
- package/templates/bootstrap/saaslayer-bootstrap-permission-set-inline-policy.json +148 -0
- package/templates/bootstrap/saaslayer-bootstrap-policy-email-sender.json +22 -0
- package/templates/bootstrap/saaslayer-bootstrap-policy-sms-number.json +22 -0
- package/templates/bootstrap/saaslayer-bootstrap-policy.json +114 -0
- package/templates/bootstrap/saaslayer-bootstrap-trust-policy.json +18 -0
- package/templates/saaslayer-foundation-region.yml +45 -1
- package/templates/saaslayer-foundation.yml +759 -309
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// Writes the account foundation's shared trust configuration (ADR 0005 §2.1): one control plane's TrustEntries entry through
|
|
2
|
+
// the installed template with only its trust statements re-rendered, and ConnectionAuthorizerArns as a parameter-only update.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const os = require('os')
|
|
6
|
+
const path = require('path')
|
|
7
|
+
const crypto = require('crypto')
|
|
8
|
+
const { STABLE_STATUSES, NO_CHANGES, describeStack, waitForChangeSet, waitForStack, formatChanges } = require('./foundation-change-set')
|
|
9
|
+
const { CFN_INLINE_TEMPLATE_LIMIT, templateInfo } = require('./foundation-template')
|
|
10
|
+
const { ENTRY_ROLES, AUTHORIZERS_PARAMETER, parseTrustEntries, mergeTrustEntry, renderFoundationTemplate, renderTrustStatements, controlPlaneIds,
|
|
11
|
+
canonicalRoleArn } = require('./trust-entries')
|
|
12
|
+
const { FOUNDATION_STACK, HOME_ROLES } = require('./foundation-home')
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {import('./foundation-change-set').AwsJson} AwsJson
|
|
16
|
+
* @typedef {import('./foundation-change-set').Wait} Wait
|
|
17
|
+
* @typedef {import('./foundation-change-set').Change} Change
|
|
18
|
+
* @typedef {import('./trust-entries').TrustEntry} TrustEntry
|
|
19
|
+
* @typedef {{ status: string, lastUpdated: string|null, params: Record<string, string>, version: string|null }} StackRead
|
|
20
|
+
* @typedef {{ status: string, reason: string, changes: Change[], parameters: Record<string, string> }} ChangeSet
|
|
21
|
+
* @typedef {{ result: 'updated'|'unchanged', attempts: number }} WriteResult
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const BUNDLED_TEMPLATE = path.join(__dirname, '..', 'templates', 'saaslayer-foundation.yml')
|
|
25
|
+
/** The first foundation version carrying TrustEntries and ConnectionAuthorizerArns. */
|
|
26
|
+
const TRUST_ENTRIES_SINCE = '7.0.0'
|
|
27
|
+
const DEFAULT_MAX_ATTEMPTS = 3
|
|
28
|
+
/** The entry roles' IAM names, by renderer role. */
|
|
29
|
+
const ROLE_NAMES = { deploy: HOME_ROLES[0], support: HOME_ROLES[1] }
|
|
30
|
+
const AUTHORIZERS_SSM_NAME = '/saaslayer/foundation/connection-authorizers'
|
|
31
|
+
/** AWS errors meaning another update got there first: the change set is gone or obsolete, or the stack is busy. */
|
|
32
|
+
const SUPERSEDED = /ChangeSetNotFound|OBSOLETE|InvalidChangeSetStatus|_IN_PROGRESS state|can ?not be updated/i
|
|
33
|
+
|
|
34
|
+
/** The stack moved under this write; the loop re-reads and tries again. */
|
|
35
|
+
class StaleWrite extends Error {}
|
|
36
|
+
|
|
37
|
+
/** @param {any} err */
|
|
38
|
+
const detail = (err) => String((err && (err.stderr || err.message)) || '')
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Canonical form of a policy value: keys sorted, one-element lists collapsed to their element (IAM accepts both).
|
|
42
|
+
* @param {unknown} value
|
|
43
|
+
* @returns {unknown}
|
|
44
|
+
*/
|
|
45
|
+
function canonical(value) {
|
|
46
|
+
if (Array.isArray(value)) return value.length === 1 ? canonical(value[0]) : value.map(canonical)
|
|
47
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map((k) => [k, canonical(value[k])]))
|
|
48
|
+
return value
|
|
49
|
+
}
|
|
50
|
+
/** @param {unknown} a @param {unknown} b */
|
|
51
|
+
const sameValue = (a, b) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b))
|
|
52
|
+
|
|
53
|
+
/** @param {string} text a CommaDelimitedList parameter value */
|
|
54
|
+
const splitList = (text) => String(text || '').split(',').map((s) => s.trim()).filter(Boolean)
|
|
55
|
+
|
|
56
|
+
/** @param {any} s a describe-stacks stack @returns {StackRead} */
|
|
57
|
+
function snapshot(s) {
|
|
58
|
+
const output = (s.Outputs || []).find((o) => o.OutputKey === 'FoundationVersion')
|
|
59
|
+
return {
|
|
60
|
+
status: s.StackStatus,
|
|
61
|
+
lastUpdated: s.LastUpdatedTime || s.CreationTime || null,
|
|
62
|
+
params: Object.fromEntries((s.Parameters || []).map((p) => [p.ParameterKey, p.ParameterValue])),
|
|
63
|
+
version: output ? output.OutputValue : null,
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The stack once no update is in progress; refuses a missing stack or one that settled in an unstable state.
|
|
69
|
+
* @param {AwsJson} aws @param {string} stackName @param {string} label @param {Wait} wait
|
|
70
|
+
* @returns {Promise<StackRead>}
|
|
71
|
+
*/
|
|
72
|
+
async function readSettled(aws, stackName, label, wait) {
|
|
73
|
+
for (let i = 0; i < wait.maxPolls; i++) {
|
|
74
|
+
const s = describeStack(aws, stackName)
|
|
75
|
+
if (!s) throw new Error(`${label} is not installed; connect the account first (saaslayer aws connect). Nothing was changed.`)
|
|
76
|
+
if (!/_IN_PROGRESS$/.test(s.StackStatus)) {
|
|
77
|
+
if (!STABLE_STATUSES.includes(s.StackStatus)) {
|
|
78
|
+
throw new Error(`${label} is ${s.StackStatus}; a trust update needs one of ${STABLE_STATUSES.join(', ')}. Resolve it in CloudFormation first. Nothing was changed.`)
|
|
79
|
+
}
|
|
80
|
+
return snapshot(s)
|
|
81
|
+
}
|
|
82
|
+
await wait.sleep(wait.pollMs)
|
|
83
|
+
}
|
|
84
|
+
throw new Error(`${label} stayed busy with another update; nothing was changed. Rerun once it finishes.`)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Whether the stack changed since `read`: an update in progress, a newer update time or any parameter value differing.
|
|
89
|
+
* @param {AwsJson} aws @param {string} stackName @param {StackRead} read
|
|
90
|
+
*/
|
|
91
|
+
function moved(aws, stackName, read) {
|
|
92
|
+
const s = describeStack(aws, stackName)
|
|
93
|
+
if (!s || /_IN_PROGRESS$/.test(s.StackStatus)) return true
|
|
94
|
+
const now = snapshot(s)
|
|
95
|
+
return now.lastUpdated !== read.lastUpdated || !sameValue(now.params, read.params)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Refuses, before any write, a foundation this CLI cannot operate on: no TrustEntries contract, or a newer version.
|
|
100
|
+
* @param {StackRead} read @param {string} label
|
|
101
|
+
*/
|
|
102
|
+
function assertOperable(read, label) {
|
|
103
|
+
const { compareVersions } = require('./commands/foundation')
|
|
104
|
+
const hasContract = 'TrustEntries' in read.params && 'ConnectionAuthorizerArns' in read.params
|
|
105
|
+
if (!hasContract || !read.version || compareVersions(read.version, TRUST_ENTRIES_SINCE) < 0) {
|
|
106
|
+
throw new Error(`${label} runs ${read.version || 'an unknown version'}, which predates per-control-plane TrustEntries; it converts through ` +
|
|
107
|
+
'`saaslayer aws connect`. Nothing was changed.')
|
|
108
|
+
}
|
|
109
|
+
const bundled = templateInfo(fs.readFileSync(BUNDLED_TEMPLATE, 'utf8')).version
|
|
110
|
+
if (compareVersions(read.version, bundled) > 0) {
|
|
111
|
+
throw new Error(`${label} runs ${read.version}, newer than this CLI's bundled ${bundled}; update the saaslayer CLI. Nothing was changed.`)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Refuses unless every other control plane's entry in `before` appears byte-for-byte in `after`.
|
|
117
|
+
* @param {string} before @param {string} after @param {string|null} ownId
|
|
118
|
+
*/
|
|
119
|
+
function assertOthersSurvive(before, after, ownId) {
|
|
120
|
+
for (const { raw, entry } of parseTrustEntries(before)) {
|
|
121
|
+
if (entry.controlPlaneId !== ownId && !after.includes(raw)) throw new Error(`trust entry ${entry.controlPlaneId} is not byte-identical`)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Change-set parameters: the values in `set`, every other installed parameter UsePreviousValue.
|
|
127
|
+
* @param {StackRead} read @param {Record<string, string>} set
|
|
128
|
+
*/
|
|
129
|
+
function changeSetParameters(read, set) {
|
|
130
|
+
return Object.keys(read.params).map((ParameterKey) => (ParameterKey in set ? { ParameterKey, ParameterValue: set[ParameterKey] } : { ParameterKey, UsePreviousValue: true }))
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* What a change set changes besides `allowed` changes and the parameter values in `set`, as refusal labels (never values).
|
|
135
|
+
* @param {ChangeSet} cs @param {StackRead} read @param {Record<string, string>} set @param {(c: Change) => boolean} allowed
|
|
136
|
+
*/
|
|
137
|
+
function unexpectedChanges(cs, read, set, allowed) {
|
|
138
|
+
const resources = cs.changes.filter((c) => !(c.action === 'Modify' && (c.replacement === 'False' || c.replacement === '') &&
|
|
139
|
+
c.scope.length === 1 && c.scope[0] === 'Properties' && (c.properties || []).length > 0 && allowed(c)))
|
|
140
|
+
.map((c) => `${c.logicalId} (${c.type} ${c.action}${(c.properties || []).length ? ` ${c.properties.join(',')}` : ''}${c.replacement === 'True' || c.replacement === 'Conditional' ? ' replacement' : ''})`)
|
|
141
|
+
const keys = new Set([...Object.keys(read.params), ...Object.keys(cs.parameters)])
|
|
142
|
+
const parameters = [...keys].filter((key) => {
|
|
143
|
+
const value = cs.parameters[key]
|
|
144
|
+
if (value === '****') return false
|
|
145
|
+
return value !== (key in set ? set[key] : read.params[key])
|
|
146
|
+
}).map((key) => `parameter ${key}`)
|
|
147
|
+
return [...resources, ...parameters]
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A private (0700) temp dir for files that may carry trust identifiers. */
|
|
151
|
+
function privateDir() {
|
|
152
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'saaslayer-trust-'))
|
|
153
|
+
return {
|
|
154
|
+
/** @param {string} name @param {string} text */
|
|
155
|
+
write(name, text) {
|
|
156
|
+
const file = path.join(dir, name)
|
|
157
|
+
fs.writeFileSync(file, text, { mode: 0o600 })
|
|
158
|
+
return file
|
|
159
|
+
},
|
|
160
|
+
remove: () => fs.rmSync(dir, { recursive: true, force: true }),
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* One guarded change set: create it from the parameters just read, refuse anything beyond what `inspect` allows, re-check
|
|
166
|
+
* the stack has not moved, execute, wait and verify. A superseded or failed change set, or a moved stack, is a StaleWrite.
|
|
167
|
+
* @param {{ aws: AwsJson, stackName: string, label: string, wait: Wait, log: (...a: unknown[]) => void, read: StackRead,
|
|
168
|
+
* set: Record<string, string>, template: string|null, allowed: (c: Change) => boolean, verify: () => void, description: string }} o
|
|
169
|
+
* template null keeps the installed template (UsePreviousTemplate)
|
|
170
|
+
* @returns {Promise<'updated'|'unchanged'>}
|
|
171
|
+
*/
|
|
172
|
+
async function applyGuarded({ aws, stackName, label, wait, log, read, set, template, allowed, verify, description }) {
|
|
173
|
+
const files = privateDir()
|
|
174
|
+
const name = `saaslayer-trust-${Date.now()}-${crypto.randomBytes(3).toString('hex')}`
|
|
175
|
+
const base = ['--stack-name', stackName, '--change-set-name', name]
|
|
176
|
+
const del = () => {
|
|
177
|
+
try {
|
|
178
|
+
aws(['cloudformation', 'delete-change-set', ...base])
|
|
179
|
+
} catch (err) {
|
|
180
|
+
if (!SUPERSEDED.test(detail(err))) throw err
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** @param {() => any} fn @param {string} reason */
|
|
184
|
+
const superseded = async (fn, reason) => {
|
|
185
|
+
try {
|
|
186
|
+
return await fn()
|
|
187
|
+
} catch (err) {
|
|
188
|
+
if (SUPERSEDED.test(detail(err))) throw new StaleWrite(reason)
|
|
189
|
+
throw err
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
const templateArgs = template === null ? ['--use-previous-template'] : ['--template-body', `file://${files.write('template.yml', template)}`]
|
|
194
|
+
await superseded(() => aws(['cloudformation', 'create-change-set', ...base, '--change-set-type', 'UPDATE', ...templateArgs,
|
|
195
|
+
'--parameters', `file://${files.write('parameters.json', JSON.stringify(changeSetParameters(read, set)))}`,
|
|
196
|
+
'--capabilities', 'CAPABILITY_NAMED_IAM', '--description', description]), 'another update is in progress')
|
|
197
|
+
/** @type {ChangeSet} */
|
|
198
|
+
const cs = await superseded(() => waitForChangeSet(aws, stackName, name, wait), 'its change set was invalidated by another update')
|
|
199
|
+
if (cs.status === 'FAILED') {
|
|
200
|
+
del()
|
|
201
|
+
if (NO_CHANGES.test(cs.reason)) return 'unchanged'
|
|
202
|
+
throw new StaleWrite(`its change set failed (${cs.reason})`)
|
|
203
|
+
}
|
|
204
|
+
if (moved(aws, stackName, read)) {
|
|
205
|
+
del()
|
|
206
|
+
throw new StaleWrite('the stack changed since it was read')
|
|
207
|
+
}
|
|
208
|
+
log(` ${label} changes (${cs.changes.length}):`)
|
|
209
|
+
for (const line of formatChanges(cs.changes)) log(line)
|
|
210
|
+
const unexpected = unexpectedChanges(cs, read, set, allowed)
|
|
211
|
+
if (unexpected.length) {
|
|
212
|
+
del()
|
|
213
|
+
throw new Error(`${label}: refused: the change set would change ${unexpected.join('; ')}, beyond this update; it was deleted, nothing was executed`)
|
|
214
|
+
}
|
|
215
|
+
if (moved(aws, stackName, read)) {
|
|
216
|
+
del()
|
|
217
|
+
throw new StaleWrite('the stack changed since it was read')
|
|
218
|
+
}
|
|
219
|
+
await superseded(() => aws(['cloudformation', 'execute-change-set', ...base]), 'its change set was invalidated by another update')
|
|
220
|
+
log(` executing, waiting for ${stackName} to finish…`)
|
|
221
|
+
await waitForStack(aws, stackName, 'UPDATE', wait)
|
|
222
|
+
try {
|
|
223
|
+
verify()
|
|
224
|
+
} catch (err) {
|
|
225
|
+
throw new Error(`${label}: the update executed but verification failed: ${err.message}`)
|
|
226
|
+
}
|
|
227
|
+
return 'updated'
|
|
228
|
+
} finally {
|
|
229
|
+
files.remove()
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Runs `attempt` until it is not stale, at most `maxAttempts` times, then stops with a clear error.
|
|
235
|
+
* @param {{ label: string, maxAttempts: number, log: (...a: unknown[]) => void, attempt: () => Promise<'updated'|'unchanged'> }} o
|
|
236
|
+
* @returns {Promise<WriteResult>}
|
|
237
|
+
*/
|
|
238
|
+
async function retryStale({ label, maxAttempts, log, attempt }) {
|
|
239
|
+
let reason = ''
|
|
240
|
+
for (let n = 1; n <= maxAttempts; n++) {
|
|
241
|
+
try {
|
|
242
|
+
return { result: await attempt(), attempts: n }
|
|
243
|
+
} catch (err) {
|
|
244
|
+
if (!(err instanceof StaleWrite)) throw err
|
|
245
|
+
reason = err.message
|
|
246
|
+
if (n < maxAttempts) log(` ${label}: ${reason}; re-reading (attempt ${n + 1} of ${maxAttempts})`)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
throw new Error(`${label}: the foundation kept changing during this write (${reason}); stopped after ${maxAttempts} attempt${maxAttempts === 1 ? '' : 's'}, ` +
|
|
250
|
+
'nothing was executed. Rerun once other foundation updates have finished.')
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The live trust statements of an IAM role.
|
|
255
|
+
* @param {AwsJson} aws @param {string} roleName
|
|
256
|
+
*/
|
|
257
|
+
function liveStatements(aws, roleName) {
|
|
258
|
+
const doc = aws(['iam', 'get-role', '--role-name', roleName]).Role.AssumeRolePolicyDocument
|
|
259
|
+
const policy = typeof doc === 'string' ? JSON.parse(decodeURIComponent(doc)) : doc
|
|
260
|
+
return [].concat(policy.Statement || [])
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The connection-authorizers SSM parameter the stack derives.
|
|
265
|
+
* @param {AwsJson} aws
|
|
266
|
+
* @returns {{ connectionAuthorizerArns: string[], controlPlanes: string[] }}
|
|
267
|
+
*/
|
|
268
|
+
function readAuthorizersParameter(aws) {
|
|
269
|
+
return JSON.parse(aws(['ssm', 'get-parameter', '--name', AUTHORIZERS_SSM_NAME]).Parameter.Value)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The stack as read back after an update, with the checks every write shares: same FoundationVersion, every entry of
|
|
274
|
+
* `read` other than `ownId` byte-identical, and the SSM parameter matching the authorizers and control planes.
|
|
275
|
+
* @param {AwsJson} aws @param {string} stackName @param {StackRead} read @param {string|null} ownId
|
|
276
|
+
*/
|
|
277
|
+
function readBack(aws, stackName, read, ownId) {
|
|
278
|
+
const after = snapshot(describeStack(aws, stackName))
|
|
279
|
+
if (after.version !== read.version) throw new Error(`FoundationVersion is ${after.version}, expected ${read.version}`)
|
|
280
|
+
assertOthersSurvive(read.params.TrustEntries, after.params.TrustEntries, ownId)
|
|
281
|
+
const ssm = readAuthorizersParameter(aws)
|
|
282
|
+
if (!sameValue(ssm.connectionAuthorizerArns, splitList(after.params.ConnectionAuthorizerArns)) || !sameValue(ssm.controlPlanes, controlPlaneIds(after.params.TrustEntries))) {
|
|
283
|
+
throw new Error(`${AUTHORIZERS_SSM_NAME} does not match ConnectionAuthorizerArns and TrustEntries`)
|
|
284
|
+
}
|
|
285
|
+
return after
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Writes this control plane's TrustEntries entry into the account foundation (home stack), changing only the entry roles'
|
|
290
|
+
* trust statements: reads the installed template (GetTemplate Original), merges `mutate(ownEntry)` into the installed
|
|
291
|
+
* TrustEntries, re-renders the two Statement lines (and the SSM controlPlanes literal), submits a change set with every
|
|
292
|
+
* other parameter UsePreviousValue, refuses any other change, executes only if the stack has not moved since the read,
|
|
293
|
+
* then verifies the read-back entries, template and live role policies. Retries a moved stack up to `maxAttempts` times.
|
|
294
|
+
* @param {{ aws: AwsJson, stackName?: string, homeRegion: string, controlPlaneId: string,
|
|
295
|
+
* mutate: (own: TrustEntry|null) => TrustEntry|Promise<TrustEntry>, mergeOptions?: { handoff?: boolean, identifierChange?: boolean },
|
|
296
|
+
* maxAttempts?: number, wait: Wait, log?: (...a: unknown[]) => void }} o
|
|
297
|
+
* @returns {Promise<WriteResult>}
|
|
298
|
+
*/
|
|
299
|
+
async function writeTrustEntries({ aws, stackName = FOUNDATION_STACK, homeRegion, controlPlaneId, mutate, mergeOptions = {}, maxAttempts = DEFAULT_MAX_ATTEMPTS, wait, log = () => {} }) {
|
|
300
|
+
const label = `${stackName} (${homeRegion})`
|
|
301
|
+
const attempt = async () => {
|
|
302
|
+
const read = await readSettled(aws, stackName, label, wait)
|
|
303
|
+
assertOperable(read, label)
|
|
304
|
+
const installedEntries = read.params.TrustEntries
|
|
305
|
+
const own = parseTrustEntries(installedEntries).find((p) => p.entry.controlPlaneId === controlPlaneId)
|
|
306
|
+
const desired = await mutate(own ? own.entry : null)
|
|
307
|
+
if (!desired || desired.controlPlaneId !== controlPlaneId) {
|
|
308
|
+
throw new Error(`trust entry update returned an entry for ${desired && desired.controlPlaneId}, not ${controlPlaneId}; nothing was changed`)
|
|
309
|
+
}
|
|
310
|
+
const merged = mergeTrustEntry(installedEntries, desired, mergeOptions)
|
|
311
|
+
const installed = aws(['cloudformation', 'get-template', '--stack-name', stackName, '--template-stage', 'Original']).TemplateBody
|
|
312
|
+
if (typeof installed !== 'string') throw new Error(`${label}: the installed template is not YAML text this CLI can patch; nothing was changed`)
|
|
313
|
+
const template = renderFoundationTemplate(installed, merged)
|
|
314
|
+
if (merged === installedEntries && template === installed) return 'unchanged'
|
|
315
|
+
if (Buffer.byteLength(template, 'utf8') > CFN_INLINE_TEMPLATE_LIMIT) {
|
|
316
|
+
throw new Error(`${label}: the installed template exceeds the ${CFN_INLINE_TEMPLATE_LIMIT}-byte inline limit; upgrade the foundation first. Nothing was changed.`)
|
|
317
|
+
}
|
|
318
|
+
const controlPlanesChanged = !sameValue(controlPlaneIds(installedEntries), controlPlaneIds(merged))
|
|
319
|
+
const roleIds = Object.values(ENTRY_ROLES).map((r) => r.logicalId)
|
|
320
|
+
return applyGuarded({
|
|
321
|
+
aws, stackName, label, wait, log, read, template, set: { TrustEntries: merged }, description: `saaslayer trust entry ${controlPlaneId}`,
|
|
322
|
+
allowed: (c) => (roleIds.includes(c.logicalId) && c.type === 'AWS::IAM::Role' && c.properties.every((p) => p === 'AssumeRolePolicyDocument')) ||
|
|
323
|
+
(controlPlanesChanged && c.logicalId === AUTHORIZERS_PARAMETER && c.type === 'AWS::SSM::Parameter' && c.properties.every((p) => p === 'Value')),
|
|
324
|
+
verify: () => {
|
|
325
|
+
const after = readBack(aws, stackName, read, controlPlaneId)
|
|
326
|
+
const entries = after.params.TrustEntries
|
|
327
|
+
const live = parseTrustEntries(entries).find((p) => p.entry.controlPlaneId === controlPlaneId)
|
|
328
|
+
if (!live || !sameValue(live.entry, desired)) throw new Error(`trust entry ${controlPlaneId} is not the one written`)
|
|
329
|
+
if (entries === merged) {
|
|
330
|
+
const now = aws(['cloudformation', 'get-template', '--stack-name', stackName, '--template-stage', 'Original']).TemplateBody
|
|
331
|
+
if (now !== template) throw new Error('the installed template is not the one submitted')
|
|
332
|
+
}
|
|
333
|
+
for (const role of /** @type {Array<'deploy'|'support'>} */ (['deploy', 'support'])) {
|
|
334
|
+
if (!sameValue(liveStatements(aws, ROLE_NAMES[role]), renderTrustStatements(entries, role))) {
|
|
335
|
+
throw new Error(`${ROLE_NAMES[role]}'s live trust policy does not match TrustEntries`)
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
},
|
|
339
|
+
})
|
|
340
|
+
}
|
|
341
|
+
return retryStale({ label, maxAttempts, log, attempt })
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Adds or removes one connection authorizer (an IAM principal ARN, stored as its path-less role ARN) through a
|
|
346
|
+
* parameter-only change set that keeps the installed template; refuses removing the last one and any change beyond the
|
|
347
|
+
* SSM parameter, then verifies the SSM parameter the stack derives. Retries a moved stack up to `maxAttempts` times.
|
|
348
|
+
* @param {{ aws: AwsJson, stackName?: string, homeRegion: string, add?: string, remove?: string, maxAttempts?: number, wait: Wait,
|
|
349
|
+
* log?: (...a: unknown[]) => void }} o
|
|
350
|
+
* @returns {Promise<WriteResult>}
|
|
351
|
+
*/
|
|
352
|
+
async function writeConnectionAuthorizers({ aws, stackName = FOUNDATION_STACK, homeRegion, add, remove, maxAttempts = DEFAULT_MAX_ATTEMPTS, wait, log = () => {} }) {
|
|
353
|
+
const label = `${stackName} (${homeRegion})`
|
|
354
|
+
if ((add === undefined) === (remove === undefined)) throw new Error('connection authorizers: give exactly one of add or remove')
|
|
355
|
+
const arn = canonicalRoleArn(add !== undefined ? add : remove)
|
|
356
|
+
const attempt = async () => {
|
|
357
|
+
const read = await readSettled(aws, stackName, label, wait)
|
|
358
|
+
assertOperable(read, label)
|
|
359
|
+
const list = splitList(read.params.ConnectionAuthorizerArns)
|
|
360
|
+
const next = add !== undefined ? (list.includes(arn) ? list : [...list, arn]) : list.filter((a) => a !== arn)
|
|
361
|
+
if (!next.length) throw new Error(`${label}: ${arn} is the last connection authorizer; add another before removing it. Nothing was changed.`)
|
|
362
|
+
if (sameValue(next, list)) return 'unchanged'
|
|
363
|
+
return applyGuarded({
|
|
364
|
+
aws, stackName, label, wait, log, read, template: null, set: { ConnectionAuthorizerArns: next.join(',') },
|
|
365
|
+
description: `saaslayer connection authorizers ${add !== undefined ? 'add' : 'remove'}`,
|
|
366
|
+
allowed: (c) => c.logicalId === AUTHORIZERS_PARAMETER && c.type === 'AWS::SSM::Parameter' && c.properties.every((p) => p === 'Value'),
|
|
367
|
+
verify: () => {
|
|
368
|
+
const after = splitList(readBack(aws, stackName, read, null).params.ConnectionAuthorizerArns)
|
|
369
|
+
const kept = list.filter((a) => a !== arn)
|
|
370
|
+
if (!kept.every((a) => after.includes(a)) || after.includes(arn) !== (add !== undefined)) {
|
|
371
|
+
throw new Error('ConnectionAuthorizerArns does not reflect this update')
|
|
372
|
+
}
|
|
373
|
+
},
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
return retryStale({ label, maxAttempts, log, attempt })
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
module.exports = { TRUST_ENTRIES_SINCE, AUTHORIZERS_SSM_NAME, writeTrustEntries, writeConnectionAuthorizers }
|
package/src/iam-session.js
CHANGED
|
@@ -5,22 +5,26 @@ const crypto = require('crypto')
|
|
|
5
5
|
const { execFileSync } = require('child_process')
|
|
6
6
|
const { signRequest } = require('./aws-sigv4')
|
|
7
7
|
|
|
8
|
+
/** @param {string} cmd @param {string[]} args */
|
|
9
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8' })
|
|
10
|
+
|
|
8
11
|
/**
|
|
9
12
|
* Your current AWS credentials (env, profile, SSO) via the AWS CLI.
|
|
10
|
-
* @param {{ profile?: string }} [opts]
|
|
13
|
+
* @param {{ profile?: string, exec?: (cmd: string, args: string[]) => string }} [opts]
|
|
11
14
|
* @returns {{ accessKeyId: string, secretAccessKey: string, sessionToken?: string }}
|
|
12
15
|
*/
|
|
13
|
-
function awsCredentials({ profile } = {}) {
|
|
16
|
+
function awsCredentials({ profile, exec = defaultExec } = {}) {
|
|
14
17
|
const args = ['configure', 'export-credentials', '--format', 'process', ...(profile ? ['--profile', profile] : [])]
|
|
15
|
-
const c = JSON.parse(
|
|
18
|
+
const c = JSON.parse(exec('aws', args))
|
|
16
19
|
return { accessKeyId: c.AccessKeyId, secretAccessKey: c.SecretAccessKey, sessionToken: c.SessionToken }
|
|
17
20
|
}
|
|
18
21
|
|
|
19
22
|
/**
|
|
20
|
-
* Signed STS GetCallerIdentity request binding the proof to `principalId
|
|
21
|
-
*
|
|
23
|
+
* Signed STS GetCallerIdentity request binding the proof to `principalId`, to the deployment it is sent to (`audience`,
|
|
24
|
+
* its API base URL) and to a one-time nonce.
|
|
25
|
+
* @param {{ principalId: string, audience: string, region: string, credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date, nonce?: string }} opts
|
|
22
26
|
*/
|
|
23
|
-
function buildStsEnvelope({ principalId, region, credentials, now = new Date(), nonce = crypto.randomUUID() }) {
|
|
27
|
+
function buildStsEnvelope({ principalId, audience, region, credentials, now = new Date(), nonce = crypto.randomUUID() }) {
|
|
24
28
|
const host = `sts.${region}.amazonaws.com`
|
|
25
29
|
const url = `https://${host}/`
|
|
26
30
|
const body = 'Action=GetCallerIdentity&Version=2011-06-15'
|
|
@@ -39,6 +43,7 @@ function buildStsEnvelope({ principalId, region, credentials, now = new Date(),
|
|
|
39
43
|
'X-Saaslayer-Principal-Id': principalId,
|
|
40
44
|
'X-Saaslayer-Nonce': nonce,
|
|
41
45
|
'X-Saaslayer-Timestamp': now.toISOString().replace(/\.\d{3}/, ''),
|
|
46
|
+
'X-Saaslayer-Audience': audience,
|
|
42
47
|
},
|
|
43
48
|
})
|
|
44
49
|
return { method: 'POST', url, headers, body }
|
|
@@ -50,8 +55,9 @@ function buildStsEnvelope({ principalId, region, credentials, now = new Date(),
|
|
|
50
55
|
* @returns {Promise<string>}
|
|
51
56
|
*/
|
|
52
57
|
async function exchangeIamToken({ apiBase, principalId, region, credentials, profile }) {
|
|
53
|
-
const
|
|
54
|
-
const
|
|
58
|
+
const base = apiBase.replace(/\/$/, '')
|
|
59
|
+
const envelope = buildStsEnvelope({ principalId, audience: base, region, credentials: credentials || awsCredentials({ profile }) })
|
|
60
|
+
const res = await fetch(`${base}/auth/aws-iam`, {
|
|
55
61
|
method: 'POST',
|
|
56
62
|
headers: { 'content-type': 'application/json' },
|
|
57
63
|
body: JSON.stringify({ principalId, envelope }),
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// CLI login-domain guards: the deployer-owned login-domain settings are refused before anything is sent; a change of the
|
|
2
|
+
// login host a user-service advertises (ActiveLoginDomain, ADR 0007 E8) needs --confirm-domain <current login domain> --reason.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
const { apiBase } = require('./api-client')
|
|
7
|
+
const { discoverDeployment } = require('./discovery')
|
|
8
|
+
|
|
9
|
+
// The shared rules (packages/config): monorepo source first (vendor/ is a prepack snapshot), else the published copy.
|
|
10
|
+
const MONOREPO_RULES = path.join(__dirname, '../../config/src/login-domain.js')
|
|
11
|
+
const VENDORED_RULES = path.join(__dirname, '../vendor/config/login-domain.js')
|
|
12
|
+
|
|
13
|
+
/** @returns {typeof import('../../config/src/login-domain.js')} */
|
|
14
|
+
function loginDomainRules() {
|
|
15
|
+
return require(fs.existsSync(MONOREPO_RULES) ? MONOREPO_RULES : VENDORED_RULES)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Each module ref's current (non-secret) setting values, as the settings read shows them.
|
|
20
|
+
* @param {import('./settings').DeploymentSettings} settings
|
|
21
|
+
* @returns {Record<string, Record<string, unknown>>}
|
|
22
|
+
*/
|
|
23
|
+
function currentValues(settings) {
|
|
24
|
+
return Object.fromEntries(settings.modules.map((m) => [m.ref || m.module, Object.fromEntries(m.settings.filter((s) => !s.secret && s.value !== null && s.value !== undefined).map((s) => [s.name, s.value]))]))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The host a ref advertises while no custom domain is active (its opaque default), from the deployment's public
|
|
29
|
+
* discovery; null when it is not discoverable (the control plane then checks the typed domain).
|
|
30
|
+
* @param {string} ref @param {string} deploymentId @param {object} flags
|
|
31
|
+
* @returns {Promise<string|null>}
|
|
32
|
+
*/
|
|
33
|
+
async function discoveredLoginHost(ref, deploymentId, flags) {
|
|
34
|
+
const instance = ref.split('@')[1]
|
|
35
|
+
try {
|
|
36
|
+
const doc = await discoverDeployment({ apiBase: apiBase(flags), deploymentId, ...(instance ? { instances: { 'user-service': instance } } : {}) })
|
|
37
|
+
return loginDomainRules().normalizeLoginDomain(doc.hostedLoginUrl) || null
|
|
38
|
+
} catch {
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The refusal as the CLI prints it: the shared code and title, then each thing that breaks and the unchanged issuer.
|
|
45
|
+
* @param {Error & { code?: string }} refused
|
|
46
|
+
* @param {import('../../config/src/login-domain.js').LoginDomainBreaks} breaks
|
|
47
|
+
* @param {string|null} oldHost
|
|
48
|
+
*/
|
|
49
|
+
function refusalError(refused, breaks, oldHost) {
|
|
50
|
+
const host = oldHost || 'the current login domain'
|
|
51
|
+
const lines = [
|
|
52
|
+
...breaks.providerRedirects.map(({ provider, redirectUri }) => ` - ${provider} redirect URI ${redirectUri}`),
|
|
53
|
+
...breaks.appCallbacks.map((url) => ` - app callback ${url}`),
|
|
54
|
+
` - apps built with SAASLAYER_HOSTED_LOGIN_URL=https://${host} (saaslayer env export) need a rebuild`,
|
|
55
|
+
` - hosted-UI sessions on ${host} sign in once more`,
|
|
56
|
+
' - the issuer does not change',
|
|
57
|
+
]
|
|
58
|
+
return Object.assign(new Error(`${refused.code}: ${refused.message}\n${lines.join('\n')}`), { code: refused.code })
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Refuse a patch that names a deployer-owned login-domain setting (LOGIN_DOMAIN_MANAGED_SETTING), before anything is sent.
|
|
63
|
+
* @param {import('./settings').SettingsPatch} patch
|
|
64
|
+
*/
|
|
65
|
+
function refuseManagedLoginDomainSettings(patch) {
|
|
66
|
+
try {
|
|
67
|
+
loginDomainRules().refuseManagedLoginDomainSettings(patch)
|
|
68
|
+
} catch (err) {
|
|
69
|
+
const refused = /** @type {Error & { code?: string }} */ (err)
|
|
70
|
+
throw Object.assign(new Error(`${refused.code}: ${refused.message}`), { code: refused.code })
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Admit the login-domain changes in a patch, or refuse before anything is sent. --confirm-domain (or --domain-handoff)
|
|
76
|
+
* with --reason is the handoff. Returns the request's domainHandoff (absent when no login domain changes) and the
|
|
77
|
+
* acknowledgements whose checklist is printed once the write is accepted.
|
|
78
|
+
* @param {{ patch: import('./settings').SettingsPatch, settings: import('./settings').DeploymentSettings, deploymentId: string, flags: Record<string, any> }} input
|
|
79
|
+
* @returns {Promise<{ domainHandoff?: { confirmDomain?: string, reason?: string }, handoffs: import('../../config/src/login-domain.js').LoginDomainHandoff[] }>}
|
|
80
|
+
*/
|
|
81
|
+
async function admitLoginDomainChanges({ patch, settings, deploymentId, flags }) {
|
|
82
|
+
const rules = loginDomainRules()
|
|
83
|
+
const stored = currentValues(settings)
|
|
84
|
+
const changes = rules.loginDomainChanges({ parameters: patch, stored })
|
|
85
|
+
const handoffRequested = flags['domain-handoff'] === true || typeof flags['confirm-domain'] === 'string'
|
|
86
|
+
if (changes.length === 0) {
|
|
87
|
+
if (handoffRequested) throw new Error(`--domain-handoff and --confirm-domain are only for a change of user-service.${rules.ACTIVE_LOGIN_DOMAIN_SETTING}`)
|
|
88
|
+
return { handoffs: [] }
|
|
89
|
+
}
|
|
90
|
+
const domainHandoff = handoffRequested ? handoffFromFlags(flags) : undefined
|
|
91
|
+
const handoffs = []
|
|
92
|
+
for (const { service, from, to } of changes) {
|
|
93
|
+
const oldHost = from || await discoveredLoginHost(service, deploymentId, flags)
|
|
94
|
+
handoffs.push(admitHandoff({ service, oldHost, newHost: to || null, settings: stored[service] || {}, domainHandoff }))
|
|
95
|
+
}
|
|
96
|
+
return { domainHandoff, handoffs }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The domainHandoff --confirm-domain and --reason give. @param {Record<string, any>} flags */
|
|
100
|
+
function handoffFromFlags(flags) {
|
|
101
|
+
return { ...(typeof flags['confirm-domain'] === 'string' ? { confirmDomain: flags['confirm-domain'] } : {}), ...(typeof flags.reason === 'string' ? { reason: flags.reason } : {}) }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* One handoff admitted by the shared rules, or the CLI refusal listing what breaks.
|
|
106
|
+
* @param {{ service: string, oldHost: string|null, newHost: string|null, settings: Record<string, unknown>, domainHandoff: unknown }} input
|
|
107
|
+
*/
|
|
108
|
+
function admitHandoff({ service, oldHost, newHost, settings, domainHandoff }) {
|
|
109
|
+
const rules = loginDomainRules()
|
|
110
|
+
try {
|
|
111
|
+
return rules.admitLoginDomainHandoff({ service, oldHost, newHost, settings, domainHandoff })
|
|
112
|
+
} catch (err) {
|
|
113
|
+
if (/** @type {{ code?: string }} */ (err).code !== rules.LOGIN_DOMAIN_HANDOFF_REQUIRED) throw err
|
|
114
|
+
throw refusalError(/** @type {Error & { code?: string }} */ (err), rules.loginDomainBreaks(settings, oldHost), oldHost)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Admit a switch of the advertised login host (`saaslayer login-domain activate|deactivate`) from --confirm-domain and
|
|
120
|
+
* --reason, or refuse before anything is sent. Returns the request's domainHandoff and the acknowledgement.
|
|
121
|
+
* @param {{ service: string, fromHost: string, toHost: string, settings: import('./settings').DeploymentSettings, flags: Record<string, any> }} input
|
|
122
|
+
*/
|
|
123
|
+
function admitLoginDomainSwitch({ service, fromHost, toHost, settings, flags }) {
|
|
124
|
+
const domainHandoff = handoffFromFlags(flags)
|
|
125
|
+
const handoff = admitHandoff({ service, oldHost: fromHost, newHost: toHost, settings: currentValues(settings)[service] || {}, domainHandoff })
|
|
126
|
+
return { domainHandoff, handoff }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The completion checklist of accepted handoffs.
|
|
131
|
+
* @param {import('../../config/src/login-domain.js').LoginDomainHandoff[]} handoffs
|
|
132
|
+
* @returns {string[]}
|
|
133
|
+
*/
|
|
134
|
+
function loginDomainChecklist(handoffs) {
|
|
135
|
+
return handoffs.flatMap((handoff) => loginDomainRules().loginDomainChecklist(handoff).map((line) => ` - ${line}`))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = { refuseManagedLoginDomainSettings, admitLoginDomainChanges, admitLoginDomainSwitch, loginDomainChecklist, VENDORED_RULES }
|