saaslayer 0.2.0 → 0.3.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 +27 -0
- package/bin/saaslayer.js +71 -6
- package/package.json +2 -2
- package/src/api-client.js +37 -1
- package/src/cognito-user-api.js +80 -0
- package/src/commands/account-email.js +43 -0
- package/src/commands/admin-allowlist.js +45 -0
- package/src/commands/login.js +53 -16
- package/src/commands/org-members.js +109 -0
- package/src/commands/trust-policies.js +172 -0
- package/src/deployment-api-auth.js +166 -8
- package/src/permissions-request.js +15 -9
package/README.md
CHANGED
|
@@ -174,6 +174,33 @@ saaslayer first-admin recover --env prod --email new-admin@example.com --reason
|
|
|
174
174
|
`GET /access-admins` reports): hand the role over with `saaslayer permissions access-admins offer` instead.
|
|
175
175
|
- Both start an operation and wait for it (`--no-wait` returns); the deployment's activity records who asked and why.
|
|
176
176
|
|
|
177
|
+
### External ID token and `saaslayer permissions trust-policies`
|
|
178
|
+
|
|
179
|
+
On a deployment that trusts your own login provider (Cognito, Auth0, Okta, …), an administrator signs in with an ID
|
|
180
|
+
token from that provider. `--id-token-file FILE` (or `$SAASLAYER_ID_TOKEN`) works with the `saaslayer permissions`
|
|
181
|
+
commands:
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
chmod 600 id.jwt
|
|
185
|
+
saaslayer permissions access-admins activate --id-token-file id.jwt --deployment dep_…
|
|
186
|
+
saaslayer permissions trust-policies list --id-token-file id.jwt --deployment dep_…
|
|
187
|
+
saaslayer permissions trust-policies add https://acme.okta.com --audience 0oa1admin --allow-any-subject \
|
|
188
|
+
--id-token-file id.jwt --deployment dep_…
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
- Pass the **ID token**, not an access token. Cognito access tokens carry no `aud`, and the deployment only accepts a
|
|
192
|
+
token whose `aud` is one of the provider's allowed audiences. Use a dedicated app client for administrators so its
|
|
193
|
+
client id can be the only admin audience.
|
|
194
|
+
- The token only goes to a pinned host: `--deployment` (the deployment's permissions API, read through the control
|
|
195
|
+
plane with your `saaslayer login`) or an https `--api-base` whose host you type to confirm (`--yes` confirms). An
|
|
196
|
+
expired token is refused before anything is sent. The token is never printed.
|
|
197
|
+
- `trust-policies add` reads `<issuer>/.well-known/openid-configuration` and refuses unless it names exactly that
|
|
198
|
+
issuer. `delete` needs `--reason` and the issuer typed to confirm. The deployment's own pool is read-only
|
|
199
|
+
(`409 FIRST_PARTY_POLICY`), and a change that would leave no usable access admin a way to sign in is refused
|
|
200
|
+
(`409 LAST_ADMIN_PROVIDER`).
|
|
201
|
+
|
|
202
|
+
Full guide: [docs/permissions-only.md](../../docs/permissions-only.md).
|
|
203
|
+
|
|
177
204
|
## License
|
|
178
205
|
|
|
179
206
|
Proprietary. All rights reserved. See [LICENSE](./LICENSE).
|
package/bin/saaslayer.js
CHANGED
|
@@ -53,9 +53,13 @@ Usage:
|
|
|
53
53
|
own trust, as your saaslayer login (no AWS credentials are sent), so the console and deploys see the new
|
|
54
54
|
version; if that fails the upgrade still stands and the console's "check again" re-reads it.
|
|
55
55
|
|
|
56
|
-
saaslayer signup [--config-url URL] [--email E --password P]
|
|
57
|
-
Create a SaaSLayer account (allowlist-gated) and log in.
|
|
56
|
+
saaslayer signup [--config-url URL] [--email E --password P] [--code C | --resend]
|
|
57
|
+
Create a SaaSLayer account (allowlist-gated), confirm the code emailed to you (prompted, or --code), and log in.
|
|
58
|
+
Without a terminal it stops once the code is sent; finish with --code. --resend emails a new code.
|
|
58
59
|
--config-url (or $SAASLAYER_CONFIG_URL) is the control-plane API; default https://api.saaslayer.com.
|
|
60
|
+
saaslayer account verify-email [--code C]
|
|
61
|
+
Prove the logged-in account owns its email (a code is emailed; type it, or pass --code). Org owners can add
|
|
62
|
+
only accounts whose email is verified.
|
|
59
63
|
saaslayer login [--email E --password P] [--config-url URL | --user-pool-id ID --client-id ID --region R]
|
|
60
64
|
Log in to your SaaSLayer account (Cognito SRP) and cache tokens in ~/.saaslayer.
|
|
61
65
|
Email/password fall back to $SAASLAYER_EMAIL/$SAASLAYER_PASSWORD, else prompt.
|
|
@@ -65,7 +69,8 @@ Usage:
|
|
|
65
69
|
Log in to a deployment's user-service as an access admin. The pool, client and API bases are
|
|
66
70
|
discovered from the deployment's public outputs (an env name resolves the active project's deployment).
|
|
67
71
|
Kept separate from your control-plane login, which stays logged in.
|
|
68
|
-
saaslayer whoami Show the current logged-in account, its
|
|
72
|
+
saaslayer whoami Show the current logged-in account, its account id (share it with an org owner to be added
|
|
73
|
+
to their org), its control plane, and the active org/project.
|
|
69
74
|
saaslayer context [--json] [--profile AWS_PROFILE] Show the control-plane account, the deployment login, the AWS
|
|
70
75
|
profile, org and project (and where each came from) and every cached identity.
|
|
71
76
|
Tokens are never printed.
|
|
@@ -139,6 +144,25 @@ Usage:
|
|
|
139
144
|
once; it counts once they accept with their own deployment login. --mode transfer (default) then removes you,
|
|
140
145
|
add keeps you. An interrupted accept leaves both admins; accept again to finish. cancel (pending offers, by you)
|
|
141
146
|
revokes the grant. activate records your own activation. See services/permissions-service/user-docs/access-admins.md.
|
|
147
|
+
saaslayer permissions trust-policies list | get <policyId> (--deployment ID | --api-base URL) [auth]
|
|
148
|
+
saaslayer permissions trust-policies add <issuerUrl> --audience A [--audience B] (--subject S … | --allow-any-subject)
|
|
149
|
+
[--principal-claim sub] [--jwks-uri URL] [--description D] (--deployment ID | --api-base URL) [auth]
|
|
150
|
+
saaslayer permissions trust-policies update <policyId> [--audience A …] [--subject S … | --allow-any-subject] [--jwks-uri URL] [--description D] …
|
|
151
|
+
saaslayer permissions trust-policies disable | enable <policyId> (--deployment ID | --api-base URL) [auth]
|
|
152
|
+
saaslayer permissions trust-policies delete <policyId> --reason TEXT [--yes] (--deployment ID | --api-base URL) [auth]
|
|
153
|
+
The external login providers (OIDC issuers: your Cognito pool, Auth0, Okta, …) whose ID tokens the deployment accepts.
|
|
154
|
+
Needs an access admin (or a trust-manager holder). <issuerUrl> is the EXACT iss of the provider's ID tokens: add
|
|
155
|
+
refuses unless <issuerUrl>/.well-known/openid-configuration names it. Providers added here are external (people get
|
|
156
|
+
ext_ principal ids) and never impersonate; the deployment's own pool is read-only (409 FIRST_PARTY_POLICY). A change
|
|
157
|
+
that would leave no usable access admin a way to sign in is refused (409 LAST_ADMIN_PROVIDER). delete asks you to
|
|
158
|
+
type the issuer (--yes confirms). See docs/permissions-only.md.
|
|
159
|
+
External ID token (saaslayer permissions commands):
|
|
160
|
+
--id-token-file FILE (or $SAASLAYER_ID_TOKEN) sends the raw OIDC ID token from your own login provider as the
|
|
161
|
+
credential — e.g. \`saaslayer permissions access-admins activate --id-token-file id.jwt --deployment dep_…\`. It goes
|
|
162
|
+
only to a pinned host: --deployment <dep_id|env> (its permissions API, read through the control plane with your
|
|
163
|
+
\`saaslayer login\`; commands that need --api-base must name that same API) or an https --api-base whose host you
|
|
164
|
+
type to confirm (--yes confirms). Expired tokens and access tokens are refused locally; never combined with --iam,
|
|
165
|
+
--token, $SAASLAYER_TOKEN or a deployment login; the token is never printed. Keep the file chmod 600.
|
|
142
166
|
|
|
143
167
|
saaslayer users export --provider cognito --user-pool-id POOL --region R [--profile P]
|
|
144
168
|
[--account-attribute ATTR] [--account-name-attribute ATTR] [--role-map map.js] --out manifest.json
|
|
@@ -209,6 +233,14 @@ Deploy & lifecycle (requires login + a connected AWS account):
|
|
|
209
233
|
Connect your AWS account to an org. Binds it to your active project by
|
|
210
234
|
default; --org-wide lets any project in the org deploy into it.
|
|
211
235
|
saaslayer project use <id> Set the active project for deploy/status (a project id tnt_… or a customer id).
|
|
236
|
+
saaslayer org members list [--org ID]
|
|
237
|
+
saaslayer org members add --user <accountId> [--role deployer] [--org ID] [--yes]
|
|
238
|
+
saaslayer org members remove --user <accountId> [--org ID]
|
|
239
|
+
saaslayer org members set-role --user <accountId> --role deployer|member [--org ID]
|
|
240
|
+
Org owners only: manage the org's members by account id (the teammate prints it with \`saaslayer whoami\`). add
|
|
241
|
+
shows the account's email and asks for it to be typed back unless --yes; an account whose email is not verified
|
|
242
|
+
is refused (EMAIL_NOT_PROVEN). A deployer may update deployments and cancel its own runs; owner powers stay with
|
|
243
|
+
owners. remove revokes the deployer role, then the membership. --org defaults to the active org.
|
|
212
244
|
saaslayer project destroy [<id>] [--yes]
|
|
213
245
|
Delete a project (the active one by default) and release its public name for reuse. Refused while any of its
|
|
214
246
|
deployments is live: destroy each with \`saaslayer destroy\` first. Asks for the id to be typed unless --yes.
|
|
@@ -313,6 +345,11 @@ Data migrations you run yourself (a deployment with migrationRunner self):
|
|
|
313
345
|
Standalone (no control plane, no report): --stack <stackName> --region <r>, with --repo the service dir.
|
|
314
346
|
Exit codes: 0 ok / up-to-date, 1 failed, 2 awaiting approval, 3 applied but not reported.
|
|
315
347
|
|
|
348
|
+
Platform operators:
|
|
349
|
+
saaslayer admin allowlist list | add <email> | remove <email>
|
|
350
|
+
The control plane's signup allowlist (the login pool's PreSignUp gate for console and CLI signup). Operators
|
|
351
|
+
only; the control plane refuses anyone else.
|
|
352
|
+
|
|
316
353
|
Global:
|
|
317
354
|
--help Show this help.`
|
|
318
355
|
|
|
@@ -397,6 +434,13 @@ async function main() {
|
|
|
397
434
|
if (run) { console.log(JSON.stringify(await run(rest, flags), null, 2)); return }
|
|
398
435
|
console.error('usage: saaslayer permissions access-admins <list|offer|status|cancel|accept|activate> [suid|transferId] --api-base URL'); process.exit(1)
|
|
399
436
|
}
|
|
437
|
+
if (cmd === 'permissions' && sub === 'trust-policies') {
|
|
438
|
+
const tp = require('../src/commands/trust-policies')
|
|
439
|
+
const rest = positional.slice(3)
|
|
440
|
+
const run = { list: tp.trustPoliciesList, get: tp.trustPoliciesGet, add: tp.trustPoliciesAdd, update: tp.trustPoliciesUpdate, disable: tp.trustPoliciesDisable, enable: tp.trustPoliciesEnable, delete: tp.trustPoliciesDelete }[positional[2]]
|
|
441
|
+
if (run) { console.log(JSON.stringify(await run(rest, flags), null, 2)); return }
|
|
442
|
+
console.error('usage: saaslayer permissions trust-policies <list|get|add|update|disable|enable|delete> [policyId|issuerUrl] (--deployment ID | --api-base URL) [auth]'); process.exit(1)
|
|
443
|
+
}
|
|
400
444
|
if (cmd === 'users') {
|
|
401
445
|
const users = require('../src/commands/users')
|
|
402
446
|
if (sub === 'export') { await users.usersExport(flags); return }
|
|
@@ -407,8 +451,8 @@ async function main() {
|
|
|
407
451
|
}
|
|
408
452
|
if (cmd === 'signup') {
|
|
409
453
|
const { signup } = require('../src/commands/login')
|
|
410
|
-
const
|
|
411
|
-
console.log(`account created — logged in as ${
|
|
454
|
+
const out = await signup(flags)
|
|
455
|
+
console.log(out.status === 'logged-in' ? `account created — logged in as ${out.email}` : out.next)
|
|
412
456
|
return
|
|
413
457
|
}
|
|
414
458
|
if (cmd === 'login') {
|
|
@@ -449,6 +493,7 @@ async function main() {
|
|
|
449
493
|
const who = whoami()
|
|
450
494
|
if (!who) { console.log('not logged in'); return }
|
|
451
495
|
console.log(`${who.email} (control plane: ${who.env})`)
|
|
496
|
+
if (who.accountId) console.log(`account id: ${who.accountId} (share this id with your org owner to be added to their org)`)
|
|
452
497
|
const ctx = require('../src/context-store').load()
|
|
453
498
|
console.log(`org: ${ctx.org || '—'} project: ${ctx.project ? `${ctx.project} (${require('../src/scope').projectIdKind(ctx.project)})` : '—'} (see: saaslayer context)`)
|
|
454
499
|
return
|
|
@@ -471,6 +516,11 @@ async function main() {
|
|
|
471
516
|
console.log('\n* = active. Switch with: saaslayer account use <email>')
|
|
472
517
|
return
|
|
473
518
|
}
|
|
519
|
+
if (cmd === 'account' && sub === 'verify-email') {
|
|
520
|
+
const out = await require('../src/commands/account-email').verifyEmail(flags)
|
|
521
|
+
console.log(out.status === 'verified' ? `email verified: ${out.email}` : out.next)
|
|
522
|
+
return
|
|
523
|
+
}
|
|
474
524
|
if (cmd === 'account' && sub === 'use') {
|
|
475
525
|
const { accountUse } = require('../src/commands/accounts')
|
|
476
526
|
const who = accountUse(positional[2])
|
|
@@ -482,7 +532,16 @@ async function main() {
|
|
|
482
532
|
if (sub === 'create') { const o = await orgs.orgCreate(flags, positional[2]); console.log(`created org ${o.name || ''} (${o.id}) — now active`); return }
|
|
483
533
|
if (sub === 'list') { const list = await orgs.orgList(flags); if (!list.length) console.log('no orgs'); else list.forEach((o) => console.log(`${o.id}${o.name ? ' ' + o.name : ''}`)); return }
|
|
484
534
|
if (sub === 'use') { const id = orgs.orgUse(flags, positional[2]); console.log(`active org: ${id}`); return }
|
|
485
|
-
|
|
535
|
+
if (sub === 'members') {
|
|
536
|
+
const members = require('../src/commands/org-members')
|
|
537
|
+
const action = positional[2]
|
|
538
|
+
if (action === 'list') { await members.membersList(flags); return }
|
|
539
|
+
if (action === 'add') { await members.membersAdd(flags, {}, positional[3]); return }
|
|
540
|
+
if (action === 'remove') { await members.membersRemove(flags, positional[3]); return }
|
|
541
|
+
if (action === 'set-role') { await members.membersSetRole(flags, positional[3]); return }
|
|
542
|
+
console.error('usage: saaslayer org members <list|add|remove|set-role> [--user <accountId>] [--role deployer|member] [--org ID]'); process.exit(1)
|
|
543
|
+
}
|
|
544
|
+
console.error('usage: saaslayer org <create|list|use|members> …'); process.exit(1)
|
|
486
545
|
}
|
|
487
546
|
if (cmd === 'project') {
|
|
488
547
|
const orgs = require('../src/commands/orgs')
|
|
@@ -508,6 +567,12 @@ async function main() {
|
|
|
508
567
|
if (sub === 'upgrade') { await foundation.foundationUpgrade(flags); return }
|
|
509
568
|
console.error('usage: saaslayer foundation <status|upgrade> [--region R] [--profile P] (see saaslayer --help)'); process.exit(1)
|
|
510
569
|
}
|
|
570
|
+
if (cmd === 'admin' && sub === 'allowlist') {
|
|
571
|
+
const allowlist = require('../src/commands/admin-allowlist')
|
|
572
|
+
const run = { list: allowlist.allowlistList, add: allowlist.allowlistAdd, remove: allowlist.allowlistRemove }[positional[2]]
|
|
573
|
+
if (run) { await run(flags, positional[3]); return }
|
|
574
|
+
console.error('usage: saaslayer admin allowlist <list|add <email>|remove <email>>'); process.exit(1)
|
|
575
|
+
}
|
|
511
576
|
if (cmd === 'stacks') { const { stacks } = require('../src/commands/stacks'); await stacks(flags); return }
|
|
512
577
|
if (cmd === 'deploy') { const { deploy } = require('../src/commands/deploy'); await deploy(flags); return }
|
|
513
578
|
if (cmd === 'status') { const { status } = require('../src/commands/lifecycle'); await status(flags); return }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "saaslayer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "SaaSLayer CLI — onboard an account (init) and register a service's permissions manifest.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"bin": {
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"access": "public"
|
|
42
42
|
},
|
|
43
43
|
"scripts": {
|
|
44
|
-
"test": "node scripts/sync-template.js --check && node scripts/sync-vendor.js --check && node bin/saaslayer.js --help >/dev/null && node test/credentials.test.js && node test/multi-account.test.js && node test/aws.test.js && node test/api-client-refresh.test.js && node test/update.test.js && node test/migrations-approve.test.js && node test/service-remove.test.js && node test/settings.test.js && node test/env-compare.test.js && node test/release-manifest.test.js && node test/operations.test.js && node test/projects.test.js && node test/activity.test.js && node test/integration-credentials.test.js && node test/users-management.test.js && node test/deploy.test.js && node test/module-catalog.test.js && node test/stacks.test.js && node test/catalog.test.js && node test/catalog-registry.test.js && node test/permissions-inspect.test.js && node test/permissions-commands.test.js && node test/iam.test.js && node test/machine-trust.test.js && node test/access-admins.test.js && node test/first-admin.test.js && node test/service-principals.test.js && node test/package-files.test.js && node test/users-export.test.js && node test/users-import.test.js && node test/users.test.js && node test/migrate.test.js && node test/foundation-template.test.js && node test/foundation.test.js && node test/scope.test.js && node test/discovery.test.js && node test/credential-profiles.test.js && node test/login-challenges.test.js && node test/login-prompt.test.js && node test/control-plane-url.test.js && echo ok",
|
|
44
|
+
"test": "node scripts/sync-template.js --check && node scripts/sync-vendor.js --check && node bin/saaslayer.js --help >/dev/null && node test/credentials.test.js && node test/multi-account.test.js && node test/aws.test.js && node test/api-client-refresh.test.js && node test/update.test.js && node test/migrations-approve.test.js && node test/service-remove.test.js && node test/settings.test.js && node test/env-compare.test.js && node test/release-manifest.test.js && node test/operations.test.js && node test/projects.test.js && node test/activity.test.js && node test/integration-credentials.test.js && node test/users-management.test.js && node test/deploy.test.js && node test/module-catalog.test.js && node test/stacks.test.js && node test/catalog.test.js && node test/catalog-registry.test.js && node test/permissions-inspect.test.js && node test/permissions-commands.test.js && node test/iam.test.js && node test/machine-trust.test.js && node test/access-admins.test.js && node test/first-admin.test.js && node test/service-principals.test.js && node test/package-files.test.js && node test/users-export.test.js && node test/users-import.test.js && node test/users.test.js && node test/migrate.test.js && node test/foundation-template.test.js && node test/foundation.test.js && node test/scope.test.js && node test/discovery.test.js && node test/credential-profiles.test.js && node test/login-challenges.test.js && node test/login-prompt.test.js && node test/control-plane-url.test.js && node test/signup.test.js && node test/org-members.test.js && echo ok && node test/id-token-auth.test.js && node test/trust-policies.test.js",
|
|
45
45
|
"sync-template": "node scripts/sync-template.js",
|
|
46
46
|
"sync-template:check": "node scripts/sync-template.js --check",
|
|
47
47
|
"prepublishOnly": "node scripts/sync-template.js",
|
package/src/api-client.js
CHANGED
|
@@ -69,6 +69,24 @@ async function freshBearer(flags = {}) {
|
|
|
69
69
|
return (await refreshTokens(current, flags)).idToken
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
/**
|
|
73
|
+
* The current control-plane login with a usable access token (refreshed first when expired): the token Cognito's
|
|
74
|
+
* own-account calls (email verification) take.
|
|
75
|
+
* @param {object} [flags]
|
|
76
|
+
* @returns {Promise<{ accessToken: string, region: string, email: string }>}
|
|
77
|
+
*/
|
|
78
|
+
async function freshAccessLogin(flags = {}) {
|
|
79
|
+
let current = creds.getCurrent()
|
|
80
|
+
if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
|
|
81
|
+
if (!isFresh(current) || !current.accessToken) {
|
|
82
|
+
if (!current.refreshToken) throw new Error('session expired — run `saaslayer login`')
|
|
83
|
+
current = await refreshTokens(current, flags)
|
|
84
|
+
}
|
|
85
|
+
if (!current.accessToken) throw new Error('this login has no access token — run `saaslayer login`')
|
|
86
|
+
const region = current.region || (await resolvePoolConfig(flags)).region
|
|
87
|
+
return { accessToken: current.accessToken, region, email: current.email }
|
|
88
|
+
}
|
|
89
|
+
|
|
72
90
|
/**
|
|
73
91
|
* @param {string} method
|
|
74
92
|
* @param {string} path
|
|
@@ -88,4 +106,22 @@ async function apiCall(method, path, body, flags, opts = {}) {
|
|
|
88
106
|
return doc
|
|
89
107
|
}
|
|
90
108
|
|
|
91
|
-
|
|
109
|
+
/**
|
|
110
|
+
* apiCall for a JSON:API route: a refusal is rethrown as `<code>: <title>` (status and body kept), so the user reads the
|
|
111
|
+
* server's reason instead of the raw document.
|
|
112
|
+
* @param {string} method
|
|
113
|
+
* @param {string} path
|
|
114
|
+
* @param {unknown} [body]
|
|
115
|
+
* @param {object} [flags]
|
|
116
|
+
*/
|
|
117
|
+
async function jsonApiCall(method, path, body, flags) {
|
|
118
|
+
try {
|
|
119
|
+
return await apiCall(method, path, body, flags)
|
|
120
|
+
} catch (err) {
|
|
121
|
+
const first = err && err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
|
|
122
|
+
if (!first) throw err
|
|
123
|
+
throw Object.assign(new Error(`${first.code || err.status}: ${first.title || first.detail || 'request refused'}`), { status: err.status, body: err.body })
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = { apiBase, bearer, freshBearer, freshAccessLogin, apiCall, jsonApiCall, isFresh, refreshCognitoTokens }
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// The public (unsigned) Cognito user-pool calls the CLI makes for an account: sign up, confirm the emailed code, resend
|
|
2
|
+
// it, and verify the email of a signed-in account. Same calls the console makes; no AWS credentials involved.
|
|
3
|
+
'use strict'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {{ region: string, clientId: string }} PoolClient
|
|
7
|
+
* @typedef {Error & { code?: string, status?: number }} CognitoError
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* One Cognito Identity Provider JSON call. A refusal throws with the exception name as `code` and Cognito's message.
|
|
12
|
+
* @param {string} region
|
|
13
|
+
* @param {string} operation e.g. SignUp
|
|
14
|
+
* @param {Record<string, unknown>} body
|
|
15
|
+
* @returns {Promise<Record<string, any>>}
|
|
16
|
+
*/
|
|
17
|
+
async function cognitoCall(region, operation, body) {
|
|
18
|
+
const res = await fetch(`https://cognito-idp.${region}.amazonaws.com/`, {
|
|
19
|
+
method: 'POST',
|
|
20
|
+
headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}` },
|
|
21
|
+
body: JSON.stringify(body),
|
|
22
|
+
})
|
|
23
|
+
const doc = await res.json().catch(() => ({}))
|
|
24
|
+
if (!res.ok) {
|
|
25
|
+
const code = String(doc.__type || '').split('#').pop() || `HTTP_${res.status}`
|
|
26
|
+
/** @type {CognitoError} */
|
|
27
|
+
const err = new Error(doc.message || doc.Message || `${operation} failed (${res.status})`)
|
|
28
|
+
err.code = code
|
|
29
|
+
err.status = res.status
|
|
30
|
+
throw err
|
|
31
|
+
}
|
|
32
|
+
return doc
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Create an unconfirmed account; Cognito emails a confirmation code (the pool's PreSignUp allowlist runs first).
|
|
37
|
+
* @param {PoolClient} pool
|
|
38
|
+
* @param {{ email: string, password: string }} input
|
|
39
|
+
*/
|
|
40
|
+
function signUp(pool, { email, password }) {
|
|
41
|
+
return cognitoCall(pool.region, 'SignUp', { ClientId: pool.clientId, Username: email, Password: password, UserAttributes: [{ Name: 'email', Value: email }] })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Confirm a signup with the emailed code: the account is CONFIRMED and its email verified.
|
|
46
|
+
* @param {PoolClient} pool
|
|
47
|
+
* @param {{ email: string, code: string }} input
|
|
48
|
+
*/
|
|
49
|
+
function confirmSignUp(pool, { email, code }) {
|
|
50
|
+
return cognitoCall(pool.region, 'ConfirmSignUp', { ClientId: pool.clientId, Username: email, ConfirmationCode: code })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Email a new signup confirmation code.
|
|
55
|
+
* @param {PoolClient} pool
|
|
56
|
+
* @param {{ email: string }} input
|
|
57
|
+
*/
|
|
58
|
+
function resendConfirmationCode(pool, { email }) {
|
|
59
|
+
return cognitoCall(pool.region, 'ResendConfirmationCode', { ClientId: pool.clientId, Username: email })
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Email a verification code to the signed-in account's email.
|
|
64
|
+
* @param {string} region
|
|
65
|
+
* @param {{ accessToken: string }} input
|
|
66
|
+
*/
|
|
67
|
+
function getEmailVerificationCode(region, { accessToken }) {
|
|
68
|
+
return cognitoCall(region, 'GetUserAttributeVerificationCode', { AccessToken: accessToken, AttributeName: 'email' })
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Verify the signed-in account's email with the emailed code (sets email_verified=true).
|
|
73
|
+
* @param {string} region
|
|
74
|
+
* @param {{ accessToken: string, code: string }} input
|
|
75
|
+
*/
|
|
76
|
+
function verifyEmailCode(region, { accessToken, code }) {
|
|
77
|
+
return cognitoCall(region, 'VerifyUserAttribute', { AccessToken: accessToken, AttributeName: 'email', Code: code })
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { signUp, confirmSignUp, resendConfirmationCode, getEmailVerificationCode, verifyEmailCode }
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// `saaslayer account verify-email` — prove the logged-in control-plane account owns its email: Cognito emails a code,
|
|
2
|
+
// the typed (or --code) code verifies it. Org owners can add only accounts whose email is proven.
|
|
3
|
+
'use strict'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {{ isTTY: boolean, prompt: (question: string, opts?: { hidden?: boolean }) => Promise<string> }} PromptIo
|
|
7
|
+
* @typedef {{ status: 'code-sent', email: string, next: string } | { status: 'verified', email: string }} VerifyOutcome
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** @type {PromptIo} */
|
|
11
|
+
const terminalIo = {
|
|
12
|
+
get isTTY() { return Boolean(process.stdin.isTTY) },
|
|
13
|
+
prompt: (question, opts) => require('./login').prompt(question, opts),
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Send a verification code to the account's email and verify it. `--code` verifies a code already sent (no new code);
|
|
18
|
+
* without a terminal and no --code it only sends one and names the command that finishes it.
|
|
19
|
+
* @param {Record<string, any>} flags --code, --config-url
|
|
20
|
+
* @param {{ io?: PromptIo }} [deps]
|
|
21
|
+
* @returns {Promise<VerifyOutcome>}
|
|
22
|
+
*/
|
|
23
|
+
async function verifyEmail(flags = {}, deps = {}) {
|
|
24
|
+
const io = deps.io || terminalIo
|
|
25
|
+
const cognito = require('../cognito-user-api')
|
|
26
|
+
const { freshAccessLogin } = require('../api-client')
|
|
27
|
+
const { accessToken, region, email } = await freshAccessLogin(flags)
|
|
28
|
+
let code = flags.code !== undefined ? String(flags.code).trim() : ''
|
|
29
|
+
if (!code) {
|
|
30
|
+
const sent = await cognito.getEmailVerificationCode(region, { accessToken })
|
|
31
|
+
const destination = (sent.CodeDeliveryDetails && sent.CodeDeliveryDetails.Destination) || email
|
|
32
|
+
if (!io.isTTY) return { status: 'code-sent', email, next: `check ${destination} for the code, then run: saaslayer account verify-email --code <code>` }
|
|
33
|
+
code = String(await io.prompt(`Code emailed to ${destination}: `)).trim()
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
await cognito.verifyEmailCode(region, { accessToken, code })
|
|
37
|
+
} catch (err) {
|
|
38
|
+
throw new Error(`email not verified: ${err.message} Run \`saaslayer account verify-email\` again for a new code`)
|
|
39
|
+
}
|
|
40
|
+
return { status: 'verified', email }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { verifyEmail }
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// `saaslayer admin allowlist list|add|remove <email>` — platform operators manage the control plane's signup allowlist
|
|
2
|
+
// (the login pool's PreSignUp gate). The server refuses anyone who is not a platform operator.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { jsonApiCall } = require('../api-client')
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {{ version: number, enabled: boolean, emails: string[] }} Allowlist
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** @param {any} doc @returns {Allowlist} */
|
|
11
|
+
function allowlistOf(doc) {
|
|
12
|
+
return doc.data.attributes
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** @param {Allowlist} list */
|
|
16
|
+
function print(list) {
|
|
17
|
+
console.log(`signup allowlist (version ${list.version}, ${list.enabled ? 'enforced' : 'not enforced: signup is open'})`)
|
|
18
|
+
if (!list.emails.length) console.log(' (no emails)')
|
|
19
|
+
for (const email of list.emails) console.log(` ${email}`)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {Record<string, any>} flags @returns {Promise<Allowlist>} */
|
|
23
|
+
async function allowlistList(flags = {}) {
|
|
24
|
+
const list = allowlistOf(await jsonApiCall('GET', '/api/signup-allowlist', undefined, flags))
|
|
25
|
+
print(list)
|
|
26
|
+
return list
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {Record<string, any>} flags @param {string} [email] @returns {Promise<Allowlist>} */
|
|
30
|
+
async function allowlistAdd(flags = {}, email) {
|
|
31
|
+
if (!email) throw new Error('usage: saaslayer admin allowlist add <email>')
|
|
32
|
+
const list = allowlistOf(await jsonApiCall('POST', '/api/signup-allowlist/emails', { email: String(email).trim().toLowerCase() }, flags))
|
|
33
|
+
print(list)
|
|
34
|
+
return list
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param {Record<string, any>} flags @param {string} [email] @returns {Promise<Allowlist>} */
|
|
38
|
+
async function allowlistRemove(flags = {}, email) {
|
|
39
|
+
if (!email) throw new Error('usage: saaslayer admin allowlist remove <email>')
|
|
40
|
+
const list = allowlistOf(await jsonApiCall('DELETE', `/api/signup-allowlist/emails/${encodeURIComponent(String(email).trim().toLowerCase())}`, undefined, flags))
|
|
41
|
+
print(list)
|
|
42
|
+
return list
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = { allowlistList, allowlistAdd, allowlistRemove }
|
package/src/commands/login.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
'use strict'
|
|
4
4
|
const readline = require('readline')
|
|
5
5
|
const creds = require('../credentials')
|
|
6
|
-
const { resolvePoolConfig, decodeJwt
|
|
6
|
+
const { resolvePoolConfig, decodeJwt } = require('../config')
|
|
7
7
|
const { discoverDeployment, discoverFromFlags } = require('../discovery')
|
|
8
8
|
|
|
9
9
|
// Prompt for a value; hidden masks input (passwords). Only used when no flag/env supplies it.
|
|
@@ -219,26 +219,63 @@ async function loginDeployment(flags, deps = {}) {
|
|
|
219
219
|
return { deploymentId, serviceInstance: profile.serviceInstance, environment, email: profile.email, userId: profile.userId }
|
|
220
220
|
}
|
|
221
221
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
222
|
+
/**
|
|
223
|
+
* @typedef {{ status: 'code-sent' | 'confirmed', email: string, next: string } | { status: 'logged-in', email: string, userId: string }} SignupOutcome
|
|
224
|
+
*/
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Create a SaaSLayer account against the control plane's login pool, the way the console does: Cognito SignUp (the
|
|
228
|
+
* pool's PreSignUp allowlist decides admission), then the code Cognito emailed confirms the account and proves the
|
|
229
|
+
* email. Then logs in. `--code` finishes a pending signup; `--resend` emails a new code. Without a terminal and no
|
|
230
|
+
* --code it stops after the code is sent and names the command that finishes it.
|
|
231
|
+
* @param {Record<string, any>} flags --email, --password, --code, --resend, --config-url
|
|
232
|
+
* @param {{ io?: LoginIo, login?: typeof login }} [deps]
|
|
233
|
+
* @returns {Promise<SignupOutcome>}
|
|
234
|
+
*/
|
|
235
|
+
async function signup(flags = {}, deps = {}) {
|
|
236
|
+
const io = deps.io || terminalIo
|
|
237
|
+
const cognito = require('../cognito-user-api')
|
|
238
|
+
const pool = await resolvePoolConfig(flags)
|
|
239
|
+
const email = String(flags.email || process.env.SAASLAYER_EMAIL || (await io.prompt('Email: '))).trim().toLowerCase()
|
|
240
|
+
if (!email.includes('@')) throw new Error('signup requires a valid --email')
|
|
241
|
+
const finish = `saaslayer signup --email ${email} --code <code>`
|
|
242
|
+
let password = flags.password || process.env.SAASLAYER_PASSWORD
|
|
243
|
+
if (flags.resend) {
|
|
244
|
+
await cognito.resendConfirmationCode(pool, { email })
|
|
245
|
+
} else if (flags.code === undefined) {
|
|
246
|
+
if (!password) password = await io.prompt('Choose a password: ', { hidden: true })
|
|
247
|
+
try {
|
|
248
|
+
await cognito.signUp(pool, { email, password })
|
|
249
|
+
} catch (err) {
|
|
250
|
+
if (err.code === 'UsernameExistsException') throw new Error(`an account already exists for ${email}: log in with \`saaslayer login\`, or finish a pending signup with \`${finish}\` (\`--resend\` emails a new code)`)
|
|
251
|
+
if (err.code === 'UserLambdaValidationException') throw new Error(`signup refused: ${err.message}`)
|
|
252
|
+
throw err
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (flags.code === undefined && !io.isTTY) return { status: 'code-sent', email, next: `check ${email} for the code, then run: ${finish}` }
|
|
256
|
+
const code = flags.code !== undefined ? String(flags.code).trim() : String(await io.prompt(`Code emailed to ${email}: `)).trim()
|
|
257
|
+
try {
|
|
258
|
+
await cognito.confirmSignUp(pool, { email, code })
|
|
259
|
+
} catch (err) {
|
|
260
|
+
throw new Error(`signup not confirmed: ${err.message} Retry with \`${finish}\`, or email a new code with \`saaslayer signup --email ${email} --resend\``)
|
|
261
|
+
}
|
|
262
|
+
if (!password && io.isTTY) password = await io.prompt('Password: ', { hidden: true })
|
|
263
|
+
if (!password) return { status: 'confirmed', email, next: `account confirmed — run: saaslayer login --email ${email}` }
|
|
264
|
+
const who = await (deps.login || login)({ ...flags, email, password })
|
|
265
|
+
return { status: 'logged-in', email: who.email, userId: who.userId }
|
|
236
266
|
}
|
|
237
267
|
|
|
268
|
+
/**
|
|
269
|
+
* The current control-plane account: its Cognito sub (userId), email, control plane, and its account id (custom:suid),
|
|
270
|
+
* the id an org owner adds members by.
|
|
271
|
+
* @returns {{ userId: string, email: string, env: string, accountId: string | null } | null}
|
|
272
|
+
*/
|
|
238
273
|
function whoami() {
|
|
239
274
|
const current = creds.getCurrent()
|
|
240
275
|
if (!current) return null
|
|
241
|
-
|
|
276
|
+
let accountId = null
|
|
277
|
+
try { accountId = decodeJwt(current.idToken)['custom:suid'] || null } catch { accountId = null }
|
|
278
|
+
return { userId: current.userId, email: current.email, env: current.env, accountId }
|
|
242
279
|
}
|
|
243
280
|
|
|
244
281
|
/**
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// `saaslayer org members list|add|remove|set-role` — an org owner manages who belongs to the org and who deploys. Members
|
|
2
|
+
// are added by account id (`saaslayer whoami` prints it); the control plane refuses accounts whose email is not verified.
|
|
3
|
+
'use strict'
|
|
4
|
+
const context = require('../context-store')
|
|
5
|
+
const { jsonApiCall } = require('../api-client')
|
|
6
|
+
const prompt = require('../prompt')
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {{ userId: string, email?: string, owner?: boolean, deployer?: boolean }} MemberRow
|
|
10
|
+
* @typedef {{ ask?: (question: string) => Promise<string> }} ConfirmIo
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @param {Record<string, any>} flags */
|
|
14
|
+
function orgOf(flags) {
|
|
15
|
+
const orgId = flags.org || context.get('org')
|
|
16
|
+
if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
|
|
17
|
+
return String(orgId)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The account id from --user or the positional argument.
|
|
22
|
+
* @param {Record<string, any>} flags
|
|
23
|
+
* @param {string | undefined} positional
|
|
24
|
+
* @param {string} usage the command, for the error
|
|
25
|
+
* @returns {string}
|
|
26
|
+
*/
|
|
27
|
+
function accountOf(flags, positional, usage) {
|
|
28
|
+
const userId = flags.user || positional
|
|
29
|
+
if (!userId || typeof userId !== 'string') throw new Error(`${usage} needs the account id: --user <accountId> (the member finds it with \`saaslayer whoami\`)`)
|
|
30
|
+
return userId
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const membersPath = (orgId) => `/api/orgs/${encodeURIComponent(orgId)}/members`
|
|
34
|
+
|
|
35
|
+
/** @param {MemberRow} m */
|
|
36
|
+
function roleOf(m) {
|
|
37
|
+
return m.owner ? 'owner' : m.deployer ? 'deployer' : 'member'
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Print and return the org's members.
|
|
42
|
+
* @param {Record<string, any>} flags --org
|
|
43
|
+
* @returns {Promise<MemberRow[]>}
|
|
44
|
+
*/
|
|
45
|
+
async function membersList(flags = {}) {
|
|
46
|
+
const orgId = orgOf(flags)
|
|
47
|
+
const doc = await jsonApiCall('GET', membersPath(orgId), undefined, flags)
|
|
48
|
+
/** @type {MemberRow[]} */
|
|
49
|
+
const rows = (doc.data || []).map((d) => d.attributes)
|
|
50
|
+
if (!rows.length) console.log(`no members in ${orgId}`)
|
|
51
|
+
for (const m of rows) console.log(`${m.userId} ${m.email || '—'} ${roleOf(m)}`)
|
|
52
|
+
return rows
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Add an account to the org by its account id (`--role deployer` also lets it deploy). The control plane is asked first
|
|
57
|
+
* which account that id is; its email is shown and must be typed back unless --yes.
|
|
58
|
+
* @param {Record<string, any>} flags --org, --user, --role, --yes
|
|
59
|
+
* @param {ConfirmIo} [io]
|
|
60
|
+
* @param {string} [positional] the account id, when not given as --user
|
|
61
|
+
* @returns {Promise<{ userId: string, email: string, deployer: boolean } | null>} null when aborted
|
|
62
|
+
*/
|
|
63
|
+
async function membersAdd(flags = {}, io = {}, positional) {
|
|
64
|
+
const userId = accountOf(flags, positional, 'org members add')
|
|
65
|
+
const role = flags.role
|
|
66
|
+
if (role !== undefined && role !== 'deployer') throw new Error('org members add: --role deployer is the only role an owner grants (omit it for a plain member)')
|
|
67
|
+
const orgId = orgOf(flags)
|
|
68
|
+
const attributes = { userId, ...(role ? { role } : {}) }
|
|
69
|
+
const preview = (await jsonApiCall('POST', membersPath(orgId), { data: { type: 'org-members', attributes: { ...attributes, dryRun: true } } }, flags)).data.attributes
|
|
70
|
+
console.log(`Adding ${preview.email} (${userId}) to org ${orgId}${role ? ' as a deployer' : ''}.`)
|
|
71
|
+
if (!flags.yes) {
|
|
72
|
+
const ask = io.ask || prompt.ask
|
|
73
|
+
const typed = await ask(`Type the account's email "${preview.email}" to confirm: `)
|
|
74
|
+
if (typed.trim().toLowerCase() !== String(preview.email).toLowerCase()) { console.log('Aborted (email did not match).'); return null }
|
|
75
|
+
}
|
|
76
|
+
const added = (await jsonApiCall('POST', membersPath(orgId), { data: { type: 'org-members', attributes } }, flags)).data.attributes
|
|
77
|
+
console.log(`✅ added ${added.email} (${userId}) to ${orgId}${added.deployer ? ' as a deployer' : ''}`)
|
|
78
|
+
return { userId, email: added.email, deployer: Boolean(added.deployer) }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Remove a member from the org (its deployer role is revoked first).
|
|
83
|
+
* @param {Record<string, any>} flags --org, --user
|
|
84
|
+
* @param {string} [positional]
|
|
85
|
+
*/
|
|
86
|
+
async function membersRemove(flags = {}, positional) {
|
|
87
|
+
const userId = accountOf(flags, positional, 'org members remove')
|
|
88
|
+
const orgId = orgOf(flags)
|
|
89
|
+
await jsonApiCall('DELETE', `${membersPath(orgId)}/${encodeURIComponent(userId)}`, undefined, flags)
|
|
90
|
+
console.log(`✅ removed ${userId} from ${orgId}`)
|
|
91
|
+
return { userId, removed: true }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Make a member a deployer (`--role deployer`) or a plain member again (`--role member`).
|
|
96
|
+
* @param {Record<string, any>} flags --org, --user, --role
|
|
97
|
+
* @param {string} [positional]
|
|
98
|
+
*/
|
|
99
|
+
async function membersSetRole(flags = {}, positional) {
|
|
100
|
+
const userId = accountOf(flags, positional, 'org members set-role')
|
|
101
|
+
if (flags.role !== 'deployer' && flags.role !== 'member') throw new Error('org members set-role needs --role deployer|member')
|
|
102
|
+
const orgId = orgOf(flags)
|
|
103
|
+
const path = `${membersPath(orgId)}/${encodeURIComponent(userId)}/roles/deployer`
|
|
104
|
+
await jsonApiCall(flags.role === 'deployer' ? 'POST' : 'DELETE', path, undefined, flags)
|
|
105
|
+
console.log(`✅ ${userId} is now a ${flags.role} of ${orgId}`)
|
|
106
|
+
return { userId, role: flags.role }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
module.exports = { membersList, membersAdd, membersRemove, membersSetRole }
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// `saaslayer permissions trust-policies list|get|add|update|disable|enable|delete`: the external login providers (OIDC issuers)
|
|
2
|
+
// a deployment trusts, through the permissions /trust-policies API. Policies made here are always external, never impersonating.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { exchangeIamToken } = require('../iam-session')
|
|
5
|
+
const { permissionsRequest } = require('../permissions-request')
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {import('../permissions-request').PermissionsFlags & { audience?: string|string[], subject?: string|string[],
|
|
9
|
+
* 'allow-any-subject'?: boolean, 'principal-claim'?: string, 'jwks-uri'?: string, description?: string, reason?: string }} TrustFlags
|
|
10
|
+
* @typedef {{ exchange?: typeof exchangeIamToken, ask?: (question: string) => Promise<string> }} Deps
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// What the API's refusals mean for the person running the command.
|
|
14
|
+
const HINTS = {
|
|
15
|
+
FIRST_PARTY_POLICY: 'this policy is the deployment\'s own login pool (first-party); it is managed by the deployment, not through this command',
|
|
16
|
+
LAST_ADMIN_PROVIDER: 'this provider is the last sign-in path of every usable access admin; add another provider (or an admin who signs in elsewhere) first',
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param {string|string[]|undefined} v @returns {string[]|undefined} */
|
|
20
|
+
const listOf = (v) => (v === undefined ? undefined : Array.isArray(v) ? v : [v])
|
|
21
|
+
|
|
22
|
+
/** @param {string} label @param {string[]} positional @param {string} what */
|
|
23
|
+
function required(label, positional, what) {
|
|
24
|
+
if (!positional[0]) throw new Error(`${label}: <${what}> is required`)
|
|
25
|
+
return positional[0]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Call a trust-policies route; a refusal with a known code gains a hint.
|
|
30
|
+
* @param {string} label @param {TrustFlags} flags @param {Deps} deps @param {string} method @param {string} path @param {object} [body]
|
|
31
|
+
*/
|
|
32
|
+
async function call(label, flags, deps, method, path, body) {
|
|
33
|
+
try {
|
|
34
|
+
return await permissionsRequest(label, flags, deps, method, path, body)
|
|
35
|
+
} catch (err) {
|
|
36
|
+
const hint = ((/** @type {{ codes?: string[] }} */ (err).codes) || []).map((c) => HINTS[/** @type {keyof typeof HINTS} */ (c)]).find(Boolean)
|
|
37
|
+
if (hint) err.message = `${err.message} — ${hint}`
|
|
38
|
+
throw err
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
|
|
43
|
+
const policyOf = (body) => ({ id: body.data.id, ...body.data.attributes })
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The subject rule: --subject (repeatable allowlist) or --allow-any-subject, never both.
|
|
47
|
+
* @param {string} label @param {TrustFlags} flags
|
|
48
|
+
* @returns {{ subjects?: string[], allowAnySubject?: boolean }}
|
|
49
|
+
*/
|
|
50
|
+
function subjectRule(label, flags) {
|
|
51
|
+
const subjects = listOf(flags.subject)
|
|
52
|
+
if (subjects && flags['allow-any-subject']) throw new Error(`${label}: pass --subject S (repeatable) or --allow-any-subject, not both`)
|
|
53
|
+
if (subjects) return { subjects, allowAnySubject: false }
|
|
54
|
+
if (flags['allow-any-subject']) return { allowAnySubject: true }
|
|
55
|
+
return {}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The provider's OIDC discovery document; refuses unless its issuer is exactly the given one (tokens must match it exactly).
|
|
60
|
+
* @param {string} label @param {string} issuerUrl
|
|
61
|
+
* @returns {Promise<{ issuer: string, jwks_uri?: string }>}
|
|
62
|
+
*/
|
|
63
|
+
async function providerConfiguration(label, issuerUrl) {
|
|
64
|
+
const url = `${issuerUrl.replace(/\/+$/, '')}/.well-known/openid-configuration`
|
|
65
|
+
/** @type {any} */
|
|
66
|
+
let config
|
|
67
|
+
try {
|
|
68
|
+
const res = await fetch(url, { method: 'GET', headers: { accept: 'application/json' } })
|
|
69
|
+
if (!res.ok) throw new Error(`${res.status}`)
|
|
70
|
+
config = await res.json()
|
|
71
|
+
} catch (err) {
|
|
72
|
+
throw new Error(`${label}: could not read ${url} (${err.message}) — is ${issuerUrl} an OIDC issuer?`)
|
|
73
|
+
}
|
|
74
|
+
if (!config || config.issuer !== issuerUrl) {
|
|
75
|
+
throw new Error(`${label}: ${url} says its issuer is "${config && config.issuer}", not "${issuerUrl}" — use the exact iss value the provider's ID tokens carry`)
|
|
76
|
+
}
|
|
77
|
+
return config
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
|
|
81
|
+
async function trustPoliciesList(positional, flags, deps = {}) {
|
|
82
|
+
const body = await call('permissions trust-policies list', flags, deps, 'GET', '/trust-policies')
|
|
83
|
+
return (body.data || []).map((/** @type {{ id: string, attributes: object }} */ d) => ({ id: d.id, ...d.attributes }))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
|
|
87
|
+
async function trustPoliciesGet(positional, flags, deps = {}) {
|
|
88
|
+
const label = 'permissions trust-policies get'
|
|
89
|
+
const id = required(label, positional, 'policyId')
|
|
90
|
+
return policyOf(await call(label, flags, deps, 'GET', `/trust-policies/${encodeURIComponent(id)}`))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Trust an external login provider: <issuerUrl> --audience A [--audience B] (--subject S … | --allow-any-subject)
|
|
95
|
+
* [--principal-claim sub] [--jwks-uri URL] [--description D]. The issuer is checked against its openid-configuration.
|
|
96
|
+
* @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
|
|
97
|
+
*/
|
|
98
|
+
async function trustPoliciesAdd(positional, flags, deps = {}) {
|
|
99
|
+
const label = 'permissions trust-policies add'
|
|
100
|
+
const issuerUrl = required(label, positional, 'issuerUrl')
|
|
101
|
+
if (!/^https:\/\//.test(issuerUrl)) throw new Error(`${label}: <issuerUrl> must be an https URL (the exact iss of the provider's ID tokens)`)
|
|
102
|
+
const audience = listOf(flags.audience)
|
|
103
|
+
if (!audience) throw new Error(`${label}: --audience <app client id> is required (repeatable)`)
|
|
104
|
+
const subjects = subjectRule(label, flags)
|
|
105
|
+
if (subjects.allowAnySubject === undefined) throw new Error(`${label}: pass --subject S (repeatable) or --allow-any-subject — a policy with neither authorizes nobody`)
|
|
106
|
+
const config = await providerConfiguration(label, issuerUrl)
|
|
107
|
+
const jwksUri = flags['jwks-uri'] || config.jwks_uri
|
|
108
|
+
const request = {
|
|
109
|
+
issuerUrl,
|
|
110
|
+
audience,
|
|
111
|
+
...(jwksUri ? { jwksUri } : {}),
|
|
112
|
+
claimMapping: { principalId: flags['principal-claim'] || 'sub' },
|
|
113
|
+
...subjects,
|
|
114
|
+
...(flags.description ? { description: flags.description } : {}),
|
|
115
|
+
external: true,
|
|
116
|
+
allowImpersonation: false,
|
|
117
|
+
}
|
|
118
|
+
return policyOf(await call(label, flags, deps, 'POST', '/trust-policies', request))
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Change a provider's audience, subject rule, JWKS URI or description. The issuer and principal claim never change (they key
|
|
123
|
+
* every principal the provider signs in).
|
|
124
|
+
* @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
|
|
125
|
+
*/
|
|
126
|
+
async function trustPoliciesUpdate(positional, flags, deps = {}) {
|
|
127
|
+
const label = 'permissions trust-policies update'
|
|
128
|
+
const id = required(label, positional, 'policyId')
|
|
129
|
+
if (flags['principal-claim'] !== undefined) throw new Error(`${label}: --principal-claim cannot change — it keys every principal this provider signs in; add a new provider instead`)
|
|
130
|
+
const audience = listOf(flags.audience)
|
|
131
|
+
const patch = {
|
|
132
|
+
...(audience ? { audience } : {}),
|
|
133
|
+
...(flags['jwks-uri'] ? { jwksUri: flags['jwks-uri'] } : {}),
|
|
134
|
+
...(flags.description !== undefined ? { description: String(flags.description) } : {}),
|
|
135
|
+
...subjectRule(label, flags),
|
|
136
|
+
}
|
|
137
|
+
if (Object.keys(patch).length === 0) throw new Error(`${label}: nothing to update — give --audience, --subject, --allow-any-subject, --jwks-uri or --description`)
|
|
138
|
+
return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, patch))
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Stop trusting a provider without deleting it. @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
|
|
142
|
+
async function trustPoliciesDisable(positional, flags, deps = {}) {
|
|
143
|
+
const label = 'permissions trust-policies disable'
|
|
144
|
+
const id = required(label, positional, 'policyId')
|
|
145
|
+
return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, { enabled: false }))
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
|
|
149
|
+
async function trustPoliciesEnable(positional, flags, deps = {}) {
|
|
150
|
+
const label = 'permissions trust-policies enable'
|
|
151
|
+
const id = required(label, positional, 'policyId')
|
|
152
|
+
return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, { enabled: true }))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Delete a provider: --reason, then its issuer typed to confirm (--yes confirms). Its people can no longer sign in.
|
|
157
|
+
* @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
|
|
158
|
+
*/
|
|
159
|
+
async function trustPoliciesDelete(positional, flags, deps = {}) {
|
|
160
|
+
const label = 'permissions trust-policies delete'
|
|
161
|
+
const id = required(label, positional, 'policyId')
|
|
162
|
+
if (!flags.reason || typeof flags.reason !== 'string') throw new Error(`${label}: --reason <text> is required`)
|
|
163
|
+
const path = `/trust-policies/${encodeURIComponent(id)}`
|
|
164
|
+
const policy = policyOf(await call(label, flags, deps, 'GET', path))
|
|
165
|
+
const issuer = String(policy.issuerUrl)
|
|
166
|
+
const ask = deps.ask || require('../prompt').ask
|
|
167
|
+
const typed = flags.yes ? issuer : await ask(`Delete trust in ${issuer}? Everyone who signs in through it loses access. Type the issuer "${issuer}" to confirm: `)
|
|
168
|
+
if (typed !== issuer) throw new Error(`${label}: not confirmed — nothing deleted`)
|
|
169
|
+
return policyOf(await call(label, flags, deps, 'DELETE', path, { reason: flags.reason }))
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
module.exports = { trustPoliciesList, trustPoliciesGet, trustPoliciesAdd, trustPoliciesUpdate, trustPoliciesDisable, trustPoliciesEnable, trustPoliciesDelete }
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
// Auth
|
|
2
|
-
//
|
|
1
|
+
// Auth for calls to a deployment's permissions/users API from the CLI: an IAM principal token (--iam), an API key (--token), a
|
|
2
|
+
// deployment login (`saaslayer login --deployment`), or an external OIDC ID token sent only to a pinned permissions API host.
|
|
3
3
|
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
4
5
|
const creds = require('./credentials')
|
|
5
6
|
const { refreshIfExpired } = require('./deployment-auth')
|
|
7
|
+
const { decodeJwt } = require('./config')
|
|
6
8
|
|
|
7
|
-
const CHOOSE = '--iam <principalId>, --token (or $SAASLAYER_TOKEN), or a deployment login (`saaslayer login --deployment <dep_id|env>`) is required'
|
|
9
|
+
const CHOOSE = '--iam <principalId>, --token (or $SAASLAYER_TOKEN), --id-token-file (or $SAASLAYER_ID_TOKEN), or a deployment login (`saaslayer login --deployment <dep_id|env>`) is required'
|
|
8
10
|
|
|
9
11
|
/**
|
|
10
12
|
* @param {string} token
|
|
@@ -26,15 +28,22 @@ function assertServes(profile, apiBase) {
|
|
|
26
28
|
}
|
|
27
29
|
|
|
28
30
|
/**
|
|
29
|
-
* Request auth headers.
|
|
31
|
+
* Request auth headers. An external ID token (--id-token-file / $SAASLAYER_ID_TOKEN) is sent only when apiBase is its pinned
|
|
32
|
+
* host (see idTokenTarget). Otherwise explicit flags win: --iam (IAM principal token as bearer), --token (api key + bearer),
|
|
30
33
|
* --deployment/--as/--user-service-instance (that deployment login's id token). Without one, the ambient source is
|
|
31
34
|
* used: $SAASLAYER_TOKEN or the current deployment login — both at once is ambiguous and refused.
|
|
32
35
|
* @param {string} apiBase
|
|
33
|
-
* @param {
|
|
34
|
-
* @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> }} deps
|
|
36
|
+
* @param {IdTokenFlags & { region?: string, profile?: string }} flags
|
|
37
|
+
* @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> } & IdTokenDeps} deps
|
|
35
38
|
* @returns {Promise<Record<string, string>>}
|
|
36
39
|
*/
|
|
37
|
-
async function authHeaders(apiBase, flags,
|
|
40
|
+
async function authHeaders(apiBase, flags, deps) {
|
|
41
|
+
const { exchange } = deps
|
|
42
|
+
const pinned = await idTokenTarget(flags, deps)
|
|
43
|
+
if (pinned) {
|
|
44
|
+
if (normBase(apiBase) !== pinned.apiBase) throw new Error(`refusing to send your ID token to ${normBase(apiBase)} — it is pinned to ${pinned.apiBase}`)
|
|
45
|
+
return pinned.headers
|
|
46
|
+
}
|
|
38
47
|
if (flags.iam && flags.token) throw new Error('pass only one of --iam, --token or a deployment login (--deployment)')
|
|
39
48
|
if (flags.iam) {
|
|
40
49
|
const region = flags.region || process.env.AWS_REGION || 'us-west-2'
|
|
@@ -58,4 +67,153 @@ async function authHeaders(apiBase, flags, { exchange }) {
|
|
|
58
67
|
return { authorization: `Bearer ${fresh.idToken}` }
|
|
59
68
|
}
|
|
60
69
|
|
|
61
|
-
|
|
70
|
+
/** @param {string} u */
|
|
71
|
+
const normBase = (u) => String(u || '').replace(/\/+$/, '')
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @typedef {{ token: string, source: string, explicit: boolean }} IdToken
|
|
75
|
+
* @typedef {{ 'api-base'?: string, 'id-token-file'?: string, token?: string, iam?: string, deployment?: string, as?: string,
|
|
76
|
+
* 'user-service-instance'?: string, yes?: boolean }} IdTokenFlags
|
|
77
|
+
* @typedef {{ ask?: (question: string) => Promise<string>, apiCall?: typeof import('./api-client').apiCall,
|
|
78
|
+
* resolveDeployment?: typeof import('./deployments').resolveDeployment }} IdTokenDeps
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The external ID token, if one was given: --id-token-file (explicit) wins over $SAASLAYER_ID_TOKEN (ambient). Warns when the
|
|
83
|
+
* file is readable by group or others. Errors name the source, never the token.
|
|
84
|
+
* @param {IdTokenFlags} flags
|
|
85
|
+
* @returns {IdToken|null}
|
|
86
|
+
*/
|
|
87
|
+
function idTokenOf(flags) {
|
|
88
|
+
const file = flags['id-token-file']
|
|
89
|
+
if (file !== undefined) {
|
|
90
|
+
if (typeof file !== 'string') throw new Error('--id-token-file <path> needs a path')
|
|
91
|
+
/** @type {string} */
|
|
92
|
+
let token
|
|
93
|
+
try {
|
|
94
|
+
if (fs.statSync(file).mode & 0o077) console.error(`warning: ${file} is readable by other users — chmod 600 it`)
|
|
95
|
+
token = fs.readFileSync(file, 'utf8').trim()
|
|
96
|
+
} catch (err) {
|
|
97
|
+
throw new Error(`--id-token-file: cannot read ${file}`)
|
|
98
|
+
}
|
|
99
|
+
return { token, source: '--id-token-file', explicit: true }
|
|
100
|
+
}
|
|
101
|
+
const env = process.env.SAASLAYER_ID_TOKEN
|
|
102
|
+
return env ? { token: env.trim(), source: '$SAASLAYER_ID_TOKEN', explicit: false } : null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Decode (no verification — the deployment verifies) and refuse a token the deployment would reject anyway: not a JWT, a
|
|
107
|
+
* Cognito access token, no aud, no exp, or expired. Messages carry the issuer and how to get a fresh ID token.
|
|
108
|
+
* @param {IdToken} idToken
|
|
109
|
+
* @returns {{ iss: string }}
|
|
110
|
+
*/
|
|
111
|
+
function checkIdToken({ token, source }) {
|
|
112
|
+
/** @type {Record<string, unknown>} */
|
|
113
|
+
let claims
|
|
114
|
+
try {
|
|
115
|
+
claims = decodeJwt(token)
|
|
116
|
+
if (!claims || typeof claims !== 'object') throw new Error('not an object')
|
|
117
|
+
} catch (err) {
|
|
118
|
+
throw new Error(`${source} is not a JWT — pass the raw ID token your login provider issued`)
|
|
119
|
+
}
|
|
120
|
+
const iss = typeof claims.iss === 'string' ? claims.iss : 'your login provider'
|
|
121
|
+
if (claims.token_use === 'access') {
|
|
122
|
+
throw new Error(`${source} holds an access token, not an ID token — access tokens carry no aud; use the ID token (Cognito: AuthenticationResult.IdToken; OIDC: id_token)`)
|
|
123
|
+
}
|
|
124
|
+
if (claims.aud === undefined) throw new Error(`${source} has no aud claim — pass the ID token, whose aud is your app client id`)
|
|
125
|
+
if (typeof claims.exp !== 'number') throw new Error(`${source} has no exp claim — pass the ID token your login provider issued`)
|
|
126
|
+
if (claims.exp <= Math.floor(Date.now() / 1000)) {
|
|
127
|
+
const at = new Date(claims.exp * 1000).toISOString()
|
|
128
|
+
throw new Error(`${source} expired at ${at} — get a fresh ID token from ${iss} (sign in again; Cognito: \`aws cognito-idp admin-initiate-auth\` or initiate-auth, then AuthenticationResult.IdToken; OIDC: the id_token of a new sign-in)`)
|
|
129
|
+
}
|
|
130
|
+
return { iss }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Refuse an ID token next to any other credential: --iam, --token, $SAASLAYER_TOKEN, a deployment login selector, or (for
|
|
135
|
+
* the ambient $SAASLAYER_ID_TOKEN) the current deployment login. An explicit --id-token-file wins over a stored login.
|
|
136
|
+
* @param {IdToken} idToken
|
|
137
|
+
* @param {IdTokenFlags} flags
|
|
138
|
+
*/
|
|
139
|
+
function refuseAmbiguous(idToken, flags) {
|
|
140
|
+
const others = [
|
|
141
|
+
flags.iam && '--iam',
|
|
142
|
+
flags.token && '--token',
|
|
143
|
+
process.env.SAASLAYER_TOKEN && '$SAASLAYER_TOKEN',
|
|
144
|
+
flags.as && '--as',
|
|
145
|
+
flags['user-service-instance'] && '--user-service-instance',
|
|
146
|
+
].filter(Boolean)
|
|
147
|
+
if (others.length) throw new Error(`an external ID token (${idToken.source}) cannot be combined with ${others.join(', ')} — pass one credential`)
|
|
148
|
+
const current = idToken.explicit ? null : creds.currentDeploymentProfile()
|
|
149
|
+
if (current) {
|
|
150
|
+
throw new Error(`both $SAASLAYER_ID_TOKEN and the deployment login ${current.deploymentId} (${current.email || current.userId}) are available — pass --id-token-file or unset $SAASLAYER_ID_TOKEN to choose`)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* A deployment's permissions API base, read through the control plane (your control-plane login): the deployment's one
|
|
156
|
+
* live permissions-service module (else its default instance), its public hostname winning over the raw endpoint.
|
|
157
|
+
* @param {IdTokenFlags} flags
|
|
158
|
+
* @param {IdTokenDeps} deps
|
|
159
|
+
* @returns {Promise<string>}
|
|
160
|
+
*/
|
|
161
|
+
async function deploymentPermissionsApiBase(flags, deps) {
|
|
162
|
+
const apiCall = deps.apiCall || require('./api-client').apiCall
|
|
163
|
+
const resolveDeployment = deps.resolveDeployment || require('./deployments').resolveDeployment
|
|
164
|
+
const selector = String(flags.deployment)
|
|
165
|
+
const deploymentId = /^dep_/.test(selector) ? selector : (await resolveDeployment({ ...flags, env: selector })).deploymentId
|
|
166
|
+
const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}`, undefined, flags)
|
|
167
|
+
/** @type {Array<{ moduleName: string|null, serviceInstance: string|null, status: string|null, outputs?: Record<string, unknown>, publicOutputs?: Record<string, unknown> }>} */
|
|
168
|
+
const modules = ((doc && doc.data && doc.data.attributes) || {}).modules || []
|
|
169
|
+
const live = modules.filter((m) => m.moduleName === 'permissions-service' && m.status !== 'DELETED')
|
|
170
|
+
if (live.length === 0) throw new Error(`deployment ${deploymentId} has no permissions-service`)
|
|
171
|
+
const chosen = live.length === 1 ? live[0] : live.find((m) => (m.serviceInstance || '_') === '_')
|
|
172
|
+
if (!chosen) throw new Error(`deployment ${deploymentId} has several permissions-service instances (${live.map((m) => m.serviceInstance).join(', ')}) — pass that instance's https --api-base instead of --deployment`)
|
|
173
|
+
const endpoint = { ...(chosen.outputs || {}), ...(chosen.publicOutputs || {}) }.ServiceEndpoint
|
|
174
|
+
if (typeof endpoint !== 'string' || !endpoint.startsWith('https://')) throw new Error(`deployment ${deploymentId} has no https permissions API endpoint yet`)
|
|
175
|
+
return normBase(endpoint)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The pinned destination for an external ID token: --deployment (resolved through the control plane; a different --api-base
|
|
180
|
+
* is refused), else an https --api-base (or $SAASLAYER_API_BASE) the user confirms by typing its host (--yes confirms).
|
|
181
|
+
* @param {{ iss: string }} claims
|
|
182
|
+
* @param {IdTokenFlags} flags
|
|
183
|
+
* @param {IdTokenDeps} deps
|
|
184
|
+
* @returns {Promise<string>}
|
|
185
|
+
*/
|
|
186
|
+
async function pinnedApiBase(claims, flags, deps) {
|
|
187
|
+
const given = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
188
|
+
if (flags.deployment) {
|
|
189
|
+
const apiBase = await deploymentPermissionsApiBase(flags, deps)
|
|
190
|
+
if (given && normBase(given) !== apiBase) throw new Error(`--api-base ${normBase(given)} is not ${flags.deployment}'s permissions API (${apiBase}) — refusing to send your ID token there`)
|
|
191
|
+
return apiBase
|
|
192
|
+
}
|
|
193
|
+
if (!given) throw new Error('an external ID token needs a pinned destination: --deployment <dep_id|env> (resolved through the control plane) or an https --api-base you confirm')
|
|
194
|
+
/** @type {URL} */
|
|
195
|
+
let url
|
|
196
|
+
try { url = new URL(given) } catch (err) { throw new Error(`--api-base ${given} must be an https URL`) }
|
|
197
|
+
if (url.protocol !== 'https:') throw new Error(`--api-base ${given} must be an https URL`)
|
|
198
|
+
const ask = deps.ask || require('./prompt').ask
|
|
199
|
+
const typed = flags.yes ? url.host : await ask(`Send your ID token from ${claims.iss} to ${url.host}? Type the host "${url.host}" to confirm: `)
|
|
200
|
+
if (typed !== url.host) throw new Error(`not confirmed — your ID token was not sent to ${url.host}`)
|
|
201
|
+
return normBase(given)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Where and how to send an external ID token, or null when none was given (other auth applies).
|
|
206
|
+
* @param {IdTokenFlags} flags
|
|
207
|
+
* @param {IdTokenDeps} [deps]
|
|
208
|
+
* @returns {Promise<{ apiBase: string, headers: Record<string, string> }|null>}
|
|
209
|
+
*/
|
|
210
|
+
async function idTokenTarget(flags, deps = {}) {
|
|
211
|
+
const idToken = idTokenOf(flags)
|
|
212
|
+
if (!idToken) return null
|
|
213
|
+
refuseAmbiguous(idToken, flags)
|
|
214
|
+
const claims = checkIdToken(idToken)
|
|
215
|
+
const apiBase = await pinnedApiBase(claims, flags, deps)
|
|
216
|
+
return { apiBase, headers: { authorization: `Bearer ${idToken.token}` } }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
module.exports = { authHeaders, idTokenTarget }
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
// One call to a deployment's permissions API from a CLI command: resolves --api-base (or $SAASLAYER_API_BASE)
|
|
2
|
-
// (deployment login, API key or
|
|
1
|
+
// One call to a deployment's permissions API from a CLI command: resolves --api-base (or $SAASLAYER_API_BASE) and the selected
|
|
2
|
+
// auth (deployment login, API key, IAM, or an external ID token to a pinned host), and throws with the API's error codes.
|
|
3
3
|
'use strict'
|
|
4
4
|
const { exchangeIamToken } = require('./iam-session')
|
|
5
|
-
const { authHeaders } = require('./deployment-api-auth')
|
|
5
|
+
const { authHeaders, idTokenTarget } = require('./deployment-api-auth')
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string
|
|
9
|
-
*
|
|
8
|
+
* @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string,
|
|
9
|
+
* 'id-token-file'?: string, yes?: boolean }} PermissionsFlags
|
|
10
|
+
* @typedef {{ exchange?: typeof exchangeIamToken } & import('./deployment-api-auth').IdTokenDeps} Deps
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
13
|
/**
|
|
@@ -25,17 +26,22 @@ function apiBaseOf(label, flags) {
|
|
|
25
26
|
* @returns {Promise<any>} the response document
|
|
26
27
|
*/
|
|
27
28
|
async function permissionsRequest(label, flags, deps, method, path, body) {
|
|
28
|
-
const
|
|
29
|
-
const
|
|
29
|
+
const pinned = await idTokenTarget(flags, deps)
|
|
30
|
+
const apiBase = pinned ? pinned.apiBase : apiBaseOf(label, flags)
|
|
31
|
+
const auth = pinned ? pinned.headers : await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
30
32
|
const res = await fetch(`${apiBase}${path}`, {
|
|
31
33
|
method,
|
|
32
34
|
headers: body ? { ...auth, 'content-type': 'application/json' } : auth,
|
|
33
35
|
...(body ? { body: JSON.stringify(body) } : {}),
|
|
36
|
+
// The ID token goes only to its pinned host: a redirect would resend it wherever the 3xx points, so none is followed.
|
|
37
|
+
...(pinned ? { redirect: /** @type {RequestRedirect} */ ('error') } : {}),
|
|
34
38
|
})
|
|
35
39
|
const json = await res.json().catch(() => ({}))
|
|
36
40
|
if (!res.ok) {
|
|
37
|
-
|
|
38
|
-
|
|
41
|
+
/** @type {Array<{ code?: string, message?: string, detail?: string }>} */
|
|
42
|
+
const errors = (json && json.errors) || []
|
|
43
|
+
const detail = errors.map((e) => [e.code, e.message || e.detail].filter(Boolean).join(': ')).join('; ') || JSON.stringify(json)
|
|
44
|
+
throw Object.assign(new Error(`${label} failed (${res.status}${detail ? ` ${detail}` : ''})`), { status: res.status, codes: errors.map((e) => e.code).filter(Boolean) })
|
|
39
45
|
}
|
|
40
46
|
return json
|
|
41
47
|
}
|