saaslayer 0.0.7 → 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 +150 -13
- package/bin/saaslayer.js +297 -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/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 +405 -0
- package/src/commands/lifecycle.js +72 -39
- 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.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.yml +23 -6
- 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/login.js
CHANGED
|
@@ -1,46 +1,163 @@
|
|
|
1
|
-
// `saaslayer login|logout|whoami` — authenticate to the
|
|
2
|
-
//
|
|
1
|
+
// `saaslayer login|logout|whoami` — authenticate via Cognito SRP (headless, D9) to the SaaSLayer control plane or, with
|
|
2
|
+
// --deployment, to a deployment's user-service (discovered from its public outputs), caching each login separately.
|
|
3
3
|
'use strict'
|
|
4
4
|
const readline = require('readline')
|
|
5
5
|
const creds = require('../credentials')
|
|
6
|
-
const { resolvePoolConfig, decodeJwt } = require('../config')
|
|
6
|
+
const { resolvePoolConfig, decodeJwt, controlPlaneUrl } = require('../config')
|
|
7
|
+
const { discoverDeployment, discoverFromFlags } = require('../discovery')
|
|
7
8
|
|
|
8
9
|
// Prompt for a value; hidden masks input (passwords). Only used when no flag/env supplies it.
|
|
9
|
-
function prompt(question, { hidden = false } = {}) {
|
|
10
|
+
function prompt(question, { hidden = false, input = process.stdin, output = process.stdout } = {}) {
|
|
10
11
|
return new Promise((resolve) => {
|
|
11
|
-
const rl = readline.createInterface({ input
|
|
12
|
+
const rl = readline.createInterface({ input, output, terminal: true })
|
|
12
13
|
if (hidden) {
|
|
13
14
|
// Suppress readline's own keystroke echo so only our mask shows (not char+mask interleaved).
|
|
14
15
|
rl._writeToOutput = () => {}
|
|
15
|
-
process.stdout.write(question)
|
|
16
16
|
const onData = (char) => {
|
|
17
17
|
char = String(char)
|
|
18
|
-
if (char === '\u007f' || char === '\b') {
|
|
19
|
-
if (['\n', '\r', '
|
|
20
|
-
|
|
18
|
+
if (char === '\u007f' || char === '\b') { output.write('\b \b'); return } // backspace
|
|
19
|
+
if (['\n', '\r', ''].includes(char)) return
|
|
20
|
+
output.write('*')
|
|
21
21
|
}
|
|
22
|
-
|
|
23
|
-
rl.question('', (answer) => {
|
|
22
|
+
input.on('data', onData)
|
|
23
|
+
rl.question('', (answer) => { input.removeListener('data', onData); rl.close(); output.write('\n'); resolve(answer) })
|
|
24
|
+
// Written after question(''): readline's line redraw clears the row, which erased a question written first.
|
|
25
|
+
output.write(question)
|
|
24
26
|
} else {
|
|
25
27
|
rl.question(question, (answer) => { rl.close(); resolve(answer) })
|
|
26
28
|
}
|
|
27
29
|
})
|
|
28
30
|
}
|
|
29
31
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Password: ', { hidden: true }))
|
|
32
|
+
/**
|
|
33
|
+
* @typedef {{ idToken: string, accessToken?: string, refreshToken?: string, expiresIn?: number }} LoginTokens
|
|
34
|
+
* @typedef {{ region: string, userPoolId: string, clientId: string }} PoolCoordinates
|
|
35
|
+
*/
|
|
35
36
|
|
|
36
|
-
|
|
37
|
-
|
|
37
|
+
/**
|
|
38
|
+
* The tokens of a finished SRP step. A step the CLI cannot answer is refused with its name.
|
|
39
|
+
* @param {{ code?: string, error?: any, response?: { tokens: LoginTokens } }} value
|
|
40
|
+
* @returns {LoginTokens}
|
|
41
|
+
*/
|
|
42
|
+
function tokensFromStep(value) {
|
|
38
43
|
if (value.code === 'ERROR') throw new Error(`login failed: ${(value.error && (value.error.message || value.error)) || 'unknown error'}`)
|
|
39
|
-
if (value.code !== 'TOKENS') {
|
|
40
|
-
throw new Error(`login requires the '${value.code}' step
|
|
44
|
+
if (value.code !== 'TOKENS' || !value.response) {
|
|
45
|
+
throw new Error(`login requires the '${value.code}' step, which the CLI cannot answer; complete it in the hosted login page`)
|
|
46
|
+
}
|
|
47
|
+
return value.response.tokens
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** SRP challenge steps the CLI answers. */
|
|
51
|
+
const CHALLENGES = ['NEW_PASSWORD_REQUIRED', 'SOFTWARE_MFA_REQUIRED', 'SMS_MFA_REQUIRED']
|
|
52
|
+
const MAX_MFA_ATTEMPTS = 3
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @typedef {{ isTTY: boolean, readStdin: () => Promise<string>, prompt: (question: string, opts?: { hidden?: boolean }) => Promise<string> }} LoginIo
|
|
56
|
+
* @typedef {{ code: string, hint?: string, error?: unknown }} ChallengeStep
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
/** @returns {Promise<string>} all of stdin */
|
|
60
|
+
async function readStdin() {
|
|
61
|
+
const chunks = []
|
|
62
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk))
|
|
63
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** @type {LoginIo} */
|
|
67
|
+
const terminalIo = { get isTTY() { return Boolean(process.stdin.isTTY) }, readStdin, prompt }
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The new password for NEW_PASSWORD_REQUIRED: piped on stdin with --new-password-stdin, else typed twice (hidden).
|
|
71
|
+
* @param {Record<string, any>} flags
|
|
72
|
+
* @param {LoginIo} io
|
|
73
|
+
* @returns {Promise<string>}
|
|
74
|
+
*/
|
|
75
|
+
async function readNewPassword(flags, io) {
|
|
76
|
+
if (flags['new-password-stdin']) {
|
|
77
|
+
const piped = (await io.readStdin()).replace(/\r?\n$/, '')
|
|
78
|
+
if (!piped) throw new Error('new password read from stdin is empty')
|
|
79
|
+
return piped
|
|
80
|
+
}
|
|
81
|
+
if (!io.isTTY) throw new Error('this account requires a new password: pipe it with --new-password-stdin, or run login in a terminal')
|
|
82
|
+
const chosen = await io.prompt('New password: ', { hidden: true })
|
|
83
|
+
if (!chosen) throw new Error('new password is empty')
|
|
84
|
+
const confirmed = await io.prompt('Confirm new password: ', { hidden: true })
|
|
85
|
+
if (chosen !== confirmed) throw new Error('new passwords do not match')
|
|
86
|
+
return chosen
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Answers the SRP challenges of one login from flags or the terminal. A code from --mfa-code is used once; when it
|
|
91
|
+
* is rejected the login fails. Typed codes are re-prompted up to MAX_MFA_ATTEMPTS. Answers are never printed.
|
|
92
|
+
* @param {Record<string, any>} flags --new-password-stdin, --mfa-code
|
|
93
|
+
* @param {LoginIo} io
|
|
94
|
+
* @returns {(step: ChallengeStep) => Promise<string>}
|
|
95
|
+
*/
|
|
96
|
+
function challengeAnswerer(flags, io) {
|
|
97
|
+
let mfaAttempts = 0
|
|
98
|
+
let mfaFromFlag = false
|
|
99
|
+
return async (step) => {
|
|
100
|
+
if (step.code === 'NEW_PASSWORD_REQUIRED') return readNewPassword(flags, io)
|
|
101
|
+
const rejected = Boolean(step.error)
|
|
102
|
+
if (rejected && mfaFromFlag) throw new Error('MFA code was rejected')
|
|
103
|
+
if (rejected && mfaAttempts >= MAX_MFA_ATTEMPTS) throw new Error(`MFA code was rejected ${MAX_MFA_ATTEMPTS} times`)
|
|
104
|
+
if (flags['mfa-code'] !== undefined && !rejected) {
|
|
105
|
+
const code = flags['mfa-code']
|
|
106
|
+
if (typeof code !== 'string' || !/^\d{6}$/.test(code)) throw new Error('--mfa-code must be 6 digits')
|
|
107
|
+
mfaFromFlag = true
|
|
108
|
+
mfaAttempts++
|
|
109
|
+
return code
|
|
110
|
+
}
|
|
111
|
+
if (!io.isTTY) throw new Error('this account requires an MFA code: pass --mfa-code <6 digits>, or run login in a terminal')
|
|
112
|
+
const source = step.code === 'SMS_MFA_REQUIRED' ? `SMS code sent to ${step.hint || 'your phone'}` : 'MFA code from your authenticator app'
|
|
113
|
+
mfaAttempts++
|
|
114
|
+
return io.prompt(`${rejected ? 'Incorrect code. ' : ''}${source}: `, { hidden: true })
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Sign in to one Cognito pool client with SRP, answering NEW_PASSWORD_REQUIRED and MFA challenges from flags or the
|
|
120
|
+
* terminal. Both login authorities go through here.
|
|
121
|
+
* @param {PoolCoordinates} pool
|
|
122
|
+
* @param {{ email: string, password: string }} credentials
|
|
123
|
+
* @param {{ flags?: Record<string, any>, io?: LoginIo, srpLogin?: Function }} [opts]
|
|
124
|
+
* @returns {Promise<LoginTokens>}
|
|
125
|
+
*/
|
|
126
|
+
async function authenticate(pool, { email, password }, { flags = {}, io = terminalIo, srpLogin } = {}) {
|
|
127
|
+
const run = srpLogin || require('@davidwells/cogneato').srpLogin
|
|
128
|
+
const steps = run({ region: pool.region, userPoolId: pool.userPoolId, clientId: pool.clientId, username: email, password })
|
|
129
|
+
const answer = challengeAnswerer(flags, io)
|
|
130
|
+
try {
|
|
131
|
+
let step = await steps.next()
|
|
132
|
+
while (!step.done && step.value && CHALLENGES.includes(step.value.code)) {
|
|
133
|
+
step = await steps.next(await answer(step.value))
|
|
134
|
+
}
|
|
135
|
+
return tokensFromStep(step.value || {})
|
|
136
|
+
} finally {
|
|
137
|
+
await steps.return(undefined)
|
|
41
138
|
}
|
|
139
|
+
}
|
|
42
140
|
|
|
43
|
-
|
|
141
|
+
/**
|
|
142
|
+
* Email + password from flags, env or an interactive prompt.
|
|
143
|
+
* @param {Record<string, any>} flags
|
|
144
|
+
* @returns {Promise<{ email: string, password: string }>}
|
|
145
|
+
*/
|
|
146
|
+
async function readCredentials(flags) {
|
|
147
|
+
const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
|
|
148
|
+
const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Password: ', { hidden: true }))
|
|
149
|
+
return { email, password }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Log in to the SaaSLayer control plane and make that account current. Deployment logins are not touched.
|
|
154
|
+
* @param {Record<string, any>} flags
|
|
155
|
+
* @param {{ authenticate?: typeof authenticate, srpLogin?: Function, io?: LoginIo }} [deps]
|
|
156
|
+
*/
|
|
157
|
+
async function login(flags = {}, deps = {}) {
|
|
158
|
+
const pool = await resolvePoolConfig(flags)
|
|
159
|
+
const { email, password } = await readCredentials(flags)
|
|
160
|
+
const tokens = await (deps.authenticate || authenticate)(pool, { email, password }, { flags, io: deps.io, srpLogin: deps.srpLogin })
|
|
44
161
|
const claims = decodeJwt(tokens.idToken)
|
|
45
162
|
const userId = claims.sub
|
|
46
163
|
const expiresAt = Math.floor(Date.now() / 1000) + (Number(tokens.expiresIn) || 3600)
|
|
@@ -48,6 +165,9 @@ async function login(flags = {}) {
|
|
|
48
165
|
userId,
|
|
49
166
|
email: claims.email || email,
|
|
50
167
|
env: flags.env || 'prod',
|
|
168
|
+
issuer: claims.iss,
|
|
169
|
+
clientId: pool.clientId,
|
|
170
|
+
region: pool.region,
|
|
51
171
|
idToken: tokens.idToken,
|
|
52
172
|
accessToken: tokens.accessToken,
|
|
53
173
|
refreshToken: tokens.refreshToken,
|
|
@@ -56,13 +176,55 @@ async function login(flags = {}) {
|
|
|
56
176
|
return { userId, email: claims.email || email }
|
|
57
177
|
}
|
|
58
178
|
|
|
179
|
+
/**
|
|
180
|
+
* `saaslayer login --deployment <dep_id|env>`: log in to a deployment's user-service (option B access admin).
|
|
181
|
+
* The pool, client and API bases come from the deployment's public discovery document; an environment name is first
|
|
182
|
+
* resolved to the project's deployment. The token must come from the discovered issuer and one of its app clients.
|
|
183
|
+
* The login is stored as its own profile and made the current deployment login; the control-plane login is kept.
|
|
184
|
+
* @param {Record<string, any>} flags --deployment, --user-service-instance, --region, --project, --config-url, --email, --password,
|
|
185
|
+
* --new-password-stdin, --mfa-code
|
|
186
|
+
* @param {{ authenticate?: typeof authenticate, discover?: typeof discoverDeployment, srpLogin?: Function, io?: LoginIo }} [deps]
|
|
187
|
+
*/
|
|
188
|
+
async function loginDeployment(flags, deps = {}) {
|
|
189
|
+
const selector = flags.deployment
|
|
190
|
+
if (!selector || typeof selector !== 'string') throw new Error('login --deployment requires a deployment id (dep_…) or an environment name')
|
|
191
|
+
const { doc, deploymentId, environment, project } = await discoverFromFlags({ ...flags, 'discovery-url': undefined }, { discover: deps.discover })
|
|
192
|
+
const instance = flags['user-service-instance'] || null
|
|
193
|
+
const pool = { region: doc.region, userPoolId: doc.userPoolId, clientId: doc.clientId }
|
|
194
|
+
const { email, password } = await readCredentials(flags)
|
|
195
|
+
const tokens = await (deps.authenticate || authenticate)(pool, { email, password }, { flags, io: deps.io, srpLogin: deps.srpLogin })
|
|
196
|
+
const claims = decodeJwt(tokens.idToken)
|
|
197
|
+
if (claims.iss !== doc.issuer) throw new Error(`login token issuer ${claims.iss} does not match deployment ${deploymentId} (${doc.issuer})`)
|
|
198
|
+
if (!doc.audience.includes(claims.aud)) throw new Error(`login token audience ${claims.aud} is not a client of deployment ${deploymentId}`)
|
|
199
|
+
const profile = creds.setDeploymentProfile({
|
|
200
|
+
deploymentId,
|
|
201
|
+
serviceInstance: instance || 'default',
|
|
202
|
+
environment,
|
|
203
|
+
project,
|
|
204
|
+
userId: claims.sub,
|
|
205
|
+
suid: claims['custom:suid'] || null,
|
|
206
|
+
email: claims.email || email,
|
|
207
|
+
issuer: doc.issuer,
|
|
208
|
+
audience: doc.audience,
|
|
209
|
+
clientId: doc.clientId,
|
|
210
|
+
region: doc.region,
|
|
211
|
+
userPoolId: doc.userPoolId,
|
|
212
|
+
usersApiBase: doc.usersApiBase,
|
|
213
|
+
permissionsApiBase: doc.permissionsApiBase,
|
|
214
|
+
idToken: tokens.idToken,
|
|
215
|
+
accessToken: tokens.accessToken,
|
|
216
|
+
refreshToken: tokens.refreshToken,
|
|
217
|
+
expiresAt: Math.floor(Date.now() / 1000) + (Number(tokens.expiresIn) || 3600),
|
|
218
|
+
})
|
|
219
|
+
return { deploymentId, serviceInstance: profile.serviceInstance, environment, email: profile.email, userId: profile.userId }
|
|
220
|
+
}
|
|
221
|
+
|
|
59
222
|
// Create a SaaSLayer account via the control-plane signup endpoint (allowlist-gated), then log in.
|
|
60
223
|
async function signup(flags = {}) {
|
|
61
|
-
const base = flags
|
|
62
|
-
if (!base) throw new Error('signup requires --config-url <control-plane API base> (or $SAASLAYER_CONFIG_URL)')
|
|
224
|
+
const base = String(controlPlaneUrl(flags).value).replace(/\/$/, '')
|
|
63
225
|
const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
|
|
64
226
|
const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Choose a password: ', { hidden: true }))
|
|
65
|
-
const res = await fetch(`${
|
|
227
|
+
const res = await fetch(`${base}/api/signup`, {
|
|
66
228
|
method: 'POST',
|
|
67
229
|
headers: { 'content-type': 'application/json' },
|
|
68
230
|
body: JSON.stringify({ email, password }),
|
|
@@ -79,9 +241,21 @@ function whoami() {
|
|
|
79
241
|
return { userId: current.userId, email: current.email, env: current.env }
|
|
80
242
|
}
|
|
81
243
|
|
|
244
|
+
/**
|
|
245
|
+
* Clear one login on the selected authority. With --deployment (and --as / --user-service-instance) the matching
|
|
246
|
+
* deployment login is removed; otherwise the control-plane account (--user accepts an email or a userId; without it,
|
|
247
|
+
* the active account). The other authority's logins are kept.
|
|
248
|
+
* @param {Record<string, any>} flags
|
|
249
|
+
* @returns {{ authority: 'deployment', deploymentId: string, email: string|null } | { authority: 'control-plane' }}
|
|
250
|
+
*/
|
|
82
251
|
function logout(flags = {}) {
|
|
83
|
-
|
|
252
|
+
if (flags.deployment || flags.as || flags['user-service-instance']) {
|
|
253
|
+
const profile = creds.selectDeploymentProfile(flags)
|
|
254
|
+
creds.clearDeploymentProfile(profile.key)
|
|
255
|
+
return { authority: 'deployment', deploymentId: profile.deploymentId, email: profile.email }
|
|
256
|
+
}
|
|
84
257
|
creds.clear(flags.user ? creds.resolve(flags.user) : undefined)
|
|
258
|
+
return { authority: 'control-plane' }
|
|
85
259
|
}
|
|
86
260
|
|
|
87
|
-
module.exports = { login, signup, whoami, logout }
|
|
261
|
+
module.exports = { login, loginDeployment, authenticate, tokensFromStep, signup, whoami, logout, prompt }
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// `saaslayer permissions machine-trust list|get|declare|update|remove|reconcile`: the deployment's trusted AWS IAM roles
|
|
2
|
+
// through the permissions machine-trust API (access-admin login, API key or IAM) — never a direct SSM write.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { exchangeIamToken } = require('../iam-session')
|
|
5
|
+
const { permissionsRequest } = require('../permissions-request')
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string,
|
|
9
|
+
* 'role-arn'?: string, scope?: string|string[], 'expected-revision'?: string, 'dry-run'?: boolean }} MachineTrustFlags
|
|
10
|
+
* @typedef {{ exchange?: typeof exchangeIamToken }} Deps
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @param {string} label @param {string[]} positional */
|
|
14
|
+
function principalIdOf(label, positional) {
|
|
15
|
+
if (!positional[0]) throw new Error(`${label}: <principalId> is required`)
|
|
16
|
+
return positional[0]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param {MachineTrustFlags} flags @returns {string[]|undefined} */
|
|
20
|
+
function scopesOf(flags) {
|
|
21
|
+
if (flags.scope === undefined) return undefined
|
|
22
|
+
return Array.isArray(flags.scope) ? flags.scope : [flags.scope]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Call a machine-trust route; throws with the API's codes and messages. */
|
|
26
|
+
const call = permissionsRequest
|
|
27
|
+
|
|
28
|
+
/** @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps] */
|
|
29
|
+
async function machineTrustList(positional, flags, deps = {}) {
|
|
30
|
+
const body = await call('permissions machine-trust list', flags, deps, 'GET', '/machine-trust')
|
|
31
|
+
return (body.data || []).map((d) => d.attributes)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps] */
|
|
35
|
+
async function machineTrustGet(positional, flags, deps = {}) {
|
|
36
|
+
const id = principalIdOf('permissions machine-trust get', positional)
|
|
37
|
+
const body = await call('permissions machine-trust get', flags, deps, 'GET', `/machine-trust/${encodeURIComponent(id)}`)
|
|
38
|
+
return body.data.attributes
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Declare a trusted role: <principalId> --role-arn ARN --scope S [--scope S2]. Creates no grant.
|
|
43
|
+
* @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
|
|
44
|
+
*/
|
|
45
|
+
async function machineTrustDeclare(positional, flags, deps = {}) {
|
|
46
|
+
const label = 'permissions machine-trust declare'
|
|
47
|
+
const principalId = principalIdOf(label, positional)
|
|
48
|
+
if (!flags['role-arn']) throw new Error(`${label}: --role-arn <arn> is required`)
|
|
49
|
+
const scopeCeiling = scopesOf(flags)
|
|
50
|
+
if (!scopeCeiling) throw new Error(`${label}: at least one --scope is required`)
|
|
51
|
+
const body = await call(label, flags, deps, 'POST', '/machine-trust', { principalId, roleArn: flags['role-arn'], scopeCeiling })
|
|
52
|
+
return { declaration: body.data.attributes, meta: body.meta || {} }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Change a declaration: <principalId> [--role-arn ARN] [--scope S …] [--expected-revision N].
|
|
57
|
+
* @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
|
|
58
|
+
*/
|
|
59
|
+
async function machineTrustUpdate(positional, flags, deps = {}) {
|
|
60
|
+
const label = 'permissions machine-trust update'
|
|
61
|
+
const principalId = principalIdOf(label, positional)
|
|
62
|
+
const scopeCeiling = scopesOf(flags)
|
|
63
|
+
if (!flags['role-arn'] && !scopeCeiling) throw new Error(`${label}: give --role-arn and/or --scope`)
|
|
64
|
+
/** @type {{ roleArn?: string, scopeCeiling?: string[], expectedRevision?: number }} */
|
|
65
|
+
const patch = {}
|
|
66
|
+
if (flags['role-arn']) patch.roleArn = flags['role-arn']
|
|
67
|
+
if (scopeCeiling) patch.scopeCeiling = scopeCeiling
|
|
68
|
+
if (flags['expected-revision'] !== undefined) {
|
|
69
|
+
const n = Number(flags['expected-revision'])
|
|
70
|
+
if (!Number.isInteger(n)) throw new Error(`${label}: --expected-revision must be an integer`)
|
|
71
|
+
patch.expectedRevision = n
|
|
72
|
+
}
|
|
73
|
+
const body = await call(label, flags, deps, 'PATCH', `/machine-trust/${encodeURIComponent(principalId)}`, patch)
|
|
74
|
+
return { declaration: body.data.attributes, meta: body.meta || {} }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Remove a declaration (its mapped principal's roles are unassigned; the report lists each).
|
|
79
|
+
* @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
|
|
80
|
+
*/
|
|
81
|
+
async function machineTrustRemove(positional, flags, deps = {}) {
|
|
82
|
+
const id = principalIdOf('permissions machine-trust remove', positional)
|
|
83
|
+
const body = await call('permissions machine-trust remove', flags, deps, 'DELETE', `/machine-trust/${encodeURIComponent(id)}`)
|
|
84
|
+
return body.data.attributes
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Rewrite the deployment's backing SSM document from the declarations.
|
|
89
|
+
* @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
|
|
90
|
+
*/
|
|
91
|
+
async function machineTrustReconcile(positional, flags, deps = {}) {
|
|
92
|
+
const body = await call('permissions machine-trust reconcile', flags, deps, 'POST', '/machine-trust/actions/reconcile', {})
|
|
93
|
+
return body.data.attributes
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
module.exports = { machineTrustList, machineTrustGet, machineTrustDeclare, machineTrustUpdate, machineTrustRemove, machineTrustReconcile }
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// `saaslayer operations get|watch|cancel <id>` and the --wait every mutating command runs: follow an operation (a deployment
|
|
2
|
+
// run) to its terminal state, print each component's outcome, and fail with the next supported command; cancel an
|
|
3
|
+
// in-flight one (needs saaslayer:deployer:deployment:cancel-run).
|
|
4
|
+
'use strict'
|
|
5
|
+
const crypto = require('crypto')
|
|
6
|
+
const path = require('path')
|
|
7
|
+
const { apiCall } = require('../api-client')
|
|
8
|
+
const { resolveDeployment } = require('../deployments')
|
|
9
|
+
|
|
10
|
+
// The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
|
|
11
|
+
// vendor/operations, synced on prepack).
|
|
12
|
+
const MONOREPO_OPERATIONS = path.join(__dirname, '../../../operations/src')
|
|
13
|
+
|
|
14
|
+
/** A module of the operations package (index by default; activity for the activity feed). @param {string} [file] */
|
|
15
|
+
function loadOperations(file = 'index') {
|
|
16
|
+
try {
|
|
17
|
+
return require(`../../vendor/operations/${file}`)
|
|
18
|
+
} catch (err) {
|
|
19
|
+
if (err && err.code !== 'MODULE_NOT_FOUND') throw err
|
|
20
|
+
return require(path.join(MONOREPO_OPERATIONS, file))
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const USAGE = 'usage: saaslayer operations <get|watch|cancel> <operationId> [--deployment ID | --project P --env E --region R] [--json] [--interval SECONDS] [--reason TEXT]'
|
|
25
|
+
|
|
26
|
+
/** A fresh request key per CLI invocation: a retry of this invocation replays its operation, a new invocation does not. */
|
|
27
|
+
function requestKeyHeaders() {
|
|
28
|
+
return { 'Idempotency-Key': `cli-${crypto.randomUUID()}` }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} operationId
|
|
33
|
+
* @param {string} deploymentId
|
|
34
|
+
*/
|
|
35
|
+
function resumeCommand(operationId, deploymentId) {
|
|
36
|
+
return `saaslayer operations watch ${operationId} --deployment ${deploymentId}`
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Seconds between polls (--interval), default 5. @param {object} flags */
|
|
40
|
+
function intervalMs(flags) {
|
|
41
|
+
const seconds = flags.interval === undefined ? 5 : Number(flags.interval)
|
|
42
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : 5000
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Read an operation. A 4xx other than 408/429 is fatal (no retry); anything else is a transient fault for the watcher.
|
|
47
|
+
* @param {string} deploymentId
|
|
48
|
+
* @param {string} operationId
|
|
49
|
+
* @param {object} flags
|
|
50
|
+
*/
|
|
51
|
+
async function fetchOperation(deploymentId, operationId, flags) {
|
|
52
|
+
try {
|
|
53
|
+
const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}/operations/${encodeURIComponent(operationId)}`, undefined, flags)
|
|
54
|
+
return loadOperations().redact(doc.data.attributes)
|
|
55
|
+
} catch (err) {
|
|
56
|
+
const status = err && err.status
|
|
57
|
+
if (status >= 400 && status < 500 && status !== 408 && status !== 429) err.fatal = true
|
|
58
|
+
throw err
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Wait for an operation to finish. Succeeded: prints its components and returns it. Failed or partial: throws an
|
|
64
|
+
* error whose message lists each component's outcome and the next supported command.
|
|
65
|
+
* @param {{ deploymentId: string, operationId: string, flags: object }} input
|
|
66
|
+
*/
|
|
67
|
+
async function followOperation({ deploymentId, operationId, flags }) {
|
|
68
|
+
const ops = loadOperations()
|
|
69
|
+
const final = await ops.watchOperation({
|
|
70
|
+
id: operationId,
|
|
71
|
+
fetchOperation: () => fetchOperation(deploymentId, operationId, flags),
|
|
72
|
+
intervalMs: intervalMs(flags),
|
|
73
|
+
onUpdate: (op) => { if (!ops.isTerminal(op.status)) console.log(` … operation ${op.id}: ${op.status}`) },
|
|
74
|
+
resumeCommand: resumeCommand(operationId, deploymentId),
|
|
75
|
+
})
|
|
76
|
+
const lines = ops.formatOperation(final)
|
|
77
|
+
if (final.status === 'succeeded') {
|
|
78
|
+
console.log(lines.join('\n'))
|
|
79
|
+
return final
|
|
80
|
+
}
|
|
81
|
+
throw Object.assign(new Error(lines.join('\n')), { operation: final })
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* After a mutating command is accepted: wait for its operation (default) or, with --no-wait, print how to follow it.
|
|
86
|
+
* Attaches the finished operation to the response it returns.
|
|
87
|
+
* @param {{ response: { data?: { attributes?: Record<string, unknown> } } & Record<string, unknown>, deploymentId: string, flags: object }} input
|
|
88
|
+
*/
|
|
89
|
+
async function finishMutation({ response, deploymentId, flags }) {
|
|
90
|
+
const attrs = (response && response.data && response.data.attributes) || {}
|
|
91
|
+
const operationId = typeof attrs.operationId === 'string' ? attrs.operationId : null
|
|
92
|
+
if (!operationId) return response
|
|
93
|
+
if (flags['no-wait'] === true || flags['no-wait'] === 'true') {
|
|
94
|
+
console.log(` follow: ${resumeCommand(operationId, deploymentId)}`)
|
|
95
|
+
return response
|
|
96
|
+
}
|
|
97
|
+
console.log(` waiting for operation ${operationId} (--no-wait to return now; resume with: ${resumeCommand(operationId, deploymentId)})`)
|
|
98
|
+
response.operation = await followOperation({ deploymentId, operationId, flags })
|
|
99
|
+
return response
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Cancel an in-flight operation: the deployer stops its execution and releases the deployment's run lock, and the
|
|
104
|
+
* deployment's activity records the cancel with the caller and --reason.
|
|
105
|
+
* @param {string} deploymentId
|
|
106
|
+
* @param {string} operationId
|
|
107
|
+
* @param {object} flags
|
|
108
|
+
* @returns {Promise<{ deploymentId: string, operationId: string, status: string }>}
|
|
109
|
+
*/
|
|
110
|
+
async function cancelOperation(deploymentId, operationId, flags) {
|
|
111
|
+
const reason = typeof flags.reason === 'string' && flags.reason.trim() ? flags.reason.trim() : null
|
|
112
|
+
const body = reason ? { data: { type: 'operation-cancellations', attributes: { reason } } } : undefined
|
|
113
|
+
const doc = await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/operations/${encodeURIComponent(operationId)}/cancel`, body, flags)
|
|
114
|
+
const result = doc.data.attributes
|
|
115
|
+
if (flags.json) {
|
|
116
|
+
console.log(JSON.stringify(result, null, 2))
|
|
117
|
+
} else {
|
|
118
|
+
console.log(`cancelled operation ${operationId} on deployment ${deploymentId} (${result.status})`)
|
|
119
|
+
console.log(` check: saaslayer operations get ${operationId} --deployment ${deploymentId}`)
|
|
120
|
+
}
|
|
121
|
+
return result
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* `saaslayer operations get|watch|cancel <id>`.
|
|
126
|
+
* @param {string|undefined} sub
|
|
127
|
+
* @param {string|undefined} operationId
|
|
128
|
+
* @param {object} flags
|
|
129
|
+
*/
|
|
130
|
+
async function operationsCommand(sub, operationId, flags) {
|
|
131
|
+
if (!['get', 'watch', 'cancel'].includes(sub) || !operationId) throw new Error(USAGE)
|
|
132
|
+
const deploymentId = flags.deployment || (await resolveDeployment(flags)).deploymentId
|
|
133
|
+
if (sub === 'cancel') return cancelOperation(deploymentId, operationId, flags)
|
|
134
|
+
if (sub === 'watch') return followOperation({ deploymentId, operationId, flags })
|
|
135
|
+
const op = await fetchOperation(deploymentId, operationId, flags)
|
|
136
|
+
console.log(flags.json ? JSON.stringify(op, null, 2) : loadOperations().formatOperation(op).join('\n'))
|
|
137
|
+
return op
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { operationsCommand, finishMutation, followOperation, requestKeyHeaders, resumeCommand, loadOperations, intervalMs }
|
package/src/commands/orgs.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
// `saaslayer org …` and `saaslayer project …` — create/list orgs and projects
|
|
2
|
-
// control-plane API, authenticated with the cached Cognito id token (Bearer). The active
|
|
3
|
-
// remembered locally so `project create` doesn't need --org each time.
|
|
1
|
+
// `saaslayer org …` and `saaslayer project …` — create/list orgs and projects, and destroy a project whose deployments
|
|
2
|
+
// are gone, against the SaaSLayer control-plane API, authenticated with the cached Cognito id token (Bearer). The active
|
|
3
|
+
// org is remembered locally so `project create` doesn't need --org each time.
|
|
4
4
|
'use strict'
|
|
5
5
|
const context = require('../context-store')
|
|
6
6
|
const { apiCall } = require('../api-client')
|
|
7
|
+
const prompt = require('../prompt')
|
|
7
8
|
|
|
8
9
|
async function orgCreate(flags, name) {
|
|
9
10
|
if (!name) throw new Error('org create requires a name')
|
|
@@ -53,4 +54,28 @@ async function projectList(flags) {
|
|
|
53
54
|
return doc.projects || []
|
|
54
55
|
}
|
|
55
56
|
|
|
56
|
-
|
|
57
|
+
/**
|
|
58
|
+
* `saaslayer project destroy [<id>] [--yes]`: delete a project (the active one by default) and release its public name.
|
|
59
|
+
* The control plane refuses while any deployment of it is live; destroy each with `saaslayer destroy` first. Needs
|
|
60
|
+
* saaslayer:deployer:project:delete. Asks for the project id to be typed unless --yes.
|
|
61
|
+
* @param {object} flags
|
|
62
|
+
* @param {string} [projectId]
|
|
63
|
+
* @param {{ ask?: (question: string) => Promise<string> }} [io] the confirmation prompt (tests pass their own)
|
|
64
|
+
* @returns {Promise<{ id: string, destroyed: boolean, releasedSlugs: string[], notOwnedSlugs: string[] } | null>} null when aborted
|
|
65
|
+
*/
|
|
66
|
+
async function projectDestroy(flags, projectId, io = {}) {
|
|
67
|
+
const id = projectId || context.get('project')
|
|
68
|
+
if (!id) throw new Error('project destroy requires a project id (or an active project: `saaslayer project use <id>`)')
|
|
69
|
+
console.log(`⚠ This will DESTROY project ${id} and release its public name. Its deployments must already be destroyed.`)
|
|
70
|
+
const ask = io.ask || prompt.ask
|
|
71
|
+
const typed = flags.yes ? id : await ask(`Type the project id "${id}" to confirm: `)
|
|
72
|
+
if (typed !== id) { console.log('Aborted (id did not match).'); return null }
|
|
73
|
+
const result = await apiCall('DELETE', `/api/projects/${encodeURIComponent(id)}`, undefined, flags)
|
|
74
|
+
const released = (result.releasedSlugs || []).map((s) => `'${s}'`).join(', ')
|
|
75
|
+
console.log(`✅ destroyed project ${id}${released ? `; released ${released}` : ''}`)
|
|
76
|
+
if ((result.notOwnedSlugs || []).length) console.log(` held by another project, left alone: ${result.notOwnedSlugs.join(', ')}`)
|
|
77
|
+
if (context.get('project') === id) context.set('project', null)
|
|
78
|
+
return result
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { orgCreate, orgList, orgUse, projectCreate, projectList, projectDestroy }
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
// `saaslayer
|
|
1
|
+
// `saaslayer permissions inspect <type>:<id> | session:<id>`: a principal's permissions from the terminal (expanded view with
|
|
2
2
|
// independent scope/assignment paging, or the stored inspection model) — never parses the compact stored schema.
|
|
3
3
|
'use strict'
|
|
4
4
|
const { exchangeIamToken } = require('../iam-session')
|
|
5
|
-
const { authHeaders } = require('../
|
|
5
|
+
const { authHeaders } = require('../deployment-api-auth')
|
|
6
6
|
|
|
7
7
|
const USAGE = '<principalType>:<id> or session:<id> (e.g. USER:alice, SERVICE_ACCOUNT:svc-1)'
|
|
8
8
|
|
|
@@ -22,7 +22,7 @@ function parseRef(raw) {
|
|
|
22
22
|
const at = s.indexOf(':')
|
|
23
23
|
const type = at > 0 ? s.slice(0, at) : ''
|
|
24
24
|
const id = at > 0 ? s.slice(at + 1) : ''
|
|
25
|
-
if (!type || !id) throw new Error(`
|
|
25
|
+
if (!type || !id) throw new Error(`permissions inspect: expected ${USAGE}`)
|
|
26
26
|
if (type.toLowerCase() === 'session') return { kind: 'session', id }
|
|
27
27
|
return { kind: 'principal', type: type.toUpperCase(), id }
|
|
28
28
|
}
|
|
@@ -104,8 +104,8 @@ function formatExpanded(view, { ref, inspection }) {
|
|
|
104
104
|
if (scopes.length) for (const scope of scopes) out.push(bucketBlock(`Scope ${scope}`, view.scoped[scope]))
|
|
105
105
|
else out.push('(no scopes on this page)')
|
|
106
106
|
const hints = []
|
|
107
|
-
if (meta.nextScopeCursor) hints.push(`more scopes: saaslayer
|
|
108
|
-
if (meta.nextAssignmentCursor) hints.push(`more assignments: saaslayer
|
|
107
|
+
if (meta.nextScopeCursor) hints.push(`more scopes: saaslayer permissions inspect ${ref} --scope-page ${meta.nextScopeCursor}`)
|
|
108
|
+
if (meta.nextAssignmentCursor) hints.push(`more assignments: saaslayer permissions inspect ${ref} --assignment-page ${meta.nextAssignmentCursor}`)
|
|
109
109
|
if (hints.length) out.push('', ...hints)
|
|
110
110
|
return out.join('\n')
|
|
111
111
|
}
|
|
@@ -145,11 +145,11 @@ async function getAttributes(url, headers, ref) {
|
|
|
145
145
|
if (res.ok) return body.data.attributes
|
|
146
146
|
const first = (body.errors && body.errors[0]) || {}
|
|
147
147
|
const detail = first.message || first.detail || res.statusText || ''
|
|
148
|
-
if (res.status === 401) throw Object.assign(new Error(`
|
|
149
|
-
if (res.status === 403) throw Object.assign(new Error(`
|
|
150
|
-
if (res.status === 404) throw Object.assign(new Error(`
|
|
151
|
-
if (res.status === 409) throw Object.assign(new Error(`
|
|
152
|
-
throw Object.assign(new Error(`
|
|
148
|
+
if (res.status === 401) throw Object.assign(new Error(`permissions inspect: not authenticated (401) — check --token / --iam`), { status: 401 })
|
|
149
|
+
if (res.status === 403) throw Object.assign(new Error(`permissions inspect: forbidden (403) — needs saaslayer:identity authority over ${ref}: ${detail}`), { status: 403 })
|
|
150
|
+
if (res.status === 404) throw Object.assign(new Error(`permissions inspect: ${ref} not found (404) — or you have no saaslayer:identity authority where it lives`), { status: 404 })
|
|
151
|
+
if (res.status === 409) throw Object.assign(new Error(`permissions inspect: the doc changed while paging (409 PermissionDocChanged) — restart without a page cursor`), { status: 409 })
|
|
152
|
+
throw Object.assign(new Error(`permissions inspect failed (${res.status}): ${detail}`), { status: res.status })
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
/**
|
|
@@ -159,11 +159,11 @@ async function getAttributes(url, headers, ref) {
|
|
|
159
159
|
* @param {{ exchange?: typeof exchangeIamToken, print?: (s: string) => void }} [deps]
|
|
160
160
|
* @returns {Promise<string>} what was printed
|
|
161
161
|
*/
|
|
162
|
-
async function
|
|
162
|
+
async function permissionsInspect(positional, flags, deps = {}) {
|
|
163
163
|
const ref = parseRef(positional[0])
|
|
164
164
|
const refText = ref.kind === 'session' ? `session:${ref.id}` : `${ref.type}:${ref.id}`
|
|
165
165
|
const apiBase = String(flags['api-base'] || process.env.SAASLAYER_API_BASE || '').replace(/\/$/, '')
|
|
166
|
-
if (!apiBase) throw new Error('
|
|
166
|
+
if (!apiBase) throw new Error('permissions inspect: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
167
167
|
const headers = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
168
168
|
const print = deps.print || ((/** @type {string} */ s) => console.log(s))
|
|
169
169
|
const emit = (/** @type {string} */ s) => { print(s); return s }
|
|
@@ -219,10 +219,10 @@ async function rbacInspect(positional, flags, deps = {}) {
|
|
|
219
219
|
return emit(formatExpanded(view, { ref: refText, inspection: stored.inspection }))
|
|
220
220
|
} catch (err) {
|
|
221
221
|
if (/** @type {any} */ (err).status !== 409 || attempt === 1) throw err
|
|
222
|
-
console.error('
|
|
222
|
+
console.error('permissions inspect: the doc was rebuilt while paging (409) — restarting from the first page')
|
|
223
223
|
}
|
|
224
224
|
}
|
|
225
|
-
throw new Error('
|
|
225
|
+
throw new Error('permissions inspect: unreachable')
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
-
module.exports = {
|
|
228
|
+
module.exports = { permissionsInspect, parseRef, formatExpanded, formatInspection, formatSize }
|