saaslayer 0.4.0 → 0.4.2

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.
@@ -108,8 +108,9 @@ const ADMIN_COMMANDS = ['create', 'get', 'list', 'update', 'disable', 'enable',
108
108
  const USAGE = `usage: saaslayer users <${['export', 'import', ...ADMIN_COMMANDS].join('|')}> … (see saaslayer --help)`
109
109
 
110
110
  /**
111
- * @typedef {{ stdin?: NodeJS.ReadableStream, log?: (line: string) => void, fetch?: typeof fetch,
111
+ * @typedef {{ stdin?: NodeJS.ReadableStream, log?: (line: string) => void, warn?: (line: string) => void, fetch?: typeof fetch,
112
112
  * exchange?: typeof exchangeIamToken, discover?: typeof discoverDeployment, sleep?: (ms: number) => Promise<void> }} AdminDeps
113
+ * warn = where warnings go (default stderr), apart from the printed JSON
113
114
  * @typedef {ReturnType<typeof usersApi>} UsersApi
114
115
  */
115
116
 
@@ -206,7 +207,8 @@ function updateRequest(attrs) {
206
207
  * Create a user (a durable operation). --password-stdin gives a permanent password (password initialization: never
207
208
  * prod); --delivery invitation mails a temporary one. Re-running the same command replays the same operation (the
208
209
  * default Idempotency-Key is derived from the email). A running operation is waited for; a failed component is an
209
- * error that says to run the same command again, which resumes it.
210
+ * error that says to run the same command again, which resumes it. A warning (e.g. the email's domain signs in through
211
+ * SSO) is printed to stderr and listed in the output; the user is created all the same.
210
212
  * @param {UsersApi} api @param {string[]} args @param {Record<string, any>} flags @param {Required<Pick<AdminDeps, 'stdin'|'log'>> & AdminDeps} deps
211
213
  */
212
214
  async function create(api, args, flags, deps) {
@@ -239,7 +241,9 @@ async function create(api, args, flags, deps) {
239
241
  const op = result.operation
240
242
  throw new Error([`users create: operation ${op.id} is ${op.status}; run the same command again to resume it`, ...ops.formatOperation(op).slice(1)].join('\n'))
241
243
  }
242
- return { result, output: { suid: result.user && result.user.id, ...(result.user ? result.user.attributes : {}), operation: result.operation.id } }
244
+ const warnings = result.warnings || []
245
+ for (const w of warnings) (deps.warn || console.error)(`warning: ${w.detail}`)
246
+ return { result, output: { suid: result.user && result.user.id, ...(result.user ? result.user.attributes : {}), operation: result.operation.id, ...(warnings.length ? { warnings: warnings.map((w) => `${w.code}: ${w.detail}`) } : {}) } }
243
247
  }
244
248
 
245
249
  /**
@@ -0,0 +1,105 @@
1
+ // `saaslayer keys create|list|revoke`: one user-service instance's customer verifier keys, through the control plane's
2
+ // instance proxy (/api/deployments/{id}/services/{ref}/verifier-keys), as the owner's own deployment login of that instance
3
+ // (`saaslayer login --deployment`). A created key is never printed: it goes only to an SSM SecureString in your AWS account
4
+ // (--to-ssm) or a new 0600 file (--to-file), and a key that cannot be stored is revoked.
5
+ 'use strict'
6
+ const { resolveInstanceProxy, instanceCall } = require('../user-service-instance')
7
+ const { openSink, writeSecret, discardSink, scrubbed, sinkName, destinationText } = require('../secret-sink')
8
+
9
+ const USAGE = 'usage: saaslayer keys <create|list|revoke> … (see saaslayer --help)'
10
+ const SCOPES = ['trusted-clients', 'token-status']
11
+
12
+ /**
13
+ * @typedef {{ keyId: string, scope: string, status: string, createdAt: string, createdBy: string, revokedAt: string|null, revokedBy: string|null }} VerifierKeyView
14
+ * @typedef {import('../secret-sink').SinkDeps} Deps
15
+ * @typedef {import('../secret-sink').Destination} Destination
16
+ */
17
+
18
+ /** @param {Record<string, any>} attrs @returns {VerifierKeyView} */
19
+ const viewOf = (attrs) => {
20
+ const { key, ...view } = attrs
21
+ return /** @type {VerifierKeyView} */ (view)
22
+ }
23
+
24
+ /** @param {VerifierKeyView} k */
25
+ function describe(k) {
26
+ const revoked = k.revokedAt ? `, revoked ${k.revokedAt} by ${k.revokedBy}` : ''
27
+ return `${k.keyId} ${k.scope} ${k.status} created ${k.createdAt} by ${k.createdBy}${revoked}`
28
+ }
29
+
30
+ /**
31
+ * `keys create --scope S (--to-ssm NAME | --to-file PATH)`: the key travels from the response straight to its sink.
32
+ * @param {Record<string, any>} flags @param {Deps} deps
33
+ * @returns {Promise<{ verifierKey: VerifierKeyView, destination: Destination }>}
34
+ */
35
+ async function create(flags, deps) {
36
+ if (!SCOPES.includes(flags.scope)) throw new Error(`--scope must be ${SCOPES.join(' or ')}`)
37
+ const sink = openSink(flags, 'a verifier key')
38
+ /** @type {string} */
39
+ let key = ''
40
+ try {
41
+ const scope = await resolveInstanceProxy(flags, 'verifier-keys')
42
+ const doc = await instanceCall('POST', scope.path, { data: { type: 'verifier-keys', attributes: { scope: flags.scope } } }, flags, scope)
43
+ key = String(doc.data.attributes.key || '')
44
+ const verifierKey = viewOf(doc.data.attributes)
45
+ let destination
46
+ try {
47
+ if (!key) throw new Error('the answer held no key')
48
+ destination = await writeSecret(sink, key, { region: scope.deployment.region, description: `SaaSLayer verifier key ${verifierKey.keyId} (${verifierKey.scope}) for ${scope.service} of ${scope.deployment.deploymentId}` }, flags, deps)
49
+ } catch (err) {
50
+ // A key nobody holds must not stay active.
51
+ discardSink(sink)
52
+ const where = sinkName(sink)
53
+ let revoked = 'it was revoked, so nothing holds a lost key'
54
+ try {
55
+ await instanceCall('DELETE', `${scope.path}/${encodeURIComponent(verifierKey.keyId)}`, undefined, flags, scope)
56
+ } catch {
57
+ revoked = `revoking it failed too: run saaslayer keys revoke ${verifierKey.keyId}`
58
+ }
59
+ throw new Error(`could not store verifier key ${verifierKey.keyId} in ${where} (${/** @type {Error} */ (err).message}); ${revoked}`)
60
+ }
61
+ const result = { verifierKey, destination }
62
+ if (flags.json) {
63
+ console.log(JSON.stringify(result, null, 2))
64
+ return result
65
+ }
66
+ console.log(`created verifier key ${verifierKey.keyId} (${verifierKey.scope}) for ${scope.service} of ${scope.deployment.deploymentId}: written to ${destinationText(destination)}; it is never shown`)
67
+ return result
68
+ } catch (err) {
69
+ discardSink(sink)
70
+ throw scrubbed(/** @type {Error} */ (err).message, key)
71
+ }
72
+ }
73
+
74
+ /** `keys list`: ids, scopes and states (a key is never listed). @param {Record<string, any>} flags */
75
+ async function list(flags) {
76
+ const scope = await resolveInstanceProxy(flags, 'verifier-keys')
77
+ const doc = await instanceCall('GET', scope.path, undefined, flags, scope)
78
+ const keys = (doc.data || []).map((/** @type {{ attributes: Record<string, any> }} */ d) => viewOf(d.attributes))
79
+ if (flags.json) console.log(JSON.stringify(keys, null, 2))
80
+ else console.log(keys.length ? keys.map(describe).join('\n') : `no verifier keys on ${scope.service} of ${scope.deployment.deploymentId}`)
81
+ return keys
82
+ }
83
+
84
+ /** `keys revoke <keyId>`: refused from its next request. @param {string|undefined} keyId @param {Record<string, any>} flags */
85
+ async function revoke(keyId, flags) {
86
+ if (!keyId) throw new Error('usage: saaslayer keys revoke <keyId> [--env E] [--service REF]')
87
+ const scope = await resolveInstanceProxy(flags, 'verifier-keys')
88
+ const doc = await instanceCall('DELETE', `${scope.path}/${encodeURIComponent(keyId)}`, undefined, flags, scope)
89
+ const k = viewOf(doc.data.attributes)
90
+ if (flags.json) console.log(JSON.stringify(k, null, 2))
91
+ else console.log(`verifier key ${k.keyId} (${k.scope}) of ${scope.service} on ${scope.deployment.deploymentId} revoked: its next request is refused`)
92
+ return k
93
+ }
94
+
95
+ /**
96
+ * @param {string|undefined} sub @param {string[]} positional @param {Record<string, any>} flags @param {Deps} [deps]
97
+ */
98
+ async function keysCommand(sub, positional, flags, deps = {}) {
99
+ if (sub === 'create') return create(flags, deps)
100
+ if (sub === 'list') return list(flags)
101
+ if (sub === 'revoke') return revoke(positional[0], flags)
102
+ throw new Error(USAGE)
103
+ }
104
+
105
+ module.exports = { keysCommand }
@@ -4,6 +4,9 @@
4
4
  const { apiCall } = require('./api-client')
5
5
  const { resolveScope, printScope, deployedProjectsHint } = require('./scope')
6
6
 
7
+ // Deployment statuses that hold no running stacks a command could act on alongside a live deployment.
8
+ const DEAD_STATUSES = new Set(['CREATE_FAILED', 'DESTROYED', 'PURGE_PENDING', 'PURGE_IN_PROGRESS', 'PURGE_FAILED', 'RETIRED'])
9
+
7
10
  async function resolveDeployment(flags) {
8
11
  const scope = resolveScope(flags, { env: 'prod' })
9
12
  printScope(scope, flags)
@@ -14,11 +17,20 @@ async function resolveDeployment(flags) {
14
17
  const group = (view.environments || []).find((g) => g.environment === env)
15
18
  let instances = group ? group.instances : []
16
19
  if (region) instances = instances.filter((i) => i.region === region)
20
+ const selected = typeof flags.deployment === 'string' && flags.deployment.startsWith('dep_') ? flags.deployment : null
21
+ if (selected) instances = instances.filter((i) => i.deploymentId === selected)
22
+ // A failed or destroyed deployment never shadows a live one in the same env; alone, it still resolves (status, destroy).
23
+ const live = instances.filter((i) => !DEAD_STATUSES.has(i.status))
24
+ if (live.length && live.length < instances.length) instances = live
17
25
  if (instances.length === 0) {
18
26
  const hint = await deployedProjectsHint(scope, flags)
19
27
  throw new Error([`no ${env} deployment${region ? ` in ${region}` : ''} for project ${project} (${scope.project.kind})`, ...hint].join('\n'))
20
28
  }
21
- if (instances.length > 1) throw new Error(`multiple ${env} deployments — pass --region <r>: ${instances.map((i) => i.region).join(', ')}`)
29
+ if (instances.length > 1) {
30
+ const regions = new Set(instances.map((i) => i.region))
31
+ if (regions.size < instances.length) throw new Error(`multiple ${env} deployments in ${[...regions].join(', ')} — pass --deployment <id>: ${instances.map((i) => i.deploymentId).join(', ')}`)
32
+ throw new Error(`multiple ${env} deployments — pass --region <r>: ${instances.map((i) => i.region).join(', ')}`)
33
+ }
22
34
  const inst = instances[0]
23
35
  return { project, env, region: inst.region, deploymentId: inst.deploymentId, status: inst.status, commitSha: inst.commitSha || null, version: inst.version || null }
24
36
  }
@@ -51,7 +51,7 @@ function refusalError(refused, breaks, oldHost) {
51
51
  const lines = [
52
52
  ...breaks.providerRedirects.map(({ provider, redirectUri }) => ` - ${provider} redirect URI ${redirectUri}`),
53
53
  ...breaks.appCallbacks.map((url) => ` - app callback ${url}`),
54
- ...breaks.passkeyRelyingParties.map((rp) => ` - passkeys for relying party ${rp}`),
54
+ ...(breaks.ssoRedirects || []).map(({ protocol, url }) => ` - every SSO connection's ${protocol === 'saml' ? 'SAML ACS URL' : 'OIDC redirect URI'} ${url}`),
55
55
  ` - apps built with SAASLAYER_HOSTED_LOGIN_URL=https://${host} (saaslayer env export) need a rebuild`,
56
56
  ` - hosted-UI sessions on ${host} sign in once more`,
57
57
  ' - the issuer does not change',
@@ -10,6 +10,9 @@ const { SEMVER } = require('./versions')
10
10
  const MANIFEST_SCHEMA_VERSION = 1
11
11
  // The module whose service writes the permission docs direct-mode readers parse, and the setting that picks the format.
12
12
  const PERMISSIONS_WRITER = Object.freeze({ module: 'permissions-service', permissionDocSetting: 'PermissionDocV2' })
13
+ // The setting that turns enterprise SSO on: with permissions-service beside it (combo A), removals commit to user-service's
14
+ // live account status, which direct-mode readers must enforce (compatibility.permissions.sso).
15
+ const SSO_CAPABILITY = Object.freeze({ module: 'user-service', setting: 'EnableSso' })
13
16
 
14
17
  const COMMIT_SHA = /^[0-9a-f]{40}$/
15
18
  const SHA256 = /^[0-9a-f]{64}$/
@@ -27,7 +30,7 @@ function directModeContract() {
27
30
  }
28
31
 
29
32
  /**
30
- * @typedef {{ decisionEngineContract: number, writes: { permissionDoc: number, registrySnapshot: number } }} WriterRelease
33
+ * @typedef {import('../../permissions-engine-core/src/direct-mode-contract.js').WriterRelease} WriterRelease
31
34
  * @typedef {{ settings: string, settingsSha256?: string }} EnvironmentRef
32
35
  * @typedef {{ schemaVersion: 1, name?: string,
33
36
  * bundle: { revision: string, version?: string, modules: Record<string, { settingsContractSha256: string }> },
@@ -104,10 +107,11 @@ function validateManifest(doc) {
104
107
  if (writer !== undefined) {
105
108
  const valid = isObject(writer) && isPositiveInt(writer.decisionEngineContract) && isObject(writer.writes)
106
109
  && isPositiveInt(writer.writes.permissionDoc) && isPositiveInt(writer.writes.registrySnapshot)
107
- if (!valid) problems.push('compatibility.permissions must be { decisionEngineContract, writes: { permissionDoc, registrySnapshot } } (positive integers)')
110
+ if (!valid) problems.push('compatibility.permissions must be { decisionEngineContract, writes: { permissionDoc, registrySnapshot }, sso? } (positive integers)')
108
111
  else {
109
- onlyFields(writer, ['decisionEngineContract', 'writes'], 'compatibility.permissions.', problems)
112
+ onlyFields(writer, ['decisionEngineContract', 'writes', 'sso'], 'compatibility.permissions.', problems)
110
113
  onlyFields(writer.writes, ['permissionDoc', 'registrySnapshot'], 'compatibility.permissions.writes.', problems)
114
+ if (writer.sso !== undefined && !isObject(writer.sso)) problems.push('compatibility.permissions.sso must be an object (checked by the direct-mode preflight)')
111
115
  }
112
116
  }
113
117
  }
@@ -197,14 +201,23 @@ const short = (sha) => (sha ? sha.slice(0, 7) : '—')
197
201
  */
198
202
  const permissionDocFormatFor = (value) => (String(value) === 'true' ? 2 : 1)
199
203
 
204
+ /** Whether an EnableSso value turns SSO on. @param {unknown} value */
205
+ const ssoOn = (value) => String(value) === 'true'
206
+
200
207
  /**
201
- * What a permissions-service deployment at this engine contract writes, given its PermissionDocV2 value.
208
+ * What a permissions-service deployment at this engine contract writes, given its PermissionDocV2 value, and with the
209
+ * deployment's user-service EnableSso on (combo A), the account-status and SSO claim contracts its direct readers must enforce.
202
210
  * @param {unknown} permissionDocV2
211
+ * @param {unknown} [enableSso] user-service EnableSso
203
212
  * @returns {WriterRelease}
204
213
  */
205
- function permissionsWriterRelease(permissionDocV2) {
206
- const { DECISION_ENGINE_CONTRACT, READABLE_FORMATS } = directModeContract()
207
- return { decisionEngineContract: DECISION_ENGINE_CONTRACT, writes: { permissionDoc: permissionDocFormatFor(permissionDocV2), registrySnapshot: Math.max(...READABLE_FORMATS.registrySnapshot) } }
214
+ function permissionsWriterRelease(permissionDocV2, enableSso) {
215
+ const { DECISION_ENGINE_CONTRACT, READABLE_FORMATS, READABLE_CONTRACTS } = directModeContract()
216
+ return {
217
+ decisionEngineContract: DECISION_ENGINE_CONTRACT,
218
+ writes: { permissionDoc: permissionDocFormatFor(permissionDocV2), registrySnapshot: Math.max(...READABLE_FORMATS.registrySnapshot) },
219
+ ...(ssoOn(enableSso) ? { sso: { currentState: 'account-status', accountStatus: Math.max(...READABLE_CONTRACTS.accountStatus), claims: Math.max(...READABLE_CONTRACTS.ssoClaims) } } : {}),
220
+ }
208
221
  }
209
222
 
210
223
  /**
@@ -314,6 +327,15 @@ function preflightManifest({ manifest, env, current, targetSchemas, envPatch, re
314
327
  add('readers', 'writer_format_mismatch', `${env} writes permissionDoc ${writes} (${PERMISSIONS_WRITER.module}.${name}) but the manifest declares permissionDoc ${release.writes.permissionDoc}`, `set ${PERMISSIONS_WRITER.module}.${name} for ${env} to match the tested release, or re-create the manifest`)
315
328
  }
316
329
  }
330
+ // SSO in combo A: removals commit to user-service's live account status, so the release must say so and readers are
331
+ // preflighted against it; an undeclared one would let a cached-doc reader pass as immediate cutoff.
332
+ const sso = deployed.get(SSO_CAPABILITY.module)
333
+ const ssoDeclared = sso && sso.settings.find((s) => s.name === SSO_CAPABILITY.setting)
334
+ const ssoPatch = envPatch && envPatch[SSO_CAPABILITY.module] && SSO_CAPABILITY.setting in envPatch[SSO_CAPABILITY.module] ? envPatch[SSO_CAPABILITY.module][SSO_CAPABILITY.setting] : undefined
335
+ const ssoRequested = ssoPatch !== undefined ? ssoPatch : ssoDeclared ? ssoDeclared.value : undefined
336
+ if (ssoOn(ssoRequested) && !(release.sso && release.sso.currentState === 'account-status')) {
337
+ add('readers', 'sso_undeclared', `${env} runs ${SSO_CAPABILITY.module}.${SSO_CAPABILITY.setting} with ${PERMISSIONS_WRITER.module} but the manifest declares no SSO current state for direct-mode readers`, 're-create the manifest from the SSO-enabled tested deployment (it records compatibility.permissions.sso)')
338
+ }
317
339
  }
318
340
 
319
341
  if (!reason && PROTECTED_ENVS.has(env)) add('reason', 'reason_required', `${env} is a protected environment: pass --reason <text>`)
@@ -329,6 +351,7 @@ function preflightManifest({ manifest, env, current, targetSchemas, envPatch, re
329
351
  module.exports = {
330
352
  MANIFEST_SCHEMA_VERSION,
331
353
  PERMISSIONS_WRITER,
354
+ SSO_CAPABILITY,
332
355
  validateManifest,
333
356
  readManifest,
334
357
  environmentSettings,
@@ -0,0 +1,77 @@
1
+ // Where a secret the CLI is shown once goes (a verifier key, a setup link, a SCIM token): an SSM SecureString in the
2
+ // caller's AWS account (--to-ssm, their credentials) or a new 0600 file (--to-file). Never stdout, stderr or an error message.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const { awsCredentials } = require('./iam-session')
6
+ const { ssmApi } = require('./ssm-api')
7
+
8
+ /**
9
+ * @typedef {{ kind: 'ssm', name: string } | { kind: 'file', path: string, fd: number }} Sink
10
+ * @typedef {{ ssm: { name: string, region: string, version: number } } | { file: { path: string } }} Destination
11
+ * @typedef {{ credentials?: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, fetch?: typeof fetch }} SinkDeps
12
+ */
13
+
14
+ /**
15
+ * An error whose message can never carry the secret, whatever produced it.
16
+ * @param {string} message @param {string} secret
17
+ */
18
+ const scrubbed = (message, secret) => new Error(secret ? message.split(secret).join('[redacted]') : message)
19
+
20
+ /**
21
+ * Where the secret goes, checked before any secret exists: exactly one of --to-ssm and --to-file. A file is created now
22
+ * (exclusively, 0600), so a path that cannot take the secret fails before the secret is made.
23
+ * @param {Record<string, any>} flags @param {string} noun what is stored, e.g. "a verifier key"
24
+ * @returns {Sink}
25
+ */
26
+ function openSink(flags, noun) {
27
+ const ssm = typeof flags['to-ssm'] === 'string' && flags['to-ssm'] ? flags['to-ssm'] : null
28
+ const file = typeof flags['to-file'] === 'string' && flags['to-file'] ? flags['to-file'] : null
29
+ if (!ssm && !file) throw new Error(`${noun} is never printed: pass --to-ssm <parameter> or --to-file <path>`)
30
+ if (ssm && file) throw new Error('pass exactly one of --to-ssm or --to-file')
31
+ if (ssm) return { kind: 'ssm', name: ssm }
32
+ let fd
33
+ try {
34
+ fd = fs.openSync(/** @type {string} */ (file), 'wx', 0o600)
35
+ } catch (err) {
36
+ if (err && /** @type {{ code?: string }} */ (err).code === 'EEXIST') throw new Error(`${file} already exists: choose a new path (a secret file is never overwritten)`)
37
+ throw new Error(`cannot create ${file}: ${/** @type {Error} */ (err).message}`)
38
+ }
39
+ fs.fchmodSync(fd, 0o600)
40
+ return { kind: 'file', path: /** @type {string} */ (file), fd }
41
+ }
42
+
43
+ /**
44
+ * Write the secret to its sink and answer where it went. An SSM parameter is replaced (the rotation use) in --ssm-region,
45
+ * else `region`.
46
+ * @param {Sink} sink @param {string} secret @param {{ description: string, region: string }} where
47
+ * @param {Record<string, any>} flags @param {SinkDeps} deps
48
+ * @returns {Promise<Destination>}
49
+ */
50
+ async function writeSecret(sink, secret, where, flags, deps) {
51
+ if (sink.kind === 'file') {
52
+ fs.writeSync(sink.fd, secret)
53
+ fs.closeSync(sink.fd)
54
+ return { file: { path: sink.path } }
55
+ }
56
+ const region = flags['ssm-region'] || where.region
57
+ const call = ssmApi({ region, credentials: deps.credentials || (() => awsCredentials({ profile: flags.profile })), fetchImpl: deps.fetch || fetch })
58
+ const doc = await call('PutParameter', { Name: sink.name, Value: secret, Type: 'SecureString', Overwrite: true, Description: where.description })
59
+ return { ssm: { name: sink.name, region, version: doc.Version } }
60
+ }
61
+
62
+ /** A sink that will not hold a secret: a created file is removed. @param {Sink} sink */
63
+ function discardSink(sink) {
64
+ if (sink.kind !== 'file') return
65
+ try { fs.closeSync(sink.fd) } catch { /* already closed */ }
66
+ try { fs.unlinkSync(sink.path) } catch { /* nothing to remove */ }
67
+ }
68
+
69
+ /** Where a sink was, for a message. @param {Sink} sink */
70
+ const sinkName = (sink) => (sink.kind === 'ssm' ? `SSM ${sink.name}` : sink.path)
71
+
72
+ /** Where a secret went, for a message. @param {Destination} destination */
73
+ const destinationText = (destination) => ('ssm' in destination
74
+ ? `SSM SecureString ${destination.ssm.name} (version ${destination.ssm.version}) in ${destination.ssm.region}`
75
+ : `${destination.file.path} (0600)`)
76
+
77
+ module.exports = { openSink, writeSecret, discardSink, scrubbed, sinkName, destinationText }
@@ -67,7 +67,7 @@ const FIELDS = [
67
67
  key: 'useCaseDetails', path: 'messagingUseCase.useCaseDetails', title: 'Use Case Details', type: 'TEXT', required: true,
68
68
  derive: (answers) => `${answers.company.name} sends one-time sign-in and account verification codes by SMS to its users who sign in with their phone number. Messages are sent only when the user asks for a code.`,
69
69
  },
70
- { key: 'optIn.category', path: null, title: 'Opt-in category', type: 'SELECT', required: false, select: (answer, options) => matchOption(answer || DEFAULT_OPT_IN_CATEGORY, options) },
70
+ { key: 'optIn.category', path: 'messagingUseCase.optInType', title: 'Opt-in type', type: 'SELECT', required: false, select: (answer, options) => matchOption(answer || DEFAULT_OPT_IN_CATEGORY, options) },
71
71
  { key: 'optIn.description', path: 'messagingUseCase.optInDescription', title: 'Opt-in Workflow Description', type: 'TEXT', required: true },
72
72
  { key: 'optIn.evidence', path: 'messagingUseCase.optInImage', title: 'Opt-in workflow image', type: 'ATTACHMENT', required: true },
73
73
  { key: 'samples.0', path: 'messageSamples.messageSample1', title: 'Message Sample 1', type: 'TEXT', required: true },
@@ -0,0 +1,21 @@
1
+ // The Cognito plan an enterprise SSO deployment runs on: turning user-service EnableSso on moves its pool from Lite to
2
+ // Essentials (managed login), which changes what monthly active users cost; the settings commands say so.
3
+ 'use strict'
4
+
5
+ /** What turning SSO on costs, in the words the settings commands print. */
6
+ const SSO_PLAN_NOTE = 'SSO deployments use the Cognito Essentials plan: native-sign-in monthly active users cost $0.015 instead of $0.0055 (10,000 free); SSO users cost $0.015 on every plan.'
7
+
8
+ /** @param {unknown} value */
9
+ const isOn = (value) => value === true || value === 'true'
10
+
11
+ /**
12
+ * Whether a user-service patch turns EnableSso on where it is off now.
13
+ * @param {Record<string, unknown>|undefined} values the patch's user-service settings
14
+ * @param {Record<string, { value?: unknown }>|undefined} current the deployment's user-service settings by name
15
+ */
16
+ function turnsSsoOn(values, current) {
17
+ if (!values || !isOn(values.EnableSso)) return false
18
+ return !isOn(current && current.EnableSso && current.EnableSso.value)
19
+ }
20
+
21
+ module.exports = { SSO_PLAN_NOTE, turnsSsoOn }
@@ -1,6 +1,9 @@
1
1
  // The user-service instance of a deployment a command acts on: --service names it (user-service or
2
2
  // user-service@<instance>), else the deployment's only one. Several without --service is refused.
3
3
  'use strict'
4
+ const { apiCall, jsonApiCall } = require('./api-client')
5
+ const { deploymentBearer } = require('./deployment-auth')
6
+ const { resolveDeployment } = require('./deployments')
4
7
 
5
8
  const USER_SERVICE = 'user-service'
6
9
 
@@ -24,4 +27,30 @@ function chooseInstance(detail, flags) {
24
27
  return instances[0]
25
28
  }
26
29
 
27
- module.exports = { chooseInstance, refOf }
30
+ /**
31
+ * The deployment (from --env/--region), its chosen user-service instance and the control plane's instance proxy path for
32
+ * one of its resources (/api/deployments/{id}/services/{ref}/{resource}).
33
+ * @param {Record<string, any>} flags @param {string} resource
34
+ * @returns {Promise<{ deployment: Awaited<ReturnType<typeof resolveDeployment>>, service: string, path: string }>}
35
+ */
36
+ async function resolveInstanceProxy(flags, resource) {
37
+ const deployment = await resolveDeployment(flags)
38
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}`, undefined, flags)
39
+ const service = refOf(/** @type {any} */ (chooseInstance({ deploymentId: deployment.deploymentId, ...doc.data.attributes }, flags)))
40
+ const path = `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/services/${encodeURIComponent(service)}/${resource}`
41
+ return { deployment, service, path }
42
+ }
43
+
44
+ /**
45
+ * A call to the instance proxy as the owner's session of that instance: the deployment login of the addressed deployment
46
+ * and user-service instance (`user-service` is the default one), selected by --as when several exist. Never printed.
47
+ * @param {string} method @param {string} path @param {unknown} body @param {Record<string, any>} flags
48
+ * @param {{ service: string, deployment: { deploymentId: string } }} scope
49
+ */
50
+ async function instanceCall(method, path, body, flags, scope) {
51
+ const instance = scope.service.includes('@') ? scope.service.slice(scope.service.indexOf('@') + 1) : 'default'
52
+ const session = await deploymentBearer({ deployment: scope.deployment.deploymentId, as: flags.as, 'user-service-instance': instance })
53
+ return jsonApiCall(method, path, body, flags, { headers: { 'X-SaaSLayer-Deployment-Token': session } })
54
+ }
55
+
56
+ module.exports = { chooseInstance, refOf, resolveInstanceProxy, instanceCall }
package/src/users-api.js CHANGED
@@ -90,12 +90,13 @@ function usersApi(target, { fetch: fetchImpl = fetch } = {}) {
90
90
  * Create a user as a durable operation. 201 created, 200 replayed or already provisioned, 202 unfinished (follow the
91
91
  * operation, or retry with the same key and body). A password needs users:set-password and EnablePasswordInitialization.
92
92
  * @param {CreateAttributes} attributes @param {string} idempotencyKey
93
- * @returns {Promise<{ status: number, user: User|null, operation: Operation }>}
93
+ * warnings = notes on the created user (e.g. EMAIL_DOMAIN_USES_SSO), never a refusal.
94
+ * @returns {Promise<{ status: number, user: User|null, operation: Operation, warnings: Array<{ code: string, detail: string }> }>}
94
95
  */
95
96
  async create(attributes, idempotencyKey) {
96
97
  const attrs = Object.fromEntries(Object.entries(attributes).filter(([, v]) => v !== undefined))
97
98
  const { status, body } = await call('POST', '/api/users', { headers: { 'idempotency-key': idempotencyKey }, body: { data: { attributes: attrs } } })
98
- return { status, user: body.data ? toUser(body.data) : null, operation: body.meta && body.meta.operation }
99
+ return { status, user: body.data ? toUser(body.data) : null, operation: body.meta && body.meta.operation, warnings: (body.meta && body.meta.warnings) || [] }
99
100
  },
100
101
  /**
101
102
  * A create without an Idempotency-Key, to learn whether the caller may create with a supplied suid without writing:
@@ -0,0 +1,148 @@
1
+ {
2
+ "Version": "2012-10-17",
3
+ "Statement": [
4
+ {
5
+ "Sid": "FoundationStacks",
6
+ "Effect": "Allow",
7
+ "Action": [
8
+ "cloudformation:CreateStack",
9
+ "cloudformation:DeleteStack",
10
+ "cloudformation:DescribeStacks",
11
+ "cloudformation:DescribeStackEvents",
12
+ "cloudformation:GetTemplate",
13
+ "cloudformation:CreateChangeSet",
14
+ "cloudformation:DescribeChangeSet",
15
+ "cloudformation:ExecuteChangeSet",
16
+ "cloudformation:DeleteChangeSet",
17
+ "cloudformation:ContinueUpdateRollback"
18
+ ],
19
+ "Resource": [
20
+ "arn:aws:cloudformation:*:*:stack/saaslayer-foundation*/*",
21
+ "arn:aws:cloudformation:*:*:changeSet/saaslayer-*/*"
22
+ ]
23
+ },
24
+ {
25
+ "Sid": "FindStacks",
26
+ "Effect": "Allow",
27
+ "Action": [
28
+ "cloudformation:ListStacks",
29
+ "cloudformation:DescribeStackResources"
30
+ ],
31
+ "Resource": "*"
32
+ },
33
+ {
34
+ "Sid": "FoundationRoles",
35
+ "Effect": "Allow",
36
+ "Action": [
37
+ "iam:CreateRole",
38
+ "iam:DeleteRole",
39
+ "iam:GetRole",
40
+ "iam:UpdateRole",
41
+ "iam:UpdateRoleDescription",
42
+ "iam:UpdateAssumeRolePolicy",
43
+ "iam:PutRolePolicy",
44
+ "iam:GetRolePolicy",
45
+ "iam:DeleteRolePolicy",
46
+ "iam:ListRolePolicies",
47
+ "iam:AttachRolePolicy",
48
+ "iam:DetachRolePolicy",
49
+ "iam:ListAttachedRolePolicies",
50
+ "iam:PutRolePermissionsBoundary",
51
+ "iam:DeleteRolePermissionsBoundary",
52
+ "iam:TagRole",
53
+ "iam:UntagRole",
54
+ "iam:ListRoleTags"
55
+ ],
56
+ "Resource": "arn:aws:iam::*:role/sl-foundation-*"
57
+ },
58
+ {
59
+ "Sid": "FoundationManagedPolicies",
60
+ "Effect": "Allow",
61
+ "Action": [
62
+ "iam:CreatePolicy",
63
+ "iam:DeletePolicy",
64
+ "iam:GetPolicy",
65
+ "iam:GetPolicyVersion",
66
+ "iam:ListPolicyVersions",
67
+ "iam:CreatePolicyVersion",
68
+ "iam:DeletePolicyVersion",
69
+ "iam:ListEntitiesForPolicy"
70
+ ],
71
+ "Resource": "arn:aws:iam::*:policy/sl-foundation-*"
72
+ },
73
+ {
74
+ "Sid": "FoundationParameter",
75
+ "Effect": "Allow",
76
+ "Action": [
77
+ "ssm:GetParameter",
78
+ "ssm:GetParameters",
79
+ "ssm:PutParameter",
80
+ "ssm:DeleteParameter",
81
+ "ssm:AddTagsToResource",
82
+ "ssm:RemoveTagsFromResource",
83
+ "ssm:ListTagsForResource"
84
+ ],
85
+ "Resource": "arn:aws:ssm:*:*:parameter/saaslayer/foundation/*"
86
+ },
87
+ {
88
+ "Sid": "ArtifactBuckets",
89
+ "Effect": "Allow",
90
+ "Action": [
91
+ "s3:CreateBucket",
92
+ "s3:DeleteBucket*",
93
+ "s3:Get*",
94
+ "s3:List*",
95
+ "s3:Put*",
96
+ "s3:TagResource",
97
+ "s3:UntagResource"
98
+ ],
99
+ "Resource": "arn:aws:s3:::sl-artifacts-*"
100
+ },
101
+ {
102
+ "Sid": "ArtifactBucketObjects",
103
+ "Effect": "Allow",
104
+ "Action": [
105
+ "s3:DeleteObject",
106
+ "s3:PutObjectAcl"
107
+ ],
108
+ "Resource": [
109
+ "arn:aws:s3:::sl-artifacts-*",
110
+ "arn:aws:s3:::sl-artifacts-*/*"
111
+ ]
112
+ },
113
+ {
114
+ "Sid": "EmailSenderDomain",
115
+ "Effect": "Allow",
116
+ "Action": [
117
+ "ses:CreateEmailIdentity",
118
+ "ses:DeleteEmailIdentity",
119
+ "ses:GetEmailIdentity",
120
+ "ses:PutEmailIdentityDkimAttributes",
121
+ "ses:PutEmailIdentityDkimSigningAttributes",
122
+ "ses:PutEmailIdentityFeedbackAttributes",
123
+ "ses:PutEmailIdentityMailFromAttributes",
124
+ "ses:TagResource",
125
+ "ses:UntagResource",
126
+ "ses:ListTagsForResource"
127
+ ],
128
+ "Resource": "arn:aws:ses:*:*:identity/*"
129
+ },
130
+ {
131
+ "Sid": "SmsSendingNumber",
132
+ "Effect": "Allow",
133
+ "Action": [
134
+ "sms-voice:RequestPhoneNumber",
135
+ "sms-voice:DescribePhoneNumbers",
136
+ "sms-voice:UpdatePhoneNumber",
137
+ "sms-voice:ReleasePhoneNumber",
138
+ "sms-voice:DescribeKeywords",
139
+ "sms-voice:PutKeyword",
140
+ "sms-voice:DeleteKeyword",
141
+ "sms-voice:TagResource",
142
+ "sms-voice:UntagResource",
143
+ "sms-voice:ListTagsForResource"
144
+ ],
145
+ "Resource": "*"
146
+ }
147
+ ]
148
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "Version": "2012-10-17",
3
+ "Statement": [
4
+ {
5
+ "Sid": "EmailSenderDomain",
6
+ "Effect": "Allow",
7
+ "Action": [
8
+ "ses:CreateEmailIdentity",
9
+ "ses:DeleteEmailIdentity",
10
+ "ses:GetEmailIdentity",
11
+ "ses:PutEmailIdentityDkimAttributes",
12
+ "ses:PutEmailIdentityDkimSigningAttributes",
13
+ "ses:PutEmailIdentityFeedbackAttributes",
14
+ "ses:PutEmailIdentityMailFromAttributes",
15
+ "ses:TagResource",
16
+ "ses:UntagResource",
17
+ "ses:ListTagsForResource"
18
+ ],
19
+ "Resource": "arn:aws:ses:*:*:identity/*"
20
+ }
21
+ ]
22
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "Version": "2012-10-17",
3
+ "Statement": [
4
+ {
5
+ "Sid": "SmsSendingNumber",
6
+ "Effect": "Allow",
7
+ "Action": [
8
+ "sms-voice:RequestPhoneNumber",
9
+ "sms-voice:DescribePhoneNumbers",
10
+ "sms-voice:UpdatePhoneNumber",
11
+ "sms-voice:ReleasePhoneNumber",
12
+ "sms-voice:DescribeKeywords",
13
+ "sms-voice:PutKeyword",
14
+ "sms-voice:DeleteKeyword",
15
+ "sms-voice:TagResource",
16
+ "sms-voice:UntagResource",
17
+ "sms-voice:ListTagsForResource"
18
+ ],
19
+ "Resource": "*"
20
+ }
21
+ ]
22
+ }