saaslayer 0.0.7 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +150 -13
- package/bin/saaslayer.js +318 -66
- package/package.json +4 -3
- package/src/api-client.js +48 -28
- package/src/aws-sigv4.js +1 -1
- package/src/commands/access-admins.js +73 -0
- package/src/commands/accounts.js +32 -3
- package/src/commands/activity.js +33 -0
- package/src/commands/aws.js +55 -6
- package/src/commands/catalog.js +30 -29
- package/src/commands/context.js +64 -0
- package/src/commands/deploy.js +79 -10
- package/src/commands/first-admin.js +42 -0
- package/src/commands/foundation.js +456 -0
- package/src/commands/integration-credentials.js +66 -0
- package/src/commands/lifecycle.js +77 -40
- package/src/commands/login.js +200 -26
- package/src/commands/machine-trust.js +96 -0
- package/src/commands/operations.js +140 -0
- package/src/commands/orgs.js +29 -4
- package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
- package/src/commands/release-manifest.js +138 -0
- package/src/commands/service-principals.js +81 -0
- package/src/commands/settings.js +140 -0
- package/src/commands/stacks.js +12 -7
- package/src/commands/users-management.js +401 -0
- package/src/commands/users.js +192 -4
- package/src/config.js +20 -7
- package/src/credentials.js +221 -34
- package/src/deployment-api-auth.js +61 -0
- package/src/deployment-auth.js +38 -0
- package/src/deployments.js +12 -13
- package/src/discovery.js +66 -0
- package/src/env-compare.js +143 -0
- package/src/iam-session.js +4 -30
- package/src/module-catalog.js +66 -0
- package/src/permissions-request.js +43 -0
- package/src/release-manifest.js +334 -0
- package/src/scope.js +114 -0
- package/src/settings.js +272 -0
- package/src/users-api.js +165 -0
- package/src/users-import/import.js +10 -10
- package/templates/saaslayer-foundation-region.yml +37 -1
- package/templates/saaslayer-foundation.yml +63 -10
- package/src/commands/iam-principals.js +0 -53
- package/src/rbac-auth.js +0 -25
- package/vendor/ids/index.d.ts +0 -21
- package/vendor/ids/index.js +0 -237
package/src/api-client.js
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
|
-
// Authenticated calls to the SaaSLayer control-plane API using the cached Cognito id token (Bearer).
|
|
2
|
-
// Shared by the org/project/aws commands.
|
|
1
|
+
// Authenticated calls to the SaaSLayer control-plane API using the cached control-plane Cognito id token (Bearer).
|
|
2
|
+
// Shared by the org/project/aws commands. Also holds the Cognito token refresh both login authorities use.
|
|
3
3
|
'use strict'
|
|
4
4
|
const creds = require('./credentials')
|
|
5
|
-
const { resolvePoolConfig } = require('./config')
|
|
5
|
+
const { resolvePoolConfig, controlPlaneUrl } = require('./config')
|
|
6
6
|
|
|
7
7
|
function apiBase(flags = {}) {
|
|
8
|
-
|
|
9
|
-
if (!base) throw new Error('control-plane API base required: pass --config-url or set $SAASLAYER_CONFIG_URL')
|
|
10
|
-
return String(base).replace(/\/$/, '')
|
|
8
|
+
return String(controlPlaneUrl(flags).value).replace(/\/$/, '')
|
|
11
9
|
}
|
|
12
10
|
|
|
13
11
|
// Refresh a little before expiry so a token never lapses mid-request.
|
|
14
12
|
const REFRESH_SKEW_SECONDS = 60
|
|
15
13
|
|
|
14
|
+
/**
|
|
15
|
+
* Whether a cached token is still usable (no expiry recorded counts as usable).
|
|
16
|
+
* @param {{ expiresAt?: number }} profile
|
|
17
|
+
*/
|
|
18
|
+
function isFresh(profile) {
|
|
19
|
+
const now = Math.floor(Date.now() / 1000)
|
|
20
|
+
return !profile.expiresAt || profile.expiresAt - REFRESH_SKEW_SECONDS > now
|
|
21
|
+
}
|
|
22
|
+
|
|
16
23
|
function bearer() {
|
|
17
24
|
const current = creds.getCurrent()
|
|
18
25
|
if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
|
|
@@ -20,52 +27,65 @@ function bearer() {
|
|
|
20
27
|
}
|
|
21
28
|
|
|
22
29
|
/**
|
|
23
|
-
* Exchange
|
|
24
|
-
*
|
|
25
|
-
* @param {
|
|
26
|
-
* @
|
|
30
|
+
* Exchange a refresh token for fresh id/access tokens with the app client that issued it (Cognito
|
|
31
|
+
* REFRESH_TOKEN_AUTH). Cognito does not rotate the refresh token, so callers keep it. Returns null when refused.
|
|
32
|
+
* @param {{ region: string, clientId: string, refreshToken: string }} input
|
|
33
|
+
* @returns {Promise<{ idToken: string, accessToken?: string, expiresAt: number } | null>}
|
|
27
34
|
*/
|
|
28
|
-
async function
|
|
29
|
-
const
|
|
30
|
-
const res = await fetch(`https://cognito-idp.${pool.region}.amazonaws.com/`, {
|
|
35
|
+
async function refreshCognitoTokens({ region, clientId, refreshToken }) {
|
|
36
|
+
const res = await fetch(`https://cognito-idp.${region}.amazonaws.com/`, {
|
|
31
37
|
method: 'POST',
|
|
32
38
|
headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'AWSCognitoIdentityProviderService.InitiateAuth' },
|
|
33
|
-
body: JSON.stringify({ AuthFlow: 'REFRESH_TOKEN_AUTH', ClientId:
|
|
39
|
+
body: JSON.stringify({ AuthFlow: 'REFRESH_TOKEN_AUTH', ClientId: clientId, AuthParameters: { REFRESH_TOKEN: refreshToken } }),
|
|
34
40
|
})
|
|
35
41
|
const doc = await res.json().catch(() => ({}))
|
|
36
42
|
const result = doc && doc.AuthenticationResult
|
|
37
|
-
if (!res.ok || !result || !result.IdToken)
|
|
38
|
-
return
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
43
|
+
if (!res.ok || !result || !result.IdToken) return null
|
|
44
|
+
return { idToken: result.IdToken, accessToken: result.AccessToken, expiresAt: Math.floor(Date.now() / 1000) + (Number(result.ExpiresIn) || 3600) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Refresh the control-plane login with the client it is bound to (else the control plane's published pool config)
|
|
49
|
+
* and persist it.
|
|
50
|
+
* @param {object} current the cached account record
|
|
51
|
+
* @param {object} flags
|
|
52
|
+
*/
|
|
53
|
+
async function refreshTokens(current, flags) {
|
|
54
|
+
const pool = current.clientId && current.region ? current : await resolvePoolConfig(flags)
|
|
55
|
+
const fresh = await refreshCognitoTokens({ region: pool.region, clientId: pool.clientId, refreshToken: current.refreshToken })
|
|
56
|
+
if (!fresh) throw new Error('session expired — run `saaslayer login`')
|
|
57
|
+
return creds.setUser({ ...current, idToken: fresh.idToken, accessToken: fresh.accessToken || current.accessToken, expiresAt: fresh.expiresAt })
|
|
44
58
|
}
|
|
45
59
|
|
|
46
60
|
/**
|
|
47
|
-
* The current id token, refreshed first when it is expired (or about to be).
|
|
61
|
+
* The current control-plane id token, refreshed first when it is expired (or about to be).
|
|
48
62
|
* @param {object} [flags]
|
|
49
63
|
*/
|
|
50
64
|
async function freshBearer(flags = {}) {
|
|
51
65
|
const current = creds.getCurrent()
|
|
52
66
|
if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
|
|
53
|
-
|
|
54
|
-
if (!current.expiresAt || current.expiresAt - REFRESH_SKEW_SECONDS > now) return current.idToken
|
|
67
|
+
if (isFresh(current)) return current.idToken
|
|
55
68
|
if (!current.refreshToken) throw new Error('session expired — run `saaslayer login`')
|
|
56
69
|
return (await refreshTokens(current, flags)).idToken
|
|
57
70
|
}
|
|
58
71
|
|
|
59
|
-
|
|
72
|
+
/**
|
|
73
|
+
* @param {string} method
|
|
74
|
+
* @param {string} path
|
|
75
|
+
* @param {unknown} [body]
|
|
76
|
+
* @param {object} [flags]
|
|
77
|
+
* @param {{ headers?: Record<string, string> }} [opts] extra request headers (e.g. Idempotency-Key)
|
|
78
|
+
*/
|
|
79
|
+
async function apiCall(method, path, body, flags, opts = {}) {
|
|
60
80
|
const token = await freshBearer(flags)
|
|
61
81
|
const res = await fetch(`${apiBase(flags)}${path}`, {
|
|
62
82
|
method,
|
|
63
|
-
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}
|
|
83
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}`, ...(opts.headers || {}) },
|
|
64
84
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
65
85
|
})
|
|
66
86
|
const doc = await res.json().catch(() => ({}))
|
|
67
|
-
if (!res.ok) throw new Error(`${method} ${path} failed (${res.status}): ${doc.error || JSON.stringify(doc)}`)
|
|
87
|
+
if (!res.ok) throw Object.assign(new Error(`${method} ${path} failed (${res.status}): ${doc.error || JSON.stringify(doc)}`), { status: res.status, body: doc })
|
|
68
88
|
return doc
|
|
69
89
|
}
|
|
70
90
|
|
|
71
|
-
module.exports = { apiBase, bearer, freshBearer, apiCall }
|
|
91
|
+
module.exports = { apiBase, bearer, freshBearer, apiCall, isFresh, refreshCognitoTokens }
|
package/src/aws-sigv4.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// AWS Signature Version 4 request signing (no SDK dependency): signs every provided header plus x-amz-date and,
|
|
2
|
-
// with temporary credentials, x-amz-security-token. Used to build the STS proof for the
|
|
2
|
+
// with temporary credentials, x-amz-security-token. Used to build the STS proof for the permissions IAM exchange.
|
|
3
3
|
'use strict'
|
|
4
4
|
const crypto = require('crypto')
|
|
5
5
|
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// `saaslayer permissions access-admins list|offer|status|cancel|accept|activate`: the deployment's administrators through the permissions
|
|
2
|
+
// API — who counts as usable, and the transfer / add-and-verify workflow (offer → target accepts → initiator leaves).
|
|
3
|
+
'use strict'
|
|
4
|
+
const { exchangeIamToken } = require('../iam-session')
|
|
5
|
+
const { permissionsRequest } = require('../permissions-request')
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @typedef {import('../permissions-request').PermissionsFlags & { mode?: string, 'expires-in-hours'?: string }} AdminFlags
|
|
9
|
+
* @typedef {{ exchange?: typeof exchangeIamToken }} Deps
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** @param {string} label @param {string[]} positional @param {string} what */
|
|
13
|
+
function required(label, positional, what) {
|
|
14
|
+
if (!positional[0]) throw new Error(`${label}: <${what}> is required`)
|
|
15
|
+
return positional[0]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
|
|
19
|
+
const transferOf = (body) => ({ id: body.data.id, ...body.data.attributes })
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The deployment's administrators and how many count as usable humans.
|
|
23
|
+
* @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps]
|
|
24
|
+
*/
|
|
25
|
+
async function adminsList(positional, flags, deps = {}) {
|
|
26
|
+
const body = await permissionsRequest('permissions access-admins list', flags, deps, 'GET', '/access-admins')
|
|
27
|
+
return { administrators: (body.data || []).map((/** @type {{ attributes: object }} */ d) => d.attributes), usableAdministrators: (body.meta || {}).usableAdministrators }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Offer your seat (--mode transfer, the default: you leave once they accept) or another seat (--mode add) to <suid>.
|
|
32
|
+
* They hold the role at once and count once they accept.
|
|
33
|
+
* @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps]
|
|
34
|
+
*/
|
|
35
|
+
async function adminsOffer(positional, flags, deps = {}) {
|
|
36
|
+
const label = 'permissions access-admins offer'
|
|
37
|
+
const targetId = required(label, positional, 'suid')
|
|
38
|
+
const mode = flags.mode || 'transfer'
|
|
39
|
+
if (mode !== 'transfer' && mode !== 'add') throw new Error(`${label}: --mode must be transfer or add`)
|
|
40
|
+
/** @type {{ targetId: string, mode: string, expiresInHours?: number }} */
|
|
41
|
+
const request = { targetId, mode }
|
|
42
|
+
if (flags['expires-in-hours'] !== undefined) request.expiresInHours = Number(flags['expires-in-hours'])
|
|
43
|
+
return transferOf(await permissionsRequest(label, flags, deps, 'POST', '/access-admins/transfers', request))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
|
|
47
|
+
async function adminsStatus(positional, flags, deps = {}) {
|
|
48
|
+
const id = required('permissions access-admins status', positional, 'transferId')
|
|
49
|
+
return transferOf(await permissionsRequest('permissions access-admins status', flags, deps, 'GET', `/access-admins/transfers/${encodeURIComponent(id)}`))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Cancel a pending offer you made (its grant is revoked). @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
|
|
53
|
+
async function adminsCancel(positional, flags, deps = {}) {
|
|
54
|
+
const id = required('permissions access-admins cancel', positional, 'transferId')
|
|
55
|
+
return transferOf(await permissionsRequest('permissions access-admins cancel', flags, deps, 'DELETE', `/access-admins/transfers/${encodeURIComponent(id)}`))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Accept an offer made to you (your own deployment login, verified email); repeat to resume an interrupted accept.
|
|
60
|
+
* @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps]
|
|
61
|
+
*/
|
|
62
|
+
async function adminsAccept(positional, flags, deps = {}) {
|
|
63
|
+
const transferId = required('permissions access-admins accept', positional, 'transferId')
|
|
64
|
+
return transferOf(await permissionsRequest('permissions access-admins accept', flags, deps, 'POST', '/me/access-admin-transfers/accept', { transferId }))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Record your own activation (your deployment login, verified email). @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
|
|
68
|
+
async function adminsActivate(positional, flags, deps = {}) {
|
|
69
|
+
const body = await permissionsRequest('permissions access-admins activate', flags, deps, 'POST', '/me/activation', {})
|
|
70
|
+
return body.data.attributes
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
module.exports = { adminsList, adminsOffer, adminsStatus, adminsCancel, adminsAccept, adminsActivate }
|
package/src/commands/accounts.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// `saaslayer accounts | account
|
|
2
|
-
// accounts
|
|
1
|
+
// `saaslayer accounts | account use <email> | deployment logins | deployment use <dep_id|env>` — inspect and switch the
|
|
2
|
+
// control-plane accounts and deployment logins cached locally, without re-authenticating. Never returns tokens.
|
|
3
3
|
'use strict'
|
|
4
4
|
const creds = require('../credentials')
|
|
5
5
|
|
|
@@ -22,4 +22,33 @@ function accountUse(selector) {
|
|
|
22
22
|
return creds.setCurrent(selector)
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* All cached deployment logins, most-recently-used first, flagging the current one and expired tokens.
|
|
27
|
+
* @returns {Array<{ deploymentId: string, environment: string|null, serviceInstance: string, email: string|null, userId: string, current: boolean, expired: boolean|null }>}
|
|
28
|
+
*/
|
|
29
|
+
function deploymentLogins() {
|
|
30
|
+
const current = creds.currentDeploymentProfile()
|
|
31
|
+
const now = Math.floor(Date.now() / 1000)
|
|
32
|
+
return creds.listDeploymentProfiles().map((p) => ({
|
|
33
|
+
deploymentId: p.deploymentId,
|
|
34
|
+
environment: p.environment || null,
|
|
35
|
+
serviceInstance: p.serviceInstance,
|
|
36
|
+
email: p.email || null,
|
|
37
|
+
userId: p.userId,
|
|
38
|
+
current: current ? p.key === current.key : false,
|
|
39
|
+
expired: typeof p.expiresAt === 'number' ? p.expiresAt <= now : null,
|
|
40
|
+
}))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Make one deployment login current: --deployment (dep id or environment) plus --as / --user-service-instance when
|
|
45
|
+
* several logins match.
|
|
46
|
+
* @param {{ deployment?: string, as?: string, 'user-service-instance'?: string }} flags
|
|
47
|
+
*/
|
|
48
|
+
function deploymentUse(flags) {
|
|
49
|
+
if (!flags.deployment && !flags.as && !flags['user-service-instance']) throw new Error('deployment use requires a <dep_id|env> (and --as <email> when several logins match)')
|
|
50
|
+
const p = creds.useDeploymentProfile(flags)
|
|
51
|
+
return { deploymentId: p.deploymentId, environment: p.environment || null, serviceInstance: p.serviceInstance, email: p.email || null }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
module.exports = { accountsList, accountUse, deploymentLogins, deploymentUse }
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// `saaslayer activity --env E`: a deployment's activity feed — every change, the customer's and any operator's, with
|
|
2
|
+
// actor, action, reason and operation id, newest first.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { apiCall } = require('../api-client')
|
|
5
|
+
const { resolveDeployment } = require('../deployments')
|
|
6
|
+
const { loadOperations } = require('./operations')
|
|
7
|
+
|
|
8
|
+
const MAX_LIMIT = 500
|
|
9
|
+
|
|
10
|
+
/** --limit as a number, or undefined when absent. @param {object} flags */
|
|
11
|
+
function limitOf(flags) {
|
|
12
|
+
if (flags.limit === undefined) return undefined
|
|
13
|
+
const n = Number(flags.limit)
|
|
14
|
+
if (!Number.isInteger(n) || n < 1 || n > MAX_LIMIT) throw new Error(`--limit must be a whole number from 1 to ${MAX_LIMIT}`)
|
|
15
|
+
return n
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Print the deployment's activity (one line per change, or the entries with --json) and return the entries.
|
|
20
|
+
* @param {object} flags
|
|
21
|
+
*/
|
|
22
|
+
async function activityCommand(flags) {
|
|
23
|
+
const limit = limitOf(flags)
|
|
24
|
+
const deploymentId = flags.deployment || (await resolveDeployment(flags)).deploymentId
|
|
25
|
+
const query = limit ? `?limit=${limit}` : ''
|
|
26
|
+
const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}/activity${query}`, undefined, flags)
|
|
27
|
+
const ops = loadOperations()
|
|
28
|
+
const entries = ((doc && doc.data) || []).map((d) => ops.redact(d.attributes))
|
|
29
|
+
console.log(flags.json ? JSON.stringify(entries, null, 2) : loadOperations('activity').formatActivity(entries).join('\n'))
|
|
30
|
+
return entries
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { activityCommand }
|
package/src/commands/aws.js
CHANGED
|
@@ -80,9 +80,49 @@ function artifactsBucketName(accountId, region) {
|
|
|
80
80
|
return `sl-artifacts-${region}-${opaqueAccountToken(accountId, 'artifacts').slice(0, 12)}`
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
// The account's email sender domain, as the region template's EmailSenderDomain AllowedPattern takes it (or '' = none).
|
|
84
|
+
const EMAIL_SENDER_DOMAIN_PATTERN = /^(([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63})?$/
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The --email-sender-domain flag, lowercased and checked before anything touches AWS; undefined when not passed.
|
|
88
|
+
* @param {Record<string, unknown>} flags
|
|
89
|
+
* @returns {string|undefined}
|
|
90
|
+
*/
|
|
91
|
+
function emailSenderDomainFlag(flags) {
|
|
92
|
+
const raw = flags['email-sender-domain']
|
|
93
|
+
if (raw === undefined) return undefined
|
|
94
|
+
const domain = String(raw === true ? '' : raw).trim().toLowerCase()
|
|
95
|
+
if (!EMAIL_SENDER_DOMAIN_PATTERN.test(domain)) throw new Error(`--email-sender-domain expects a domain like acme.com ('' removes it), got '${raw}'`)
|
|
96
|
+
return domain
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The region stack's email sender outputs: the SES identity ARN and the DKIM CNAME records for the domain's DNS.
|
|
101
|
+
* @param {Array<{ OutputKey: string, OutputValue: string }>} outputs
|
|
102
|
+
* @returns {{ identityArn: string, records: string[] }|null}
|
|
103
|
+
*/
|
|
104
|
+
function emailSenderOutputs(outputs) {
|
|
105
|
+
const value = (key) => ((outputs || []).find((o) => o.OutputKey === key) || {}).OutputValue
|
|
106
|
+
const records = value('EmailSenderDkimRecords')
|
|
107
|
+
if (!records) return null
|
|
108
|
+
return { identityArn: value('EmailSenderIdentityArn') || '', records: records.split('\n').filter(Boolean) }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Prints what the customer's DNS admin adds, and the setting that sends through the domain once verified.
|
|
113
|
+
* @param {(...a: unknown[]) => void} log @param {string} domain @param {{ identityArn: string, records: string[] }} sender
|
|
114
|
+
*/
|
|
115
|
+
function logEmailSenderRecords(log, domain, sender) {
|
|
116
|
+
log(` email sender domain ${domain}: add these DKIM records to its DNS (CNAME, TTL 300 or the default):`)
|
|
117
|
+
for (const record of sender.records) log(` ${record}`)
|
|
118
|
+
log(' once verified (saaslayer foundation status), send through it with:')
|
|
119
|
+
log(` saaslayer settings set CognitoEmailSenderArn=${sender.identityArn} CognitoEmailFromAddress='<Name> <no-reply@${domain}>'`)
|
|
120
|
+
}
|
|
121
|
+
|
|
83
122
|
// Build the `aws cloudformation deploy` argv for the per-region foundation stack. Pure — unit-testable.
|
|
84
|
-
// No IAM in this stack, so no CAPABILITY_NAMED_IAM; a no-op re-deploy must be clean, not a failure.
|
|
85
|
-
|
|
123
|
+
// No IAM in this stack, so no CAPABILITY_NAMED_IAM; a no-op re-deploy must be clean, not a failure. Without
|
|
124
|
+
// emailSenderDomain no override is passed, so a re-run keeps the sender domain the stack already has.
|
|
125
|
+
function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templateFile = FOUNDATION_REGION_TEMPLATE, emailSenderDomain }) {
|
|
86
126
|
return [
|
|
87
127
|
'cloudformation', 'deploy',
|
|
88
128
|
'--template-file', templateFile,
|
|
@@ -91,13 +131,15 @@ function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templ
|
|
|
91
131
|
'--no-fail-on-empty-changeset',
|
|
92
132
|
'--parameter-overrides',
|
|
93
133
|
`ArtifactsBucketName=${bucket}`,
|
|
134
|
+
...(emailSenderDomain !== undefined ? [`EmailSenderDomain=${emailSenderDomain}`] : []),
|
|
94
135
|
]
|
|
95
136
|
}
|
|
96
137
|
|
|
97
|
-
// Deploy the per-region foundation stack (shared artifact bucket) with the caller's
|
|
98
|
-
|
|
138
|
+
// Deploy the per-region foundation stack (shared artifact bucket, optional email sender domain) with the caller's
|
|
139
|
+
// creds (or injected `env`).
|
|
140
|
+
function deployFoundationRegion({ accountId, region, env, emailSenderDomain }) {
|
|
99
141
|
const bucket = artifactsBucketName(accountId, region)
|
|
100
|
-
execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket }),
|
|
142
|
+
execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket, emailSenderDomain }),
|
|
101
143
|
{ stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
|
|
102
144
|
return bucket
|
|
103
145
|
}
|
|
@@ -107,6 +149,7 @@ async function awsConnect(flags) {
|
|
|
107
149
|
const region = flags.region || 'us-east-1'
|
|
108
150
|
const orgId = flags.org || context.get('org')
|
|
109
151
|
if (!accountId) throw new Error('aws connect requires --aws-account <12-digit id>')
|
|
152
|
+
const emailSenderDomain = emailSenderDomainFlag(flags)
|
|
110
153
|
if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
|
|
111
154
|
// D5: bind the account to the active project by default; --org-wide opens it to all org projects.
|
|
112
155
|
const orgWide = flags['org-wide'] === true || flags['org-wide'] === 'true'
|
|
@@ -118,8 +161,13 @@ async function awsConnect(flags) {
|
|
|
118
161
|
console.log(` registered (trust secret minted); deploying the account-global foundation stack into ${accountId} with your AWS creds…`)
|
|
119
162
|
deployFoundation({ controlPlaneAccount: conn.controlPlaneAccountId, externalId: conn.externalId, region, stackNamePrefix: conn.stackNamePrefix, orgId })
|
|
120
163
|
console.log(` global foundation deployed; deploying the per-region foundation (shared artifact bucket) into ${region}…`)
|
|
121
|
-
const bucket = deployFoundationRegion({ accountId, region })
|
|
164
|
+
const bucket = deployFoundationRegion({ accountId, region, emailSenderDomain })
|
|
122
165
|
console.log(` per-region foundation deployed (bucket ${bucket}); verifying cross-account trust…`)
|
|
166
|
+
if (emailSenderDomain) {
|
|
167
|
+
const described = JSON.parse(execFileSync('aws', ['cloudformation', 'describe-stacks', '--stack-name', foundationRegionStackName(region), '--region', region, '--output', 'json'], { encoding: 'utf8' }))
|
|
168
|
+
const sender = emailSenderOutputs(described.Stacks[0].Outputs)
|
|
169
|
+
if (sender) logEmailSenderRecords(console.log, emailSenderDomain, sender)
|
|
170
|
+
}
|
|
123
171
|
const v = await apiCall('POST', '/api/aws/connect/verify', { accountId, region }, flags)
|
|
124
172
|
console.log(`✅ AWS account ${accountId} connected to org ${orgId} (${v.bootstrapStatus})`)
|
|
125
173
|
return v
|
|
@@ -128,5 +176,6 @@ async function awsConnect(flags) {
|
|
|
128
176
|
module.exports = {
|
|
129
177
|
awsConnect, deployFoundation, foundationDeployArgs, FOUNDATION_TEMPLATE,
|
|
130
178
|
deployFoundationRegion, foundationRegionDeployArgs, foundationRegionStackName, artifactsBucketName,
|
|
179
|
+
emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords,
|
|
131
180
|
FOUNDATION_REGION_TEMPLATE,
|
|
132
181
|
}
|
package/src/commands/catalog.js
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
// `saaslayer
|
|
2
|
-
// /catalog/:product),
|
|
1
|
+
// `saaslayer permissions model apply|get|export`, `saaslayer permissions owner bootstrap|reconcile` and `saaslayer permissions
|
|
2
|
+
// register`: apply a product's role catalog (PUT /catalog/:product), bootstrap or reconcile its org owners, register a
|
|
3
|
+
// service under its product, and export the published registry snapshot.
|
|
3
4
|
'use strict'
|
|
4
5
|
const fs = require('fs')
|
|
5
6
|
const path = require('path')
|
|
6
7
|
const { exchangeIamToken } = require('../iam-session')
|
|
7
|
-
const { authHeaders } = require('../
|
|
8
|
+
const { authHeaders } = require('../deployment-api-auth')
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* @typedef {{ type: 'string' | 'number' | 'boolean' | 'string[]' | 'principalRef' | 'ip', required: boolean, nullable?: boolean, pii?: boolean }} AttributeSchema
|
|
11
|
-
* @typedef {{ product: string, catalogVersion: number,
|
|
12
|
+
* @typedef {{ product: string, service?: string, catalogVersion: number,
|
|
12
13
|
* resources: Record<string, { actions: string[], attributes?: Record<string, AttributeSchema> }>,
|
|
13
14
|
* trustedContext?: boolean, contextSchema?: Record<string, AttributeSchema>,
|
|
14
15
|
* roles: object[], delegation?: object, selfCheck?: object[] }} CatalogManifest
|
|
@@ -86,9 +87,9 @@ function registryLine(registry) {
|
|
|
86
87
|
*/
|
|
87
88
|
async function catalogApply(positional, flags, deps = {}) {
|
|
88
89
|
const manifestPath = positional[0]
|
|
89
|
-
if (!manifestPath) throw new Error('
|
|
90
|
+
if (!manifestPath) throw new Error('permissions model apply: a manifest path is required')
|
|
90
91
|
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
91
|
-
if (!apiBase) throw new Error('
|
|
92
|
+
if (!apiBase) throw new Error('permissions model apply: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
92
93
|
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
93
94
|
/** @type {CatalogManifest} */
|
|
94
95
|
const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
|
|
@@ -105,12 +106,12 @@ async function catalogApply(positional, flags, deps = {}) {
|
|
|
105
106
|
})
|
|
106
107
|
const body = await res.json().catch(() => ({}))
|
|
107
108
|
if (!res.ok) {
|
|
108
|
-
throw new Error(`
|
|
109
|
+
throw new Error(`permissions model apply failed (${res.status}): ${apiErrorDetail(body)}`)
|
|
109
110
|
}
|
|
110
111
|
const a = body.data.attributes
|
|
111
112
|
const summary = formatApplyResult(a)
|
|
112
113
|
console.log(summary)
|
|
113
|
-
if (a.plan === 'apply' && !a.dryRun && a.verified !== true) throw new Error('
|
|
114
|
+
if (a.plan === 'apply' && !a.dryRun && a.verified !== true) throw new Error('permissions model apply: roles were written but not verified on read-back')
|
|
114
115
|
return summary
|
|
115
116
|
}
|
|
116
117
|
|
|
@@ -135,12 +136,12 @@ async function callCatalog(label, url, init) {
|
|
|
135
136
|
*/
|
|
136
137
|
async function catalogBootstrapOwner(positional, flags, deps = {}) {
|
|
137
138
|
const product = positional[0]
|
|
138
|
-
if (!product) throw new Error('
|
|
139
|
-
if (!flags.org || !flags.user) throw new Error('
|
|
139
|
+
if (!product) throw new Error('permissions owner bootstrap: a product is required')
|
|
140
|
+
if (!flags.org || !flags.user) throw new Error('permissions owner bootstrap: --org and --user are required')
|
|
140
141
|
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
141
|
-
if (!apiBase) throw new Error('
|
|
142
|
+
if (!apiBase) throw new Error('permissions owner bootstrap: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
142
143
|
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
143
|
-
return callCatalog('
|
|
144
|
+
return callCatalog('permissions owner bootstrap', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/bootstrap-owner`, {
|
|
144
145
|
method: 'POST',
|
|
145
146
|
headers: { ...auth, 'content-type': 'application/json' },
|
|
146
147
|
body: JSON.stringify({ orgId: flags.org, userId: flags.user }),
|
|
@@ -155,15 +156,15 @@ async function catalogBootstrapOwner(positional, flags, deps = {}) {
|
|
|
155
156
|
*/
|
|
156
157
|
async function catalogReconcileOwners(positional, flags, deps = {}) {
|
|
157
158
|
const product = positional[0]
|
|
158
|
-
if (!product) throw new Error('
|
|
159
|
+
if (!product) throw new Error('permissions owner reconcile: a product is required')
|
|
159
160
|
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
160
|
-
if (!apiBase) throw new Error('
|
|
161
|
+
if (!apiBase) throw new Error('permissions owner reconcile: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
161
162
|
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
162
163
|
const query = new URLSearchParams()
|
|
163
164
|
if (flags.apply) query.set('apply', 'true')
|
|
164
165
|
if (flags.org) query.set('orgId', flags.org)
|
|
165
166
|
const qs = query.toString()
|
|
166
|
-
return callCatalog('
|
|
167
|
+
return callCatalog('permissions owner reconcile', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/reconcile-owners${qs ? `?${qs}` : ''}`, {
|
|
167
168
|
method: 'POST',
|
|
168
169
|
headers: { ...auth, 'content-type': 'application/json' },
|
|
169
170
|
})
|
|
@@ -178,35 +179,35 @@ async function catalogReconcileOwners(positional, flags, deps = {}) {
|
|
|
178
179
|
*/
|
|
179
180
|
async function catalogGet(positional, flags, deps = {}) {
|
|
180
181
|
const product = positional[0]
|
|
181
|
-
if (!product) throw new Error('
|
|
182
|
+
if (!product) throw new Error('permissions model get: a product is required')
|
|
182
183
|
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
183
|
-
if (!apiBase) throw new Error('
|
|
184
|
+
if (!apiBase) throw new Error('permissions model get: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
184
185
|
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
185
186
|
const res = await fetch(`${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}`, { method: 'GET', headers: auth })
|
|
186
187
|
const body = await res.json().catch(() => ({}))
|
|
187
188
|
if (!res.ok) {
|
|
188
189
|
const detail = (body.errors || []).map((e) => e.message || e.detail).filter(Boolean).join('; ') || JSON.stringify(body)
|
|
189
|
-
throw new Error(`
|
|
190
|
+
throw new Error(`permissions model get failed (${res.status}): ${detail}`)
|
|
190
191
|
}
|
|
191
192
|
return body.data.attributes
|
|
192
193
|
}
|
|
193
194
|
|
|
194
195
|
/**
|
|
195
|
-
* Register (upsert) a service's
|
|
196
|
+
* Register (upsert) a service's permissions manifest under its product (POST /catalog/register). A service belongs to
|
|
196
197
|
* exactly one product: --product (or the manifest's `product`) is required.
|
|
197
198
|
* @param {string[]} positional [manifestPath]
|
|
198
199
|
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, product?: string }} flags
|
|
199
200
|
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
200
201
|
* @returns {Promise<string>} the printed summary
|
|
201
202
|
*/
|
|
202
|
-
async function
|
|
203
|
+
async function permissionsRegister(positional, flags, deps = {}) {
|
|
203
204
|
const manifestPath = positional[0]
|
|
204
|
-
if (!manifestPath) throw new Error('
|
|
205
|
+
if (!manifestPath) throw new Error('permissions register: a manifest path is required')
|
|
205
206
|
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
206
|
-
if (!apiBase) throw new Error('
|
|
207
|
+
if (!apiBase) throw new Error('permissions register: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
207
208
|
const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
|
|
208
209
|
const product = flags.product || manifest.product
|
|
209
|
-
if (!product) throw new Error('
|
|
210
|
+
if (!product) throw new Error('permissions register: --product is required (the product that owns this service)')
|
|
210
211
|
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
211
212
|
const a = await callCatalog('register', `${apiBase.replace(/\/$/, '')}/catalog/register`, {
|
|
212
213
|
method: 'POST',
|
|
@@ -222,7 +223,7 @@ async function rbacRegister(positional, flags, deps = {}) {
|
|
|
222
223
|
}
|
|
223
224
|
|
|
224
225
|
/**
|
|
225
|
-
* Write the currently published registry snapshot ({ meta, snapshot }) to a file — the pinned registry
|
|
226
|
+
* Write the currently published registry snapshot ({ meta, snapshot }) to a file — the pinned registry @saaslayer/permissions
|
|
226
227
|
* direct mode loads (GET /catalog/registry/snapshot).
|
|
227
228
|
* @param {string[]} positional unused
|
|
228
229
|
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, snapshot?: boolean, out?: string }} flags
|
|
@@ -230,16 +231,16 @@ async function rbacRegister(positional, flags, deps = {}) {
|
|
|
230
231
|
* @returns {Promise<string>} the written path
|
|
231
232
|
*/
|
|
232
233
|
async function catalogExport(positional, flags, deps = {}) {
|
|
233
|
-
if (!flags.snapshot) throw new Error('
|
|
234
|
-
if (!flags.out || flags.out === true) throw new Error('
|
|
234
|
+
if (!flags.snapshot) throw new Error('permissions model export: --snapshot is required (the only export format)')
|
|
235
|
+
if (!flags.out || flags.out === true) throw new Error('permissions model export: --out <file> is required')
|
|
235
236
|
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
236
|
-
if (!apiBase) throw new Error('
|
|
237
|
+
if (!apiBase) throw new Error('permissions model export: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
237
238
|
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
238
|
-
const a = await callCatalog('
|
|
239
|
+
const a = await callCatalog('permissions model export', `${apiBase.replace(/\/$/, '')}/catalog/registry/snapshot`, { method: 'GET', headers: auth })
|
|
239
240
|
const outPath = path.resolve(String(flags.out))
|
|
240
241
|
fs.writeFileSync(outPath, `${JSON.stringify({ meta: a.meta, snapshot: a.snapshot }, null, 2)}\n`)
|
|
241
242
|
console.log(`wrote registry snapshot v${a.snapshot && a.snapshot.version} to ${outPath}`)
|
|
242
243
|
return outPath
|
|
243
244
|
}
|
|
244
245
|
|
|
245
|
-
module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport,
|
|
246
|
+
module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport, permissionsRegister, formatApplyResult }
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// `saaslayer context` — what the CLI will act as and on: the control-plane account, the deployment login, the AWS
|
|
2
|
+
// profile, the control-plane URL, the org and project (with where each came from) and every cached identity. No tokens.
|
|
3
|
+
'use strict'
|
|
4
|
+
const context = require('../context-store')
|
|
5
|
+
const { projectIdKind } = require('../scope')
|
|
6
|
+
const { accountsList, deploymentLogins } = require('./accounts')
|
|
7
|
+
const { controlPlaneUrl } = require('../config')
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {object} flags
|
|
11
|
+
*/
|
|
12
|
+
function contextShow(flags) {
|
|
13
|
+
const current = accountsList().find((a) => a.current)
|
|
14
|
+
const org = context.get('org')
|
|
15
|
+
const project = context.get('project')
|
|
16
|
+
const logins = deploymentLogins()
|
|
17
|
+
const deployment = logins.find((d) => d.current) || null
|
|
18
|
+
const awsEnv = process.env.AWS_PROFILE
|
|
19
|
+
return {
|
|
20
|
+
account: current ? { email: current.email, userId: current.userId, controlPlane: current.env } : null,
|
|
21
|
+
controlPlaneUrl: controlPlaneUrl(flags),
|
|
22
|
+
org: org ? { value: org, source: 'context' } : { value: null, source: null },
|
|
23
|
+
project: project ? { value: project, source: 'context', kind: projectIdKind(project) } : { value: null, source: null, kind: null },
|
|
24
|
+
deployment,
|
|
25
|
+
awsProfile: flags.profile ? { value: flags.profile, source: 'flag' } : awsEnv ? { value: awsEnv, source: 'env' } : { value: null, source: null },
|
|
26
|
+
deploymentLogins: logins,
|
|
27
|
+
identities: accountsList().map((a) => ({ email: a.email, userId: a.userId, controlPlane: a.env, current: a.current, expired: a.expired })),
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {ReturnType<typeof contextShow>} ctx
|
|
33
|
+
* @returns {string[]}
|
|
34
|
+
*/
|
|
35
|
+
function formatContext(ctx) {
|
|
36
|
+
const lines = [
|
|
37
|
+
ctx.account ? `account: ${ctx.account.email} (${ctx.account.userId}) control plane: ${ctx.account.controlPlane}` : 'account: — (run `saaslayer login`)',
|
|
38
|
+
`control plane url: ${ctx.controlPlaneUrl.value} (from ${ctx.controlPlaneUrl.source})`,
|
|
39
|
+
ctx.org.value ? `org: ${ctx.org.value} (from context)` : 'org: — (run `saaslayer org use <id>`)',
|
|
40
|
+
ctx.project.value ? `project: ${ctx.project.value} (${ctx.project.kind}, from context)` : 'project: — (run `saaslayer project use <id>`)',
|
|
41
|
+
ctx.deployment ? `deployment login: ${deploymentLabel(ctx.deployment)}` : 'deployment login: — (run `saaslayer login --deployment <dep_id|env>`)',
|
|
42
|
+
ctx.awsProfile.value ? `aws profile: ${ctx.awsProfile.value} (from ${ctx.awsProfile.source})` : 'aws profile: — (ambient AWS credentials)',
|
|
43
|
+
'cached identities:',
|
|
44
|
+
]
|
|
45
|
+
if (!ctx.identities.length) lines.push(' none — run `saaslayer login`')
|
|
46
|
+
for (const i of ctx.identities) {
|
|
47
|
+
lines.push(`${i.current ? '*' : ' '} ${i.email} [control plane: ${i.controlPlane}]${i.expired === true ? ' (token expired)' : ''}`)
|
|
48
|
+
}
|
|
49
|
+
for (const d of ctx.deploymentLogins) {
|
|
50
|
+
lines.push(`${d.current ? '*' : ' '} ${deploymentLabel(d)}${d.expired === true ? ' (token expired)' : ''}`)
|
|
51
|
+
}
|
|
52
|
+
lines.push('--project/--org/--env on a command override this context for that command; --deployment/--as pick a deployment login; --profile picks the AWS profile.')
|
|
53
|
+
return lines
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {{ deploymentId: string, environment: string|null, serviceInstance: string, email: string|null, userId: string }} d
|
|
58
|
+
* @returns {string}
|
|
59
|
+
*/
|
|
60
|
+
function deploymentLabel(d) {
|
|
61
|
+
return `${d.deploymentId}${d.environment ? ` [${d.environment}]` : ''} (user-service ${d.serviceInstance}) as ${d.email || d.userId}`
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
module.exports = { contextShow, formatContext }
|