saaslayer 0.4.1 → 0.4.3
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/bin/saaslayer.js +91 -6
- package/package.json +5 -6
- package/src/api-client.js +3 -2
- package/src/commands/foundation.js +5 -3
- package/src/commands/hooks.js +4 -9
- package/src/commands/operations.js +1 -1
- package/src/commands/release-manifest.js +3 -1
- package/src/commands/settings.js +2 -0
- package/src/commands/sms.js +35 -4
- package/src/commands/sso.js +913 -0
- package/src/commands/users-management.js +2 -2
- package/src/commands/users.js +7 -3
- package/src/commands/verifier-keys.js +105 -0
- package/src/login-domain.js +1 -0
- package/src/release-manifest.js +30 -7
- package/src/secret-sink.js +77 -0
- package/src/sms/registration-fields.js +1 -1
- package/src/sso-plan.js +21 -0
- package/src/user-service-instance.js +30 -1
- package/src/users-api.js +3 -2
- package/src/users-import/ids.js +1 -1
- package/templates/saaslayer-foundation-region.yml +10 -2
- package/templates/saaslayer-foundation.yml +33 -5
- package/vendor/config/login-domain.js +213 -0
- package/vendor/discovery/index.d.mts +109 -0
- package/vendor/discovery/index.mjs +409 -0
- package/vendor/ids/index.d.ts +21 -0
- package/vendor/ids/index.js +237 -0
- package/vendor/migrations/backups.js +118 -0
- package/vendor/migrations/child.js +78 -0
- package/vendor/migrations/credentials.js +103 -0
- package/vendor/migrations/errors.js +30 -0
- package/vendor/migrations/exec-child.js +78 -0
- package/vendor/migrations/gate.js +51 -0
- package/vendor/migrations/index.js +30 -0
- package/vendor/migrations/inventory.js +92 -0
- package/vendor/migrations/log.js +14 -0
- package/vendor/migrations/release.js +45 -0
- package/vendor/migrations/report.js +129 -0
- package/vendor/migrations/rules.js +104 -0
- package/vendor/migrations/run.js +311 -0
- package/vendor/migrations/session-policy.js +37 -0
- package/vendor/migrations/step-guard.js +82 -0
- package/vendor/operations/activity.d.ts +21 -0
- package/vendor/operations/activity.js +126 -0
- package/vendor/operations/index.d.ts +60 -0
- package/vendor/operations/index.js +471 -0
- package/vendor/permissions-engine-core/account-status.js +270 -0
- package/vendor/permissions-engine-core/delegation.js +174 -0
- package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
- package/vendor/permissions-engine-core/sso-claims.js +206 -0
- package/vendor/user-management/cognito/emails/token-registry.js +48 -0
- package/vendor/user-management/email/validate.js +207 -0
- package/vendor/user-management/extensibility/hook-contract.js +720 -0
- package/vendor/user-management/extensibility/safe-webhook.js +85 -0
- package/vendor/user-management/identity/admission.js +215 -0
- package/vendor/user-management/identity/attr.js +27 -0
- package/vendor/user-management/identity/attribute-registry.js +115 -0
- package/vendor/user-management/identity/email.js +25 -0
- package/vendor/user-management/identity/ensure-suid.js +74 -0
- package/vendor/user-management/identity/pointers.js +192 -0
- package/vendor/user-management/identity/stitch-provider.js +275 -0
- package/vendor/user-management/management/apply-request.js +227 -0
- package/vendor/user-management/management/core-profile.js +110 -0
- package/vendor/user-management/management/index.js +23 -0
- package/vendor/user-management/management/purposes.js +94 -0
- package/vendor/user-management/management/registry.js +569 -0
- package/vendor/user-management/store/table.js +332 -0
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
// `saaslayer sso …`: one user-service instance's enterprise SSO connections through the control plane's SSO proxy
|
|
2
|
+
// (/api/deployments/{id}/services/{ref}/sso/…) as the owner's own deployment login, plus group mappings on the permissions API.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const { ask: promptAsk } = require('../prompt')
|
|
6
|
+
const { resolveInstanceProxy, instanceCall } = require('../user-service-instance')
|
|
7
|
+
const { openSink, writeSecret, discardSink, scrubbed, sinkName, destinationText } = require('../secret-sink')
|
|
8
|
+
const { permissionsRequest } = require('../permissions-request')
|
|
9
|
+
|
|
10
|
+
const USAGE = 'usage: saaslayer sso <list|status|add|update|activate|disable|rotate|remove|domains|link|scim|reactivate|audit|mappings|enforcement> … (see saaslayer --help)'
|
|
11
|
+
const PROTOCOLS = ['saml', 'oidc']
|
|
12
|
+
const GOOGLE_ISSUER = 'https://accounts.google.com'
|
|
13
|
+
const DNS_RECORD_PREFIX = '_saaslayer-sso.'
|
|
14
|
+
const DNS_VALUE_PREFIX = 'saaslayer-sso-verification='
|
|
15
|
+
// The setup page the instance's emails link to (user-service health-sweep), on the customer's app.
|
|
16
|
+
const SETUP_PAGE = '/sso-setup#setup='
|
|
17
|
+
// An initial SCIM sync of a large directory is written over several calls; this many at most per command.
|
|
18
|
+
const SYNC_CALLS = 50
|
|
19
|
+
// The user doc that explains every sign-in refusal reason (docs/_user-facing/sso-troubleshooting.md).
|
|
20
|
+
const TROUBLESHOOTING = 'sso-troubleshooting'
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {import('../secret-sink').SinkDeps & { stdin?: NodeJS.ReadableStream & { isTTY?: boolean }, interactive?: boolean,
|
|
24
|
+
* ask?: (question: string) => Promise<string> }} Deps
|
|
25
|
+
* @typedef {{ deployment: { deploymentId: string, region: string }, service: string, path: string }} Target
|
|
26
|
+
* @typedef {{ kind: string, text: string }} Note
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
// Settings flags, in the order a patch is built and its changes are listed (connection-policy fields).
|
|
30
|
+
const TEXT_FLAGS = /** @type {Array<[string, string]>} */ ([['provider-tenant', 'providerTenant'], ['subject-source', 'subjectSource'], ['deprovision', 'deprovision'], ['mfa', 'mfa'], ['delegated-tokens', 'delegatedTokens']])
|
|
31
|
+
const SWITCH_FLAGS = /** @type {Array<[string, string]>} */ ([['jit', 'jit'], ['create-personal-org', 'createPersonalOrg']])
|
|
32
|
+
const NUMBER_FLAGS = /** @type {Array<[string, string]>} */ ([['session-cap-hours', 'sessionCapHours'], ['token-ttl-minutes', 'tokenTtlMinutes']])
|
|
33
|
+
|
|
34
|
+
/** What a refusal needs next, by its code. */
|
|
35
|
+
const HINTS = /** @type {Record<string, string>} */ ({
|
|
36
|
+
SSO_CONNECTION_VERSION_CONFLICT: 'the connection changed since it was read: run the command again (it reads the current version first)',
|
|
37
|
+
SSO_CONNECTION_INCOMPLETE: 'the IT admin completes them on the setup page (saaslayer sso link issue), or set them with saaslayer sso update',
|
|
38
|
+
SSO_IDENTITY_NAMESPACE_IMMUTABLE: 'issuer, providerTenant, subjectSource and idp.clientId are fixed once a connection is activated: migrate, or add a replacement connection',
|
|
39
|
+
SSO_MANAGEMENT_FIELD_FORBIDDEN: 'only the deployment owner sets tenant, orgIds, managerGroup and breakGlass',
|
|
40
|
+
SSO_LIFECYCLE_AUTHORITY_REQUIRED: 'deleting a connection or turning its domain enforcement off needs the deployment owner or the tenant\'s org admin',
|
|
41
|
+
SSO_TURN_OFF_PENDING: 'EnableSso is being turned off on this deployment: no connection can be added until that change finishes or is abandoned',
|
|
42
|
+
SSO_CONNECTION_LIMIT_REACHED: 'the instance holds as many connections as its SsoMaxConnections setting allows: remove one, or raise the setting',
|
|
43
|
+
SSO_CONNECTION_HAS_SSO_ONLY_PEOPLE: 'the delete policy is block_while_sso_only: give those people another way in, or change it with saaslayer sso update --delete-policy',
|
|
44
|
+
SSO_CONNECTION_DELETE_INCOMPLETE: 'the delete stopped part way and is kept where it was: run the same saaslayer sso remove again to resume',
|
|
45
|
+
SSO_RUNTIME_UNAVAILABLE: 'Cognito could not apply the connection (or the instance has no callback URLs); the change is saved: run the command again',
|
|
46
|
+
SSO_RUNTIME_BUSY: 'another change to this connection is being applied: run the command again shortly',
|
|
47
|
+
SSO_DOMAIN_CLAIMED: 'another connection on this instance owns the domain',
|
|
48
|
+
SSO_SCIM_SYNC_NOT_PENDING: 'SCIM has written no groups yet (start provisioning in the identity provider first), or it already is the group authority',
|
|
49
|
+
SSO_EMAIL_SENDER_REQUIRED: 'domain enforcement and break-glass email their notices and codes: set a sender first (saaslayer update --param user-service.CognitoEmailFromAddress=<verified SES address>)',
|
|
50
|
+
OWNER_ONLY: 'SSO management needs an owner of the org that owns this deployment',
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
// The flags that set each IdP field a draft may still lack (the instance's missingIdpFields).
|
|
54
|
+
const MISSING_FIELD_FLAGS = /** @type {Record<string, string>} */ ({ issuer: '--issuer', 'idp.metadata': '--metadata-url or --metadata-file', 'idp.clientId': '--client-id', 'idp.clientSecret': '--client-secret-stdin' })
|
|
55
|
+
|
|
56
|
+
/** @param {unknown} v */
|
|
57
|
+
const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
|
|
58
|
+
/** @param {unknown} v @returns {string[]} */
|
|
59
|
+
const listOf = (v) => (v === undefined || v === true ? [] : Array.isArray(v) ? v.map(String) : [String(v)])
|
|
60
|
+
|
|
61
|
+
/** @param {Record<string, any>} flags @param {string} flag */
|
|
62
|
+
function wholeNumber(flags, flag) {
|
|
63
|
+
const v = flags[flag]
|
|
64
|
+
if (v === undefined) return undefined
|
|
65
|
+
const n = Number(v)
|
|
66
|
+
if (v === true || !Number.isInteger(n)) throw new Error(`--${flag} must be a whole number`)
|
|
67
|
+
return n
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @param {Record<string, any>} flags @param {string} flag */
|
|
71
|
+
function onOff(flags, flag) {
|
|
72
|
+
const v = flags[flag]
|
|
73
|
+
if (v === undefined) return undefined
|
|
74
|
+
if (['on', 'true'].includes(String(v))) return true
|
|
75
|
+
if (['off', 'false'].includes(String(v))) return false
|
|
76
|
+
throw new Error(`--${flag} must be on or off`)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** @param {string} label @param {Record<string, any>} flags */
|
|
80
|
+
function requireReason(label, flags) {
|
|
81
|
+
const reason = text(flags.reason)
|
|
82
|
+
if (!reason) throw new Error(`${label}: --reason <text> is required`)
|
|
83
|
+
return reason
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The client secret piped on stdin (one trailing newline dropped). A terminal stdin is refused: the secret is never
|
|
88
|
+
* typed where it could echo, and never taken from a flag, a settings file or the environment.
|
|
89
|
+
* @param {Deps} deps
|
|
90
|
+
*/
|
|
91
|
+
async function readSecret(deps) {
|
|
92
|
+
const stdin = deps.stdin || process.stdin
|
|
93
|
+
if (stdin.isTTY) throw new Error('--client-secret-stdin reads the secret from a pipe or file, e.g. saaslayer sso rotate <connectionId> --client-secret-stdin < secret.txt')
|
|
94
|
+
let data = ''
|
|
95
|
+
for await (const chunk of stdin) data += chunk
|
|
96
|
+
const secret = data.replace(/\r?\n$/, '')
|
|
97
|
+
if (!secret) throw new Error('the client secret on stdin is empty')
|
|
98
|
+
return secret
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A JSON settings file (the API's connection attributes), never holding the client secret. @param {string} file */
|
|
102
|
+
function settingsFile(file) {
|
|
103
|
+
let parsed
|
|
104
|
+
try {
|
|
105
|
+
parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
106
|
+
} catch (err) {
|
|
107
|
+
throw new Error(`--settings-file ${file}: ${/** @type {Error} */ (err).message}`)
|
|
108
|
+
}
|
|
109
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`--settings-file ${file} must hold one JSON object of connection settings`)
|
|
110
|
+
if (parsed.idp && typeof parsed.idp === 'object' && 'clientSecret' in parsed.idp) throw new Error('a settings file never holds the client secret: pass it on stdin with --client-secret-stdin')
|
|
111
|
+
return /** @type {Record<string, any>} */ (parsed)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The provider registration a command carries: SAML metadata (URL or file) or the OIDC client (id, scopes, the secret from
|
|
116
|
+
* stdin). Undefined when none is given.
|
|
117
|
+
* @param {Record<string, any>} flags @param {Deps} deps
|
|
118
|
+
*/
|
|
119
|
+
async function idpOf(flags, deps) {
|
|
120
|
+
if (flags['client-secret'] !== undefined) throw new Error('the client secret is never taken as a flag: pass it on stdin with --client-secret-stdin')
|
|
121
|
+
/** @type {Record<string, any>} */
|
|
122
|
+
const idp = {}
|
|
123
|
+
if (text(flags['metadata-url'])) idp.metadataUrl = text(flags['metadata-url'])
|
|
124
|
+
if (text(flags['metadata-file'])) idp.metadataXml = fs.readFileSync(/** @type {string} */ (text(flags['metadata-file'])), 'utf8')
|
|
125
|
+
if (text(flags['client-id'])) idp.clientId = text(flags['client-id'])
|
|
126
|
+
if (flags['oidc-scope'] !== undefined) idp.scopes = listOf(flags['oidc-scope'])
|
|
127
|
+
if (flags['client-secret-stdin']) idp.clientSecret = await readSecret(deps)
|
|
128
|
+
return Object.keys(idp).length ? idp : undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The settings a command sets, from its flags over an optional --settings-file, in the connection's field order. An update
|
|
133
|
+
* then takes the parts the flags leave out from the stored connection (keptFromCurrent).
|
|
134
|
+
* @param {Record<string, any>} flags @param {Deps} deps @param {string} [connectionId] the connection an update edits
|
|
135
|
+
* @returns {Promise<Record<string, any>>}
|
|
136
|
+
*/
|
|
137
|
+
async function settingsOf(flags, deps, connectionId) {
|
|
138
|
+
/** @type {Record<string, any>} */
|
|
139
|
+
const set = text(flags['settings-file']) ? settingsFile(/** @type {string} */ (text(flags['settings-file']))) : {}
|
|
140
|
+
const idp = await idpOf(flags, deps)
|
|
141
|
+
if (idp) set.idp = { ...(set.idp || {}), ...idp }
|
|
142
|
+
for (const [flag, field] of TEXT_FLAGS) if (text(flags[flag])) set[field] = text(flags[flag])
|
|
143
|
+
if (flags.org !== undefined) set.orgIds = listOf(flags.org)
|
|
144
|
+
for (const [flag, field] of SWITCH_FLAGS) { const v = onOff(flags, flag); if (v !== undefined) set[field] = v }
|
|
145
|
+
const scim = onOff(flags, 'scim')
|
|
146
|
+
if (scim !== undefined) set.scim = { enabled: scim }
|
|
147
|
+
for (const [flag, field] of NUMBER_FLAGS) { const v = wholeNumber(flags, flag); if (v !== undefined) set[field] = v }
|
|
148
|
+
const tiles = onOff(flags, 'idp-initiated')
|
|
149
|
+
if (tiles !== undefined) set.idpInitiated = tiles
|
|
150
|
+
const enforce = onOff(flags, 'enforce')
|
|
151
|
+
const noticeDays = wholeNumber(flags, 'notice-days')
|
|
152
|
+
if (enforce === false) throw new Error(`turning enforcement off is its own audited action: saaslayer sso enforcement disable ${connectionId || '<connectionId>'} --reason <text>`)
|
|
153
|
+
if (enforce || noticeDays !== undefined) set.enforcement = { enabled: enforce === true, ...(noticeDays !== undefined ? { noticeDays } : {}) }
|
|
154
|
+
if (flags['manager-group'] !== undefined) set.managerGroup = String(flags['manager-group']) === 'none' ? null : String(flags['manager-group'])
|
|
155
|
+
const grantMinutes = wholeNumber(flags, 'break-glass-minutes')
|
|
156
|
+
if (flags['break-glass'] !== undefined || grantMinutes !== undefined) {
|
|
157
|
+
set.breakGlass = { suids: listOf(flags['break-glass']).filter((s) => s !== 'none'), ...(grantMinutes !== undefined ? { grantMinutes } : {}) }
|
|
158
|
+
}
|
|
159
|
+
if (text(flags['delete-policy'])) set.deletePolicy = text(flags['delete-policy'])
|
|
160
|
+
return set
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* An update's settings with what its flags leave out kept as stored: --notice-days alone keeps enforcement on or off, and
|
|
165
|
+
* --break-glass-minutes alone keeps the allowlist.
|
|
166
|
+
* @param {Record<string, any>} set @param {Record<string, any>} flags @param {Record<string, any>} current
|
|
167
|
+
*/
|
|
168
|
+
function keptFromCurrent(set, flags, current) {
|
|
169
|
+
if (set.enforcement && flags.enforce === undefined) set.enforcement.enabled = !!(current.enforcement && current.enforcement.enabled)
|
|
170
|
+
if (set.breakGlass && flags['break-glass'] === undefined) set.breakGlass.suids = (current.breakGlass && current.breakGlass.suids) || []
|
|
171
|
+
return set
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The DNS proof each unverified domain needs. @param {Record<string, any>} connection */
|
|
175
|
+
const dnsOf = (connection) => (connection.domains || [])
|
|
176
|
+
.filter((/** @type {Record<string, any>} */ d) => d.status !== 'verified' && d.token)
|
|
177
|
+
.map((/** @type {Record<string, any>} */ d) => ({ domain: d.domain, type: 'TXT', name: `${DNS_RECORD_PREFIX}${d.domain}`, value: `${DNS_VALUE_PREFIX}${d.token}` }))
|
|
178
|
+
|
|
179
|
+
/** A DNS record as a listing row. @param {{ name: string, value: string }} r */
|
|
180
|
+
const recordText = (r) => `TXT ${r.name} "${r.value}"`
|
|
181
|
+
/** A DNS record inside a sentence. @param {{ name: string, value: string }} r */
|
|
182
|
+
const proofText = (r) => `TXT ${r.name} "${r.value}"`
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* What the owner should know about a connection: what locks at activation, where its groups come from, the Cognito tier
|
|
186
|
+
* and anything left pending.
|
|
187
|
+
* @param {Record<string, any>} c
|
|
188
|
+
* @returns {Note[]}
|
|
189
|
+
*/
|
|
190
|
+
function notesOf(c) {
|
|
191
|
+
/** @type {Note[]} */
|
|
192
|
+
const notes = []
|
|
193
|
+
if (c.missingIdpFields && c.missingIdpFields.length) notes.push({ kind: 'setup', text: `missing before activation: ${missingText(c)}` })
|
|
194
|
+
if (!c.activatedAt && c.status !== 'deleted') notes.push({ kind: 'namespace', text: 'issuer, providerTenant, subjectSource and idp.clientId lock at the first activation: changing them later needs a migration or a replacement connection' })
|
|
195
|
+
if (c.issuer === GOOGLE_ISSUER) notes.push({ kind: 'google', text: 'Google sign-in carries no groups and Google directory sync is not supported yet: group mappings, managerGroup and SCIM-based removal do not apply to this connection' })
|
|
196
|
+
else if (c.protocol === 'saml' && !(c.scim && c.scim.enabled)) notes.push({ kind: 'groups', text: 'SAML sign-ins carry no group authority: turn SCIM on (--scim on) for group-based access and directory-driven removal' })
|
|
197
|
+
notes.push({ kind: 'tier', text: 'SSO runs the pool on Cognito Essentials with V1 claims: the sso_* claims are flat strings in ID tokens only. Claims in access tokens need UserPoolTier ESSENTIALS or PLUS set explicitly and PreTokenClaimsVersion V2_0' })
|
|
198
|
+
if (c.status === 'deleting') notes.push({ kind: 'pending', text: `a delete is in progress: run saaslayer sso remove ${c.connectionId} --reason <text> again to finish it` })
|
|
199
|
+
if (c.enforcement && c.enforcement.enabled && c.enforcement.cutoverAt && Date.parse(c.enforcement.cutoverAt) > Date.now()) notes.push({ kind: 'pending', text: `domain enforcement ends native sign-in for its verified domains at ${c.enforcement.cutoverAt}` })
|
|
200
|
+
return notes
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** A connection's missing IdP fields with the flags that set them, or '' when it is complete. @param {Record<string, any>} c */
|
|
204
|
+
const missingText = (c) => (c.missingIdpFields || []).map((/** @type {string} */ f) => `${f} (${MISSING_FIELD_FLAGS[f] || f})`).join(', ')
|
|
205
|
+
|
|
206
|
+
/** What the identity provider registers, as one line. @param {Record<string, any>} sp */
|
|
207
|
+
const registrationText = (sp) => (sp.acsUrl
|
|
208
|
+
? `register in the identity provider: entity id ${sp.entityId}, ACS URL ${sp.acsUrl}`
|
|
209
|
+
: `register in the identity provider: redirect URI ${sp.redirectUri}`)
|
|
210
|
+
|
|
211
|
+
/** @param {unknown} v */
|
|
212
|
+
const shown = (v) => {
|
|
213
|
+
const s = JSON.stringify(v === undefined ? null : v)
|
|
214
|
+
return s.length > 60 ? `${s.slice(0, 57)}...` : s.replace(/^"(.*)"$/, '$1')
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** @param {Array<{ field: string, before?: unknown, after?: unknown }>} changes */
|
|
218
|
+
const changesText = (changes) => changes.map((ch) => `${ch.field} ${shown(ch.before)} → ${shown(ch.after)}`).join('; ')
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* A refusal as `<code>: <title>`, the fields at fault and the next step; with --json the refusal document is printed as is.
|
|
222
|
+
* @param {any} err @param {Record<string, any>} flags @param {Target|null} target
|
|
223
|
+
*/
|
|
224
|
+
function refusalOf(err, flags, target) {
|
|
225
|
+
const first = err && err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
|
|
226
|
+
if (!first) return err
|
|
227
|
+
if (flags.json) console.log(JSON.stringify({ errors: err.body.errors }, null, 2))
|
|
228
|
+
const lines = [`${first.code || err.status}: ${first.title || first.detail || 'request refused'}`]
|
|
229
|
+
const fields = first.meta && Array.isArray(first.meta.fields) ? first.meta.fields : []
|
|
230
|
+
for (const f of fields) lines.push(` ${f.field}: ${f.reason}`)
|
|
231
|
+
const where = target ? `${target.service} of ${target.deployment.deploymentId}` : 'this instance'
|
|
232
|
+
const hint = first.code === 'DEPLOYMENT_LOGIN_REQUIRED'
|
|
233
|
+
? `run saaslayer login --deployment ${target ? target.deployment.deploymentId : '<deploymentId>'} as an owner of the deployment's org`
|
|
234
|
+
: first.code === 'NOT_FOUND' && err.status === 404 ? `no such connection within reach, or SSO is not enabled on ${where} (EnableSso)` : HINTS[first.code]
|
|
235
|
+
if (hint) lines.push(hint)
|
|
236
|
+
return Object.assign(new Error(lines.join('\n')), { status: err.status, body: err.body, code: first.code })
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Confirm a destructive step: --yes, else the typed connection id at an interactive prompt.
|
|
241
|
+
* @param {string} warning @param {string} connectionId @param {Record<string, any>} flags @param {Deps} deps
|
|
242
|
+
*/
|
|
243
|
+
async function confirmed(warning, connectionId, flags, deps) {
|
|
244
|
+
if (flags.yes) return
|
|
245
|
+
const interactive = deps.interactive !== undefined ? deps.interactive : !!process.stdin.isTTY
|
|
246
|
+
if (!interactive) throw new Error(`${warning}: pass --yes to confirm`)
|
|
247
|
+
console.log(warning)
|
|
248
|
+
const typed = await (deps.ask || promptAsk)(`Type the connection id "${connectionId}" to confirm: `)
|
|
249
|
+
if (typed !== connectionId) throw new Error('aborted: the connection id did not match')
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* The instance's SSO API through the proxy, as the owner's session.
|
|
254
|
+
* @param {Record<string, any>} flags
|
|
255
|
+
*/
|
|
256
|
+
async function instanceOf(flags) {
|
|
257
|
+
const target = /** @type {Target} */ (await resolveInstanceProxy(flags, 'sso'))
|
|
258
|
+
/** @param {string} method @param {string} sub @param {unknown} [body] */
|
|
259
|
+
const call = async (method, sub, body) => {
|
|
260
|
+
try {
|
|
261
|
+
return await instanceCall(method, `${target.path}${sub}`, body, flags, target)
|
|
262
|
+
} catch (err) {
|
|
263
|
+
// The refusal's hint names the deployment and instance it came from.
|
|
264
|
+
throw Object.assign(/** @type {Error} */ (err), { target })
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const where = `${target.service} of ${target.deployment.deploymentId}`
|
|
268
|
+
return { target, call, where }
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** @param {string|undefined} id @param {string} usage */
|
|
272
|
+
function connectionIdOf(id, usage) {
|
|
273
|
+
if (!id) throw new Error(`usage: ${usage}`)
|
|
274
|
+
return encodeURIComponent(id)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** @param {Awaited<ReturnType<typeof instanceOf>>} api @param {string} id */
|
|
278
|
+
async function readConnection(api, id) {
|
|
279
|
+
return /** @type {Record<string, any>} */ ((await api.call('GET', `/connections/${id}`)).data.attributes)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Print a connection edit (create, update, domains): what changed, what the IdP registers (create), the DNS proofs and notes.
|
|
284
|
+
* @param {string} headline @param {Record<string, any>} c @param {Record<string, any>} meta @param {Record<string, any>} flags
|
|
285
|
+
* @param {Note[]} notes @param {{ serviceProvider?: Record<string, any> }} [extra]
|
|
286
|
+
*/
|
|
287
|
+
function printEdit(headline, c, meta, flags, notes, extra = {}) {
|
|
288
|
+
const dns = dnsOf(c)
|
|
289
|
+
const result = { connection: c, changes: meta.changes || [], ...(meta.runtime ? { runtime: meta.runtime } : {}), ...(extra.serviceProvider ? { serviceProvider: extra.serviceProvider } : {}), dns, notes }
|
|
290
|
+
if (flags.json) {
|
|
291
|
+
console.log(JSON.stringify(result, null, 2))
|
|
292
|
+
return result
|
|
293
|
+
}
|
|
294
|
+
console.log(headline)
|
|
295
|
+
if (extra.serviceProvider && !extra.serviceProvider.unavailable) console.log(registrationText(extra.serviceProvider))
|
|
296
|
+
if (dns.length) {
|
|
297
|
+
console.log('publish these DNS records, then check them with saaslayer sso domains verify:')
|
|
298
|
+
for (const r of dns) console.log(` ${recordText(r)}`)
|
|
299
|
+
}
|
|
300
|
+
if (meta.runtime && meta.runtime.outcome === 'failed') console.log(`pending: the edit is saved but Cognito was not updated (${meta.runtime.error}): run saaslayer sso activate ${c.connectionId} to apply it`)
|
|
301
|
+
for (const n of notes) console.log(`note (${n.kind}): ${n.text}`)
|
|
302
|
+
return result
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** `sso list [--tenant T]`. @param {Record<string, any>} flags */
|
|
306
|
+
async function list(flags) {
|
|
307
|
+
const api = await instanceOf(flags)
|
|
308
|
+
const tenant = text(flags.tenant)
|
|
309
|
+
const doc = await api.call('GET', `/connections${tenant ? `?tenant=${encodeURIComponent(tenant)}` : ''}`)
|
|
310
|
+
const connections = (doc.data || []).map((/** @type {{ attributes: Record<string, any> }} */ d) => d.attributes)
|
|
311
|
+
if (flags.json) {
|
|
312
|
+
console.log(JSON.stringify(connections, null, 2))
|
|
313
|
+
return connections
|
|
314
|
+
}
|
|
315
|
+
if (!connections.length) console.log(`no SSO connections${tenant ? ` for tenant ${tenant}` : ''} on ${api.where}`)
|
|
316
|
+
for (const c of connections) {
|
|
317
|
+
const domains = (c.domains || []).map((/** @type {Record<string, any>} */ d) => `${d.domain} (${d.status})`).join(', ')
|
|
318
|
+
console.log(`${c.connectionId} ${c.tenant} ${c.protocol} ${c.status} ${c.issuer || '(no issuer yet)'}${domains ? ` domains: ${domains}` : ''}`)
|
|
319
|
+
}
|
|
320
|
+
return connections
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* `sso add --tenant T --protocol P [--issuer I …]`: a draft; refused when the tenant already has one for that issuer, or
|
|
325
|
+
* (without --issuer) an issuer-less draft of that protocol. Without IdP flags it starts from scratch: it prints what the
|
|
326
|
+
* IdP registers and what is missing, for a setup link's IT admin to complete.
|
|
327
|
+
*/
|
|
328
|
+
async function add(/** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
329
|
+
const tenant = text(flags.tenant)
|
|
330
|
+
if (!tenant) throw new Error('sso add: --tenant <org id> is required')
|
|
331
|
+
const protocol = text(flags.protocol)
|
|
332
|
+
if (!protocol || !PROTOCOLS.includes(protocol)) throw new Error('sso add: --protocol must be saml or oidc')
|
|
333
|
+
const settings = await settingsOf(flags, deps)
|
|
334
|
+
/** @type {Record<string, any>} */
|
|
335
|
+
const attributes = { tenant, protocol, ...(text(flags.issuer) ? { issuer: text(flags.issuer) } : {}), ...settings }
|
|
336
|
+
if (flags.domain !== undefined) attributes.domains = listOf(flags.domain).map((d) => d.trim().toLowerCase())
|
|
337
|
+
const api = await instanceOf(flags)
|
|
338
|
+
const existing = (await api.call('GET', `/connections?tenant=${encodeURIComponent(tenant)}`)).data || []
|
|
339
|
+
const live = existing.map((/** @type {{ attributes: Record<string, any> }} */ d) => d.attributes).filter((/** @type {Record<string, any>} */ c) => c.status !== 'deleted')
|
|
340
|
+
if (attributes.issuer) {
|
|
341
|
+
const same = live.find((/** @type {Record<string, any>} */ c) => c.issuer === attributes.issuer)
|
|
342
|
+
if (same) throw new Error(`tenant ${tenant} already has SSO connection ${same.connectionId} for issuer ${same.issuer} (${same.status}): change it with saaslayer sso update ${same.connectionId}`)
|
|
343
|
+
} else {
|
|
344
|
+
const draft = live.find((/** @type {Record<string, any>} */ c) => !c.issuer && c.protocol === protocol && c.status === 'draft')
|
|
345
|
+
if (draft) throw new Error(`tenant ${tenant} already has draft SSO connection ${draft.connectionId} (${protocol}) with no issuer yet: complete it with saaslayer sso update ${draft.connectionId}, or hand it over with saaslayer sso link issue ${draft.connectionId}`)
|
|
346
|
+
}
|
|
347
|
+
const doc = await api.call('POST', '/connections', { data: { type: 'sso-connections', attributes } })
|
|
348
|
+
const c = doc.data.attributes
|
|
349
|
+
let serviceProvider
|
|
350
|
+
try {
|
|
351
|
+
serviceProvider = (await api.call('GET', `/connections/${encodeURIComponent(c.connectionId)}/service-provider`)).data.attributes
|
|
352
|
+
} catch (err) {
|
|
353
|
+
serviceProvider = { unavailable: /** @type {Error} */ (err).message.split('\n')[0] }
|
|
354
|
+
}
|
|
355
|
+
const result = printEdit(`created SSO connection ${c.connectionId} (${c.protocol}, ${c.status}) for tenant ${c.tenant} on ${api.where}`, c, doc.meta || {}, flags, notesOf(c), { serviceProvider })
|
|
356
|
+
if (!flags.json) {
|
|
357
|
+
console.log(c.missingIdpFields && c.missingIdpFields.length
|
|
358
|
+
? `next: saaslayer sso link issue ${c.connectionId} hands the rest to the customer's IT admin (or set them with saaslayer sso update ${c.connectionId}), then saaslayer sso activate ${c.connectionId}`
|
|
359
|
+
: `next: saaslayer sso domains verify ${c.connectionId} <domain>, then saaslayer sso activate ${c.connectionId} (saaslayer sso link issue hands the setup to the customer's IT admin)`)
|
|
360
|
+
}
|
|
361
|
+
return result
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* PATCH settings at the version read; a re-run with the same values changes nothing.
|
|
366
|
+
* @param {Awaited<ReturnType<typeof instanceOf>>} api @param {Record<string, any>} current @param {Record<string, any>} attributes
|
|
367
|
+
* @param {Record<string, any>} flags @param {Note[]} [extraNotes]
|
|
368
|
+
*/
|
|
369
|
+
async function patch(api, current, attributes, flags, extraNotes = []) {
|
|
370
|
+
const doc = await api.call('PATCH', `/connections/${encodeURIComponent(current.connectionId)}`, { data: { type: 'sso-connections', id: current.connectionId, attributes }, meta: { expectedVersion: current.version } })
|
|
371
|
+
const c = doc.data.attributes
|
|
372
|
+
const meta = doc.meta || {}
|
|
373
|
+
const changes = meta.changes || []
|
|
374
|
+
const headline = changes.length
|
|
375
|
+
? `updated SSO connection ${c.connectionId} (version ${c.version}): ${changesText(changes)}`
|
|
376
|
+
: `nothing changed on SSO connection ${c.connectionId} (version ${c.version})`
|
|
377
|
+
return printEdit(headline, c, meta, flags, [...extraNotes, ...notesOf(c).filter((n) => n.kind !== 'tier')])
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** `sso update <id> …settings`. @param {string|undefined} id @param {Record<string, any>} flags @param {Deps} deps */
|
|
381
|
+
async function update(id, flags, deps) {
|
|
382
|
+
const conn = connectionIdOf(id, 'saaslayer sso update <connectionId> [settings flags | --settings-file FILE]')
|
|
383
|
+
if (flags.domain !== undefined) throw new Error('domains change with saaslayer sso domains add|remove <connectionId> <domain> (each keeps its DNS proof)')
|
|
384
|
+
if (flags.tenant !== undefined || flags.protocol !== undefined) throw new Error('a connection never moves to another tenant or protocol: add a replacement connection')
|
|
385
|
+
const settings = await settingsOf(flags, deps, id)
|
|
386
|
+
if (text(flags.issuer)) settings.issuer = text(flags.issuer)
|
|
387
|
+
if (!Object.keys(settings).length) throw new Error('sso update: nothing to change: pass a setting flag or --settings-file')
|
|
388
|
+
const api = await instanceOf(flags)
|
|
389
|
+
const current = await readConnection(api, conn)
|
|
390
|
+
const attributes = keptFromCurrent(settings, flags, current)
|
|
391
|
+
if (attributes.enforcement && attributes.enforcement.enabled && !(current.enforcement && current.enforcement.enabled)) {
|
|
392
|
+
const days = attributes.enforcement.noticeDays !== undefined ? attributes.enforcement.noticeDays : (current.enforcement && current.enforcement.noticeDays)
|
|
393
|
+
await confirmed(`domain enforcement ends native sign-in (password, social, passkey) for every verified domain of ${current.connectionId} after ${days} days' notice, and signs those people out then`, current.connectionId, flags, deps)
|
|
394
|
+
}
|
|
395
|
+
return patch(api, current, attributes, flags)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** `sso status <id>`: settings, health, what the IdP registers, DNS proofs and notes. */
|
|
399
|
+
async function status(/** @type {string|undefined} */ id, /** @type {Record<string, any>} */ flags) {
|
|
400
|
+
const conn = connectionIdOf(id, 'saaslayer sso status <connectionId>')
|
|
401
|
+
const api = await instanceOf(flags)
|
|
402
|
+
const c = await readConnection(api, conn)
|
|
403
|
+
/** @param {string} sub */
|
|
404
|
+
const optional = async (sub) => {
|
|
405
|
+
try {
|
|
406
|
+
return (await api.call('GET', `/connections/${conn}${sub}`)).data.attributes
|
|
407
|
+
} catch (err) {
|
|
408
|
+
return { unavailable: /** @type {Error} */ (err).message.split('\n')[0] }
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const health = c.status === 'deleted' ? null : await optional('/health')
|
|
412
|
+
const serviceProvider = c.status === 'deleted' ? null : await optional('/service-provider')
|
|
413
|
+
const result = { connection: c, health, serviceProvider, dns: dnsOf(c), notes: notesOf(c) }
|
|
414
|
+
if (flags.json) {
|
|
415
|
+
console.log(JSON.stringify(result, null, 2))
|
|
416
|
+
return result
|
|
417
|
+
}
|
|
418
|
+
console.log(`SSO connection ${c.connectionId} (${c.protocol}, ${c.status}, version ${c.version}) for tenant ${c.tenant} on ${api.where}`)
|
|
419
|
+
console.log(` issuer ${c.issuer || 'not set yet'}; sessions ${c.sessionCapHours} h, tokens ${c.tokenTtlMinutes} min; MFA ${c.mfa}; JIT ${c.jit ? 'on' : 'off'}; SCIM ${c.scim && c.scim.enabled ? 'on' : 'off'}; delete policy ${c.deletePolicy}`)
|
|
420
|
+
if (health && !health.unavailable) {
|
|
421
|
+
const cert = health.certificate && health.certificate.state !== 'not-applicable' ? `; certificate ${health.certificate.state}${health.certificate.daysLeft != null ? ` (${health.certificate.daysLeft} days left)` : ''}` : ''
|
|
422
|
+
const signIn = `sign-in ${health.signIn.state}${health.signIn.lastSuccessAt ? ` (last success ${health.signIn.lastSuccessAt})` : ''}`
|
|
423
|
+
const scim = health.provisioning.scim
|
|
424
|
+
console.log(`health: ${health.overall} — ${signIn}${cert}; SCIM ${scim.state}${scim.reason ? ` (${scim.reason})` : ''}`)
|
|
425
|
+
for (const issue of health.issues || []) {
|
|
426
|
+
const categories = issue.categories || (issue.category ? [issue.category] : [])
|
|
427
|
+
console.log(` issue: ${issue.kind}${categories.length ? ` (${categories.join(', ')})` : ''}`)
|
|
428
|
+
if (issue.kind !== 'login-failure') continue
|
|
429
|
+
for (const f of health.signIn.failures || []) if (f.sinceLastSuccess) console.log(` refused: ${f.reason} (last ${f.lastAt}); see: ${TROUBLESHOOTING}`)
|
|
430
|
+
}
|
|
431
|
+
} else if (health) console.log(`health: unavailable (${health.unavailable})`)
|
|
432
|
+
if (serviceProvider && !serviceProvider.unavailable) console.log(registrationText(serviceProvider))
|
|
433
|
+
for (const d of c.domains || []) {
|
|
434
|
+
const proof = dnsOf({ domains: [d] })[0]
|
|
435
|
+
console.log(`domain ${d.domain}: ${d.status}${proof ? ` — publish ${proofText(proof)}` : ''}`)
|
|
436
|
+
}
|
|
437
|
+
for (const n of result.notes) console.log(`note (${n.kind}): ${n.text}`)
|
|
438
|
+
return result
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** `sso activate <id>`: Cognito gets the provider and client, then the connection is trusted. */
|
|
442
|
+
async function activate(/** @type {string|undefined} */ id, /** @type {Record<string, any>} */ flags) {
|
|
443
|
+
const conn = connectionIdOf(id, 'saaslayer sso activate <connectionId>')
|
|
444
|
+
const api = await instanceOf(flags)
|
|
445
|
+
const doc = await api.call('POST', `/connections/${conn}/activate`)
|
|
446
|
+
const c = doc.data.attributes
|
|
447
|
+
const runtime = (doc.meta && doc.meta.runtime) || {}
|
|
448
|
+
const result = { connection: c, runtime, notes: notesOf(c) }
|
|
449
|
+
if (flags.json) console.log(JSON.stringify(result, null, 2))
|
|
450
|
+
else {
|
|
451
|
+
console.log(`activated SSO connection ${c.connectionId}: Cognito ${runtime.outcome || 'holds'} its provider and app client${runtime.clientId ? ` ${runtime.clientId}` : ''}`)
|
|
452
|
+
console.log('note (namespace): the identity namespace (issuer, providerTenant, subjectSource, idp.clientId) is now fixed: a change needs a migration or a replacement connection')
|
|
453
|
+
}
|
|
454
|
+
return result
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** `sso disable <id>`: trust withdrawn at once; everything kept for re-activation. */
|
|
458
|
+
async function disable(/** @type {string|undefined} */ id, /** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
459
|
+
const conn = connectionIdOf(id, 'saaslayer sso disable <connectionId> [--yes]')
|
|
460
|
+
await confirmed(`disabling withdraws trust at once: every SSO sign-in and session of ${decodeURIComponent(conn)} stops`, decodeURIComponent(conn), flags, deps)
|
|
461
|
+
const api = await instanceOf(flags)
|
|
462
|
+
const c = (await api.call('POST', `/connections/${conn}/disable`)).data.attributes
|
|
463
|
+
if (flags.json) console.log(JSON.stringify({ connection: c }, null, 2))
|
|
464
|
+
else console.log(`disabled SSO connection ${c.connectionId}: its settings, provider and client are kept; saaslayer sso activate ${c.connectionId} trusts it again`)
|
|
465
|
+
return { connection: c }
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** `sso rotate <id> (--metadata-url U | --metadata-file F | --client-secret-stdin)`: in place, same client and sessions. */
|
|
469
|
+
async function rotate(/** @type {string|undefined} */ id, /** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
470
|
+
const conn = connectionIdOf(id, 'saaslayer sso rotate <connectionId> (--metadata-url URL | --metadata-file FILE | --client-secret-stdin)')
|
|
471
|
+
const given = ['metadata-url', 'metadata-file', 'client-secret-stdin'].filter((f) => flags[f] !== undefined)
|
|
472
|
+
const other = ['issuer', 'client-id', 'oidc-scope', 'provider-tenant', 'subject-source', 'settings-file'].filter((f) => flags[f] !== undefined)
|
|
473
|
+
if (other.length) throw new Error(`rotate changes only the metadata or the client secret (not --${other.join(', --')}): use saaslayer sso update`)
|
|
474
|
+
if (given.length !== 1) throw new Error('rotate takes exactly one of --metadata-url, --metadata-file or --client-secret-stdin')
|
|
475
|
+
const idp = /** @type {Record<string, any>} */ (await idpOf(flags, deps))
|
|
476
|
+
const api = await instanceOf(flags)
|
|
477
|
+
const current = await readConnection(api, conn)
|
|
478
|
+
const doc = await api.call('POST', `/connections/${conn}/rotate`, { data: { type: 'sso-connections', attributes: { idp } }, meta: { expectedVersion: current.version } })
|
|
479
|
+
const c = doc.data.attributes
|
|
480
|
+
const runtime = (doc.meta && doc.meta.runtime) || null
|
|
481
|
+
if (flags.json) console.log(JSON.stringify({ connection: c, changes: (doc.meta && doc.meta.changes) || [], runtime }, null, 2))
|
|
482
|
+
else console.log(`rotated SSO connection ${c.connectionId} (version ${c.version})${runtime ? `; Cognito ${runtime.outcome} client ${runtime.clientId || ''}`.trimEnd() : ''}`)
|
|
483
|
+
return { connection: c, runtime }
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** `sso remove <id> --reason R [--sso-only-people N] [--yes]`: the confirmed, resumable delete. */
|
|
487
|
+
async function remove(/** @type {string|undefined} */ id, /** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
488
|
+
const conn = connectionIdOf(id, 'saaslayer sso remove <connectionId> --reason <text> [--sso-only-people N] [--yes]')
|
|
489
|
+
const reason = requireReason('sso remove', flags)
|
|
490
|
+
const api = await instanceOf(flags)
|
|
491
|
+
const current = await readConnection(api, conn)
|
|
492
|
+
if (current.status === 'deleted') {
|
|
493
|
+
if (flags.json) console.log(JSON.stringify({ connection: current }, null, 2))
|
|
494
|
+
else console.log(`SSO connection ${current.connectionId} is already deleted`)
|
|
495
|
+
return { connection: current }
|
|
496
|
+
}
|
|
497
|
+
const impact = (await api.call('GET', `/connections/${conn}/deletion-impact`)).data.attributes
|
|
498
|
+
const fate = { keep_dormant_reinvite: 'keeps them as dormant accounts to re-invite', block_while_sso_only: 'refuses the delete while any exist', delete_sso_only_people: 'deletes them permanently' }[/** @type {'keep_dormant_reinvite'} */ (impact.deletePolicy)] || impact.deletePolicy
|
|
499
|
+
if (!flags.json) console.log(`deleting ${current.connectionId} (tenant ${current.tenant}): ${impact.people} people, ${impact.ssoOnlyPeople} whose only way in is this connection; policy ${impact.deletePolicy} ${fate}${impact.enforcement && impact.enforcement.enabled ? '; domain enforcement is turned off first' : ''}`)
|
|
500
|
+
/** @type {Record<string, any>} */
|
|
501
|
+
const meta = { confirm: current.connectionId, reason }
|
|
502
|
+
if (impact.deletePolicy === 'delete_sso_only_people' && impact.ssoOnlyPeople > 0) {
|
|
503
|
+
const typed = wholeNumber(flags, 'sso-only-people')
|
|
504
|
+
if (typed === undefined) throw new Error(`policy delete_sso_only_people deletes ${impact.ssoOnlyPeople} people permanently: pass --sso-only-people ${impact.ssoOnlyPeople} to confirm`)
|
|
505
|
+
if (typed !== impact.ssoOnlyPeople) throw new Error(`--sso-only-people ${typed} does not match the ${impact.ssoOnlyPeople} SSO-only people now: check saaslayer sso status ${current.connectionId} and confirm again`)
|
|
506
|
+
meta.ssoOnlyPeople = typed
|
|
507
|
+
}
|
|
508
|
+
const interactive = deps.interactive !== undefined ? deps.interactive : !!process.stdin.isTTY
|
|
509
|
+
if (!flags.yes && !interactive) throw new Error(`pass --yes to confirm deleting ${current.connectionId} non-interactively`)
|
|
510
|
+
await confirmed(`deleting ${current.connectionId} ends its sign-ins and removes its provider, client and directory links`, current.connectionId, flags, deps)
|
|
511
|
+
const doc = await api.call('DELETE', `/connections/${conn}`, { meta })
|
|
512
|
+
const c = doc.data.attributes
|
|
513
|
+
const deletion = (doc.meta && doc.meta.deletion) || null
|
|
514
|
+
if (flags.json) console.log(JSON.stringify({ connection: c, deletion }, null, 2))
|
|
515
|
+
else {
|
|
516
|
+
const p = deletion ? deletion.people : null
|
|
517
|
+
console.log(`deleted SSO connection ${c.connectionId}${p ? `: ${p.people} people, ${p.ssoOnly} SSO-only (${p.dormant} kept dormant, ${p.deleted} deleted)` : ''}`)
|
|
518
|
+
}
|
|
519
|
+
return { connection: c, deletion }
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** `sso domains add|remove|verify <id> <domain>`. */
|
|
523
|
+
async function domains(/** @type {string|undefined} */ action, /** @type {string[]} */ rest, /** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
524
|
+
const usage = 'saaslayer sso domains add|remove|verify <connectionId> <domain>'
|
|
525
|
+
if (!['add', 'remove', 'verify'].includes(String(action)) || !rest[0] || !rest[1]) throw new Error(`usage: ${usage}`)
|
|
526
|
+
const conn = encodeURIComponent(rest[0])
|
|
527
|
+
const domain = rest[1].trim().toLowerCase()
|
|
528
|
+
const api = await instanceOf(flags)
|
|
529
|
+
if (action === 'verify') {
|
|
530
|
+
const doc = await api.call('POST', `/connections/${conn}/domains/${encodeURIComponent(domain)}/verify`)
|
|
531
|
+
const c = doc.data.attributes
|
|
532
|
+
const check = (doc.meta && doc.meta.check) || { domain, result: 'unknown', verified: false }
|
|
533
|
+
const proof = dnsOf(c).find((r) => r.domain === domain)
|
|
534
|
+
if (flags.json) console.log(JSON.stringify({ connection: c, check, dns: proof ? [proof] : [] }, null, 2))
|
|
535
|
+
else if (check.verified) console.log(`${domain}: verified for ${c.connectionId}`)
|
|
536
|
+
else console.log(`${domain}: ${check.result}${proof ? ` — publish ${proofText(proof)} and run this again` : ''}`)
|
|
537
|
+
return { connection: c, check }
|
|
538
|
+
}
|
|
539
|
+
const current = await readConnection(api, conn)
|
|
540
|
+
const entries = /** @type {Array<Record<string, any>>} */ (current.domains || [])
|
|
541
|
+
const entry = entries.find((d) => d.domain === domain)
|
|
542
|
+
if (action === 'add' && entry) {
|
|
543
|
+
if (flags.json) console.log(JSON.stringify({ connection: current, changes: [], dns: dnsOf(current), notes: [] }, null, 2))
|
|
544
|
+
else console.log(`${domain} is already listed on ${current.connectionId} (${entry.status})`)
|
|
545
|
+
return { connection: current, changes: [] }
|
|
546
|
+
}
|
|
547
|
+
if (action === 'remove' && !entry) {
|
|
548
|
+
if (flags.json) console.log(JSON.stringify({ connection: current, changes: [], dns: dnsOf(current), notes: [] }, null, 2))
|
|
549
|
+
else console.log(`${domain} is not listed on ${current.connectionId}`)
|
|
550
|
+
return { connection: current, changes: [] }
|
|
551
|
+
}
|
|
552
|
+
if (action === 'remove' && entry && entry.status === 'verified') await confirmed(`${domain} is verified: removing it stops routing its sign-ins to this connection and releases its claim`, current.connectionId, flags, deps)
|
|
553
|
+
const names = action === 'add' ? [...entries.map((d) => d.domain), domain] : entries.map((d) => d.domain).filter((d) => d !== domain)
|
|
554
|
+
return patch(api, current, { domains: names }, flags)
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Store a once-shown secret, or undo what made it: the secret never reaches the terminal or an error message.
|
|
559
|
+
* @param {import('../secret-sink').Sink} sink @param {string} secret
|
|
560
|
+
* @param {{ description: string, region: string, noun: string, lost: string, id: string, undo: () => Promise<unknown>, undoHint: string }} what
|
|
561
|
+
* @param {Record<string, any>} flags @param {Deps} deps
|
|
562
|
+
*/
|
|
563
|
+
async function keepOrUndo(sink, secret, what, flags, deps) {
|
|
564
|
+
try {
|
|
565
|
+
if (!secret) throw new Error('the answer held no secret')
|
|
566
|
+
return await writeSecret(sink, secret, what, flags, deps)
|
|
567
|
+
} catch (err) {
|
|
568
|
+
// A secret nobody holds must not stay usable.
|
|
569
|
+
discardSink(sink)
|
|
570
|
+
let undone = `it was revoked, so nothing holds a lost ${what.lost}`
|
|
571
|
+
try {
|
|
572
|
+
await what.undo()
|
|
573
|
+
} catch {
|
|
574
|
+
undone = `revoking it failed too: run ${what.undoHint}`
|
|
575
|
+
}
|
|
576
|
+
throw new Error(`could not store ${what.noun} ${what.id} in ${sinkName(sink)} (${/** @type {Error} */ (err).message}); ${undone}`)
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** `sso link issue|status|revoke <id>`: the connection's one setup link for its IT admin. */
|
|
581
|
+
async function link(/** @type {string|undefined} */ action, /** @type {string[]} */ rest, /** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
582
|
+
if (!['issue', 'status', 'revoke'].includes(String(action)) || !rest[0]) throw new Error('usage: saaslayer sso link issue|status|revoke <connectionId> …')
|
|
583
|
+
const conn = encodeURIComponent(rest[0])
|
|
584
|
+
if (action !== 'issue') {
|
|
585
|
+
const api = await instanceOf(flags)
|
|
586
|
+
const l = (await api.call(action === 'status' ? 'GET' : 'DELETE', `/connections/${conn}/setup-link`)).data.attributes
|
|
587
|
+
if (flags.json) console.log(JSON.stringify(l, null, 2))
|
|
588
|
+
else if (action === 'status') console.log(`setup link ${l.linkId} of ${l.connectionId}: ${l.status} until ${l.expiresAt}, opened ${l.openCount} times${l.lastOpenedAt ? ` (last ${l.lastOpenedAt})` : ''}; issued ${l.issuedAt} by ${l.issuedBy}`)
|
|
589
|
+
else console.log(`setup link ${l.linkId} of ${l.connectionId} revoked: it and every session it opened are refused from their next request`)
|
|
590
|
+
return l
|
|
591
|
+
}
|
|
592
|
+
const validHours = wholeNumber(flags, 'valid-hours')
|
|
593
|
+
const appUrl = text(flags['app-url'])
|
|
594
|
+
const sink = openSink(flags, 'a setup link')
|
|
595
|
+
let token = ''
|
|
596
|
+
try {
|
|
597
|
+
const api = await instanceOf(flags)
|
|
598
|
+
let active = null
|
|
599
|
+
try {
|
|
600
|
+
const l = (await api.call('GET', `/connections/${conn}/setup-link`)).data.attributes
|
|
601
|
+
if (l.status === 'active') active = l
|
|
602
|
+
} catch (err) {
|
|
603
|
+
if (/** @type {{ status?: number }} */ (err).status !== 404) throw err
|
|
604
|
+
}
|
|
605
|
+
if (active && !flags.replace) throw new Error(`setup link ${active.linkId} is active until ${active.expiresAt}: a new one ends it and every session it opened; pass --replace`)
|
|
606
|
+
const doc = await api.call('POST', `/connections/${conn}/setup-link`, { data: { type: 'sso-setup-links', attributes: validHours !== undefined ? { validHours } : {} } })
|
|
607
|
+
token = String(doc.data.attributes.token || '')
|
|
608
|
+
const { token: _shownOnce, ...view } = doc.data.attributes
|
|
609
|
+
const replaced = (doc.meta && doc.meta.replaced) || null
|
|
610
|
+
const value = appUrl && token ? `${appUrl.replace(/\/$/, '')}${SETUP_PAGE}${token}` : token
|
|
611
|
+
const destination = await keepOrUndo(sink, value, {
|
|
612
|
+
noun: 'setup link',
|
|
613
|
+
lost: 'link',
|
|
614
|
+
id: view.linkId,
|
|
615
|
+
region: api.target.deployment.region,
|
|
616
|
+
description: `SaaSLayer SSO setup link ${view.linkId} for ${view.connectionId} on ${api.where}`,
|
|
617
|
+
undo: () => api.call('DELETE', `/connections/${conn}/setup-link`),
|
|
618
|
+
undoHint: `saaslayer sso link revoke ${view.connectionId}`,
|
|
619
|
+
}, flags, deps)
|
|
620
|
+
const result = { setupLink: view, destination, replaced }
|
|
621
|
+
if (flags.json) console.log(JSON.stringify(result, null, 2))
|
|
622
|
+
else {
|
|
623
|
+
console.log(`issued setup link ${view.linkId} for ${view.connectionId}, valid until ${view.expiresAt}: written to ${destinationText(destination)}; it is never shown${replaced ? ` (replaced setup link ${replaced})` : ''}`)
|
|
624
|
+
console.log(appUrl
|
|
625
|
+
? 'send it to the customer\'s IT admin over a private channel; it ends when setup completes, when revoked or replaced, or at its expiry'
|
|
626
|
+
: `it holds the link token: the IT admin opens <your app>${SETUP_PAGE}<token> (pass --app-url to store the whole link); send it over a private channel`)
|
|
627
|
+
}
|
|
628
|
+
return result
|
|
629
|
+
} catch (err) {
|
|
630
|
+
discardSink(sink)
|
|
631
|
+
throw scrubbed(/** @type {Error} */ (err).message, token)
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** `sso scim status|issue|rotate|revoke|sync-complete <id> [credentialId]`. */
|
|
636
|
+
async function scimCommand(/** @type {string|undefined} */ action, /** @type {string[]} */ rest, /** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
637
|
+
if (!['status', 'issue', 'rotate', 'revoke', 'sync-complete'].includes(String(action)) || !rest[0]) throw new Error('usage: saaslayer sso scim status|issue|rotate|revoke|sync-complete <connectionId> [credentialId] …')
|
|
638
|
+
const conn = encodeURIComponent(rest[0])
|
|
639
|
+
const base = `/connections/${conn}/scim/credentials`
|
|
640
|
+
if ((action === 'rotate' || action === 'revoke') && !rest[1]) throw new Error(`usage: saaslayer sso scim ${action} <connectionId> <credentialId>`)
|
|
641
|
+
if (action === 'sync-complete') return syncComplete(conn, flags)
|
|
642
|
+
if (action === 'status' || action === 'revoke') {
|
|
643
|
+
const api = await instanceOf(flags)
|
|
644
|
+
if (action === 'revoke') {
|
|
645
|
+
const cred = (await api.call('DELETE', `${base}/${encodeURIComponent(rest[1])}`)).data.attributes
|
|
646
|
+
if (flags.json) console.log(JSON.stringify(cred, null, 2))
|
|
647
|
+
else console.log(`SCIM token ${cred.credentialId} of ${cred.connectionId} revoked: its next SCIM request is refused`)
|
|
648
|
+
return cred
|
|
649
|
+
}
|
|
650
|
+
const doc = await api.call('GET', base)
|
|
651
|
+
const creds = (doc.data || []).map((/** @type {{ attributes: Record<string, any> }} */ d) => d.attributes)
|
|
652
|
+
const result = { scimUrl: doc.meta && doc.meta.scimUrl, credentials: creds }
|
|
653
|
+
if (flags.json) console.log(JSON.stringify(result, null, 2))
|
|
654
|
+
else {
|
|
655
|
+
console.log(`SCIM URL: ${result.scimUrl}`)
|
|
656
|
+
if (!creds.length) console.log(`no SCIM tokens: issue one with saaslayer sso scim issue ${decodeURIComponent(conn)} --to-ssm NAME | --to-file PATH`)
|
|
657
|
+
for (const c of creds) console.log(`${c.credentialId} ${c.status} …${c.hint} created ${c.createdAt}${c.expiresAt ? ` expires ${c.expiresAt}` : ''}${c.replacedBy ? ` replaced by ${c.replacedBy}` : ''}`)
|
|
658
|
+
}
|
|
659
|
+
return result
|
|
660
|
+
}
|
|
661
|
+
const expiresInDays = wholeNumber(flags, 'expires-in-days')
|
|
662
|
+
const overlapSeconds = wholeNumber(flags, 'overlap-seconds')
|
|
663
|
+
const sink = openSink(flags, 'a SCIM token')
|
|
664
|
+
let token = ''
|
|
665
|
+
try {
|
|
666
|
+
const api = await instanceOf(flags)
|
|
667
|
+
let doc
|
|
668
|
+
if (action === 'issue') {
|
|
669
|
+
const listed = (await api.call('GET', base)).data || []
|
|
670
|
+
const active = listed.map((/** @type {{ attributes: Record<string, any> }} */ d) => d.attributes).find((/** @type {Record<string, any>} */ c) => c.status === 'active')
|
|
671
|
+
if (active) throw new Error(`SCIM token ${active.credentialId} is active: replace it with saaslayer sso scim rotate ${decodeURIComponent(conn)} ${active.credentialId} (or revoke it first)`)
|
|
672
|
+
doc = await api.call('POST', base, { data: { type: 'sso-scim-credentials', attributes: expiresInDays !== undefined ? { expiresInDays } : {} } })
|
|
673
|
+
} else {
|
|
674
|
+
doc = await api.call('POST', `${base}/${encodeURIComponent(rest[1])}/rotate`, { data: { type: 'sso-scim-credential-rotations', attributes: { ...(overlapSeconds !== undefined ? { overlapSeconds } : {}), ...(expiresInDays !== undefined ? { expiresInDays } : {}) } } })
|
|
675
|
+
}
|
|
676
|
+
token = String(doc.data.attributes.token || '')
|
|
677
|
+
const { token: _shownOnce, ...view } = doc.data.attributes
|
|
678
|
+
const meta = doc.meta || {}
|
|
679
|
+
const destination = await keepOrUndo(sink, token, {
|
|
680
|
+
noun: 'SCIM token',
|
|
681
|
+
lost: 'token',
|
|
682
|
+
id: view.credentialId,
|
|
683
|
+
region: api.target.deployment.region,
|
|
684
|
+
description: `SaaSLayer SCIM token ${view.credentialId} for ${view.connectionId} on ${api.where}`,
|
|
685
|
+
undo: () => api.call('DELETE', `${base}/${encodeURIComponent(view.credentialId)}`),
|
|
686
|
+
undoHint: `saaslayer sso scim revoke ${view.connectionId} ${view.credentialId}`,
|
|
687
|
+
}, flags, deps).catch((err) => {
|
|
688
|
+
const replaced = meta.replaced
|
|
689
|
+
throw replaced ? new Error(`${err.message}; ${replaced.credentialId} still ends at ${replaced.expiresAt}: rotate again before then`) : err
|
|
690
|
+
})
|
|
691
|
+
const result = { credential: view, scimUrl: meta.scimUrl, destination, ...(meta.replaced ? { replaced: meta.replaced } : {}) }
|
|
692
|
+
if (flags.json) console.log(JSON.stringify(result, null, 2))
|
|
693
|
+
else {
|
|
694
|
+
console.log(action === 'issue'
|
|
695
|
+
? `issued SCIM token ${view.credentialId} for ${view.connectionId}: written to ${destinationText(destination)}; it is never shown`
|
|
696
|
+
: `rotated SCIM token ${meta.replaced.credentialId} → ${view.credentialId} for ${view.connectionId}: written to ${destinationText(destination)}; ${meta.replaced.credentialId} keeps working until ${meta.replaced.expiresAt}`)
|
|
697
|
+
console.log(`SCIM URL: ${meta.scimUrl} (enter it with the token in the identity provider)`)
|
|
698
|
+
}
|
|
699
|
+
return result
|
|
700
|
+
} catch (err) {
|
|
701
|
+
discardSink(sink)
|
|
702
|
+
throw scrubbed(/** @type {Error} */ (err).message, token)
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** `sso scim sync-complete <id>`: confirm the initial sync, continuing a large directory until SCIM is the authority. */
|
|
707
|
+
async function syncComplete(/** @type {string} */ conn, /** @type {Record<string, any>} */ flags) {
|
|
708
|
+
const api = await instanceOf(flags)
|
|
709
|
+
let last = null
|
|
710
|
+
for (let i = 0; i < SYNC_CALLS; i++) {
|
|
711
|
+
last = (await api.call('POST', `/connections/${conn}/scim/initial-sync-complete`)).data.attributes
|
|
712
|
+
if (last.complete) break
|
|
713
|
+
if (!flags.json) console.log(`initial SCIM sync of ${last.connectionId} in progress: ${last.people} people written; continuing`)
|
|
714
|
+
}
|
|
715
|
+
if (flags.json) console.log(JSON.stringify(last, null, 2))
|
|
716
|
+
else if (last && last.complete) console.log(`initial SCIM sync of ${last.connectionId} complete (generation ${last.generation}): SCIM is now its group authority`)
|
|
717
|
+
else console.log(`initial SCIM sync of ${decodeURIComponent(conn)} still in progress after ${SYNC_CALLS} calls: run this again to continue`)
|
|
718
|
+
return last
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** `sso reactivate <id> --directory-id ID --reason R`: restore one deactivated person of a connection without SCIM. */
|
|
722
|
+
async function reactivate(/** @type {string|undefined} */ id, /** @type {Record<string, any>} */ flags) {
|
|
723
|
+
const conn = connectionIdOf(id, 'saaslayer sso reactivate <connectionId> --directory-id ID --reason <text>')
|
|
724
|
+
const directoryId = text(flags['directory-id'])
|
|
725
|
+
if (!directoryId) throw new Error('sso reactivate: --directory-id <id> is required (the person\'s stable id at the identity provider)')
|
|
726
|
+
const reason = requireReason('sso reactivate', flags)
|
|
727
|
+
const api = await instanceOf(flags)
|
|
728
|
+
const r = (await api.call('POST', `/connections/${conn}/identity-reactivations`, { data: { type: 'sso-identity-reactivations', attributes: { directoryId, reason } } })).data.attributes
|
|
729
|
+
if (flags.json) console.log(JSON.stringify(r, null, 2))
|
|
730
|
+
else console.log(`reactivated directory identity ${directoryId} of ${r.connectionId} as ${r.suid}`)
|
|
731
|
+
return r
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/**
|
|
735
|
+
* Why a refused event was refused, as codes and server-written text only (never an email or subject): a sign-in's reason
|
|
736
|
+
* code, or a SCIM request's method, resource, status, scimType and detail. Null for anything else.
|
|
737
|
+
* @param {Record<string, any>} e
|
|
738
|
+
*/
|
|
739
|
+
function refusalReasonOf(e) {
|
|
740
|
+
const d = e.details
|
|
741
|
+
if (e.outcome !== 'refused' || !d || typeof d !== 'object') return null
|
|
742
|
+
if (e.type === 'sign-in.refused' && d.reason) return `${d.reason}; see: ${TROUBLESHOOTING}`
|
|
743
|
+
if (e.type === 'scim.request') return `${[d.method, d.resource, d.status, d.scimType].filter((v) => v !== undefined).join(' ')}${d.detail ? `: ${d.detail}` : ''}`
|
|
744
|
+
return null
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* `sso audit [<id> | --tenant T] [--type T] [--from] [--to] [--limit N] [--cursor C] [--include-exports]`: one page, newest
|
|
749
|
+
* first. The exports' own audit.exported events are listed only with --include-exports (or a --type naming them).
|
|
750
|
+
*/
|
|
751
|
+
async function audit(/** @type {string|undefined} */ id, /** @type {Record<string, any>} */ flags) {
|
|
752
|
+
const query = new URLSearchParams()
|
|
753
|
+
if (!id && text(flags.tenant)) query.set('tenant', /** @type {string} */ (text(flags.tenant)))
|
|
754
|
+
for (const key of ['limit', 'type', 'from', 'to', 'cursor']) if (text(flags[key])) query.set(key, /** @type {string} */ (text(flags[key])))
|
|
755
|
+
if (flags['include-exports'] === true) query.set('includeExports', 'true')
|
|
756
|
+
const api = await instanceOf(flags)
|
|
757
|
+
const sub = id ? `/connections/${encodeURIComponent(id)}/audit` : '/audit'
|
|
758
|
+
const doc = await api.call('GET', `${sub}${query.toString() ? `?${query}` : ''}`)
|
|
759
|
+
const events = (doc.data || []).map((/** @type {{ attributes: Record<string, any> }} */ d) => d.attributes)
|
|
760
|
+
const next = doc.links && doc.links.next ? new URL(doc.links.next, 'https://x.invalid').searchParams.get('cursor') : null
|
|
761
|
+
if (flags.json) {
|
|
762
|
+
console.log(JSON.stringify({ events, cursor: next }, null, 2))
|
|
763
|
+
return { events, cursor: next }
|
|
764
|
+
}
|
|
765
|
+
if (!events.length) console.log('no SSO audit events')
|
|
766
|
+
for (const e of events) {
|
|
767
|
+
console.log(`${e.at} ${e.type} ${e.outcome} ${e.actor} (${e.source})${e.person ? ` person ${e.person}` : ''}${e.correlationId ? ` op ${e.correlationId}` : ''}`)
|
|
768
|
+
const reason = refusalReasonOf(e)
|
|
769
|
+
if (reason) console.log(` refused: ${reason}`)
|
|
770
|
+
}
|
|
771
|
+
if (next) console.log(`more: --cursor ${next}`)
|
|
772
|
+
return { events, cursor: next }
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** `sso mappings show|ceiling|rules <id> --tenant ORG …`: group-to-role mappings on the deployment's permissions API. */
|
|
776
|
+
async function mappings(/** @type {string|undefined} */ action, /** @type {string[]} */ rest, /** @type {Record<string, any>} */ flags) {
|
|
777
|
+
if (!['show', 'ceiling', 'rules'].includes(String(action)) || !rest[0]) throw new Error('usage: saaslayer sso mappings show|ceiling|rules <connectionId> --tenant ORG … (--deployment ID | --api-base URL) [auth]')
|
|
778
|
+
const tenant = text(flags.tenant)
|
|
779
|
+
if (!tenant) throw new Error('sso mappings: --tenant <org id> is required (the connection\'s tenant org)')
|
|
780
|
+
const source = `sso:${rest[0]}`
|
|
781
|
+
const label = `sso mappings ${action}`
|
|
782
|
+
const at = `/sso-group-mappings/${encodeURIComponent(source)}/orgs/${encodeURIComponent(tenant)}`
|
|
783
|
+
/** @param {string} method @param {string} sub @param {object} [body] */
|
|
784
|
+
const request = (method, sub, body) => permissionsRequest(label, flags, {}, method, `${at}${sub}`, body)
|
|
785
|
+
const read = async () => {
|
|
786
|
+
try {
|
|
787
|
+
return (await request('GET', '')).data.attributes
|
|
788
|
+
} catch (err) {
|
|
789
|
+
if (/** @type {{ status?: number }} */ (err).status === 404) return null
|
|
790
|
+
throw err
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
/** @type {Record<string, any>|null} */
|
|
794
|
+
let mapping
|
|
795
|
+
let recompute = null
|
|
796
|
+
if (action === 'show') mapping = await read()
|
|
797
|
+
else if (action === 'ceiling') {
|
|
798
|
+
const attributes = { allowedOrgIds: listOf(flags['allow-org']), approvedRoles: listOf(flags['approve-role']) }
|
|
799
|
+
if (!attributes.allowedOrgIds.length) throw new Error(`${label}: at least one --allow-org <org id> is required (repeatable)`)
|
|
800
|
+
const doc = await request('PUT', '/ceiling', { data: { type: 'sso-group-mapping-ceilings', attributes } })
|
|
801
|
+
mapping = doc.data.attributes
|
|
802
|
+
recompute = (doc.meta && doc.meta.recompute) || null
|
|
803
|
+
} else {
|
|
804
|
+
const file = text(flags.file)
|
|
805
|
+
if (!file) throw new Error(`${label}: --file <rules.json> is required ({ rules: [{ group, orgId, roleIds }], defaultGrant })`)
|
|
806
|
+
const rules = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
807
|
+
const current = await read()
|
|
808
|
+
if (!current) throw new Error(`no group mapping for ${source} in ${tenant} yet: the deployment owner sets its ceiling first (saaslayer sso mappings ceiling)`)
|
|
809
|
+
const doc = await request('PUT', '/rules', { data: { type: 'sso-group-mapping-rules', attributes: rules }, meta: { expectedPolicyRevision: current.policyRevision } })
|
|
810
|
+
mapping = doc.data.attributes
|
|
811
|
+
recompute = (doc.meta && doc.meta.recompute) || null
|
|
812
|
+
}
|
|
813
|
+
if (flags.json) {
|
|
814
|
+
console.log(JSON.stringify({ mapping, recompute }, null, 2))
|
|
815
|
+
return { mapping, recompute }
|
|
816
|
+
}
|
|
817
|
+
if (!mapping) {
|
|
818
|
+
console.log(`no group mapping for ${source} in ${tenant}`)
|
|
819
|
+
return { mapping, recompute }
|
|
820
|
+
}
|
|
821
|
+
const people = recompute && recompute.people !== undefined ? `; ${recompute.people} people recomputed` : ''
|
|
822
|
+
console.log(`${action === 'show' ? 'mapping' : action} of ${source} in ${tenant}${action === 'show' ? '' : ' set'} (revision ${mapping.policyRevision}): orgs ${(mapping.allowedOrgIds || []).join(', ') || 'none'}; privileged roles ${(mapping.approvedRoles || []).join(', ') || 'none'}${people}`)
|
|
823
|
+
for (const r of mapping.rules || []) console.log(` rule: group ${r.group} → ${r.orgId} roles ${(r.roleIds || []).join(', ')}`)
|
|
824
|
+
if (mapping.defaultGrant) console.log(` default: ${mapping.defaultGrant.orgId} roles ${(mapping.defaultGrant.roleIds || []).join(', ')}`)
|
|
825
|
+
return { mapping, recompute }
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** The affected people of an enforcement overview as text: an upper bound, per domain. @param {Record<string, any>} o */
|
|
829
|
+
const affectedText = (o) => `up to ${o.affected.total} people${o.affected.domains.length ? ` (${o.affected.domains.map((/** @type {{ domain: string, affected: number }} */ d) => `${d.domain} ${d.affected}`).join(', ')})` : ''}`
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* `sso enforcement status <id>`: where domain enforcement stands, the sweep's progress and how many people it affects.
|
|
833
|
+
* @param {string|undefined} id @param {Record<string, any>} flags
|
|
834
|
+
*/
|
|
835
|
+
async function enforcementStatus(id, flags) {
|
|
836
|
+
const conn = connectionIdOf(id, 'saaslayer sso enforcement status <connectionId>')
|
|
837
|
+
const api = await instanceOf(flags)
|
|
838
|
+
const o = /** @type {Record<string, any>} */ ((await api.call('GET', `/connections/${conn}/enforcement`)).data.attributes)
|
|
839
|
+
if (flags.json) {
|
|
840
|
+
console.log(JSON.stringify(o, null, 2))
|
|
841
|
+
return o
|
|
842
|
+
}
|
|
843
|
+
const effect = o.inEffect ? 'in effect: native sign-in of its verified domains is refused'
|
|
844
|
+
: o.state === 'off' ? 'native sign-in is allowed' : o.connectionStatus !== 'active' ? `not in effect: the connection is ${o.connectionStatus}` : 'not yet in effect: native sign-in is allowed until the cutover'
|
|
845
|
+
const when = o.state === 'enforced' ? ` since ${o.cutoverAt}` : o.state === 'scheduled' ? ` from ${o.cutoverAt} (scheduled ${o.scheduledAt}, ${o.noticeDays} days' notice)` : ''
|
|
846
|
+
console.log(`domain enforcement of ${o.connectionId}: ${o.state}${when} (${effect})`)
|
|
847
|
+
if (o.progress) console.log(`sweep: notices ${o.progress.notice}, reminder ${o.progress.reminder}, sign-outs ${o.progress.cutover} (${o.progress.revoked} done, ${o.progress.failed} failed, retried each run)`)
|
|
848
|
+
if (o.state === 'off' && o.disabledAt) console.log(`turned off ${o.disabledAt} by ${o.disabledBy}: ${o.disableReason}`)
|
|
849
|
+
console.log(`affected: ${affectedText(o)}: accounts holding a verified email in the domain; people created by an SSO sign-in hold none and are not counted (enforcement leaves their SSO sign-in alone)`)
|
|
850
|
+
return o
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* `sso enforcement disable <id> --reason R [--yes]`: the audited turn-off (or a scheduled cutover's cancel) at the version
|
|
855
|
+
* read, after the typed connection id; native sign-in of its domains works again at once.
|
|
856
|
+
* @param {string|undefined} id @param {Record<string, any>} flags @param {Deps} deps
|
|
857
|
+
*/
|
|
858
|
+
async function enforcementDisable(id, flags, deps) {
|
|
859
|
+
const conn = connectionIdOf(id, 'saaslayer sso enforcement disable <connectionId> --reason TEXT [--yes]')
|
|
860
|
+
const reason = requireReason('sso enforcement disable', flags)
|
|
861
|
+
const api = await instanceOf(flags)
|
|
862
|
+
const current = await readConnection(api, conn)
|
|
863
|
+
const o = /** @type {Record<string, any>} */ ((await api.call('GET', `/connections/${conn}/enforcement`)).data.attributes)
|
|
864
|
+
if (o.state === 'off') {
|
|
865
|
+
const result = { connection: current, changes: [] }
|
|
866
|
+
if (flags.json) console.log(JSON.stringify(result, null, 2))
|
|
867
|
+
else console.log(`domain enforcement is already off on ${current.connectionId}: nothing to do`)
|
|
868
|
+
return result
|
|
869
|
+
}
|
|
870
|
+
const domains = o.affected.domains.map((/** @type {{ domain: string }} */ d) => d.domain).join(', ')
|
|
871
|
+
await confirmed(`turning domain enforcement off lets ${affectedText({ affected: { ...o.affected, domains: [] } })} of ${domains || 'its domains'} sign in without SSO again at once`, current.connectionId, flags, deps)
|
|
872
|
+
const doc = await api.call('POST', `/connections/${conn}/enforcement/disable`, { meta: { reason, expectedVersion: current.version } })
|
|
873
|
+
const result = { connection: doc.data.attributes, changes: (doc.meta && doc.meta.changes) || [] }
|
|
874
|
+
if (flags.json) console.log(JSON.stringify(result, null, 2))
|
|
875
|
+
else console.log(`turned domain enforcement off on ${result.connection.connectionId}: native sign-in of its domains works again now (reason recorded: ${reason}); to enforce again, saaslayer sso update ${result.connection.connectionId} --enforce on starts a new notice period`)
|
|
876
|
+
return result
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/** `sso enforcement status|disable <id>`. */
|
|
880
|
+
async function enforcement(/** @type {string|undefined} */ action, /** @type {string[]} */ rest, /** @type {Record<string, any>} */ flags, /** @type {Deps} */ deps) {
|
|
881
|
+
if (action === 'status') return enforcementStatus(rest[0], flags)
|
|
882
|
+
if (action === 'disable') return enforcementDisable(rest[0], flags, deps)
|
|
883
|
+
throw new Error('usage: saaslayer sso enforcement status|disable <connectionId> [--reason TEXT] [--yes] [--json]')
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/**
|
|
887
|
+
* @param {string|undefined} sub @param {string[]} positional the words after the subcommand
|
|
888
|
+
* @param {Record<string, any>} flags @param {Deps} [deps]
|
|
889
|
+
*/
|
|
890
|
+
async function ssoCommand(sub, positional, flags, deps = {}) {
|
|
891
|
+
try {
|
|
892
|
+
if (sub === 'list') return await list(flags)
|
|
893
|
+
if (sub === 'status') return await status(positional[0], flags)
|
|
894
|
+
if (sub === 'add') return await add(flags, deps)
|
|
895
|
+
if (sub === 'update') return await update(positional[0], flags, deps)
|
|
896
|
+
if (sub === 'activate') return await activate(positional[0], flags)
|
|
897
|
+
if (sub === 'disable') return await disable(positional[0], flags, deps)
|
|
898
|
+
if (sub === 'rotate') return await rotate(positional[0], flags, deps)
|
|
899
|
+
if (sub === 'remove') return await remove(positional[0], flags, deps)
|
|
900
|
+
if (sub === 'domains') return await domains(positional[0], positional.slice(1), flags, deps)
|
|
901
|
+
if (sub === 'link') return await link(positional[0], positional.slice(1), flags, deps)
|
|
902
|
+
if (sub === 'scim') return await scimCommand(positional[0], positional.slice(1), flags, deps)
|
|
903
|
+
if (sub === 'reactivate') return await reactivate(positional[0], flags)
|
|
904
|
+
if (sub === 'audit') return await audit(positional[0], flags)
|
|
905
|
+
if (sub === 'mappings') return await mappings(positional[0], positional.slice(1), flags)
|
|
906
|
+
if (sub === 'enforcement') return await enforcement(positional[0], positional.slice(1), flags, deps)
|
|
907
|
+
} catch (err) {
|
|
908
|
+
throw refusalOf(err, flags, /** @type {{ target?: Target }} */ (err).target || null)
|
|
909
|
+
}
|
|
910
|
+
throw new Error(USAGE)
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
module.exports = { ssoCommand }
|