saaslayer 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +195 -8
- package/bin/saaslayer.js +454 -38
- package/package.json +19 -4
- package/src/api-client.js +91 -0
- package/src/aws-sigv4.js +47 -0
- package/src/commands/access-admins.js +73 -0
- package/src/commands/accounts.js +54 -0
- package/src/commands/activity.js +33 -0
- package/src/commands/aws.js +132 -0
- package/src/commands/catalog.js +246 -0
- package/src/commands/context.js +64 -0
- package/src/commands/deploy.js +118 -0
- package/src/commands/first-admin.js +42 -0
- package/src/commands/foundation.js +405 -0
- package/src/commands/lifecycle.js +124 -0
- package/src/commands/login.js +261 -0
- package/src/commands/machine-trust.js +96 -0
- package/src/commands/migrate.js +290 -0
- package/src/commands/operations.js +140 -0
- package/src/commands/orgs.js +81 -0
- package/src/commands/permissions-inspect.js +228 -0
- package/src/commands/release-manifest.js +138 -0
- package/src/commands/service-principals.js +81 -0
- package/src/commands/settings.js +140 -0
- package/src/commands/stacks.js +22 -0
- package/src/commands/users.js +269 -0
- package/src/config.js +49 -0
- package/src/context-store.js +37 -0
- package/src/credentials.js +285 -0
- package/src/deployment-api-auth.js +61 -0
- package/src/deployment-auth.js +38 -0
- package/src/deployments.js +26 -0
- package/src/discovery.js +66 -0
- package/src/env-compare.js +143 -0
- package/src/foundation-template.js +57 -0
- package/src/iam-session.js +67 -0
- package/src/migrations-lib.js +15 -0
- package/src/module-catalog.js +66 -0
- package/src/permissions-request.js +43 -0
- package/src/prompt.js +19 -0
- package/src/release-manifest.js +334 -0
- package/src/scope.js +114 -0
- package/src/settings.js +272 -0
- package/src/users-api.js +165 -0
- package/src/users-import/ids.js +24 -0
- package/src/users-import/import.js +292 -0
- package/src/users-import/manifest.js +90 -0
- package/src/users-import/providers/cognito.js +61 -0
- package/src/users-import/providers/index.js +24 -0
- package/templates/saaslayer-foundation-region.yml +109 -0
- package/templates/{host-account.yml → saaslayer-foundation.yml} +381 -87
|
@@ -0,0 +1,91 @@
|
|
|
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
|
+
'use strict'
|
|
4
|
+
const creds = require('./credentials')
|
|
5
|
+
const { resolvePoolConfig, controlPlaneUrl } = require('./config')
|
|
6
|
+
|
|
7
|
+
function apiBase(flags = {}) {
|
|
8
|
+
return String(controlPlaneUrl(flags).value).replace(/\/$/, '')
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Refresh a little before expiry so a token never lapses mid-request.
|
|
12
|
+
const REFRESH_SKEW_SECONDS = 60
|
|
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
|
+
|
|
23
|
+
function bearer() {
|
|
24
|
+
const current = creds.getCurrent()
|
|
25
|
+
if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
|
|
26
|
+
return current.idToken
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
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>}
|
|
34
|
+
*/
|
|
35
|
+
async function refreshCognitoTokens({ region, clientId, refreshToken }) {
|
|
36
|
+
const res = await fetch(`https://cognito-idp.${region}.amazonaws.com/`, {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'AWSCognitoIdentityProviderService.InitiateAuth' },
|
|
39
|
+
body: JSON.stringify({ AuthFlow: 'REFRESH_TOKEN_AUTH', ClientId: clientId, AuthParameters: { REFRESH_TOKEN: refreshToken } }),
|
|
40
|
+
})
|
|
41
|
+
const doc = await res.json().catch(() => ({}))
|
|
42
|
+
const result = doc && doc.AuthenticationResult
|
|
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 })
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The current control-plane id token, refreshed first when it is expired (or about to be).
|
|
62
|
+
* @param {object} [flags]
|
|
63
|
+
*/
|
|
64
|
+
async function freshBearer(flags = {}) {
|
|
65
|
+
const current = creds.getCurrent()
|
|
66
|
+
if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
|
|
67
|
+
if (isFresh(current)) return current.idToken
|
|
68
|
+
if (!current.refreshToken) throw new Error('session expired — run `saaslayer login`')
|
|
69
|
+
return (await refreshTokens(current, flags)).idToken
|
|
70
|
+
}
|
|
71
|
+
|
|
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 = {}) {
|
|
80
|
+
const token = await freshBearer(flags)
|
|
81
|
+
const res = await fetch(`${apiBase(flags)}${path}`, {
|
|
82
|
+
method,
|
|
83
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}`, ...(opts.headers || {}) },
|
|
84
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
85
|
+
})
|
|
86
|
+
const doc = await res.json().catch(() => ({}))
|
|
87
|
+
if (!res.ok) throw Object.assign(new Error(`${method} ${path} failed (${res.status}): ${doc.error || JSON.stringify(doc)}`), { status: res.status, body: doc })
|
|
88
|
+
return doc
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
module.exports = { apiBase, bearer, freshBearer, apiCall, isFresh, refreshCognitoTokens }
|
package/src/aws-sigv4.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
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 permissions IAM exchange.
|
|
3
|
+
'use strict'
|
|
4
|
+
const crypto = require('crypto')
|
|
5
|
+
|
|
6
|
+
const sha256 = (data) => crypto.createHash('sha256').update(data, 'utf8').digest('hex')
|
|
7
|
+
const hmac = (key, data) => crypto.createHmac('sha256', key).update(data, 'utf8').digest()
|
|
8
|
+
const encode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {{ method: string, url: string, headers: Record<string, string>, body: string, region: string, service: string,
|
|
12
|
+
* credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date }} req
|
|
13
|
+
* @returns {{ headers: Record<string, string> }} the input headers plus X-Amz-Date, X-Amz-Security-Token and Authorization
|
|
14
|
+
*/
|
|
15
|
+
function signRequest({ method, url, headers, body, region, service, credentials, now = new Date() }) {
|
|
16
|
+
const amzDate = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
|
|
17
|
+
const date = amzDate.slice(0, 8)
|
|
18
|
+
const out = { ...headers, 'X-Amz-Date': amzDate }
|
|
19
|
+
if (credentials.sessionToken) out['X-Amz-Security-Token'] = credentials.sessionToken
|
|
20
|
+
|
|
21
|
+
const u = new URL(url)
|
|
22
|
+
const query = [...u.searchParams.entries()]
|
|
23
|
+
.map(([k, v]) => [encode(k), encode(v)])
|
|
24
|
+
.sort((a, b) => (a[0] === b[0] ? a[1].localeCompare(b[1]) : a[0] < b[0] ? -1 : 1))
|
|
25
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
26
|
+
.join('&')
|
|
27
|
+
const canonical = Object.entries(out)
|
|
28
|
+
.map(([k, v]) => [k.toLowerCase(), String(v).trim().replace(/\s+/g, ' ')])
|
|
29
|
+
.sort((a, b) => (a[0] < b[0] ? -1 : 1))
|
|
30
|
+
const signedHeaders = canonical.map(([k]) => k).join(';')
|
|
31
|
+
const canonicalRequest = [
|
|
32
|
+
method.toUpperCase(),
|
|
33
|
+
u.pathname || '/',
|
|
34
|
+
query,
|
|
35
|
+
canonical.map(([k, v]) => `${k}:${v}\n`).join(''),
|
|
36
|
+
signedHeaders,
|
|
37
|
+
sha256(body || ''),
|
|
38
|
+
].join('\n')
|
|
39
|
+
const scope = `${date}/${region}/${service}/aws4_request`
|
|
40
|
+
const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256(canonicalRequest)].join('\n')
|
|
41
|
+
const key = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey}`, date), region), service), 'aws4_request')
|
|
42
|
+
const signature = crypto.createHmac('sha256', key).update(stringToSign, 'utf8').digest('hex')
|
|
43
|
+
out.Authorization = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
|
|
44
|
+
return { headers: out }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
module.exports = { signRequest }
|
|
@@ -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 }
|
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
'use strict'
|
|
4
|
+
const creds = require('../credentials')
|
|
5
|
+
|
|
6
|
+
// All cached accounts, most-recently-used first, flagging the active one and whether its token is expired.
|
|
7
|
+
function accountsList() {
|
|
8
|
+
const current = creds.getCurrent()
|
|
9
|
+
const now = Math.floor(Date.now() / 1000)
|
|
10
|
+
return creds.list().map((u) => ({
|
|
11
|
+
userId: u.userId,
|
|
12
|
+
email: u.email,
|
|
13
|
+
env: u.env,
|
|
14
|
+
current: current ? u.userId === current.userId : false,
|
|
15
|
+
expired: typeof u.expiresAt === 'number' ? u.expiresAt <= now : null,
|
|
16
|
+
}))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Switch the active account to `selector` (an email or userId). Returns the now-current account.
|
|
20
|
+
function accountUse(selector) {
|
|
21
|
+
if (!selector) throw new Error('account use requires an <email> or <userId>')
|
|
22
|
+
return creds.setCurrent(selector)
|
|
23
|
+
}
|
|
24
|
+
|
|
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 }
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// `saaslayer aws connect` — connect the caller's own AWS account (cloud-prem) to an org. Mints a
|
|
2
|
+
// per-host-account trust secret via the control-plane API, deploys the SaaSLayer foundation stack into
|
|
3
|
+
// that account using the operator's AMBIENT AWS creds, then verifies the cross-account trust.
|
|
4
|
+
'use strict'
|
|
5
|
+
const fs = require('fs')
|
|
6
|
+
const os = require('os')
|
|
7
|
+
const path = require('path')
|
|
8
|
+
const crypto = require('crypto')
|
|
9
|
+
const { execFileSync } = require('child_process')
|
|
10
|
+
const context = require('../context-store')
|
|
11
|
+
const { apiCall } = require('../api-client')
|
|
12
|
+
|
|
13
|
+
// CloudFormation's inline template limit is 51,200 bytes. The foundation template exceeds it with its
|
|
14
|
+
// comments (~40% of the file), so `aws cloudformation deploy --template-file` would demand --s3-bucket.
|
|
15
|
+
// Strip full-line comments + blank lines into a temp file for the deploy — the SOURCE keeps every comment.
|
|
16
|
+
// Safe: the foundation template has no inline `#` inside quoted values (only full-line comments).
|
|
17
|
+
function strippedTemplate(templateFile) {
|
|
18
|
+
const out = fs.readFileSync(templateFile, 'utf8')
|
|
19
|
+
.split('\n')
|
|
20
|
+
.filter((l) => { const t = l.trim(); return t !== '' && !t.startsWith('#') })
|
|
21
|
+
.join('\n')
|
|
22
|
+
const tmp = path.join(os.tmpdir(), `saaslayer-foundation-${process.pid}.yml`)
|
|
23
|
+
fs.writeFileSync(tmp, out)
|
|
24
|
+
return tmp
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Absolute path to the bundled foundation template. This template file is the SHARED contract between
|
|
28
|
+
// `saaslayer aws connect` (customer BYO, ambient creds) and cplane account-vending (assumed-role creds) —
|
|
29
|
+
// see control-plane/cli/src/accounts/foundation.ts, which deploys this same template + param contract.
|
|
30
|
+
const FOUNDATION_TEMPLATE = path.join(__dirname, '..', '..', 'templates', 'saaslayer-foundation.yml')
|
|
31
|
+
|
|
32
|
+
// Build the `aws cloudformation deploy` argv for the foundation stack. Pure — unit-testable, and shared
|
|
33
|
+
// so the stack name + param contract live in one place.
|
|
34
|
+
function foundationDeployArgs({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId = '', templateFile = FOUNDATION_TEMPLATE }) {
|
|
35
|
+
return [
|
|
36
|
+
'cloudformation', 'deploy',
|
|
37
|
+
'--template-file', templateFile,
|
|
38
|
+
'--stack-name', 'saaslayer-foundation',
|
|
39
|
+
'--region', region,
|
|
40
|
+
'--capabilities', 'CAPABILITY_NAMED_IAM',
|
|
41
|
+
'--parameter-overrides',
|
|
42
|
+
`ControlPlaneAccountId=${controlPlaneAccount}`,
|
|
43
|
+
`ExternalId=${externalId}`,
|
|
44
|
+
`StackNamePrefix=${stackNamePrefix}`,
|
|
45
|
+
`OrgId=${orgId}`,
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Deploy the bundled foundation template into the target account. `env` lets a caller inject ASSUMED
|
|
50
|
+
// role creds (AWS_ACCESS_KEY_ID/SECRET/SESSION_TOKEN); omit to use the caller's ambient creds.
|
|
51
|
+
function deployFoundation({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId, env }) {
|
|
52
|
+
const templateFile = strippedTemplate(FOUNDATION_TEMPLATE)
|
|
53
|
+
execFileSync('aws', foundationDeployArgs({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId, templateFile }),
|
|
54
|
+
{ stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The account-global saaslayer-foundation stack holds IAM only (a role can't be created twice, so it's
|
|
58
|
+
// account-scoped). Region-bound resources — first the shared deployment-artifact bucket — live in a SEPARATE
|
|
59
|
+
// per-region stack, so a fully-deployable account needs BOTH. `aws connect` deploys both.
|
|
60
|
+
const FOUNDATION_REGION_TEMPLATE = path.join(__dirname, '..', '..', 'templates', 'saaslayer-foundation-region.yml')
|
|
61
|
+
|
|
62
|
+
// The per-region stack name: `saaslayer-foundation-<region>`. The region in the name IS the scope signal
|
|
63
|
+
// (`saaslayer-foundation` = account-global; `saaslayer-foundation-<region>` = that region).
|
|
64
|
+
function foundationRegionStackName(region) {
|
|
65
|
+
return `saaslayer-foundation-${region}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Derive the shared artifact bucket name. MUST mirror the deployer's derivation byte-for-byte so the bucket this
|
|
69
|
+
// creates == the SERVERLESS_DEPLOYMENT_BUCKET the deployer injects. Source of truth (kept in sync, conformance-
|
|
70
|
+
// tested): control-plane/services/deployer-service/src/refs.ts opaqueAccountToken/artifactsBucketName, and
|
|
71
|
+
// @saaslayer/config. The published CLI can't take those (unpublished) workspace deps, so it inlines the algorithm.
|
|
72
|
+
function opaqueAccountToken(accountId, purpose) {
|
|
73
|
+
const acct = String(accountId == null ? '' : accountId).trim()
|
|
74
|
+
const p = String(purpose == null ? '' : purpose).trim()
|
|
75
|
+
if (!acct) throw new Error('opaqueAccountToken: accountId is required')
|
|
76
|
+
if (!p) throw new Error('opaqueAccountToken: purpose is required')
|
|
77
|
+
return crypto.createHash('sha256').update(`${acct}|${p}`).digest('hex').slice(0, 20)
|
|
78
|
+
}
|
|
79
|
+
function artifactsBucketName(accountId, region) {
|
|
80
|
+
return `sl-artifacts-${region}-${opaqueAccountToken(accountId, 'artifacts').slice(0, 12)}`
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 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
|
+
function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templateFile = FOUNDATION_REGION_TEMPLATE }) {
|
|
86
|
+
return [
|
|
87
|
+
'cloudformation', 'deploy',
|
|
88
|
+
'--template-file', templateFile,
|
|
89
|
+
'--stack-name', foundationRegionStackName(region),
|
|
90
|
+
'--region', region,
|
|
91
|
+
'--no-fail-on-empty-changeset',
|
|
92
|
+
'--parameter-overrides',
|
|
93
|
+
`ArtifactsBucketName=${bucket}`,
|
|
94
|
+
]
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Deploy the per-region foundation stack (shared artifact bucket) with the caller's creds (or injected `env`).
|
|
98
|
+
function deployFoundationRegion({ accountId, region, env }) {
|
|
99
|
+
const bucket = artifactsBucketName(accountId, region)
|
|
100
|
+
execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket }),
|
|
101
|
+
{ stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
|
|
102
|
+
return bucket
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function awsConnect(flags) {
|
|
106
|
+
const accountId = flags['aws-account']
|
|
107
|
+
const region = flags.region || 'us-east-1'
|
|
108
|
+
const orgId = flags.org || context.get('org')
|
|
109
|
+
if (!accountId) throw new Error('aws connect requires --aws-account <12-digit id>')
|
|
110
|
+
if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
|
|
111
|
+
// D5: bind the account to the active project by default; --org-wide opens it to all org projects.
|
|
112
|
+
const orgWide = flags['org-wide'] === true || flags['org-wide'] === 'true'
|
|
113
|
+
const projectId = orgWide ? undefined : flags.project || context.get('project')
|
|
114
|
+
|
|
115
|
+
const scope = orgWide ? 'all projects in the org' : projectId ? `project ${projectId}` : 'all projects in the org (no active project)'
|
|
116
|
+
console.log(`Connecting AWS account ${accountId} (${region}) to org ${orgId} — deployable by ${scope}…`)
|
|
117
|
+
const conn = await apiCall('POST', '/api/aws/connect', { accountId, region, orgId, projectId, orgWide }, flags)
|
|
118
|
+
console.log(` registered (trust secret minted); deploying the account-global foundation stack into ${accountId} with your AWS creds…`)
|
|
119
|
+
deployFoundation({ controlPlaneAccount: conn.controlPlaneAccountId, externalId: conn.externalId, region, stackNamePrefix: conn.stackNamePrefix, orgId })
|
|
120
|
+
console.log(` global foundation deployed; deploying the per-region foundation (shared artifact bucket) into ${region}…`)
|
|
121
|
+
const bucket = deployFoundationRegion({ accountId, region })
|
|
122
|
+
console.log(` per-region foundation deployed (bucket ${bucket}); verifying cross-account trust…`)
|
|
123
|
+
const v = await apiCall('POST', '/api/aws/connect/verify', { accountId, region }, flags)
|
|
124
|
+
console.log(`✅ AWS account ${accountId} connected to org ${orgId} (${v.bootstrapStatus})`)
|
|
125
|
+
return v
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
module.exports = {
|
|
129
|
+
awsConnect, deployFoundation, foundationDeployArgs, FOUNDATION_TEMPLATE,
|
|
130
|
+
deployFoundationRegion, foundationRegionDeployArgs, foundationRegionStackName, artifactsBucketName,
|
|
131
|
+
FOUNDATION_REGION_TEMPLATE,
|
|
132
|
+
}
|