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,140 @@
|
|
|
1
|
+
// `saaslayer operations get|watch|cancel <id>` and the --wait every mutating command runs: follow an operation (a deployment
|
|
2
|
+
// run) to its terminal state, print each component's outcome, and fail with the next supported command; cancel an
|
|
3
|
+
// in-flight one (needs saaslayer:deployer:deployment:cancel-run).
|
|
4
|
+
'use strict'
|
|
5
|
+
const crypto = require('crypto')
|
|
6
|
+
const path = require('path')
|
|
7
|
+
const { apiCall } = require('../api-client')
|
|
8
|
+
const { resolveDeployment } = require('../deployments')
|
|
9
|
+
|
|
10
|
+
// The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
|
|
11
|
+
// vendor/operations, synced on prepack).
|
|
12
|
+
const MONOREPO_OPERATIONS = path.join(__dirname, '../../../operations/src')
|
|
13
|
+
|
|
14
|
+
/** A module of the operations package (index by default; activity for the activity feed). @param {string} [file] */
|
|
15
|
+
function loadOperations(file = 'index') {
|
|
16
|
+
try {
|
|
17
|
+
return require(`../../vendor/operations/${file}`)
|
|
18
|
+
} catch (err) {
|
|
19
|
+
if (err && err.code !== 'MODULE_NOT_FOUND') throw err
|
|
20
|
+
return require(path.join(MONOREPO_OPERATIONS, file))
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const USAGE = 'usage: saaslayer operations <get|watch|cancel> <operationId> [--deployment ID | --project P --env E --region R] [--json] [--interval SECONDS] [--reason TEXT]'
|
|
25
|
+
|
|
26
|
+
/** A fresh request key per CLI invocation: a retry of this invocation replays its operation, a new invocation does not. */
|
|
27
|
+
function requestKeyHeaders() {
|
|
28
|
+
return { 'Idempotency-Key': `cli-${crypto.randomUUID()}` }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} operationId
|
|
33
|
+
* @param {string} deploymentId
|
|
34
|
+
*/
|
|
35
|
+
function resumeCommand(operationId, deploymentId) {
|
|
36
|
+
return `saaslayer operations watch ${operationId} --deployment ${deploymentId}`
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Seconds between polls (--interval), default 5. @param {object} flags */
|
|
40
|
+
function intervalMs(flags) {
|
|
41
|
+
const seconds = flags.interval === undefined ? 5 : Number(flags.interval)
|
|
42
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : 5000
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Read an operation. A 4xx other than 408/429 is fatal (no retry); anything else is a transient fault for the watcher.
|
|
47
|
+
* @param {string} deploymentId
|
|
48
|
+
* @param {string} operationId
|
|
49
|
+
* @param {object} flags
|
|
50
|
+
*/
|
|
51
|
+
async function fetchOperation(deploymentId, operationId, flags) {
|
|
52
|
+
try {
|
|
53
|
+
const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}/operations/${encodeURIComponent(operationId)}`, undefined, flags)
|
|
54
|
+
return loadOperations().redact(doc.data.attributes)
|
|
55
|
+
} catch (err) {
|
|
56
|
+
const status = err && err.status
|
|
57
|
+
if (status >= 400 && status < 500 && status !== 408 && status !== 429) err.fatal = true
|
|
58
|
+
throw err
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Wait for an operation to finish. Succeeded: prints its components and returns it. Failed or partial: throws an
|
|
64
|
+
* error whose message lists each component's outcome and the next supported command.
|
|
65
|
+
* @param {{ deploymentId: string, operationId: string, flags: object }} input
|
|
66
|
+
*/
|
|
67
|
+
async function followOperation({ deploymentId, operationId, flags }) {
|
|
68
|
+
const ops = loadOperations()
|
|
69
|
+
const final = await ops.watchOperation({
|
|
70
|
+
id: operationId,
|
|
71
|
+
fetchOperation: () => fetchOperation(deploymentId, operationId, flags),
|
|
72
|
+
intervalMs: intervalMs(flags),
|
|
73
|
+
onUpdate: (op) => { if (!ops.isTerminal(op.status)) console.log(` … operation ${op.id}: ${op.status}`) },
|
|
74
|
+
resumeCommand: resumeCommand(operationId, deploymentId),
|
|
75
|
+
})
|
|
76
|
+
const lines = ops.formatOperation(final)
|
|
77
|
+
if (final.status === 'succeeded') {
|
|
78
|
+
console.log(lines.join('\n'))
|
|
79
|
+
return final
|
|
80
|
+
}
|
|
81
|
+
throw Object.assign(new Error(lines.join('\n')), { operation: final })
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* After a mutating command is accepted: wait for its operation (default) or, with --no-wait, print how to follow it.
|
|
86
|
+
* Attaches the finished operation to the response it returns.
|
|
87
|
+
* @param {{ response: { data?: { attributes?: Record<string, unknown> } } & Record<string, unknown>, deploymentId: string, flags: object }} input
|
|
88
|
+
*/
|
|
89
|
+
async function finishMutation({ response, deploymentId, flags }) {
|
|
90
|
+
const attrs = (response && response.data && response.data.attributes) || {}
|
|
91
|
+
const operationId = typeof attrs.operationId === 'string' ? attrs.operationId : null
|
|
92
|
+
if (!operationId) return response
|
|
93
|
+
if (flags['no-wait'] === true || flags['no-wait'] === 'true') {
|
|
94
|
+
console.log(` follow: ${resumeCommand(operationId, deploymentId)}`)
|
|
95
|
+
return response
|
|
96
|
+
}
|
|
97
|
+
console.log(` waiting for operation ${operationId} (--no-wait to return now; resume with: ${resumeCommand(operationId, deploymentId)})`)
|
|
98
|
+
response.operation = await followOperation({ deploymentId, operationId, flags })
|
|
99
|
+
return response
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Cancel an in-flight operation: the deployer stops its execution and releases the deployment's run lock, and the
|
|
104
|
+
* deployment's activity records the cancel with the caller and --reason.
|
|
105
|
+
* @param {string} deploymentId
|
|
106
|
+
* @param {string} operationId
|
|
107
|
+
* @param {object} flags
|
|
108
|
+
* @returns {Promise<{ deploymentId: string, operationId: string, status: string }>}
|
|
109
|
+
*/
|
|
110
|
+
async function cancelOperation(deploymentId, operationId, flags) {
|
|
111
|
+
const reason = typeof flags.reason === 'string' && flags.reason.trim() ? flags.reason.trim() : null
|
|
112
|
+
const body = reason ? { data: { type: 'operation-cancellations', attributes: { reason } } } : undefined
|
|
113
|
+
const doc = await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/operations/${encodeURIComponent(operationId)}/cancel`, body, flags)
|
|
114
|
+
const result = doc.data.attributes
|
|
115
|
+
if (flags.json) {
|
|
116
|
+
console.log(JSON.stringify(result, null, 2))
|
|
117
|
+
} else {
|
|
118
|
+
console.log(`cancelled operation ${operationId} on deployment ${deploymentId} (${result.status})`)
|
|
119
|
+
console.log(` check: saaslayer operations get ${operationId} --deployment ${deploymentId}`)
|
|
120
|
+
}
|
|
121
|
+
return result
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* `saaslayer operations get|watch|cancel <id>`.
|
|
126
|
+
* @param {string|undefined} sub
|
|
127
|
+
* @param {string|undefined} operationId
|
|
128
|
+
* @param {object} flags
|
|
129
|
+
*/
|
|
130
|
+
async function operationsCommand(sub, operationId, flags) {
|
|
131
|
+
if (!['get', 'watch', 'cancel'].includes(sub) || !operationId) throw new Error(USAGE)
|
|
132
|
+
const deploymentId = flags.deployment || (await resolveDeployment(flags)).deploymentId
|
|
133
|
+
if (sub === 'cancel') return cancelOperation(deploymentId, operationId, flags)
|
|
134
|
+
if (sub === 'watch') return followOperation({ deploymentId, operationId, flags })
|
|
135
|
+
const op = await fetchOperation(deploymentId, operationId, flags)
|
|
136
|
+
console.log(flags.json ? JSON.stringify(op, null, 2) : loadOperations().formatOperation(op).join('\n'))
|
|
137
|
+
return op
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { operationsCommand, finishMutation, followOperation, requestKeyHeaders, resumeCommand, loadOperations, intervalMs }
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// `saaslayer org …` and `saaslayer project …` — create/list orgs and projects, and destroy a project whose deployments
|
|
2
|
+
// are gone, against the SaaSLayer control-plane API, authenticated with the cached Cognito id token (Bearer). The active
|
|
3
|
+
// org is remembered locally so `project create` doesn't need --org each time.
|
|
4
|
+
'use strict'
|
|
5
|
+
const context = require('../context-store')
|
|
6
|
+
const { apiCall } = require('../api-client')
|
|
7
|
+
const prompt = require('../prompt')
|
|
8
|
+
|
|
9
|
+
async function orgCreate(flags, name) {
|
|
10
|
+
if (!name) throw new Error('org create requires a name')
|
|
11
|
+
const org = await apiCall('POST', '/api/orgs', { name }, flags)
|
|
12
|
+
context.set('org', org.id)
|
|
13
|
+
return org
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function orgList(flags) {
|
|
17
|
+
const doc = await apiCall('GET', '/api/orgs', undefined, flags)
|
|
18
|
+
return doc.orgs || []
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function orgUse(_flags, orgId) {
|
|
22
|
+
if (!orgId) throw new Error('org use requires an org id')
|
|
23
|
+
context.set('org', orgId)
|
|
24
|
+
return orgId
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Derive an API-valid deploy slug from a name: letter-first, lowercase alnum + single hyphens, <=15 chars.
|
|
28
|
+
function slugify(name) {
|
|
29
|
+
const s = String(name).toLowerCase()
|
|
30
|
+
.replace(/[^a-z0-9]+/g, '-') // non-alnum -> hyphen
|
|
31
|
+
.replace(/-+/g, '-') // collapse hyphens
|
|
32
|
+
.replace(/^-+|-+$/g, '') // trim hyphens
|
|
33
|
+
.replace(/^[^a-z]+/, '') // enforce letter-first
|
|
34
|
+
.slice(0, 15)
|
|
35
|
+
.replace(/-+$/, '') // no trailing hyphen after truncation
|
|
36
|
+
return s
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function projectCreate(flags, name) {
|
|
40
|
+
if (!name) throw new Error('project create requires a name')
|
|
41
|
+
const orgId = flags.org || context.get('org')
|
|
42
|
+
if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
|
|
43
|
+
const slug = flags.slug || slugify(name)
|
|
44
|
+
if (!slug) throw new Error('project create requires a slug (letter-first, lowercase, <=15 chars) — pass --slug')
|
|
45
|
+
const project = await apiCall('POST', '/api/projects', { name, orgId, slug }, flags)
|
|
46
|
+
context.set('project', project.id)
|
|
47
|
+
return project
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function projectList(flags) {
|
|
51
|
+
const orgId = flags.org || context.get('org')
|
|
52
|
+
if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
|
|
53
|
+
const doc = await apiCall('GET', `/api/projects?orgId=${encodeURIComponent(orgId)}`, undefined, flags)
|
|
54
|
+
return doc.projects || []
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* `saaslayer project destroy [<id>] [--yes]`: delete a project (the active one by default) and release its public name.
|
|
59
|
+
* The control plane refuses while any deployment of it is live; destroy each with `saaslayer destroy` first. Needs
|
|
60
|
+
* saaslayer:deployer:project:delete. Asks for the project id to be typed unless --yes.
|
|
61
|
+
* @param {object} flags
|
|
62
|
+
* @param {string} [projectId]
|
|
63
|
+
* @param {{ ask?: (question: string) => Promise<string> }} [io] the confirmation prompt (tests pass their own)
|
|
64
|
+
* @returns {Promise<{ id: string, destroyed: boolean, releasedSlugs: string[], notOwnedSlugs: string[] } | null>} null when aborted
|
|
65
|
+
*/
|
|
66
|
+
async function projectDestroy(flags, projectId, io = {}) {
|
|
67
|
+
const id = projectId || context.get('project')
|
|
68
|
+
if (!id) throw new Error('project destroy requires a project id (or an active project: `saaslayer project use <id>`)')
|
|
69
|
+
console.log(`⚠ This will DESTROY project ${id} and release its public name. Its deployments must already be destroyed.`)
|
|
70
|
+
const ask = io.ask || prompt.ask
|
|
71
|
+
const typed = flags.yes ? id : await ask(`Type the project id "${id}" to confirm: `)
|
|
72
|
+
if (typed !== id) { console.log('Aborted (id did not match).'); return null }
|
|
73
|
+
const result = await apiCall('DELETE', `/api/projects/${encodeURIComponent(id)}`, undefined, flags)
|
|
74
|
+
const released = (result.releasedSlugs || []).map((s) => `'${s}'`).join(', ')
|
|
75
|
+
console.log(`✅ destroyed project ${id}${released ? `; released ${released}` : ''}`)
|
|
76
|
+
if ((result.notOwnedSlugs || []).length) console.log(` held by another project, left alone: ${result.notOwnedSlugs.join(', ')}`)
|
|
77
|
+
if (context.get('project') === id) context.set('project', null)
|
|
78
|
+
return result
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { orgCreate, orgList, orgUse, projectCreate, projectList, projectDestroy }
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// `saaslayer permissions inspect <type>:<id> | session:<id>`: a principal's permissions from the terminal (expanded view with
|
|
2
|
+
// independent scope/assignment paging, or the stored inspection model) — never parses the compact stored schema.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { exchangeIamToken } = require('../iam-session')
|
|
5
|
+
const { authHeaders } = require('../deployment-api-auth')
|
|
6
|
+
|
|
7
|
+
const USAGE = '<principalType>:<id> or session:<id> (e.g. USER:alice, SERVICE_ACCOUNT:svc-1)'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {{ kind: 'principal', type: string, id: string } | { kind: 'session', id: string }} InspectRef
|
|
11
|
+
* @typedef {{ action: string, resource: string, service?: string, roleId?: string, policyId?: string, when?: object, expiresAt?: string }} Entry
|
|
12
|
+
* @typedef {{ allows: Entry[], denies: Entry[] }} Bucket
|
|
13
|
+
* @typedef {{ roleId: string, scope: string|null, isDirect?: boolean, isDerived?: boolean, inheritedFrom?: string|null, expiresAt?: string }} Assignment
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {string|undefined} raw
|
|
18
|
+
* @returns {InspectRef}
|
|
19
|
+
*/
|
|
20
|
+
function parseRef(raw) {
|
|
21
|
+
const s = typeof raw === 'string' ? raw : ''
|
|
22
|
+
const at = s.indexOf(':')
|
|
23
|
+
const type = at > 0 ? s.slice(0, at) : ''
|
|
24
|
+
const id = at > 0 ? s.slice(at + 1) : ''
|
|
25
|
+
if (!type || !id) throw new Error(`permissions inspect: expected ${USAGE}`)
|
|
26
|
+
if (type.toLowerCase() === 'session') return { kind: 'session', id }
|
|
27
|
+
return { kind: 'principal', type: type.toUpperCase(), id }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @param {number} n */
|
|
31
|
+
const bytes = (n) => `${Number(n || 0).toLocaleString('en-US')} B`
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* One line of size stats from the inspection model.
|
|
35
|
+
* @param {Record<string, any>|null} inspection
|
|
36
|
+
*/
|
|
37
|
+
function formatSize(inspection) {
|
|
38
|
+
if (!inspection) return 'size (no stored doc)'
|
|
39
|
+
const { size, counts } = inspection
|
|
40
|
+
const parts = [
|
|
41
|
+
`main ${bytes(size.itemSizeBytes)} (${size.percentOfGate}% of the ${bytes(size.gateBytes)} gate)`,
|
|
42
|
+
`overflow ${bytes(size.overflowItemSizeBytes)}`,
|
|
43
|
+
]
|
|
44
|
+
if (inspection.defCount !== undefined) parts.push(`defs ${inspection.defCount}`, `ref sets ${inspection.refSetCount || 0}`)
|
|
45
|
+
if (counts) parts.push(`scopes ${counts.scopeCount}`)
|
|
46
|
+
return `size ${parts.join(' ')}`
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @param {Assignment} a */
|
|
50
|
+
function assignmentKind(a) {
|
|
51
|
+
if (a.isDerived) return 'derived'
|
|
52
|
+
if (a.isDirect === false) return a.inheritedFrom ? `inherited from ${a.inheritedFrom}` : 'inherited'
|
|
53
|
+
return 'direct'
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Left-aligned columns.
|
|
58
|
+
* @param {string[][]} rows
|
|
59
|
+
*/
|
|
60
|
+
function table(rows) {
|
|
61
|
+
const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => r[i].length)))
|
|
62
|
+
return rows.map((r) => ` ${r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(widths[i]))).join(' ')}`.trimEnd()).join('\n')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @param {'allow'|'deny'} effect
|
|
67
|
+
* @param {Entry} e
|
|
68
|
+
*/
|
|
69
|
+
function entryLine(effect, e) {
|
|
70
|
+
const parts = [effect === 'allow' ? 'allow' : 'deny ', e.action, e.resource, e.service === undefined ? '(no service)' : e.service]
|
|
71
|
+
if (e.roleId) parts.push(`role ${e.roleId}`)
|
|
72
|
+
if (e.policyId) parts.push(`policy ${e.policyId}`)
|
|
73
|
+
if (e.when) parts.push(`when ${JSON.stringify(e.when)}`)
|
|
74
|
+
if (e.expiresAt) parts.push(`expires ${e.expiresAt}`)
|
|
75
|
+
return ` ${parts.join(' ')}`
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** @param {string} title @param {Bucket} bucket */
|
|
79
|
+
function bucketBlock(title, bucket) {
|
|
80
|
+
const lines = [...(bucket.allows || []).map((e) => entryLine('allow', e)), ...(bucket.denies || []).map((e) => entryLine('deny', e))]
|
|
81
|
+
return [title, ...(lines.length ? lines : [' (empty)'])].join('\n')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The expanded view as text: header + size, assignments page, global, the scope page, next-page commands.
|
|
86
|
+
* @param {Record<string, any>} view GET /principals/:type/:id/permissions attributes
|
|
87
|
+
* @param {{ ref: string, inspection: Record<string, any>|null }} opts
|
|
88
|
+
*/
|
|
89
|
+
function formatExpanded(view, { ref, inspection }) {
|
|
90
|
+
const meta = view.meta || {}
|
|
91
|
+
const label = inspection ? inspection.label : `schemaVersion ${meta.schemaVersion ?? '-'}`
|
|
92
|
+
const out = [
|
|
93
|
+
`${ref} doc v${view.version || 0} ${label}${view.status === 'not_materialized' ? ' (not materialized)' : ''}`,
|
|
94
|
+
formatSize(inspection),
|
|
95
|
+
'',
|
|
96
|
+
`Assignments (${(view.roles || []).length} of ${meta.assignmentCount ?? (view.roles || []).length})`,
|
|
97
|
+
]
|
|
98
|
+
const roles = /** @type {Assignment[]} */ (view.roles || [])
|
|
99
|
+
if (roles.length) out.push(table([['ROLE', 'SCOPE', 'KIND', 'EXPIRES'], ...roles.map((a) => [a.roleId, a.scope || 'global', assignmentKind(a), a.expiresAt || '-'])]))
|
|
100
|
+
else out.push(' (none)')
|
|
101
|
+
out.push('', bucketBlock('Global', view.global || { allows: [], denies: [] }))
|
|
102
|
+
const scopes = Object.keys(view.scoped || {})
|
|
103
|
+
out.push('')
|
|
104
|
+
if (scopes.length) for (const scope of scopes) out.push(bucketBlock(`Scope ${scope}`, view.scoped[scope]))
|
|
105
|
+
else out.push('(no scopes on this page)')
|
|
106
|
+
const hints = []
|
|
107
|
+
if (meta.nextScopeCursor) hints.push(`more scopes: saaslayer permissions inspect ${ref} --scope-page ${meta.nextScopeCursor}`)
|
|
108
|
+
if (meta.nextAssignmentCursor) hints.push(`more assignments: saaslayer permissions inspect ${ref} --assignment-page ${meta.nextAssignmentCursor}`)
|
|
109
|
+
if (hints.length) out.push('', ...hints)
|
|
110
|
+
return out.join('\n')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The stored inspection model as text (principal or session doc).
|
|
115
|
+
* @param {Record<string, any>} inspection
|
|
116
|
+
* @param {{ ref: string, session?: { sessionId: string, sessionKind: string, ceilingMode: string|null, status: string, expiresAt: string } }} opts
|
|
117
|
+
*/
|
|
118
|
+
function formatInspection(inspection, { ref, session }) {
|
|
119
|
+
const out = [`${ref} ${inspection.label} ${inspection.docKind} doc`]
|
|
120
|
+
if (session) out.push(`session ${session.sessionId} ${session.sessionKind} ceiling ${session.ceilingMode || 'none'} ${session.status} expires ${session.expiresAt}`)
|
|
121
|
+
out.push(formatSize(inspection))
|
|
122
|
+
const c = inspection.counts
|
|
123
|
+
if (c) out.push(`counts allows ${c.allowCount} denies ${c.denyCount} scopes ${c.scopeCount} assignments ${c.assignmentCount}`)
|
|
124
|
+
if (inspection.overflow && inspection.overflow.present) out.push(`overflow item ${inspection.overflow.scopeCount} scopes`)
|
|
125
|
+
if (Array.isArray(inspection.defs) && inspection.defs.length) {
|
|
126
|
+
out.push('', table([['DEF', 'SOURCE', 'SERVICE', 'ALLOWS', 'DENIES', 'REFS'], ...inspection.defs.map((/** @type {any} */ d) => [d.id, String(d.src), d.svc || '-', String(d.allowCount), String(d.denyCount), `${d.refCount}${d.unused ? ' (unused)' : ''}`])]))
|
|
127
|
+
}
|
|
128
|
+
if (Array.isArray(inspection.buckets) && inspection.buckets.length) {
|
|
129
|
+
out.push('', table([['SCOPE', 'ALLOWS', 'DENIES'], ...inspection.buckets.map((/** @type {any} */ b) => [b.scope, String(b.allowCount), String(b.denyCount)])]))
|
|
130
|
+
}
|
|
131
|
+
const problems = inspection.problems || []
|
|
132
|
+
if (problems.length) out.push('', `PROBLEMS (${problems.length})`, ...problems.map((/** @type {any} */ p) => ` ${p.reason} at ${p.path}`))
|
|
133
|
+
else out.push('problems none')
|
|
134
|
+
return out.join('\n')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* GET a JSON:API resource; errors carry a clear message per status.
|
|
139
|
+
* @param {string} url @param {Record<string, string>} headers @param {string} ref
|
|
140
|
+
* @returns {Promise<Record<string, any>>} data.attributes
|
|
141
|
+
*/
|
|
142
|
+
async function getAttributes(url, headers, ref) {
|
|
143
|
+
const res = await fetch(url, { method: 'GET', headers })
|
|
144
|
+
const body = /** @type {any} */ (await res.json().catch(() => ({})))
|
|
145
|
+
if (res.ok) return body.data.attributes
|
|
146
|
+
const first = (body.errors && body.errors[0]) || {}
|
|
147
|
+
const detail = first.message || first.detail || res.statusText || ''
|
|
148
|
+
if (res.status === 401) throw Object.assign(new Error(`permissions inspect: not authenticated (401) — check --token / --iam`), { status: 401 })
|
|
149
|
+
if (res.status === 403) throw Object.assign(new Error(`permissions inspect: forbidden (403) — needs saaslayer:identity authority over ${ref}: ${detail}`), { status: 403 })
|
|
150
|
+
if (res.status === 404) throw Object.assign(new Error(`permissions inspect: ${ref} not found (404) — or you have no saaslayer:identity authority where it lives`), { status: 404 })
|
|
151
|
+
if (res.status === 409) throw Object.assign(new Error(`permissions inspect: the doc changed while paging (409 PermissionDocChanged) — restart without a page cursor`), { status: 409 })
|
|
152
|
+
throw Object.assign(new Error(`permissions inspect failed (${res.status}): ${detail}`), { status: res.status })
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* @param {string[]} positional [ref]
|
|
157
|
+
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, scope?: string|string[], 'scope-page'?: string,
|
|
158
|
+
* 'assignment-page'?: string, 'all-scopes'?: boolean, stored?: boolean, json?: boolean }} flags
|
|
159
|
+
* @param {{ exchange?: typeof exchangeIamToken, print?: (s: string) => void }} [deps]
|
|
160
|
+
* @returns {Promise<string>} what was printed
|
|
161
|
+
*/
|
|
162
|
+
async function permissionsInspect(positional, flags, deps = {}) {
|
|
163
|
+
const ref = parseRef(positional[0])
|
|
164
|
+
const refText = ref.kind === 'session' ? `session:${ref.id}` : `${ref.type}:${ref.id}`
|
|
165
|
+
const apiBase = String(flags['api-base'] || process.env.SAASLAYER_API_BASE || '').replace(/\/$/, '')
|
|
166
|
+
if (!apiBase) throw new Error('permissions inspect: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
167
|
+
const headers = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
168
|
+
const print = deps.print || ((/** @type {string} */ s) => console.log(s))
|
|
169
|
+
const emit = (/** @type {string} */ s) => { print(s); return s }
|
|
170
|
+
|
|
171
|
+
if (ref.kind === 'session') {
|
|
172
|
+
const a = await getAttributes(`${apiBase}/sessions/${encodeURIComponent(ref.id)}/permissions?view=stored&format=inspection`, headers, refText)
|
|
173
|
+
if (flags.json) return emit(JSON.stringify(a, null, 2))
|
|
174
|
+
if (!a.inspection) return emit(`${refText} (no stored permission set)`)
|
|
175
|
+
return emit(formatInspection(a.inspection, { ref: refText, session: a.session }))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const base = `${apiBase}/principals/${encodeURIComponent(ref.type)}/${encodeURIComponent(ref.id)}/permissions`
|
|
179
|
+
if (flags.stored) {
|
|
180
|
+
if (flags.json) return emit(JSON.stringify(await getAttributes(`${base}?view=stored`, headers, refText), null, 2))
|
|
181
|
+
const a = await getAttributes(`${base}?view=stored&format=inspection`, headers, refText)
|
|
182
|
+
if (!a.inspection) return emit(`${refText} (no stored doc — not materialized)`)
|
|
183
|
+
return emit(formatInspection(a.inspection, { ref: refText }))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const scopes = flags.scope === undefined ? [] : (Array.isArray(flags.scope) ? flags.scope : [flags.scope])
|
|
187
|
+
/** @param {{ scopeCursor?: string|null }} [page] */
|
|
188
|
+
const query = (page = {}) => {
|
|
189
|
+
const q = new URLSearchParams()
|
|
190
|
+
for (const s of scopes) q.append('scope', String(s))
|
|
191
|
+
const scopeCursor = page.scopeCursor !== undefined ? page.scopeCursor : flags['scope-page']
|
|
192
|
+
if (scopeCursor) q.set('scopeCursor', String(scopeCursor))
|
|
193
|
+
if (flags['assignment-page']) q.set('assignmentCursor', String(flags['assignment-page']))
|
|
194
|
+
const s = q.toString()
|
|
195
|
+
return s ? `${base}?${s}` : base
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (!flags['all-scopes']) {
|
|
199
|
+
const view = await getAttributes(query(), headers, refText)
|
|
200
|
+
if (flags.json) return emit(JSON.stringify(view, null, 2))
|
|
201
|
+
const stored = await getAttributes(`${base}?view=stored&format=inspection`, headers, refText)
|
|
202
|
+
return emit(formatExpanded(view, { ref: refText, inspection: stored.inspection }))
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// --all-scopes: follow the scope cursor to the end; a rebuild mid-way (409) restarts once from the first page
|
|
206
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
207
|
+
try {
|
|
208
|
+
const first = await getAttributes(query({ scopeCursor: null }), headers, refText)
|
|
209
|
+
const scoped = { ...first.scoped }
|
|
210
|
+
let cursor = first.meta && first.meta.nextScopeCursor
|
|
211
|
+
while (cursor) {
|
|
212
|
+
const next = await getAttributes(query({ scopeCursor: cursor }), headers, refText)
|
|
213
|
+
Object.assign(scoped, next.scoped)
|
|
214
|
+
cursor = next.meta && next.meta.nextScopeCursor
|
|
215
|
+
}
|
|
216
|
+
const view = { ...first, scoped, meta: { ...first.meta, nextScopeCursor: null } }
|
|
217
|
+
if (flags.json) return emit(JSON.stringify(view, null, 2))
|
|
218
|
+
const stored = await getAttributes(`${base}?view=stored&format=inspection`, headers, refText)
|
|
219
|
+
return emit(formatExpanded(view, { ref: refText, inspection: stored.inspection }))
|
|
220
|
+
} catch (err) {
|
|
221
|
+
if (/** @type {any} */ (err).status !== 409 || attempt === 1) throw err
|
|
222
|
+
console.error('permissions inspect: the doc was rebuilt while paging (409) — restarting from the first page')
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
throw new Error('permissions inspect: unreachable')
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
module.exports = { permissionsInspect, parseRef, formatExpanded, formatInspection, formatSize }
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// `saaslayer update --manifest FILE` (preflight, then move the release through /update and write the environment's
|
|
2
|
+
// settings through the settings route) and `saaslayer release-manifest create` (record a tested deployment's release).
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const { apiCall } = require('../api-client')
|
|
6
|
+
const { finishMutation, requestKeyHeaders } = require('./operations')
|
|
7
|
+
const { applySettings, fetchSchema, readDeploymentSettings } = require('./settings')
|
|
8
|
+
const { formatChanges } = require('../settings')
|
|
9
|
+
const rm = require('../release-manifest')
|
|
10
|
+
const { version: CLI_VERSION } = require('../../package.json')
|
|
11
|
+
|
|
12
|
+
const USAGE = 'usage: saaslayer release-manifest create --env E [--out FILE] [--name NAME] (see saaslayer --help)'
|
|
13
|
+
|
|
14
|
+
/** @param {object} flags @param {string} name */
|
|
15
|
+
const flagOn = (flags, name) => flags[name] === true || flags[name] === 'true'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Each bundle module's contract at the bundle revision, or the error code that kept it out.
|
|
19
|
+
* @param {rm.ReleaseManifest} manifest @param {object} flags
|
|
20
|
+
* @returns {Promise<Record<string, { schema?: import('../settings').SettingsSchema, error?: string }>>}
|
|
21
|
+
*/
|
|
22
|
+
async function fetchTargetSchemas(manifest, flags) {
|
|
23
|
+
const entries = await Promise.all(Object.keys(manifest.bundle.modules).map(async (module) => {
|
|
24
|
+
try {
|
|
25
|
+
return [module, { schema: await fetchSchema(module, manifest.bundle.revision, flags) }]
|
|
26
|
+
} catch (err) {
|
|
27
|
+
if (!err.status || err.status >= 500) throw err
|
|
28
|
+
const code = err.body && err.body.errors && err.body.errors[0] && err.body.errors[0].code
|
|
29
|
+
return [module, { error: code || `HTTP ${err.status}` }]
|
|
30
|
+
}
|
|
31
|
+
}))
|
|
32
|
+
return Object.fromEntries(entries)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* `update --manifest FILE [--env E] [--settings F] [--reason T] [--force] [--dry-run] [--no-wait]`. Refuses on any
|
|
37
|
+
* preflight problem before anything is sent.
|
|
38
|
+
* @param {object} flags
|
|
39
|
+
*/
|
|
40
|
+
async function updateFromManifest(flags) {
|
|
41
|
+
if (flags['commit-sha'] !== undefined || flags.commitSha !== undefined || flags.param !== undefined) {
|
|
42
|
+
throw new Error('--manifest sets the release and settings: drop --commit-sha and --param')
|
|
43
|
+
}
|
|
44
|
+
const file = flags.manifest
|
|
45
|
+
if (typeof file !== 'string') throw new Error('update --manifest needs a release manifest file')
|
|
46
|
+
const manifest = rm.readManifest(file)
|
|
47
|
+
const { deployment, settings } = await readDeploymentSettings(flags)
|
|
48
|
+
const env = deployment.env
|
|
49
|
+
const envPatch = rm.environmentSettings(manifest, file, env, flags.settings)
|
|
50
|
+
const result = rm.preflightManifest({
|
|
51
|
+
manifest,
|
|
52
|
+
env,
|
|
53
|
+
current: settings,
|
|
54
|
+
targetSchemas: await fetchTargetSchemas(manifest, flags),
|
|
55
|
+
envPatch,
|
|
56
|
+
reason: typeof flags.reason === 'string' ? flags.reason : undefined,
|
|
57
|
+
cliVersion: CLI_VERSION,
|
|
58
|
+
noWait: flagOn(flags, 'no-wait'),
|
|
59
|
+
})
|
|
60
|
+
const target = manifest.bundle.revision
|
|
61
|
+
const where = `${env} (${deployment.deploymentId})`
|
|
62
|
+
if (!result.ok) {
|
|
63
|
+
const lines = result.problems.map((p) => ` - ${p.code}: ${p.message}${p.action ? `\n → ${p.action}` : ''}`)
|
|
64
|
+
throw new Error(`preflight ${where} failed — nothing was changed:\n${lines.join('\n')}`)
|
|
65
|
+
}
|
|
66
|
+
console.log(`preflight ${where}: ok${manifest.name ? ` (${manifest.name})` : ''}`)
|
|
67
|
+
console.log(` release: ${result.fromRevisions.map((r) => r.slice(0, 7)).join(', ')} → ${target.slice(0, 7)}${result.moveRelease ? '' : ' (already deployed)'}`)
|
|
68
|
+
if (result.patch) for (const line of formatChanges(result.patch, settings)) console.log(line)
|
|
69
|
+
else console.log(` settings: ${envPatch ? 'match' : `none named for ${env}`}`)
|
|
70
|
+
if (flagOn(flags, 'dry-run')) {
|
|
71
|
+
console.log('[dry-run] nothing was changed')
|
|
72
|
+
return result
|
|
73
|
+
}
|
|
74
|
+
if (!result.moveRelease && !result.patch) {
|
|
75
|
+
console.log(`${deployment.deploymentId} already runs ${target.slice(0, 7)} and its settings match: nothing to change`)
|
|
76
|
+
return result
|
|
77
|
+
}
|
|
78
|
+
if (result.moveRelease) {
|
|
79
|
+
const attributes = { commitSha: target }
|
|
80
|
+
if (flags.reason) attributes.reason = flags.reason
|
|
81
|
+
if (flagOn(flags, 'force')) attributes.force = true
|
|
82
|
+
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
|
|
83
|
+
console.log(`✅ release move to ${target.slice(0, 7)} started for ${deployment.deploymentId}`)
|
|
84
|
+
await finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
|
|
85
|
+
}
|
|
86
|
+
if (result.patch) await applySettings(result.patch, flags)
|
|
87
|
+
return result
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* `release-manifest create --env E [--out FILE] [--name NAME]`: the revision, settings-contract hashes and permissions writer
|
|
92
|
+
* declaration of a tested deployment, and this CLI's version. Reader declarations and environment settings are left
|
|
93
|
+
* for the author: a missing reader declaration is never inferred.
|
|
94
|
+
* @param {object} flags
|
|
95
|
+
*/
|
|
96
|
+
async function createManifest(flags) {
|
|
97
|
+
const { deployment, settings } = await readDeploymentSettings(flags)
|
|
98
|
+
const revisions = [...new Set(settings.modules.map((m) => m.revision))]
|
|
99
|
+
if (revisions.length !== 1 || !revisions[0]) {
|
|
100
|
+
throw new Error(`${deployment.deploymentId} runs more than one revision (${settings.modules.map((m) => `${m.module}@${(m.revision || '—').slice(0, 7)}`).join(', ')}): update it to one tested release first`)
|
|
101
|
+
}
|
|
102
|
+
const revision = /** @type {string} */ (revisions[0])
|
|
103
|
+
/** @type {Record<string, { settingsContractSha256: string }>} */
|
|
104
|
+
const modules = {}
|
|
105
|
+
for (const m of settings.modules) modules[m.module] = { settingsContractSha256: rm.contractHash(await fetchSchema(m.module, revision, flags)) }
|
|
106
|
+
const writer = settings.modules.find((m) => m.module === rm.PERMISSIONS_WRITER.module)
|
|
107
|
+
const docSetting = writer && writer.settings.find((s) => s.name === rm.PERMISSIONS_WRITER.permissionDocSetting)
|
|
108
|
+
const manifest = {
|
|
109
|
+
schemaVersion: rm.MANIFEST_SCHEMA_VERSION,
|
|
110
|
+
...(typeof flags.name === 'string' ? { name: flags.name } : {}),
|
|
111
|
+
bundle: { revision, modules },
|
|
112
|
+
tooling: { cli: CLI_VERSION },
|
|
113
|
+
...(writer ? { compatibility: { permissions: rm.permissionsWriterRelease(docSetting ? docSetting.value : undefined) } } : {}),
|
|
114
|
+
environments: {},
|
|
115
|
+
}
|
|
116
|
+
const { problems } = rm.validateManifest(manifest)
|
|
117
|
+
if (problems.length) throw new Error(`release manifest for ${deployment.deploymentId} is invalid:\n${problems.map((p) => ` - ${p}`).join('\n')}`)
|
|
118
|
+
const text = `${JSON.stringify(manifest, null, 2)}\n`
|
|
119
|
+
if (typeof flags.out === 'string') {
|
|
120
|
+
fs.writeFileSync(flags.out, text)
|
|
121
|
+
console.log(`release manifest for ${deployment.deploymentId} @ ${revision.slice(0, 7)} written to ${flags.out}`)
|
|
122
|
+
} else {
|
|
123
|
+
console.log(text)
|
|
124
|
+
}
|
|
125
|
+
if (writer) console.log('next: add permissionsDirectMode.readers (an empty list when no app reads the permissions table directly) and environments.<env>.settings')
|
|
126
|
+
return manifest
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @param {string|undefined} sub
|
|
131
|
+
* @param {object} flags
|
|
132
|
+
*/
|
|
133
|
+
async function releaseManifestCommand(sub, flags) {
|
|
134
|
+
if (sub === 'create') return createManifest(flags)
|
|
135
|
+
throw new Error(USAGE)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = { updateFromManifest, releaseManifestCommand }
|