identityscope 0.0.0-stage → 0.28.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/LICENSE +21 -0
- package/README.md +917 -3
- package/SECURITY.md +56 -0
- package/dist/core/audit-readiness.d.ts +158 -0
- package/dist/core/audit-readiness.js +357 -0
- package/dist/core/audit-readiness.js.map +1 -0
- package/dist/core/certs.d.ts +68 -0
- package/dist/core/certs.js +132 -0
- package/dist/core/certs.js.map +1 -0
- package/dist/core/checks.d.ts +133 -0
- package/dist/core/checks.js +512 -0
- package/dist/core/checks.js.map +1 -0
- package/dist/core/cloud-rules.d.ts +20 -0
- package/dist/core/cloud-rules.js +44 -0
- package/dist/core/cloud-rules.js.map +1 -0
- package/dist/core/compare.d.ts +45 -0
- package/dist/core/compare.js +372 -0
- package/dist/core/compare.js.map +1 -0
- package/dist/core/conditions.d.ts +10 -0
- package/dist/core/conditions.js +201 -0
- package/dist/core/conditions.js.map +1 -0
- package/dist/core/credentials.d.ts +71 -0
- package/dist/core/credentials.js +211 -0
- package/dist/core/credentials.js.map +1 -0
- package/dist/core/datasets.d.ts +53 -0
- package/dist/core/datasets.js +596 -0
- package/dist/core/datasets.js.map +1 -0
- package/dist/core/definition.d.ts +32 -0
- package/dist/core/definition.js +301 -0
- package/dist/core/definition.js.map +1 -0
- package/dist/core/discover.d.ts +32 -0
- package/dist/core/discover.js +105 -0
- package/dist/core/discover.js.map +1 -0
- package/dist/core/engine.d.ts +18 -0
- package/dist/core/engine.js +290 -0
- package/dist/core/engine.js.map +1 -0
- package/dist/core/fields.d.ts +16 -0
- package/dist/core/fields.js +132 -0
- package/dist/core/fields.js.map +1 -0
- package/dist/core/governance-trail.d.ts +211 -0
- package/dist/core/governance-trail.js +557 -0
- package/dist/core/governance-trail.js.map +1 -0
- package/dist/core/http-transport.d.ts +66 -0
- package/dist/core/http-transport.js +247 -0
- package/dist/core/http-transport.js.map +1 -0
- package/dist/core/index.d.ts +13 -0
- package/dist/core/index.js +16 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/insights.d.ts +176 -0
- package/dist/core/insights.js +417 -0
- package/dist/core/insights.js.map +1 -0
- package/dist/core/joiner-evidence.d.ts +98 -0
- package/dist/core/joiner-evidence.js +254 -0
- package/dist/core/joiner-evidence.js.map +1 -0
- package/dist/core/lab/credential-map.d.ts +50 -0
- package/dist/core/lab/credential-map.js +163 -0
- package/dist/core/lab/credential-map.js.map +1 -0
- package/dist/core/lab/javadate.d.ts +7 -0
- package/dist/core/lab/javadate.js +307 -0
- package/dist/core/lab/javadate.js.map +1 -0
- package/dist/core/lab/jsonpath.d.ts +11 -0
- package/dist/core/lab/jsonpath.js +273 -0
- package/dist/core/lab/jsonpath.js.map +1 -0
- package/dist/core/lab/policy-preview.d.ts +43 -0
- package/dist/core/lab/policy-preview.js +78 -0
- package/dist/core/lab/policy-preview.js.map +1 -0
- package/dist/core/lab/rfc5646.d.ts +2 -0
- package/dist/core/lab/rfc5646.js +421 -0
- package/dist/core/lab/rfc5646.js.map +1 -0
- package/dist/core/lab/transform-impact.d.ts +63 -0
- package/dist/core/lab/transform-impact.js +138 -0
- package/dist/core/lab/transform-impact.js.map +1 -0
- package/dist/core/lab/transform-people.d.ts +61 -0
- package/dist/core/lab/transform-people.js +132 -0
- package/dist/core/lab/transform-people.js.map +1 -0
- package/dist/core/lab/transforms.d.ts +79 -0
- package/dist/core/lab/transforms.js +738 -0
- package/dist/core/lab/transforms.js.map +1 -0
- package/dist/core/lab/velocity.d.ts +33 -0
- package/dist/core/lab/velocity.js +874 -0
- package/dist/core/lab/velocity.js.map +1 -0
- package/dist/core/lab/workflow-health.d.ts +80 -0
- package/dist/core/lab/workflow-health.js +234 -0
- package/dist/core/lab/workflow-health.js.map +1 -0
- package/dist/core/lab/workflows.d.ts +87 -0
- package/dist/core/lab/workflows.js +568 -0
- package/dist/core/lab/workflows.js.map +1 -0
- package/dist/core/lifecycle-gaps.d.ts +192 -0
- package/dist/core/lifecycle-gaps.js +389 -0
- package/dist/core/lifecycle-gaps.js.map +1 -0
- package/dist/core/logs.d.ts +145 -0
- package/dist/core/logs.js +342 -0
- package/dist/core/logs.js.map +1 -0
- package/dist/core/lookup.d.ts +129 -0
- package/dist/core/lookup.js +289 -0
- package/dist/core/lookup.js.map +1 -0
- package/dist/core/model-insights.d.ts +247 -0
- package/dist/core/model-insights.js +474 -0
- package/dist/core/model-insights.js.map +1 -0
- package/dist/core/narrow.d.ts +23 -0
- package/dist/core/narrow.js +137 -0
- package/dist/core/narrow.js.map +1 -0
- package/dist/core/nerm.d.ts +154 -0
- package/dist/core/nerm.js +397 -0
- package/dist/core/nerm.js.map +1 -0
- package/dist/core/operations-watch.d.ts +232 -0
- package/dist/core/operations-watch.js +491 -0
- package/dist/core/operations-watch.js.map +1 -0
- package/dist/core/output/csv.d.ts +6 -0
- package/dist/core/output/csv.js +22 -0
- package/dist/core/output/csv.js.map +1 -0
- package/dist/core/output/html.d.ts +11 -0
- package/dist/core/output/html.js +66 -0
- package/dist/core/output/html.js.map +1 -0
- package/dist/core/output/xlsx.d.ts +3 -0
- package/dist/core/output/xlsx.js +130 -0
- package/dist/core/output/xlsx.js.map +1 -0
- package/dist/core/output/zip.d.ts +16 -0
- package/dist/core/output/zip.js +106 -0
- package/dist/core/output/zip.js.map +1 -0
- package/dist/core/ownership.d.ts +39 -0
- package/dist/core/ownership.js +100 -0
- package/dist/core/ownership.js.map +1 -0
- package/dist/core/patterns.d.ts +11 -0
- package/dist/core/patterns.js +31 -0
- package/dist/core/patterns.js.map +1 -0
- package/dist/core/preview.d.ts +96 -0
- package/dist/core/preview.js +173 -0
- package/dist/core/preview.js.map +1 -0
- package/dist/core/roles.d.ts +125 -0
- package/dist/core/roles.js +420 -0
- package/dist/core/roles.js.map +1 -0
- package/dist/core/tenant.d.ts +67 -0
- package/dist/core/tenant.js +194 -0
- package/dist/core/tenant.js.map +1 -0
- package/dist/core/threat-signals.d.ts +112 -0
- package/dist/core/threat-signals.js +250 -0
- package/dist/core/threat-signals.js.map +1 -0
- package/dist/core/threat-watch.d.ts +144 -0
- package/dist/core/threat-watch.js +282 -0
- package/dist/core/threat-watch.js.map +1 -0
- package/dist/core/transport.d.ts +82 -0
- package/dist/core/transport.js +312 -0
- package/dist/core/transport.js.map +1 -0
- package/dist/core/types.d.ts +137 -0
- package/dist/core/types.js +10 -0
- package/dist/core/types.js.map +1 -0
- package/dist/core/warnings.d.ts +236 -0
- package/dist/core/warnings.js +504 -0
- package/dist/core/warnings.js.map +1 -0
- package/dist/demo/tenant.d.ts +1572 -0
- package/dist/demo/tenant.js +1023 -0
- package/dist/demo/tenant.js.map +1 -0
- package/dist/node/attribute-history.d.ts +22 -0
- package/dist/node/attribute-history.js +86 -0
- package/dist/node/attribute-history.js.map +1 -0
- package/dist/node/changes.d.ts +20 -0
- package/dist/node/changes.js +78 -0
- package/dist/node/changes.js.map +1 -0
- package/dist/node/cli.d.ts +2 -0
- package/dist/node/cli.js +291 -0
- package/dist/node/cli.js.map +1 -0
- package/dist/node/config.d.ts +72 -0
- package/dist/node/config.js +203 -0
- package/dist/node/config.js.map +1 -0
- package/dist/node/credentials.d.ts +13 -0
- package/dist/node/credentials.js +24 -0
- package/dist/node/credentials.js.map +1 -0
- package/dist/node/delivery.d.ts +10 -0
- package/dist/node/delivery.js +105 -0
- package/dist/node/delivery.js.map +1 -0
- package/dist/node/doctor.d.ts +2 -0
- package/dist/node/doctor.js +151 -0
- package/dist/node/doctor.js.map +1 -0
- package/dist/node/drift.d.ts +31 -0
- package/dist/node/drift.js +56 -0
- package/dist/node/drift.js.map +1 -0
- package/dist/node/evidence.d.ts +42 -0
- package/dist/node/evidence.js +129 -0
- package/dist/node/evidence.js.map +1 -0
- package/dist/node/exceptions.d.ts +30 -0
- package/dist/node/exceptions.js +83 -0
- package/dist/node/exceptions.js.map +1 -0
- package/dist/node/history.d.ts +35 -0
- package/dist/node/history.js +74 -0
- package/dist/node/history.js.map +1 -0
- package/dist/node/index.d.ts +7 -0
- package/dist/node/index.js +8 -0
- package/dist/node/index.js.map +1 -0
- package/dist/node/keep.d.ts +9 -0
- package/dist/node/keep.js +39 -0
- package/dist/node/keep.js.map +1 -0
- package/dist/node/loader.d.ts +7 -0
- package/dist/node/loader.js +35 -0
- package/dist/node/loader.js.map +1 -0
- package/dist/node/log-files.d.ts +16 -0
- package/dist/node/log-files.js +93 -0
- package/dist/node/log-files.js.map +1 -0
- package/dist/node/monthly.d.ts +41 -0
- package/dist/node/monthly.js +108 -0
- package/dist/node/monthly.js.map +1 -0
- package/dist/node/oauth-login.d.ts +45 -0
- package/dist/node/oauth-login.js +121 -0
- package/dist/node/oauth-login.js.map +1 -0
- package/dist/node/packs.d.ts +32 -0
- package/dist/node/packs.js +43 -0
- package/dist/node/packs.js.map +1 -0
- package/dist/node/privileged-seen.d.ts +11 -0
- package/dist/node/privileged-seen.js +41 -0
- package/dist/node/privileged-seen.js.map +1 -0
- package/dist/node/recipients.d.ts +17 -0
- package/dist/node/recipients.js +51 -0
- package/dist/node/recipients.js.map +1 -0
- package/dist/node/runner.d.ts +51 -0
- package/dist/node/runner.js +298 -0
- package/dist/node/runner.js.map +1 -0
- package/dist/node/runtime.d.ts +12 -0
- package/dist/node/runtime.js +13 -0
- package/dist/node/runtime.js.map +1 -0
- package/dist/node/schedules.d.ts +87 -0
- package/dist/node/schedules.js +141 -0
- package/dist/node/schedules.js.map +1 -0
- package/dist/node/secrets.d.ts +37 -0
- package/dist/node/secrets.js +219 -0
- package/dist/node/secrets.js.map +1 -0
- package/dist/node/support.d.ts +14 -0
- package/dist/node/support.js +133 -0
- package/dist/node/support.js.map +1 -0
- package/dist/node/tenants.d.ts +93 -0
- package/dist/node/tenants.js +255 -0
- package/dist/node/tenants.js.map +1 -0
- package/dist/node/ui-page.d.ts +1 -0
- package/dist/node/ui-page.js +3 -0
- package/dist/node/ui-page.js.map +1 -0
- package/dist/node/ui-server.d.ts +48 -0
- package/dist/node/ui-server.js +2665 -0
- package/dist/node/ui-server.js.map +1 -0
- package/dist/node/write.d.ts +9 -0
- package/dist/node/write.js +53 -0
- package/dist/node/write.js.map +1 -0
- package/dist/reports/builtin.generated.d.ts +1 -0
- package/dist/reports/builtin.generated.js +49 -0
- package/dist/reports/builtin.generated.js.map +1 -0
- package/dist/reports/library.d.ts +6 -0
- package/dist/reports/library.js +18 -0
- package/dist/reports/library.js.map +1 -0
- package/launcher/IdentityScope.cmd +11 -0
- package/package.json +69 -4
- package/reports/access-profile-members.yaml +29 -0
- package/reports/access-profile-membership-counts.yaml +17 -0
- package/reports/access-profiles-without-owner.yaml +16 -0
- package/reports/access-request-audit-trail.yaml +36 -0
- package/reports/accounts-by-source.yaml +19 -0
- package/reports/active-identities-without-manager.yaml +22 -0
- package/reports/aggregation-failures.yaml +29 -0
- package/reports/aggregation-history.yaml +27 -0
- package/reports/all-sources.yaml +16 -0
- package/reports/application-accounts.yaml +32 -0
- package/reports/application-entitlements.yaml +31 -0
- package/reports/campaign-progress.yaml +23 -0
- package/reports/certification-decisions.yaml +31 -0
- package/reports/direct-reports-per-manager.yaml +20 -0
- package/reports/disabled-accounts-of-active-people.yaml +33 -0
- package/reports/duplicate-emails.yaml +16 -0
- package/reports/entitlement-holders.yaml +35 -0
- package/reports/entitlements-held-by-inactive-identities.yaml +31 -0
- package/reports/entitlements-without-owner.yaml +28 -0
- package/reports/identities-by-lifecycle-state.yaml +15 -0
- package/reports/identities-missing-key-attributes.yaml +27 -0
- package/reports/identities-with-processing-errors.yaml +19 -0
- package/reports/identity-attribute-mappings.yaml +27 -0
- package/reports/machine-accounts.yaml +28 -0
- package/reports/managers-and-direct-reports.yaml +23 -0
- package/reports/most-access.yaml +18 -0
- package/reports/new-identities.yaml +24 -0
- package/reports/old-passwords.yaml +35 -0
- package/reports/pending-reviews-by-reviewer.yaml +20 -0
- package/reports/person-access.yaml +31 -0
- package/reports/privileged-access.yaml +29 -0
- package/reports/provisioning-error-causes.yaml +27 -0
- package/reports/provisioning-errors.yaml +32 -0
- package/reports/provisioning-failures.yaml +28 -0
- package/reports/recent-access-requests.yaml +22 -0
- package/reports/recent-activity.yaml +32 -0
- package/reports/recent-leavers.yaml +34 -0
- package/reports/role-members.yaml +29 -0
- package/reports/role-membership-counts.yaml +18 -0
- package/reports/roles-without-owner.yaml +17 -0
- package/reports/sources-needing-attention.yaml +23 -0
- package/reports/stuck-access-requests.yaml +29 -0
- package/reports/team-access.yaml +30 -0
- package/reports/terminated-users-with-active-accounts.yaml +46 -0
- package/reports/uncorrelated-accounts.yaml +38 -0
- package/ui/js/00-setup.js +6 -0
- package/ui/js/01-small-helpers.js +143 -0
- package/ui/js/02-connection.js +150 -0
- package/ui/js/03-health-check.js +17 -0
- package/ui/js/04-library.js +135 -0
- package/ui/js/05-pickers.js +163 -0
- package/ui/js/06-report-view.js +157 -0
- package/ui/js/07-fields.js +85 -0
- package/ui/js/08-designer.js +360 -0
- package/ui/js/09-yaml.js +22 -0
- package/ui/js/10-instant-check.js +171 -0
- package/ui/js/11-lookup.js +161 -0
- package/ui/js/12-tenant.js +115 -0
- package/ui/js/13-source-configuration-and-diagnostics.js +64 -0
- package/ui/js/14-certifications.js +68 -0
- package/ui/js/15-monthly-report.js +24 -0
- package/ui/js/16-ownership.js +39 -0
- package/ui/js/17-compare-tenants.js +102 -0
- package/ui/js/18-audit.js +181 -0
- package/ui/js/19-insights.js +108 -0
- package/ui/js/20-role-mining.js +35 -0
- package/ui/js/21-share-reports.js +45 -0
- package/ui/js/22-partner-overview-all-customer-tenants.js +228 -0
- package/ui/js/23-in-app-guidance.js +217 -0
- package/ui/js/24-role-tools.js +220 -0
- package/ui/js/25-schedules.js +264 -0
- package/ui/js/26-start.js +7 -0
- package/ui/js/27-warnings.js +224 -0
- package/ui/js/28-audit-readiness.js +99 -0
- package/ui/js/29-lifecycle.js +182 -0
- package/ui/js/30-labs.js +265 -0
- package/ui/js/31-build.js +203 -0
- package/ui/js/32-lab-examples.js +148 -0
- package/ui/js/33-finder.js +89 -0
- package/ui/js/34-governance.js +129 -0
- package/ui/js/35-watch.js +266 -0
- package/ui/js/36-model.js +247 -0
- package/ui/js/37-logs-and-watch.js +224 -0
- package/ui/shell.html +112 -0
- package/ui/style.css +350 -0
|
@@ -0,0 +1,2665 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { getHeapStatistics } from 'node:v8';
|
|
5
|
+
import { createServer } from 'node:http';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { OPERATORS } from '../core/conditions.js';
|
|
8
|
+
import { DATASETS } from '../core/datasets.js';
|
|
9
|
+
import { CHECKS, OVERVIEW_DEFAULT, checksHeadline, checksTable, runChecks } from '../core/checks.js';
|
|
10
|
+
import { discoverFields, pickOptions } from '../core/discover.js';
|
|
11
|
+
import { findPeople, personDetail, sourceDetail, sourcesOverview } from '../core/lookup.js';
|
|
12
|
+
import { attributeChanges } from './attribute-history.js';
|
|
13
|
+
import { assertNermReadOnly, nermBaseUrl, nermOverview, nermRisk, nermSessions, nermSync, nermUsers } from '../core/nerm.js';
|
|
14
|
+
import { attributeSyncDrift, changesOutsideIsc, entitlementOwners, groupApprovals, leaverRemovalTimes, managerLeft, massChange, provisioningLoops, ruleUsage } from '../core/operations-watch.js';
|
|
15
|
+
import { accessSpikes, adminActivity, selfApprovals, signInSignals } from '../core/threat-signals.js';
|
|
16
|
+
import { accountsOutsideIsc, privilegedGained, riskByPerson, sensitiveChanges } from '../core/threat-watch.js';
|
|
17
|
+
import { jmlPreview, stuckRequests } from '../core/preview.js';
|
|
18
|
+
import { ccgReader, sourceLog } from '../core/logs.js';
|
|
19
|
+
import { linesOfFiles, linesOfStream, logFilesAt } from './log-files.js';
|
|
20
|
+
import { loadPrivileged, savePrivileged } from './privileged-seen.js';
|
|
21
|
+
import { accessOutsideModel, aggregationSafety, governanceGroups, lifecycleSettings, multipleAccounts, passwordFailures, reassignedReviews, roleComposition, serviceAccounts } from '../core/model-insights.js';
|
|
22
|
+
import { accountExpiry, approverChain, personTimeline, requestTrail, revokesNotDone, TRAIL_HEADERS, trailRows } from '../core/governance-trail.js';
|
|
23
|
+
import { certificationsOverview } from '../core/certs.js';
|
|
24
|
+
import { COMPARE_KINDS, applyIgnore, compareTenants, settingKey } from '../core/compare.js';
|
|
25
|
+
import { ownershipOverview } from '../core/ownership.js';
|
|
26
|
+
import { reclaimOverview, requestInsights, roleMining, sodOverview, validateSodRules } from '../core/insights.js';
|
|
27
|
+
import { ChangeHistory, diffSnapshots, takeSnapshot } from './changes.js';
|
|
28
|
+
import { buildEvidencePack, EVIDENCE_SECTIONS } from './evidence.js';
|
|
29
|
+
import { makePack, readPack } from './packs.js';
|
|
30
|
+
import { supportFile } from './support.js';
|
|
31
|
+
import { IS_EXE, IS_NODE_BUNDLE, UPDATE_URL } from './runtime.js';
|
|
32
|
+
import { credentialsOverview, ownTokenExpiry, withoutSecrets } from '../core/credentials.js';
|
|
33
|
+
import { TransformEngine } from '../core/lab/transforms.js';
|
|
34
|
+
import { readMappings, readTransforms, runOnPeople } from '../core/lab/transform-people.js';
|
|
35
|
+
import { allStepNames, readHistory, replay, simulate } from '../core/lab/workflows.js';
|
|
36
|
+
import { credentialMap } from '../core/lab/credential-map.js';
|
|
37
|
+
import { transformImpact } from '../core/lab/transform-impact.js';
|
|
38
|
+
import { policyPreview } from '../core/lab/policy-preview.js';
|
|
39
|
+
import { listExecutions, workflowHealth } from '../core/lab/workflow-health.js';
|
|
40
|
+
import { Baselines, drift } from './drift.js';
|
|
41
|
+
import { pageList, listWarnings } from '../core/transport.js';
|
|
42
|
+
import { accessEnding, ATTRIBUTE_NAME, catalogQuality, identityGrowth, iscAdmins, levelLabel, peopleEnding, reviewerReminders, stuckOnLeavers } from '../core/warnings.js';
|
|
43
|
+
import { newAdmins, readCounts, recordCount } from './keep.js';
|
|
44
|
+
import { eachPerson, leaverWork, linkedAdminAccounts, missedJoiners, moverLeftoversStreamed, readPeople } from '../core/lifecycle-gaps.js';
|
|
45
|
+
import { joinerEvidence } from '../core/joiner-evidence.js';
|
|
46
|
+
import { acceptedFor, addException, endException, readExceptions, stateOf, validateException } from './exceptions.js';
|
|
47
|
+
import { accessOutliers, identityDataQuality, provisioningSpeed, reviewCoverage } from '../core/audit-readiness.js';
|
|
48
|
+
import { checkAllTenants, lastKnown, overviewHeadline, overviewTable, TenantRegistry } from './tenants.js';
|
|
49
|
+
import { monthlyData, monthlyHtml } from './monthly.js';
|
|
50
|
+
import { clusterHealth, consoleUrl, sourceConfiguration, sourceDiagnostic, tenantOverview } from '../core/tenant.js';
|
|
51
|
+
import { History } from './history.js';
|
|
52
|
+
import { compareRoles, criteriaProblems, getRole, roleImpact, sourceNameMap, tableResult } from '../core/roles.js';
|
|
53
|
+
import { DefinitionError, parseDefinition, toYaml, validateDefinition } from '../core/definition.js';
|
|
54
|
+
import { runReport } from '../core/engine.js';
|
|
55
|
+
import { HttpError, HttpTransport, normalizeBaseUrl } from '../core/http-transport.js';
|
|
56
|
+
import { builtinReports, builtinSource } from '../reports/library.js';
|
|
57
|
+
import { parseConfig } from './config.js';
|
|
58
|
+
import { createMailer } from './delivery.js';
|
|
59
|
+
import { runDoctor } from './doctor.js';
|
|
60
|
+
import { ALL_TENANTS_CHECK, INSTANT_CHECK, isSpecialJob, readCheckSettings, readOverviewChecks, readPeopleSettings, runJob } from './runner.js';
|
|
61
|
+
import { cronToWhen, describeWhen, disableTask, enableTask, queryTask, readLogTail, readSchedules, realExec, schedulesPath, SMTP_SECRET, validateWhen, webhookSecret, whenToCron, writeSchedules, } from './schedules.js';
|
|
62
|
+
import { appHome, mergedEnv, readSecrets, secretsStatus, writeSecrets } from './secrets.js';
|
|
63
|
+
import { checkRecipients } from './recipients.js';
|
|
64
|
+
import { exchangeCode, SignInSession, startLogin } from './oauth-login.js';
|
|
65
|
+
import { listCustom } from './loader.js';
|
|
66
|
+
import { UI_PAGE } from './ui-page.js';
|
|
67
|
+
import { fileName, MIME, render } from './write.js';
|
|
68
|
+
/** The name the demo tenant goes by on screen and in files kept on this computer. */
|
|
69
|
+
export const DEMO_TENANT = 'demo-tenant';
|
|
70
|
+
/** The job a piece of work belongs to, so every ISC request can see whether it was stopped. */
|
|
71
|
+
const jobContext = new AsyncLocalStorage();
|
|
72
|
+
class Stopped extends Error {
|
|
73
|
+
constructor() {
|
|
74
|
+
super('Stopped.');
|
|
75
|
+
this.name = 'Stopped';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** True when version a is newer than b (both x.y.z). */
|
|
79
|
+
export function newerVersion(a, b) {
|
|
80
|
+
const pa = a.split('.').map(Number);
|
|
81
|
+
const pb = b.split('.').map(Number);
|
|
82
|
+
for (let i = 0; i < 3; i++)
|
|
83
|
+
if ((pa[i] ?? 0) !== (pb[i] ?? 0))
|
|
84
|
+
return (pa[i] ?? 0) > (pb[i] ?? 0);
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
const reqWantsNow = (req) => /[?&]now=1\b/.test(req.url ?? '');
|
|
88
|
+
/** The current job's cancel signal, made on first use. */
|
|
89
|
+
function jobSignal() {
|
|
90
|
+
const j = jobContext.getStore();
|
|
91
|
+
if (!j)
|
|
92
|
+
return undefined;
|
|
93
|
+
j.abort ??= new AbortController();
|
|
94
|
+
return j.abort.signal;
|
|
95
|
+
}
|
|
96
|
+
const stoppedError = (e) => (jobContext.getStore()?.stopped ? new Stopped() : e);
|
|
97
|
+
/** Shows waits (rate limits, retries) in the current job's progress line. */
|
|
98
|
+
function noteWait(ms, reason) {
|
|
99
|
+
const j = jobContext.getStore();
|
|
100
|
+
if (!j || j.state !== 'running')
|
|
101
|
+
return;
|
|
102
|
+
const base = (j.progress ?? '').replace(/ · waiting \d+ s \(.*\)$/, '');
|
|
103
|
+
j.progress = `${base} · waiting ${Math.max(1, Math.round(ms / 1000))} s (${reason})`;
|
|
104
|
+
}
|
|
105
|
+
/** Ends the current job's work once it was stopped, including requests still waiting for ISC. */
|
|
106
|
+
const stoppable = (t) => ({
|
|
107
|
+
label: t.label,
|
|
108
|
+
request: (r) => {
|
|
109
|
+
if (jobContext.getStore()?.stopped)
|
|
110
|
+
return Promise.reject(new Stopped());
|
|
111
|
+
return t.request({ ...r, signal: r.signal ?? jobSignal() }).catch((e) => Promise.reject(stoppedError(e)));
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
const SHOWN_ROWS = 500;
|
|
115
|
+
const MAX_BODY = 2 * 1024 * 1024;
|
|
116
|
+
const ID = /^[a-z0-9][a-z0-9-]*$/;
|
|
117
|
+
class HttpProblem extends Error {
|
|
118
|
+
status;
|
|
119
|
+
constructor(status, message) {
|
|
120
|
+
super(message);
|
|
121
|
+
this.status = status;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The report screen: a small web server on this computer only (127.0.0.1).
|
|
126
|
+
* The browser page gets a random key in the address; every API call must
|
|
127
|
+
* carry it, and requests for other host names are refused, so other web sites
|
|
128
|
+
* cannot use the server. Credentials stay in this process's memory and are
|
|
129
|
+
* never sent back to the page.
|
|
130
|
+
*/
|
|
131
|
+
export async function startUiServer(opts = {}) {
|
|
132
|
+
const home = opts.home ?? appHome();
|
|
133
|
+
const baseEnv = opts.env ?? process.env;
|
|
134
|
+
const env = () => mergedEnv(baseEnv, home);
|
|
135
|
+
const exec = opts.exec ?? realExec;
|
|
136
|
+
const log0 = opts.log ?? (() => { });
|
|
137
|
+
const log = (l) => {
|
|
138
|
+
doing = l.slice(0, 200);
|
|
139
|
+
log0(l);
|
|
140
|
+
};
|
|
141
|
+
// The last errors, for the support file (redacted there).
|
|
142
|
+
const recentErrors = [];
|
|
143
|
+
const noteError = (m) => {
|
|
144
|
+
recentErrors.push(`${new Date().toISOString().slice(11, 19)} ${m}`);
|
|
145
|
+
if (recentErrors.length > 50)
|
|
146
|
+
recentErrors.shift();
|
|
147
|
+
};
|
|
148
|
+
const token = randomBytes(24).toString('base64url');
|
|
149
|
+
const reportsDir = opts.reportsDir ?? join(home, 'reports');
|
|
150
|
+
let creds;
|
|
151
|
+
let signedInAs;
|
|
152
|
+
const pendingLogins = new Map();
|
|
153
|
+
const settingsFile = join(home, 'settings.json');
|
|
154
|
+
const readSettings = () => {
|
|
155
|
+
try {
|
|
156
|
+
return JSON.parse(readFileSync(settingsFile, 'utf8'));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return {};
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
const scheduleRuns = new Map();
|
|
163
|
+
const jobs = new Map();
|
|
164
|
+
// A list ISC cut short must never pass silently: it becomes a yellow note on the result.
|
|
165
|
+
listWarnings.sink = (m) => {
|
|
166
|
+
const j = jobContext.getStore();
|
|
167
|
+
if (!j)
|
|
168
|
+
return;
|
|
169
|
+
j.warnings ??= [];
|
|
170
|
+
if (j.warnings.length < 20 && !j.warnings.includes(m))
|
|
171
|
+
j.warnings.push(m);
|
|
172
|
+
};
|
|
173
|
+
// ---------- staying alive on very large tenants ----------
|
|
174
|
+
// 1. While something runs, a small file says what it was doing. If the program dies (the window
|
|
175
|
+
// just closes), the next start can say where it stopped. Nothing about people is in it.
|
|
176
|
+
// 2. When memory is nearly full, running work is stopped with a clear message instead of a crash.
|
|
177
|
+
const activityFile = join(home, 'last-activity.json');
|
|
178
|
+
let lastCrash;
|
|
179
|
+
try {
|
|
180
|
+
if (existsSync(activityFile)) {
|
|
181
|
+
lastCrash = JSON.parse(readFileSync(activityFile, 'utf8'));
|
|
182
|
+
unlinkSync(activityFile);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
/* unreadable: ignore */
|
|
187
|
+
}
|
|
188
|
+
let doing = '';
|
|
189
|
+
let lastWritten = '';
|
|
190
|
+
const MEMORY_STOP = 'Stopped: this needs more memory than IdentityScope has on this computer. Nothing was changed. Check fewer tenants at once, or tell us which check it was (shown in the progress line).';
|
|
191
|
+
const guard = setInterval(() => {
|
|
192
|
+
const running = [...jobs.values()].filter((j) => j.state === 'running');
|
|
193
|
+
for (const j of jobs.values())
|
|
194
|
+
if (j.memoryStop && j.state === 'error' && j.error !== MEMORY_STOP)
|
|
195
|
+
j.error = MEMORY_STOP;
|
|
196
|
+
if (!running.length) {
|
|
197
|
+
if (lastWritten) {
|
|
198
|
+
lastWritten = '';
|
|
199
|
+
try {
|
|
200
|
+
unlinkSync(activityFile);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
/* already gone */
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const h = getHeapStatistics();
|
|
209
|
+
const mb = (n) => Math.round(n / 1048576);
|
|
210
|
+
const line = JSON.stringify({ at: new Date().toISOString(), doing, progress: running.map((j) => j.progress).join(' | ').slice(0, 600), memoryMB: mb(h.used_heap_size), limitMB: mb(h.heap_size_limit), version: opts.version });
|
|
211
|
+
if (line !== lastWritten) {
|
|
212
|
+
lastWritten = line;
|
|
213
|
+
try {
|
|
214
|
+
writeFileSync(activityFile, line, { mode: 0o600 });
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
/* the folder may be read-only */
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// IDENTITYSCOPE_MEMORY_STOP_MB sets the limit by hand (also used by the tests).
|
|
221
|
+
const byHand = Number(env()['IDENTITYSCOPE_MEMORY_STOP_MB']);
|
|
222
|
+
if (h.used_heap_size > (byHand > 0 ? byHand * 1048576 : 0.82 * h.heap_size_limit)) {
|
|
223
|
+
for (const j of running) {
|
|
224
|
+
j.memoryStop = true;
|
|
225
|
+
j.stopped = true;
|
|
226
|
+
j.abort?.abort();
|
|
227
|
+
}
|
|
228
|
+
noteError(`memory guard: stopped ${running.length} job(s) at ${mb(h.used_heap_size)} of ${mb(h.heap_size_limit)} MB while ${doing}`);
|
|
229
|
+
}
|
|
230
|
+
}, 1000);
|
|
231
|
+
guard.unref();
|
|
232
|
+
const evidencePacks = new Map();
|
|
233
|
+
let partnerLast;
|
|
234
|
+
let transport;
|
|
235
|
+
/** The signed-in ISC transport itself (not wrapped), whose token NERM accepts. */
|
|
236
|
+
let rawIsc;
|
|
237
|
+
let tenant;
|
|
238
|
+
// A second tenant, only for comparing configuration (in memory only).
|
|
239
|
+
let transportB;
|
|
240
|
+
let tenantB;
|
|
241
|
+
// Drop-down choices and discovered fields, per connection (cleared on connect and disconnect).
|
|
242
|
+
const lookups = new Map();
|
|
243
|
+
const cached = (key, make) => {
|
|
244
|
+
let p = lookups.get(key);
|
|
245
|
+
if (!p) {
|
|
246
|
+
p = make();
|
|
247
|
+
lookups.set(key, p);
|
|
248
|
+
p.catch(() => lookups.delete(key));
|
|
249
|
+
}
|
|
250
|
+
return p;
|
|
251
|
+
};
|
|
252
|
+
let port = 0;
|
|
253
|
+
const makeTransport = opts.transportFactory ??
|
|
254
|
+
((c) => new HttpTransport({ ...c, onWait: noteWait }));
|
|
255
|
+
const envCreds = () => {
|
|
256
|
+
const e = env();
|
|
257
|
+
const baseUrl = e['ISC_BASE_URL'] ?? e['ISC_TENANT'] ?? e['SAIL_BASE_URL'];
|
|
258
|
+
const clientId = e['ISC_CLIENT_ID'] ?? e['SAIL_CLIENT_ID'];
|
|
259
|
+
const clientSecret = e['ISC_CLIENT_SECRET'] ?? e['SAIL_CLIENT_SECRET'];
|
|
260
|
+
return { baseUrl, clientId, clientSecret };
|
|
261
|
+
};
|
|
262
|
+
const allReports = () => {
|
|
263
|
+
const custom = listCustom(reportsDir).map((r) => ({ definition: r.definition, custom: true, yaml: readFileSync(r.file, 'utf8') }));
|
|
264
|
+
const builtin = builtinReports().map((d) => ({ definition: d, custom: false, yaml: builtinSource(d.id) ?? toYaml(d) }));
|
|
265
|
+
return [...custom, ...builtin];
|
|
266
|
+
};
|
|
267
|
+
const findReport = (id) => allReports().find((r) => r.definition.id === id);
|
|
268
|
+
// Every call this screen makes to ISC is counted and shown in the header.
|
|
269
|
+
let apiCalls = 0;
|
|
270
|
+
let apiBase;
|
|
271
|
+
const counted = (t) => ({
|
|
272
|
+
label: t.label,
|
|
273
|
+
request: (r) => {
|
|
274
|
+
if (jobContext.getStore()?.stopped)
|
|
275
|
+
return Promise.reject(new Stopped());
|
|
276
|
+
apiCalls++;
|
|
277
|
+
return t.request({ ...r, signal: r.signal ?? jobSignal() }).catch((e) => Promise.reject(stoppedError(e)));
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
const diagnosticsOn = () => readSettings().diagnostics === true;
|
|
281
|
+
const send = (res, status, data) => {
|
|
282
|
+
const body = JSON.stringify(data);
|
|
283
|
+
res.writeHead(status, {
|
|
284
|
+
'x-isc-api-calls': String(apiCalls),
|
|
285
|
+
'content-type': 'application/json; charset=utf-8',
|
|
286
|
+
'cache-control': 'no-store',
|
|
287
|
+
'x-content-type-options': 'nosniff',
|
|
288
|
+
});
|
|
289
|
+
res.end(body);
|
|
290
|
+
};
|
|
291
|
+
const readJson = async (req) => {
|
|
292
|
+
const chunks = [];
|
|
293
|
+
let size = 0;
|
|
294
|
+
for await (const c of req) {
|
|
295
|
+
size += c.length;
|
|
296
|
+
if (size > MAX_BODY)
|
|
297
|
+
throw new HttpProblem(413, 'Request too large');
|
|
298
|
+
chunks.push(c);
|
|
299
|
+
}
|
|
300
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
301
|
+
if (text === '')
|
|
302
|
+
return {};
|
|
303
|
+
try {
|
|
304
|
+
const v = JSON.parse(text);
|
|
305
|
+
if (v === null || typeof v !== 'object' || Array.isArray(v))
|
|
306
|
+
throw new Error();
|
|
307
|
+
return v;
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
throw new HttpProblem(400, 'Invalid JSON');
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
const keyOk = (given) => {
|
|
314
|
+
if (!given)
|
|
315
|
+
return false;
|
|
316
|
+
const a = Buffer.from(given);
|
|
317
|
+
const b = Buffer.from(token);
|
|
318
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
319
|
+
};
|
|
320
|
+
const definitionFrom = (body) => {
|
|
321
|
+
if (typeof body['yaml'] === 'string')
|
|
322
|
+
return parseDefinition(body['yaml'], 'the YAML');
|
|
323
|
+
if (body['definition'] && typeof body['definition'] === 'object') {
|
|
324
|
+
const problems = validateDefinition(body['definition']);
|
|
325
|
+
if (problems.length)
|
|
326
|
+
throw new DefinitionError('The report has problems', problems);
|
|
327
|
+
return body['definition'];
|
|
328
|
+
}
|
|
329
|
+
if (typeof body['id'] === 'string') {
|
|
330
|
+
const r = findReport(body['id']);
|
|
331
|
+
if (!r)
|
|
332
|
+
throw new HttpProblem(404, `Unknown report "${body['id']}"`);
|
|
333
|
+
return r.definition;
|
|
334
|
+
}
|
|
335
|
+
throw new HttpProblem(400, 'Give a report id, definition or yaml');
|
|
336
|
+
};
|
|
337
|
+
// Demo mode: a made-up tenant served from inside this program, so the tool can be tried without
|
|
338
|
+
// connecting anything. It listens on this computer only and is stopped on disconnect.
|
|
339
|
+
let demo;
|
|
340
|
+
const stopDemo = async () => {
|
|
341
|
+
const d = demo;
|
|
342
|
+
demo = undefined;
|
|
343
|
+
if (d)
|
|
344
|
+
await d.close().catch(() => undefined);
|
|
345
|
+
};
|
|
346
|
+
const startDemo = async () => {
|
|
347
|
+
await stopDemo();
|
|
348
|
+
// The made-up data is dated relative to this moment (see demo/tenant.ts).
|
|
349
|
+
if (!process.env['IDENTITYSCOPE_DEMO_NOW'])
|
|
350
|
+
process.env['IDENTITYSCOPE_DEMO_NOW'] = new Date().toISOString();
|
|
351
|
+
const { startMockIsc } = await import('../demo/tenant.js');
|
|
352
|
+
const d = await startMockIsc({ keepLog: false });
|
|
353
|
+
try {
|
|
354
|
+
await connect({ baseUrl: d.url, clientId: 'test-client', clientSecret: 'test-secret' }, true);
|
|
355
|
+
}
|
|
356
|
+
catch (e) {
|
|
357
|
+
await d.close().catch(() => undefined);
|
|
358
|
+
throw e;
|
|
359
|
+
}
|
|
360
|
+
demo = d;
|
|
361
|
+
tenant = DEMO_TENANT;
|
|
362
|
+
log('connected to the demo tenant (made-up data)');
|
|
363
|
+
};
|
|
364
|
+
const connect = async (c, forDemo = false) => {
|
|
365
|
+
if (!forDemo)
|
|
366
|
+
await stopDemo();
|
|
367
|
+
if (!c.baseUrl || !c.clientId || !c.clientSecret)
|
|
368
|
+
throw new HttpProblem(400, 'Enter the tenant, client ID and client secret.');
|
|
369
|
+
let t;
|
|
370
|
+
try {
|
|
371
|
+
t = makeTransport({ baseUrl: c.baseUrl, clientId: c.clientId, clientSecret: c.clientSecret });
|
|
372
|
+
}
|
|
373
|
+
catch (e) {
|
|
374
|
+
throw new HttpProblem(400, e.message);
|
|
375
|
+
}
|
|
376
|
+
try {
|
|
377
|
+
await t.request({ method: 'GET', path: '/sources/v1', query: { limit: 1 } });
|
|
378
|
+
}
|
|
379
|
+
catch (e) {
|
|
380
|
+
if (e instanceof HttpError && e.status === 403) {
|
|
381
|
+
// Signed in, but this token cannot read sources; reports on other data can still work.
|
|
382
|
+
}
|
|
383
|
+
else if (e instanceof HttpError && e.status === 401) {
|
|
384
|
+
throw new HttpProblem(401, 'Sign-in failed. Check the client ID and secret, and that the token has not expired.');
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
throw new HttpProblem(502, e.message.replace(/Sign-in to (\S+) failed \(HTTP 401\)\./, 'Sign-in failed.'));
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
transport = counted(t);
|
|
391
|
+
rawIsc = t instanceof HttpTransport ? t : undefined;
|
|
392
|
+
tenant = t.label;
|
|
393
|
+
apiBase = normalizeBaseUrl(c.baseUrl);
|
|
394
|
+
signedInAs = undefined;
|
|
395
|
+
lookups.clear();
|
|
396
|
+
creds = { baseUrl: c.baseUrl, clientId: c.clientId, clientSecret: c.clientSecret };
|
|
397
|
+
log(`connected to ${tenant}`);
|
|
398
|
+
};
|
|
399
|
+
const api = async (req, res, url) => {
|
|
400
|
+
const route = `${req.method} ${url.pathname}`;
|
|
401
|
+
const need = () => {
|
|
402
|
+
if (!transport)
|
|
403
|
+
throw new HttpProblem(409, 'Connect to a tenant first.');
|
|
404
|
+
return transport;
|
|
405
|
+
};
|
|
406
|
+
if (route === 'GET /api/last-crash')
|
|
407
|
+
return send(res, 200, { crash: lastCrash ?? null });
|
|
408
|
+
if (route === 'POST /api/last-crash/dismiss') {
|
|
409
|
+
lastCrash = undefined;
|
|
410
|
+
return send(res, 200, {});
|
|
411
|
+
}
|
|
412
|
+
if (route === 'GET /api/state') {
|
|
413
|
+
const e = envCreds();
|
|
414
|
+
return send(res, 200, {
|
|
415
|
+
version: opts.version ?? '',
|
|
416
|
+
connected: Boolean(transport),
|
|
417
|
+
tenant,
|
|
418
|
+
demo: Boolean(demo),
|
|
419
|
+
reportsDir,
|
|
420
|
+
remembered: Boolean(readSecrets(home)['ISC_CLIENT_SECRET']),
|
|
421
|
+
signedInAs,
|
|
422
|
+
consoleUrl: apiBase && !demo ? consoleUrl(apiBase) : null,
|
|
423
|
+
compareWith: tenantB ?? null,
|
|
424
|
+
apiCalls,
|
|
425
|
+
diagnostics: diagnosticsOn(),
|
|
426
|
+
signIn: { ...(readSettings().signIn ?? {}), redirectUri: `http://localhost:${port}/callback` },
|
|
427
|
+
windows: process.platform === 'win32' || opts.exec !== undefined,
|
|
428
|
+
saved: { baseUrl: e.baseUrl ?? '', hasCredentials: Boolean(e.baseUrl && e.clientId && e.clientSecret) },
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
if (route === 'POST /api/demo/start') {
|
|
432
|
+
await startDemo();
|
|
433
|
+
return send(res, 200, { connected: true, tenant, demo: true });
|
|
434
|
+
}
|
|
435
|
+
if (route === 'POST /api/connect') {
|
|
436
|
+
const b = await readJson(req);
|
|
437
|
+
if (b['useSaved'] === true)
|
|
438
|
+
await connect(envCreds());
|
|
439
|
+
else
|
|
440
|
+
await connect({
|
|
441
|
+
baseUrl: String(b['baseUrl'] ?? '').trim(),
|
|
442
|
+
clientId: String(b['clientId'] ?? '').trim(),
|
|
443
|
+
clientSecret: String(b['clientSecret'] ?? '').trim(),
|
|
444
|
+
});
|
|
445
|
+
return send(res, 200, { connected: true, tenant });
|
|
446
|
+
}
|
|
447
|
+
if (route === 'POST /api/login/start') {
|
|
448
|
+
const b = await readJson(req);
|
|
449
|
+
const baseUrl = String(b['baseUrl'] ?? '').trim();
|
|
450
|
+
const clientId = String(b['clientId'] ?? '').trim();
|
|
451
|
+
const clientSecret = String(b['clientSecret'] ?? '').trim() || undefined;
|
|
452
|
+
if (!baseUrl || !clientId)
|
|
453
|
+
throw new HttpProblem(400, 'Enter the tenant and the OAuth client ID.');
|
|
454
|
+
let p;
|
|
455
|
+
try {
|
|
456
|
+
p = await startLogin({ baseUrl, clientId, clientSecret, redirectUri: `http://localhost:${port}/callback` }, opts.fetch);
|
|
457
|
+
}
|
|
458
|
+
catch (e) {
|
|
459
|
+
throw new HttpProblem(400, e.message);
|
|
460
|
+
}
|
|
461
|
+
for (const [k, v] of pendingLogins)
|
|
462
|
+
if (Date.now() - v.created > 10 * 60_000)
|
|
463
|
+
pendingLogins.delete(k);
|
|
464
|
+
pendingLogins.set(p.state, p);
|
|
465
|
+
mkdirSync(home, { recursive: true });
|
|
466
|
+
writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), signIn: { baseUrl, clientId } }, null, 2));
|
|
467
|
+
return send(res, 200, { authorizeUrl: p.authorizeUrl });
|
|
468
|
+
}
|
|
469
|
+
if (route === 'POST /api/remember') {
|
|
470
|
+
const b = await readJson(req);
|
|
471
|
+
if (b['remember'] === false) {
|
|
472
|
+
writeSecrets({ ISC_BASE_URL: undefined, ISC_CLIENT_ID: undefined, ISC_CLIENT_SECRET: undefined }, home);
|
|
473
|
+
return send(res, 200, { remembered: false });
|
|
474
|
+
}
|
|
475
|
+
if (demo)
|
|
476
|
+
throw new HttpProblem(400, 'This is the demo tenant; there is nothing to remember. Connect to your own tenant first.');
|
|
477
|
+
if (!creds && signedInAs !== undefined) {
|
|
478
|
+
throw new HttpProblem(400, 'Automatic runs cannot use a sign-in, because sign-ins expire. Connect with a personal access token of a reporting identity, then remember it.');
|
|
479
|
+
}
|
|
480
|
+
if (!creds)
|
|
481
|
+
throw new HttpProblem(409, 'Connect first.');
|
|
482
|
+
writeSecrets({ ISC_BASE_URL: creds.baseUrl, ISC_CLIENT_ID: creds.clientId, ISC_CLIENT_SECRET: creds.clientSecret }, home);
|
|
483
|
+
return send(res, 200, { remembered: true });
|
|
484
|
+
}
|
|
485
|
+
if (route.startsWith('GET /api/schedules') || route.startsWith('PUT /api/schedules') || route.startsWith('POST /api/schedules') || route.startsWith('DELETE /api/schedules')) {
|
|
486
|
+
return schedulesApi(req, res, route);
|
|
487
|
+
}
|
|
488
|
+
const pick = /^GET \/api\/pick\/(sources|roles|accessProfiles)$/.exec(route);
|
|
489
|
+
if (pick) {
|
|
490
|
+
const t = need();
|
|
491
|
+
const kind = pick[1];
|
|
492
|
+
try {
|
|
493
|
+
return send(res, 200, { options: await cached(`pick:${kind}`, () => pickOptions(t, kind)) });
|
|
494
|
+
}
|
|
495
|
+
catch (e) {
|
|
496
|
+
throw new HttpProblem(e instanceof HttpError && e.status === 403 ? 403 : 502, `Could not read the list of ${kind === 'accessProfiles' ? 'access profiles' : kind}: ${e.message}`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const disc = /^GET \/api\/discover\/([A-Za-z]+)$/.exec(route);
|
|
500
|
+
if (disc) {
|
|
501
|
+
const t = need();
|
|
502
|
+
const ds = disc[1];
|
|
503
|
+
if (!(ds in DATASETS))
|
|
504
|
+
throw new HttpProblem(404, 'Unknown dataset');
|
|
505
|
+
try {
|
|
506
|
+
return send(res, 200, await cached(`discover:${ds}`, () => discoverFields(t, ds)));
|
|
507
|
+
}
|
|
508
|
+
catch (e) {
|
|
509
|
+
throw new HttpProblem(e instanceof HttpError && e.status === 403 ? 403 : 502, `Could not read sample ${DATASETS[ds].label.toLowerCase()}: ${e.message}`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (route === 'POST /api/disconnect') {
|
|
513
|
+
await stopDemo();
|
|
514
|
+
lookups.clear();
|
|
515
|
+
transportB = undefined;
|
|
516
|
+
tenantB = undefined;
|
|
517
|
+
transport = undefined;
|
|
518
|
+
rawIsc = undefined;
|
|
519
|
+
tenant = undefined;
|
|
520
|
+
creds = undefined;
|
|
521
|
+
signedInAs = undefined;
|
|
522
|
+
jobs.clear();
|
|
523
|
+
return send(res, 200, { connected: false });
|
|
524
|
+
}
|
|
525
|
+
if (route === 'GET /api/reports') {
|
|
526
|
+
return send(res, 200, allReports().map((r) => ({ ...r })));
|
|
527
|
+
}
|
|
528
|
+
if (route === 'GET /api/catalog') {
|
|
529
|
+
return send(res, 200, { datasets: Object.values(DATASETS), operators: OPERATORS });
|
|
530
|
+
}
|
|
531
|
+
if (route === 'POST /api/yaml') {
|
|
532
|
+
const b = await readJson(req);
|
|
533
|
+
return send(res, 200, { yaml: toYaml(b['definition']), problems: validateDefinition(b['definition']) });
|
|
534
|
+
}
|
|
535
|
+
if (route === 'POST /api/parse') {
|
|
536
|
+
const b = await readJson(req);
|
|
537
|
+
return send(res, 200, { definition: parseDefinition(String(b['yaml'] ?? ''), 'the YAML') });
|
|
538
|
+
}
|
|
539
|
+
if (route === 'POST /api/reports') {
|
|
540
|
+
const b = await readJson(req);
|
|
541
|
+
const def = definitionFrom(b);
|
|
542
|
+
if (builtinReports().some((d) => d.id === def.id)) {
|
|
543
|
+
throw new HttpProblem(400, `"${def.id}" is a built-in report. Give your copy another ID.`);
|
|
544
|
+
}
|
|
545
|
+
if (!ID.test(def.id))
|
|
546
|
+
throw new HttpProblem(400, 'The report ID may only use lowercase letters, digits and dashes.');
|
|
547
|
+
mkdirSync(reportsDir, { recursive: true });
|
|
548
|
+
writeFileSync(join(reportsDir, `${def.id}.yaml`), typeof b['yaml'] === 'string' ? b['yaml'] : toYaml(def));
|
|
549
|
+
return send(res, 200, { saved: def.id });
|
|
550
|
+
}
|
|
551
|
+
const del = /^DELETE \/api\/reports\/([a-z0-9-]+)$/.exec(route);
|
|
552
|
+
if (del) {
|
|
553
|
+
const file = join(reportsDir, `${del[1]}.yaml`);
|
|
554
|
+
if (!existsSync(file))
|
|
555
|
+
throw new HttpProblem(404, 'Only reports you saved can be deleted.');
|
|
556
|
+
unlinkSync(file);
|
|
557
|
+
return send(res, 200, { deleted: del[1] });
|
|
558
|
+
}
|
|
559
|
+
if (route === 'POST /api/run') {
|
|
560
|
+
const t = need();
|
|
561
|
+
const b = await readJson(req);
|
|
562
|
+
const def = definitionFrom(b);
|
|
563
|
+
const params = (b['params'] && typeof b['params'] === 'object' ? b['params'] : {});
|
|
564
|
+
for (const k of Object.keys(params))
|
|
565
|
+
if (params[k] === '' || params[k] === null)
|
|
566
|
+
delete params[k];
|
|
567
|
+
const preview = typeof b['preview'] === 'number' && b['preview'] > 0 ? b['preview'] : undefined;
|
|
568
|
+
const groupBy = Array.isArray(b['groupBy']) ? b['groupBy'].filter((x) => typeof x === 'string' && x !== '') : undefined;
|
|
569
|
+
const id = randomBytes(8).toString('hex');
|
|
570
|
+
const job = { id, state: 'running', progress: 'Starting...', started: Date.now() };
|
|
571
|
+
jobs.set(id, job);
|
|
572
|
+
while (jobs.size > 20)
|
|
573
|
+
jobs.delete(jobs.keys().next().value);
|
|
574
|
+
log(`running ${def.id}`);
|
|
575
|
+
jobContext.run(job, () => runReport(def, {
|
|
576
|
+
transport: t,
|
|
577
|
+
params,
|
|
578
|
+
previewLimit: preview,
|
|
579
|
+
groupBy: groupBy && groupBy.length ? groupBy : undefined,
|
|
580
|
+
onProgress: (m) => (job.progress = m),
|
|
581
|
+
})).then((result) => {
|
|
582
|
+
job.result = result;
|
|
583
|
+
job.state = 'done';
|
|
584
|
+
}, (e) => {
|
|
585
|
+
job.error = e.problems ? `${e.message.split('\n')[0]}\n${e.problems.join('\n')}` : e.message;
|
|
586
|
+
job.state = 'error';
|
|
587
|
+
});
|
|
588
|
+
return send(res, 202, { job: id });
|
|
589
|
+
}
|
|
590
|
+
// ---------- instant check ----------
|
|
591
|
+
if (route === 'GET /api/checks') {
|
|
592
|
+
const settings = readCheckSettings(home);
|
|
593
|
+
return send(res, 200, {
|
|
594
|
+
checks: CHECKS.map((c) => ({ id: c.id, label: c.label, description: c.description, unit: c.unit, report: c.report, growth: c.growth === true, optIn: c.optIn === true, defaults: c.defaults, settings: settings[c.id] ?? {} })),
|
|
595
|
+
trends: transport && tenant ? new History(join(home, 'history.json')).trends(tenant) : {},
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
if (route === 'PUT /api/checks/settings') {
|
|
599
|
+
const b = await readJson(req);
|
|
600
|
+
const input = (b['checks'] && typeof b['checks'] === 'object' ? b['checks'] : {});
|
|
601
|
+
const problems = [];
|
|
602
|
+
const out = {};
|
|
603
|
+
const whole = (v, min, max) => typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max;
|
|
604
|
+
for (const c of CHECKS) {
|
|
605
|
+
const v = input[c.id];
|
|
606
|
+
if (!v)
|
|
607
|
+
continue;
|
|
608
|
+
const one = {};
|
|
609
|
+
if (v['enabled'] === false)
|
|
610
|
+
one.enabled = false;
|
|
611
|
+
else if (v['enabled'] === true && c.optIn)
|
|
612
|
+
one.enabled = true;
|
|
613
|
+
if (v['warn'] !== undefined)
|
|
614
|
+
whole(v['warn'], 1, 1e9) ? (one.warn = v['warn']) : problems.push(`${c.label}: the amber limit must be a whole number of at least 1`);
|
|
615
|
+
if (v['bad'] !== undefined)
|
|
616
|
+
whole(v['bad'], 1, 1e9) ? (one.bad = v['bad']) : problems.push(`${c.label}: the red limit must be a whole number of at least 1`);
|
|
617
|
+
if ((one.bad ?? c.defaults.bad) < (one.warn ?? c.defaults.warn))
|
|
618
|
+
problems.push(`${c.label}: the red limit must not be lower than the amber limit`);
|
|
619
|
+
if (v['days'] !== undefined && c.defaults.days !== undefined)
|
|
620
|
+
whole(v['days'], 1, 365) ? (one.days = v['days']) : problems.push(`${c.label}: days must be 1 to 365`);
|
|
621
|
+
out[c.id] = one;
|
|
622
|
+
}
|
|
623
|
+
if (problems.length)
|
|
624
|
+
throw new DefinitionError('Some limits are not valid', problems);
|
|
625
|
+
writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), checks: out }, null, 2));
|
|
626
|
+
return send(res, 200, { saved: true });
|
|
627
|
+
}
|
|
628
|
+
if (route === 'POST /api/checks/run') {
|
|
629
|
+
const t = need();
|
|
630
|
+
const b = await readJson(req);
|
|
631
|
+
const tenantKey = tenant ?? 'tenant';
|
|
632
|
+
const history = new History(join(home, 'history.json'));
|
|
633
|
+
const id = randomBytes(8).toString('hex');
|
|
634
|
+
const job = { id, state: 'running', progress: 'Starting the checks...', started: Date.now() };
|
|
635
|
+
jobs.set(id, job);
|
|
636
|
+
while (jobs.size > 20)
|
|
637
|
+
jobs.delete(jobs.keys().next().value);
|
|
638
|
+
const only = Array.isArray(b['only']) ? b['only'].map(String) : undefined;
|
|
639
|
+
log('running the instant check');
|
|
640
|
+
jobContext.run(job, () => runChecks({
|
|
641
|
+
transport: t,
|
|
642
|
+
loadReport: (rid) => {
|
|
643
|
+
const r = findReport(rid);
|
|
644
|
+
if (!r)
|
|
645
|
+
throw new Error(`Report ${rid} is missing`);
|
|
646
|
+
return r.definition;
|
|
647
|
+
},
|
|
648
|
+
settings: readCheckSettings(home),
|
|
649
|
+
people: readPeopleSettings(home),
|
|
650
|
+
accepted: acceptedFor(home, tenantKey, opts.now?.()),
|
|
651
|
+
previous: history.previousChecks(tenantKey),
|
|
652
|
+
only,
|
|
653
|
+
onProgress: (m) => (job.progress = m),
|
|
654
|
+
})).then((results) => {
|
|
655
|
+
if (job.stopped) {
|
|
656
|
+
job.error = 'Stopped. Nothing was saved from this check.';
|
|
657
|
+
job.state = 'error';
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
history.recordChecks(tenantKey, results);
|
|
661
|
+
job.result = checksTable(results, job.started, tenantKey);
|
|
662
|
+
job.extra = { results: results.map(({ keys: _k, ...r }) => r), headline: checksHeadline(results) };
|
|
663
|
+
job.state = 'done';
|
|
664
|
+
}, (e) => {
|
|
665
|
+
job.error = e.message;
|
|
666
|
+
job.state = 'error';
|
|
667
|
+
});
|
|
668
|
+
return send(res, 202, { job: id });
|
|
669
|
+
}
|
|
670
|
+
// ---------- background work with a downloadable table ----------
|
|
671
|
+
const background = (label, work) => {
|
|
672
|
+
const id = randomBytes(8).toString('hex');
|
|
673
|
+
const job = { id, state: 'running', progress: 'Starting...', started: Date.now() };
|
|
674
|
+
jobs.set(id, job);
|
|
675
|
+
while (jobs.size > 20)
|
|
676
|
+
jobs.delete(jobs.keys().next().value);
|
|
677
|
+
log(label);
|
|
678
|
+
jobContext.run(job, () => work((m) => (job.progress = m))).then((r) => {
|
|
679
|
+
if (job.stopped) {
|
|
680
|
+
job.error = 'Stopped.';
|
|
681
|
+
job.state = 'error';
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
job.result = r.table;
|
|
685
|
+
job.extra = r.extra;
|
|
686
|
+
job.state = 'done';
|
|
687
|
+
}, (e) => {
|
|
688
|
+
job.error = e.status === 403 ? 'No permission with the current sign-in or token.' : e.message;
|
|
689
|
+
job.state = 'error';
|
|
690
|
+
});
|
|
691
|
+
return id;
|
|
692
|
+
};
|
|
693
|
+
if (route === 'POST /api/certifications/run') {
|
|
694
|
+
const t = need();
|
|
695
|
+
const b = await readJson(req);
|
|
696
|
+
const days = Math.min(365, Math.max(7, Number(b['days']) || 90));
|
|
697
|
+
return send(res, 202, {
|
|
698
|
+
job: background('reading certifications', async (progress) => {
|
|
699
|
+
const o = await certificationsOverview(t, { days, items: b['items'] !== false, onProgress: progress });
|
|
700
|
+
const rows = o.reviewers.map((r) => [r.name, r.campaigns.join(', '), r.certifications, r.decisionsMade, r.decisionsTotal, r.approved, r.revoked, r.approveRate, r.overdueOpen]);
|
|
701
|
+
return { extra: o, table: tableResult('Certification reviewers', ['Reviewer', 'Campaigns', 'Reviews', 'Decisions made', 'Decisions total', 'Approved', 'Revoked', 'Approve %', 'Overdue reviews'], rows, Date.now()) };
|
|
702
|
+
}),
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
if (route === 'POST /api/ownership/run') {
|
|
706
|
+
const t = need();
|
|
707
|
+
return send(res, 202, {
|
|
708
|
+
job: background('reading ownership', async (progress) => {
|
|
709
|
+
const o = await ownershipOverview(t, progress);
|
|
710
|
+
const rows = o.orphaned.map((x) => [x.type, x.name, x.source ?? null, x.ownerName ?? null, x.ownerStatus === 'not found' ? 'no longer in ISC' : x.ownerStatus, x.lifecycleState ?? null]);
|
|
711
|
+
const { objects, ...rest } = o;
|
|
712
|
+
return { extra: { ...rest, objects }, table: tableResult('Objects owned by people who left', ['Type', 'Object', 'Source', 'Owner', 'Owner status', 'Owner lifecycle state'], rows, Date.now(), o.notes) };
|
|
713
|
+
}),
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
if (route === 'POST /api/compare/connect') {
|
|
717
|
+
const b = await readJson(req);
|
|
718
|
+
const c = { baseUrl: String(b['baseUrl'] ?? '').trim(), clientId: String(b['clientId'] ?? '').trim(), clientSecret: String(b['clientSecret'] ?? '').trim() };
|
|
719
|
+
if (!c.baseUrl || !c.clientId || !c.clientSecret)
|
|
720
|
+
throw new HttpProblem(400, 'Enter the other tenant, client ID and client secret.');
|
|
721
|
+
let t2;
|
|
722
|
+
try {
|
|
723
|
+
t2 = makeTransport(c);
|
|
724
|
+
await t2.request({ method: 'GET', path: '/sources/v1', query: { limit: 1 } });
|
|
725
|
+
}
|
|
726
|
+
catch (e) {
|
|
727
|
+
if (!(e instanceof HttpError && e.status === 403))
|
|
728
|
+
throw new HttpProblem(e instanceof HttpError && e.status === 401 ? 401 : 400, e.message);
|
|
729
|
+
t2 = makeTransport(c);
|
|
730
|
+
}
|
|
731
|
+
if (t2.label && t2.label === tenant)
|
|
732
|
+
throw new HttpProblem(400, 'That is the tenant you are already connected to. Connect the other one (for example production).');
|
|
733
|
+
transportB = counted(t2);
|
|
734
|
+
tenantB = t2.label;
|
|
735
|
+
log(`connected to ${tenantB} for comparison`);
|
|
736
|
+
return send(res, 200, { tenant: tenantB });
|
|
737
|
+
}
|
|
738
|
+
if (route === 'POST /api/compare/disconnect') {
|
|
739
|
+
transportB = undefined;
|
|
740
|
+
tenantB = undefined;
|
|
741
|
+
return send(res, 200, { ok: true });
|
|
742
|
+
}
|
|
743
|
+
// Settings the user chose to ignore when comparing tenants ("kind|setting"), kept on this computer.
|
|
744
|
+
const ignoreFile = join(home, 'compare-ignore.json');
|
|
745
|
+
const readIgnore = () => {
|
|
746
|
+
try {
|
|
747
|
+
const v = JSON.parse(readFileSync(ignoreFile, 'utf8'));
|
|
748
|
+
return Array.isArray(v) ? v.map(String).slice(0, 500) : [];
|
|
749
|
+
}
|
|
750
|
+
catch {
|
|
751
|
+
return [];
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
if (route === 'GET /api/compare')
|
|
755
|
+
return send(res, 200, { tenant, other: tenantB ?? null, kinds: COMPARE_KINDS.filter((k) => !k.optIn), ignore: readIgnore() });
|
|
756
|
+
if (route === 'POST /api/compare/ignore') {
|
|
757
|
+
const b = await readJson(req);
|
|
758
|
+
const kind = String(b['kind'] ?? '');
|
|
759
|
+
if (!COMPARE_KINDS.some((k) => k.kind === kind))
|
|
760
|
+
throw new HttpProblem(400, 'Unknown kind.');
|
|
761
|
+
const key = `${kind}|${settingKey(String(b['setting'] ?? '')).slice(0, 300)}`;
|
|
762
|
+
const list = readIgnore().filter((x) => x !== key);
|
|
763
|
+
if (b['ignore'] !== false)
|
|
764
|
+
list.push(key);
|
|
765
|
+
mkdirSync(home, { recursive: true });
|
|
766
|
+
writeFileSync(ignoreFile, JSON.stringify(list, null, 2), { mode: 0o600 });
|
|
767
|
+
return send(res, 200, { ignore: list });
|
|
768
|
+
}
|
|
769
|
+
if (route === 'POST /api/compare/run') {
|
|
770
|
+
const t = need();
|
|
771
|
+
if (!transportB)
|
|
772
|
+
throw new HttpProblem(400, 'Connect the other tenant first.');
|
|
773
|
+
const t2 = transportB;
|
|
774
|
+
const b = await readJson(req);
|
|
775
|
+
const plain = COMPARE_KINDS.filter((k) => !k.optIn);
|
|
776
|
+
const kinds = (Array.isArray(b['kinds']) ? b['kinds'] : plain.map((k) => k.kind)).map(String).filter((k) => plain.some((x) => x.kind === k));
|
|
777
|
+
// Cloud rule code only when the user turned it on: it starts an SP-Config export job of rules in each tenant.
|
|
778
|
+
if (b['cloudRuleCode'] === true)
|
|
779
|
+
kinds.push('cloudRules');
|
|
780
|
+
const [la, lb] = [tenant ?? 'this tenant', tenantB ?? 'other tenant'];
|
|
781
|
+
return send(res, 202, {
|
|
782
|
+
job: background('comparing tenants', async (progress) => {
|
|
783
|
+
const ignored = readIgnore();
|
|
784
|
+
const r = applyIgnore(await compareTenants(t, t2, kinds, progress), new Set(ignored));
|
|
785
|
+
const rows = [];
|
|
786
|
+
for (const k of r) {
|
|
787
|
+
for (const n of k.onlyA)
|
|
788
|
+
rows.push([k.label, n, `only in ${la}`, null, null, null]);
|
|
789
|
+
for (const n of k.onlyB)
|
|
790
|
+
rows.push([k.label, n, `only in ${lb}`, null, null, null]);
|
|
791
|
+
for (const d of k.different)
|
|
792
|
+
for (const x of d.differences)
|
|
793
|
+
rows.push([k.label, d.name, 'different', x.path, x.a, x.b]);
|
|
794
|
+
}
|
|
795
|
+
return { extra: { a: la, b: lb, kinds: r, ignored }, table: tableResult(`Tenant comparison: ${la} vs ${lb}`, ['Type', 'Object', 'Result', 'Setting', la, lb], rows, Date.now(), ignored.length ? [`Settings ignored (chosen on the compare screen): ${ignored.map((x) => x.replace('|', ': ')).join(', ')}`] : []) };
|
|
796
|
+
}),
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
// ---------- partner overview: many customer tenants ----------
|
|
800
|
+
const registry = () => new TenantRegistry(home);
|
|
801
|
+
const testTenant = async (c) => {
|
|
802
|
+
let t;
|
|
803
|
+
try {
|
|
804
|
+
t = makeTransport(c);
|
|
805
|
+
}
|
|
806
|
+
catch (e) {
|
|
807
|
+
throw new HttpProblem(400, e.message);
|
|
808
|
+
}
|
|
809
|
+
try {
|
|
810
|
+
await t.request({ method: 'GET', path: '/sources/v1', query: { limit: 1 } });
|
|
811
|
+
}
|
|
812
|
+
catch (e) {
|
|
813
|
+
if (e instanceof HttpError && e.status === 403)
|
|
814
|
+
return 'Connected, but this token cannot read sources; some checks will show "no permission".';
|
|
815
|
+
if (e instanceof HttpError && e.status === 401)
|
|
816
|
+
throw new HttpProblem(400, 'Sign-in failed. Check the client ID and secret, and that the token has not expired.');
|
|
817
|
+
throw new HttpProblem(400, `Could not reach the tenant: ${e.message.split('\n')[0]}`);
|
|
818
|
+
}
|
|
819
|
+
return undefined;
|
|
820
|
+
};
|
|
821
|
+
if (route === 'GET /api/tenants') {
|
|
822
|
+
const r = registry();
|
|
823
|
+
const history = new History(join(home, 'history.json'));
|
|
824
|
+
return send(res, 200, {
|
|
825
|
+
tenants: r.list().map((t) => ({ ...t, hasSecret: r.hasSecret(t.id) })),
|
|
826
|
+
lastKnown: lastKnown(r, history),
|
|
827
|
+
lastRun: partnerLast,
|
|
828
|
+
checks: CHECKS.filter((c) => readOverviewChecks(home).includes(c.id)).map((c) => ({ id: c.id, label: c.label, unit: c.unit })),
|
|
829
|
+
allChecks: CHECKS.map((c) => ({ id: c.id, label: c.label, quick: OVERVIEW_DEFAULT.includes(c.id) })),
|
|
830
|
+
connectedTo: tenant ?? null,
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
if (route === 'PUT /api/tenants/checks') {
|
|
834
|
+
const b = await readJson(req);
|
|
835
|
+
const known = new Set(CHECKS.map((c) => c.id));
|
|
836
|
+
const ids = (Array.isArray(b['ids']) ? b['ids'] : []).map(String).filter((x) => known.has(x));
|
|
837
|
+
if (!ids.length)
|
|
838
|
+
throw new HttpProblem(400, 'Pick at least one check.');
|
|
839
|
+
const same = ids.length === OVERVIEW_DEFAULT.length && OVERVIEW_DEFAULT.every((x) => ids.includes(x));
|
|
840
|
+
writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), overviewChecks: same ? undefined : ids }, null, 2));
|
|
841
|
+
return send(res, 200, { checks: readOverviewChecks(home) });
|
|
842
|
+
}
|
|
843
|
+
if (route === 'POST /api/tenants') {
|
|
844
|
+
const b = await readJson(req);
|
|
845
|
+
const input = { name: String(b['name'] ?? ''), baseUrl: String(b['baseUrl'] ?? '').trim(), clientId: String(b['clientId'] ?? '').trim(), clientSecret: String(b['clientSecret'] ?? '').trim(), notes: b['notes'] === undefined ? undefined : String(b['notes']) };
|
|
846
|
+
if (!input.baseUrl || !input.clientId || !input.clientSecret)
|
|
847
|
+
throw new HttpProblem(400, 'Enter the tenant, client ID and client secret.');
|
|
848
|
+
const note = await testTenant(input);
|
|
849
|
+
try {
|
|
850
|
+
const entry = registry().add(input);
|
|
851
|
+
log(`all tenants: added tenant ${entry.name}`);
|
|
852
|
+
return send(res, 200, { tenant: entry, note });
|
|
853
|
+
}
|
|
854
|
+
catch (e) {
|
|
855
|
+
throw new HttpProblem(400, e.message);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
const partnerRoute = /^(PUT|DELETE|POST) \/api\/tenants\/([A-Z0-9]{8})(\/open)?$/.exec(route);
|
|
859
|
+
if (partnerRoute && !(partnerRoute[1] === 'POST' && !partnerRoute[3])) {
|
|
860
|
+
const [, method, id, open] = partnerRoute;
|
|
861
|
+
const r = registry();
|
|
862
|
+
if (!r.get(id))
|
|
863
|
+
throw new HttpProblem(404, 'Unknown tenant.');
|
|
864
|
+
if (method === 'DELETE') {
|
|
865
|
+
r.remove(id);
|
|
866
|
+
if (partnerLast)
|
|
867
|
+
partnerLast = { ...partnerLast, results: partnerLast.results.filter((x) => x.id !== id) };
|
|
868
|
+
return send(res, 200, { removed: true });
|
|
869
|
+
}
|
|
870
|
+
if (method === 'POST' && open) {
|
|
871
|
+
const c = r.credentials(id);
|
|
872
|
+
if (!c)
|
|
873
|
+
throw new HttpProblem(400, 'No client secret saved for this tenant. Edit it and enter the secret.');
|
|
874
|
+
await connect(c);
|
|
875
|
+
return send(res, 200, { connected: true, tenant, name: r.get(id).name });
|
|
876
|
+
}
|
|
877
|
+
if (method === 'PUT') {
|
|
878
|
+
const b = await readJson(req);
|
|
879
|
+
const cur = r.credentials(id);
|
|
880
|
+
const secret = String(b['clientSecret'] ?? '').trim();
|
|
881
|
+
const next = { baseUrl: String(b['baseUrl'] ?? r.get(id).baseUrl).trim(), clientId: String(b['clientId'] ?? r.get(id).clientId).trim(), clientSecret: secret || cur?.clientSecret || '' };
|
|
882
|
+
let note;
|
|
883
|
+
if (secret || next.baseUrl !== r.get(id).baseUrl || next.clientId !== r.get(id).clientId) {
|
|
884
|
+
if (!next.clientSecret)
|
|
885
|
+
throw new HttpProblem(400, 'Enter the client secret.');
|
|
886
|
+
note = await testTenant(next);
|
|
887
|
+
}
|
|
888
|
+
try {
|
|
889
|
+
const entry = r.update(id, { name: b['name'] === undefined ? undefined : String(b['name']), baseUrl: next.baseUrl, clientId: next.clientId, clientSecret: secret || undefined, notes: b['notes'] === undefined ? undefined : String(b['notes']) });
|
|
890
|
+
return send(res, 200, { tenant: entry, note });
|
|
891
|
+
}
|
|
892
|
+
catch (e) {
|
|
893
|
+
throw new HttpProblem(400, e.message);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
if (route === 'POST /api/tenants/run') {
|
|
898
|
+
const b = await readJson(req);
|
|
899
|
+
const ids = Array.isArray(b['ids']) ? b['ids'].map(String) : undefined;
|
|
900
|
+
if (!registry().list().length)
|
|
901
|
+
throw new HttpProblem(400, 'Add a tenant first.');
|
|
902
|
+
return send(res, 202, {
|
|
903
|
+
job: background('checking all tenants', async (progress) => {
|
|
904
|
+
const started = Date.now();
|
|
905
|
+
const history = new History(join(home, 'history.json'));
|
|
906
|
+
const results = await checkAllTenants({
|
|
907
|
+
registry: registry(),
|
|
908
|
+
acceptedFor: (k) => acceptedFor(home, k, opts.now?.()),
|
|
909
|
+
makeTransport: (c) => stoppable(makeTransport(c)),
|
|
910
|
+
loadReport: (rid) => {
|
|
911
|
+
const f = findReport(rid);
|
|
912
|
+
if (!f)
|
|
913
|
+
throw new Error(`Report ${rid} is missing`);
|
|
914
|
+
return f.definition;
|
|
915
|
+
},
|
|
916
|
+
settings: readCheckSettings(home),
|
|
917
|
+
only: readOverviewChecks(home),
|
|
918
|
+
history,
|
|
919
|
+
ids,
|
|
920
|
+
// One tenant at a time: three large tenants side by side need three times the memory.
|
|
921
|
+
concurrency: 1,
|
|
922
|
+
onProgress: progress,
|
|
923
|
+
});
|
|
924
|
+
if (jobContext.getStore()?.stopped)
|
|
925
|
+
throw new Stopped();
|
|
926
|
+
const fresh = ids && partnerLast ? [...partnerLast.results.filter((x) => !ids.includes(x.id)), ...results] : results;
|
|
927
|
+
partnerLast = { at: new Date().toISOString(), headline: overviewHeadline(fresh), results: fresh };
|
|
928
|
+
log(`all tenants: ${partnerLast.headline}`);
|
|
929
|
+
const shown = readOverviewChecks(home);
|
|
930
|
+
return { extra: partnerLast, table: overviewTable(fresh, CHECKS.filter((c) => shown.includes(c.id)).map((c) => ({ id: c.id, label: c.label })), started) };
|
|
931
|
+
}),
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
const warnSettings = () => (readSettings().warnings ?? {});
|
|
935
|
+
// ---------- labs (evaluated on this computer; ISC is only read) ----------
|
|
936
|
+
const labTestsFile = join(home, 'lab-tests.json');
|
|
937
|
+
const readLabTests = () => {
|
|
938
|
+
try {
|
|
939
|
+
return JSON.parse(readFileSync(labTestsFile, 'utf8'));
|
|
940
|
+
}
|
|
941
|
+
catch {
|
|
942
|
+
return {};
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
const tenantTransforms = async () => (transport ? await readTransforms(transport) : []);
|
|
946
|
+
// Draft transforms typed into the lab; a draft overrides a saved transform with the same name.
|
|
947
|
+
const labDrafts = (v) => {
|
|
948
|
+
if (v === undefined || v === null)
|
|
949
|
+
return [];
|
|
950
|
+
if (!Array.isArray(v) || v.length > 100 || v.some((x) => !x || typeof x !== 'object' || typeof x['name'] !== 'string'))
|
|
951
|
+
throw new HttpProblem(400, 'Other transforms must be a JSON list of transforms, each with a "name".');
|
|
952
|
+
return v;
|
|
953
|
+
};
|
|
954
|
+
if (route === 'GET /api/lab/transforms') {
|
|
955
|
+
const t = need();
|
|
956
|
+
const [transforms, mappings] = await Promise.all([readTransforms(t), readMappings(t)]);
|
|
957
|
+
return send(res, 200, withoutSecrets({ transforms, mappings }));
|
|
958
|
+
}
|
|
959
|
+
if (route === 'POST /api/lab/transform/run') {
|
|
960
|
+
const b = await readJson(req);
|
|
961
|
+
const transform = b['transform'];
|
|
962
|
+
if (!transform || typeof transform !== 'object')
|
|
963
|
+
throw new HttpProblem(400, 'The transform must be a JSON object.');
|
|
964
|
+
const drafts = labDrafts(b['transforms']);
|
|
965
|
+
const engine = TransformEngine.fromList([...(await tenantTransforms()), ...drafts], opts.now?.() ?? new Date());
|
|
966
|
+
const input = (b['input'] && typeof b['input'] === 'object' ? b['input'] : {});
|
|
967
|
+
const cases = Array.isArray(b['cases']) ? b['cases'].slice(0, 200) : [];
|
|
968
|
+
return send(res, 200, {
|
|
969
|
+
result: engine.run(transform, input),
|
|
970
|
+
cases: cases.map((c) => {
|
|
971
|
+
const r = engine.run(transform, (c['input'] ?? {}));
|
|
972
|
+
const got = r.value === null || r.value === undefined ? '' : String(r.value);
|
|
973
|
+
return { name: c['name'], expected: c['expected'] ?? '', got, status: r.status, error: r.error, pass: got === String(c['expected'] ?? '') };
|
|
974
|
+
}),
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
if (route === 'GET /api/lab/tests')
|
|
978
|
+
return send(res, 200, readLabTests()[tenant ?? 'tenant'] ?? {});
|
|
979
|
+
if (route === 'POST /api/lab/tests') {
|
|
980
|
+
const b = await readJson(req);
|
|
981
|
+
const name = String(b['transform'] ?? '').trim();
|
|
982
|
+
if (!name)
|
|
983
|
+
throw new HttpProblem(400, 'Name the transform these tests belong to.');
|
|
984
|
+
const cases = Array.isArray(b['cases']) ? withoutSecrets(b['cases']).slice(0, 200) : [];
|
|
985
|
+
const all = readLabTests();
|
|
986
|
+
const mine = { ...(all[tenant ?? 'tenant'] ?? {}), [name]: cases };
|
|
987
|
+
if (!cases.length)
|
|
988
|
+
delete mine[name];
|
|
989
|
+
all[tenant ?? 'tenant'] = mine;
|
|
990
|
+
mkdirSync(home, { recursive: true });
|
|
991
|
+
writeFileSync(labTestsFile, JSON.stringify(all, null, 2), { mode: 0o600 });
|
|
992
|
+
return send(res, 200, mine);
|
|
993
|
+
}
|
|
994
|
+
if (route === 'POST /api/lab/transform/people') {
|
|
995
|
+
const t = need();
|
|
996
|
+
const b = await readJson(req);
|
|
997
|
+
const transform = b['transform'];
|
|
998
|
+
if (!transform || typeof transform !== 'object')
|
|
999
|
+
throw new HttpProblem(400, 'The transform must be a JSON object.');
|
|
1000
|
+
const attribute = typeof b['attribute'] === 'string' && b['attribute'].trim() ? b['attribute'].trim() : undefined;
|
|
1001
|
+
return send(res, 202, {
|
|
1002
|
+
job: background('trying a transform on people', async (progress) => {
|
|
1003
|
+
const o = await runOnPeople(t, {
|
|
1004
|
+
transform: transform,
|
|
1005
|
+
transforms: [...(await readTransforms(t)), ...labDrafts(b['transforms'])],
|
|
1006
|
+
attribute,
|
|
1007
|
+
query: typeof b['query'] === 'string' ? b['query'] : undefined,
|
|
1008
|
+
count: Number(b['count']) || 200,
|
|
1009
|
+
now: opts.now?.() ?? new Date(),
|
|
1010
|
+
onProgress: progress,
|
|
1011
|
+
});
|
|
1012
|
+
const rows = o.rows.map((r) => [r.person, r.current ?? null, r.result ?? null, r.status === 'ok' ? (attribute ? (r.same ? 'same' : 'different') : 'ok') : r.status, r.error ?? null]);
|
|
1013
|
+
const cols = attribute ? ['Person', `In ISC now (${attribute})`, 'Offline result', 'Result', 'Problem'] : ['Person', 'Current', 'Offline result', 'Result', 'Problem'];
|
|
1014
|
+
return { extra: { ...o, rows: o.rows.slice(0, 2000) }, table: tableResult(attribute ? `Transform check: ${attribute}` : 'Transform trial run', cols, rows, Date.now(), [...o.assumptions, ...o.notes]) };
|
|
1015
|
+
}),
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
if (route === 'GET /api/lab/workflows') {
|
|
1019
|
+
const t = need();
|
|
1020
|
+
const list = [];
|
|
1021
|
+
for await (const w of pageList(t, '/workflows/v1', {}))
|
|
1022
|
+
list.push({ id: w['id'], name: w['name'], enabled: w['enabled'], trigger: w['trigger'], definition: w['definition'] });
|
|
1023
|
+
return send(res, 200, withoutSecrets(list));
|
|
1024
|
+
}
|
|
1025
|
+
if (route === 'POST /api/lab/workflow/simulate') {
|
|
1026
|
+
const b = await readJson(req);
|
|
1027
|
+
const def = b['definition'];
|
|
1028
|
+
if (!def || typeof def !== 'object' || !def['steps'])
|
|
1029
|
+
throw new HttpProblem(400, 'The definition needs "start" and "steps".');
|
|
1030
|
+
const mocks = (b['mocks'] && typeof b['mocks'] === 'object' ? b['mocks'] : {});
|
|
1031
|
+
return send(res, 200, withoutSecrets(simulate(def, b['trigger'] ?? {}, { mocks, now: opts.now?.() ?? new Date() })));
|
|
1032
|
+
}
|
|
1033
|
+
if (route === 'POST /api/lab/workflow/replay') {
|
|
1034
|
+
const t = need();
|
|
1035
|
+
const b = await readJson(req);
|
|
1036
|
+
const id = String(b['workflowId'] ?? '');
|
|
1037
|
+
if (!/^[A-Za-z0-9-]+$/.test(id))
|
|
1038
|
+
throw new HttpProblem(400, 'Pick a workflow.');
|
|
1039
|
+
const draft = b['definition'] && typeof b['definition'] === 'object' ? b['definition'] : undefined;
|
|
1040
|
+
const count = Math.min(Math.max(Number(b['count']) || 20, 1), 100);
|
|
1041
|
+
return send(res, 202, {
|
|
1042
|
+
job: background('replaying workflow runs', async (progress) => {
|
|
1043
|
+
progress('Reading recent runs...');
|
|
1044
|
+
const runs = await listExecutions(t, id, { max: count });
|
|
1045
|
+
const results = [];
|
|
1046
|
+
const notes = [];
|
|
1047
|
+
let archived = 0;
|
|
1048
|
+
for (const [i, r] of runs.entries()) {
|
|
1049
|
+
progress(`Replaying run ${i + 1} of ${runs.length}...`);
|
|
1050
|
+
const eid = String(r['id'] ?? '');
|
|
1051
|
+
if (!/^[A-Za-z0-9-]+$/.test(eid))
|
|
1052
|
+
continue;
|
|
1053
|
+
let h;
|
|
1054
|
+
try {
|
|
1055
|
+
h = (await t.request({ method: 'GET', path: `/workflow-executions/v1/${eid}/history-v2` })).data;
|
|
1056
|
+
}
|
|
1057
|
+
catch (e) {
|
|
1058
|
+
if (e.status === 404) {
|
|
1059
|
+
archived++;
|
|
1060
|
+
continue;
|
|
1061
|
+
}
|
|
1062
|
+
throw e;
|
|
1063
|
+
}
|
|
1064
|
+
const recordedDef = h['definition'];
|
|
1065
|
+
const def = draft ?? recordedDef;
|
|
1066
|
+
if (!def) {
|
|
1067
|
+
notes.push(`Run ${eid} has no definition in its history.`);
|
|
1068
|
+
continue;
|
|
1069
|
+
}
|
|
1070
|
+
const rec = readHistory(h, allStepNames(def));
|
|
1071
|
+
results.push({ ...replay(def, rec, eid, { now: opts.now?.() ?? new Date() }), status: String(r['status'] ?? rec.status ?? ''), started: String(r['startTime'] ?? '') });
|
|
1072
|
+
}
|
|
1073
|
+
if (archived)
|
|
1074
|
+
notes.push(`${archived} run${archived === 1 ? ' is' : 's are'} older than ISC keeps history for (90 days) or could not be found.`);
|
|
1075
|
+
const rows = results.map((x) => [x.started ?? null, x.status ?? null, x.realPath.join(' > '), x.simPath.join(' > '), x.same ? 'same path' : x.noTrigger ? 'no trigger recorded' : 'different', x.divergence ? `step ${x.divergence.index + 1}: ISC went to ${x.divergence.real ?? 'end'}, simulation to ${x.divergence.simulated ?? 'end'}` : null]);
|
|
1076
|
+
const same = results.filter((x) => x.same).length;
|
|
1077
|
+
return {
|
|
1078
|
+
extra: withoutSecrets({ results, same, total: results.length, draft: Boolean(draft), notes }),
|
|
1079
|
+
table: tableResult(draft ? 'Draft replayed on real runs' : 'Workflow replay', ['Started', 'Status in ISC', 'Path in ISC', draft ? 'Path with the draft' : 'Simulated path', 'Result', 'Where they part'], rows, Date.now(), notes),
|
|
1080
|
+
};
|
|
1081
|
+
}),
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
if (route === 'POST /api/lab/credentials/run') {
|
|
1085
|
+
const t = need();
|
|
1086
|
+
const host = apiBase ? new URL(apiBase).host : '';
|
|
1087
|
+
return send(res, 202, {
|
|
1088
|
+
job: background('mapping credentials', async (progress) => {
|
|
1089
|
+
const m = await credentialMap(t, host, progress);
|
|
1090
|
+
const rows = m.uses.map((u) => [u.target || null, u.clientId ?? u.user ?? null, u.where, u.object, u.step ?? null, u.authType ?? null, u.parameterStorage ? 'Parameter Storage' : u.hasSecret ? 'typed in' : 'none', u.flags.join('; ') || null]);
|
|
1091
|
+
return { extra: m, table: tableResult('Credential map', ['Target', 'Client ID or user', 'Where', 'Name', 'Step', 'Auth', 'Secret kept as', 'Notes'], rows, Date.now(), m.notes) };
|
|
1092
|
+
}),
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
if (route === 'GET /api/warnings/settings')
|
|
1096
|
+
return send(res, 200, warnSettings());
|
|
1097
|
+
if (route === 'PUT /api/warnings/settings') {
|
|
1098
|
+
const b = await readJson(req);
|
|
1099
|
+
const problems = [];
|
|
1100
|
+
const out = { ...warnSettings() };
|
|
1101
|
+
const pp = (b['people'] && typeof b['people'] === 'object' ? b['people'] : undefined);
|
|
1102
|
+
let turnOn = false;
|
|
1103
|
+
if (pp) {
|
|
1104
|
+
const people = {};
|
|
1105
|
+
const a = String(pp['endDateAttribute'] ?? '').trim();
|
|
1106
|
+
if (a)
|
|
1107
|
+
ATTRIBUTE_NAME.test(a) ? ((people.endDateAttribute = a), (turnOn = true)) : problems.push('The end-date attribute may only have letters, digits and _');
|
|
1108
|
+
const q = String(pp['query'] ?? '').trim();
|
|
1109
|
+
if (q)
|
|
1110
|
+
q.length <= 500 ? (people.query = q) : problems.push('The search query is too long (500 characters at most)');
|
|
1111
|
+
out.people = people;
|
|
1112
|
+
}
|
|
1113
|
+
if (b['licensed'] !== undefined) {
|
|
1114
|
+
const n = b['licensed'] === '' || b['licensed'] === null ? undefined : Number(b['licensed']);
|
|
1115
|
+
if (n === undefined)
|
|
1116
|
+
delete out.licensed;
|
|
1117
|
+
else
|
|
1118
|
+
Number.isInteger(n) && n >= 1 && n <= 1e8 ? (out.licensed = n) : problems.push('The licensed number must be a whole number of at least 1');
|
|
1119
|
+
}
|
|
1120
|
+
if (b['basis'] !== undefined)
|
|
1121
|
+
b['basis'] === 'active' || b['basis'] === 'all' ? (out.basis = b['basis']) : problems.push('Count basis must be all or active');
|
|
1122
|
+
if (problems.length)
|
|
1123
|
+
throw new DefinitionError('Some settings are not valid', problems);
|
|
1124
|
+
const cur = readSettings();
|
|
1125
|
+
const checks = { ...(cur.checks ?? {}) };
|
|
1126
|
+
// Saving an end-date attribute turns on the "Active after end date" tile, unless it was turned off on purpose.
|
|
1127
|
+
if (turnOn && checks['past-end-date']?.enabled !== false)
|
|
1128
|
+
checks['past-end-date'] = { ...(checks['past-end-date'] ?? {}), enabled: true };
|
|
1129
|
+
writeFileSync(settingsFile, JSON.stringify({ ...cur, checks, warnings: out }, null, 2));
|
|
1130
|
+
return send(res, 200, { saved: true });
|
|
1131
|
+
}
|
|
1132
|
+
const wm = /^POST \/api\/warnings\/(access-ending|stuck|reminders|admins|catalog|people|growth|account-expiry|revokes|request-trail|approver-chain)\/run$/.exec(route);
|
|
1133
|
+
if (wm) {
|
|
1134
|
+
const t = need();
|
|
1135
|
+
const b = await readJson(req);
|
|
1136
|
+
const days = (min, max, dflt) => Math.min(max, Math.max(min, Math.round(Number(b['days'])) || dflt));
|
|
1137
|
+
const key = tenant ?? t.label ?? 'tenant';
|
|
1138
|
+
const kind = wm[1];
|
|
1139
|
+
const now = opts.now?.() ?? new Date();
|
|
1140
|
+
const expiryInput = { ids: (Array.isArray(b['sourceIds']) ? b['sourceIds'] : []).map(String).filter((x) => /^[A-Za-z0-9-]{1,64}$/.test(x)).slice(0, 20), attribute: typeof b['attribute'] === 'string' && b['attribute'].trim() ? b['attribute'].trim() : 'accountExpires' };
|
|
1141
|
+
if (kind === 'account-expiry') {
|
|
1142
|
+
if (!expiryInput.ids.length)
|
|
1143
|
+
return send(res, 400, { error: 'Pick at least one source.' });
|
|
1144
|
+
if (!ATTRIBUTE_NAME.test(expiryInput.attribute))
|
|
1145
|
+
return send(res, 400, { error: 'The attribute name may only use letters, digits and _.' });
|
|
1146
|
+
}
|
|
1147
|
+
const work = async (progress) => {
|
|
1148
|
+
switch (kind) {
|
|
1149
|
+
case 'access-ending': {
|
|
1150
|
+
const o = await accessEnding(t, { now, days: days(1, 365, 30), onProgress: progress });
|
|
1151
|
+
const rows = o.rows.map((x) => [x.person, x.personStatus ?? null, x.access, x.type, x.removeDate.slice(0, 10), x.daysLeft, x.manager ?? null, x.requester ?? null]);
|
|
1152
|
+
return { extra: o, table: tableResult('Access ending', ['Person', 'Person status', 'Access', 'Type', 'Ends', 'Days left', 'Manager', 'Requested by'], rows, Date.now(), o.notes) };
|
|
1153
|
+
}
|
|
1154
|
+
case 'stuck': {
|
|
1155
|
+
const o = await stuckOnLeavers(t, { now, onProgress: progress });
|
|
1156
|
+
const rows = o.rows.map((x) => [x.kind, x.item, x.waitingOn, x.status, x.detail]);
|
|
1157
|
+
return { extra: o, table: tableResult('Waiting on people who left', ['What', 'Item', 'Waiting on', 'Status', 'When'], rows, Date.now(), o.notes) };
|
|
1158
|
+
}
|
|
1159
|
+
case 'reminders': {
|
|
1160
|
+
const o = await reviewerReminders(t, { now, days: days(0, 90, 7), onProgress: progress });
|
|
1161
|
+
const rows = o.rows.map((x) => [x.reviewer, x.reviewerEmail ?? null, x.reviewerStatus ?? null, x.campaign, x.certification, x.due ? x.due.slice(0, 10) : null, x.daysLeft, x.decisionsLeft]);
|
|
1162
|
+
return { extra: o, table: tableResult('Certifications due soon', ['Reviewer', 'Email', 'Reviewer status', 'Campaign', 'Certification', 'Due', 'Days left', 'Decisions left'], rows, Date.now(), o.notes) };
|
|
1163
|
+
}
|
|
1164
|
+
case 'admins': {
|
|
1165
|
+
const o = await iscAdmins(t, { onProgress: progress });
|
|
1166
|
+
const seen = newAdmins(home, key, o.rows.map((r) => r.id), now.toISOString());
|
|
1167
|
+
const rows = o.rows.map((x) => ({ ...x, isNew: seen.fresh.has(x.id) }));
|
|
1168
|
+
const table = rows.map((x) => [x.person, x.email ?? null, x.levels.map(levelLabel).join(', '), x.status, x.lifecycle ?? null, x.isNew ? 'yes' : null]);
|
|
1169
|
+
return { extra: { ...o, rows, since: seen.since }, table: tableResult('ISC user levels', ['Person', 'Email', 'User levels', 'Status', 'Lifecycle state', 'New since last look'], table, Date.now(), o.notes) };
|
|
1170
|
+
}
|
|
1171
|
+
case 'catalog': {
|
|
1172
|
+
const o = await catalogQuality(t, { onProgress: progress });
|
|
1173
|
+
const rows = [...o.rows.map((x) => [x.type, x.name, x.source ?? null, x.owner ?? null, x.issues.join(', ')]), ...(o.unused ?? []).map((x) => [x.type, x.name, x.source ?? null, x.owner ?? null, 'Nobody has it'])];
|
|
1174
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Access catalog gaps', ['Type', 'Name', 'Source', 'Owner', 'Missing'], rows, Date.now(), o.notes) };
|
|
1175
|
+
}
|
|
1176
|
+
case 'people': {
|
|
1177
|
+
const o = await peopleEnding(t, { ...(warnSettings().people ?? {}), now, days: days(1, 365, 30), onProgress: progress });
|
|
1178
|
+
const rows = [...o.pastEnd.map((x) => ['Past end date', x.person, x.endDate.slice(0, 10), x.daysLeft, x.manager ?? null, x.lifecycle ?? null]), ...o.endingSoon.map((x) => ['Ending soon', x.person, x.endDate.slice(0, 10), x.daysLeft, x.manager ?? null, x.lifecycle ?? null])];
|
|
1179
|
+
return { extra: o, table: tableResult('People at or past their end date', ['Group', 'Person', 'End date', 'Days left', 'Manager', 'Lifecycle state'], rows, Date.now(), o.notes) };
|
|
1180
|
+
}
|
|
1181
|
+
case 'account-expiry': {
|
|
1182
|
+
const { ids, attribute } = expiryInput;
|
|
1183
|
+
const o = await accountExpiry(t, { now, days: days(1, 365, 30), sourceIds: ids, attribute, onProgress: progress });
|
|
1184
|
+
const rows = o.rows.map((x) => [x.account, x.person ?? null, x.source, x.expires, x.daysLeft, x.disabled ? 'disabled' : 'enabled', x.raw]);
|
|
1185
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult(`Accounts expiring (${attribute})`, ['Account', 'Person', 'Source', 'Expires', 'Days left', 'Account', 'Value in ISC'], rows, Date.now(), o.notes) };
|
|
1186
|
+
}
|
|
1187
|
+
case 'revokes': {
|
|
1188
|
+
const o = await revokesNotDone(t, { now, days: days(7, 365, 90), onProgress: progress });
|
|
1189
|
+
const rows = o.rows.map((x) => [x.person, x.access, x.accessType, x.campaign, x.certification, x.reviewer ?? null, x.signedOff ? x.signedOff.slice(0, 10) : null, x.daysSinceSignOff, x.status, x.alsoFromRole ? 'yes' : null]);
|
|
1190
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Revoked in a certification but still held', ['Person', 'Access', 'Type', 'Campaign', 'Certification', 'Reviewer', 'Signed off', 'Days since sign-off', 'Status', 'Person also has roles or access profiles'], rows, Date.now(), o.notes) };
|
|
1191
|
+
}
|
|
1192
|
+
case 'request-trail': {
|
|
1193
|
+
const text = (k) => (typeof b[k] === 'string' ? b[k].slice(0, 200) : undefined);
|
|
1194
|
+
const o = await requestTrail(t, { now, days: days(1, 365, 30), item: text('item'), person: text('person'), onProgress: progress });
|
|
1195
|
+
return { extra: { ...o, requests: o.requests.slice(0, 3000), more: Math.max(0, o.requests.length - 3000) }, table: tableResult('Access request audit trail', TRAIL_HEADERS, trailRows(o), Date.now(), o.notes) };
|
|
1196
|
+
}
|
|
1197
|
+
case 'approver-chain': {
|
|
1198
|
+
const o = await approverChain(t, { onProgress: progress });
|
|
1199
|
+
const rows = o.rows.map((x) => [x.type, x.name, x.source ?? null, x.owner ?? null, x.requestable ? 'yes' : 'no', x.request.join(' → ') || null, x.revoke.join(' → ') || null, x.commentsRequired ? 'yes' : 'no', x.flags.join('; ') || null]);
|
|
1200
|
+
return { extra: o, table: tableResult('Approver chain', ['Type', 'Name', 'Source', 'Owner', 'Requestable', 'Request approvals', 'Revoke approvals', 'Comment required', 'Problems'], rows, Date.now(), o.notes) };
|
|
1201
|
+
}
|
|
1202
|
+
default: {
|
|
1203
|
+
const st = warnSettings();
|
|
1204
|
+
const o = await identityGrowth(t, { now, history: readCounts(home, key), licensed: st.licensed, basis: st.basis, onProgress: progress });
|
|
1205
|
+
const history = o.total !== null && o.active !== null ? recordCount(home, key, { date: now.toISOString().slice(0, 10), total: o.total, active: o.active }) : readCounts(home, key);
|
|
1206
|
+
const rows = o.monthly.map((m) => [m.month, m.added]);
|
|
1207
|
+
return { extra: { ...o, history }, table: tableResult('New identities per month', ['Month', 'New identities'], rows, Date.now(), o.notes) };
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
};
|
|
1211
|
+
return send(res, 202, { job: background('reading ' + kind.replace('-', ' '), work) });
|
|
1212
|
+
}
|
|
1213
|
+
// ---------- logs: ccg.log from a file on this computer or an uploaded copy ----------
|
|
1214
|
+
const ccgFilter = (get) => {
|
|
1215
|
+
const s = (k, max = 200) => (typeof get(k) === 'string' && String(get(k)).trim() ? String(get(k)).trim().slice(0, max) : undefined);
|
|
1216
|
+
const level = s('level')?.toUpperCase();
|
|
1217
|
+
const date = (k) => (s(k) && Number.isFinite(Date.parse(s(k))) ? new Date(Date.parse(s(k))).toISOString() : undefined);
|
|
1218
|
+
return { source: s('source'), text: s('text'), operation: s('operation'), level: level === 'ERROR' || level === 'WARN' || level === 'INFO' || level === 'DEBUG' ? level : undefined, from: date('from'), to: date('to') };
|
|
1219
|
+
};
|
|
1220
|
+
const ccgJob = (o, files) => {
|
|
1221
|
+
const rows = o.groups.map((g) => [g.level, g.source, g.operation, g.count, g.first ? g.first.slice(0, 19).replace('T', ' ') : null, g.last ? g.last.slice(0, 19).replace('T', ' ') : null, g.example, g.exception ?? null, g.logger]);
|
|
1222
|
+
return { extra: { ...o, groups: o.groups.slice(0, 1000), moreGroups: Math.max(0, o.groups.length - 1000), files }, table: tableResult('Errors and warnings in the connector log', ['Level', 'Source', 'Operation', 'Times', 'First', 'Last', 'Message', 'Error detail', 'Logger'], rows, Date.now(), o.notes) };
|
|
1223
|
+
};
|
|
1224
|
+
if (route === 'POST /api/logs/ccg/run') {
|
|
1225
|
+
const b = await readJson(req);
|
|
1226
|
+
const path = typeof b['path'] === 'string' ? b['path'].trim().replace(/^"|"$/g, '') : '';
|
|
1227
|
+
if (!path || path.length > 1000)
|
|
1228
|
+
return send(res, 400, { error: 'Give the path of ccg.log, or of the folder that holds it, on this computer.' });
|
|
1229
|
+
let files;
|
|
1230
|
+
try {
|
|
1231
|
+
files = logFilesAt(path);
|
|
1232
|
+
}
|
|
1233
|
+
catch (e) {
|
|
1234
|
+
throw new HttpProblem(400, e.message);
|
|
1235
|
+
}
|
|
1236
|
+
const filter = ccgFilter((k) => b[k]);
|
|
1237
|
+
return send(res, 202, {
|
|
1238
|
+
job: background('reading a connector log', async (progress) => {
|
|
1239
|
+
const r = ccgReader(filter);
|
|
1240
|
+
for await (const line of linesOfFiles(files, progress))
|
|
1241
|
+
r.add(line);
|
|
1242
|
+
return ccgJob(r.done(), files.map((f) => f.file));
|
|
1243
|
+
}),
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
if (route === 'POST /api/logs/ccg/upload') {
|
|
1247
|
+
// The file itself is the request body; it is read as it arrives and never written to disk.
|
|
1248
|
+
const filter = ccgFilter((k) => url.searchParams.get(k) ?? undefined);
|
|
1249
|
+
const name = (url.searchParams.get('name') ?? 'uploaded file').slice(0, 200);
|
|
1250
|
+
const r = ccgReader(filter);
|
|
1251
|
+
for await (const line of linesOfStream(req, /\.gz$/i.test(name)))
|
|
1252
|
+
r.add(line);
|
|
1253
|
+
const out = r.done();
|
|
1254
|
+
return send(res, 202, { job: background('reading an uploaded connector log', async () => ccgJob(out, [name])) });
|
|
1255
|
+
}
|
|
1256
|
+
// ---------- 0.23.0: drift, incidents and cleanup ----------
|
|
1257
|
+
const ow = /^POST \/api\/watch\/(mass-change|loops|outside|leaver-times|rules|sync-drift|group-approvals|owners|manager-left|attr-history|lifecycle-settings|gov-groups|signins|self-approvals|admin-activity|access-spikes|outside-model|composition|agg-safety|service-accounts|multi-accounts|password-failures|reassigned|priv-gained|outside-accounts|sensitive|risk|jml-preview|stuck-requests|source-log)\/run$/.exec(route);
|
|
1258
|
+
if (ow) {
|
|
1259
|
+
const t = need();
|
|
1260
|
+
const b = await readJson(req);
|
|
1261
|
+
const num = (k, min, max, dflt) => {
|
|
1262
|
+
const v = Number(b[k]);
|
|
1263
|
+
return Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : dflt;
|
|
1264
|
+
};
|
|
1265
|
+
const ids = (Array.isArray(b['sourceIds']) ? b['sourceIds'] : []).map(String).filter((x) => /^[A-Za-z0-9-]{1,64}$/.test(x)).slice(0, 20);
|
|
1266
|
+
const kind = ow[1];
|
|
1267
|
+
if ((kind === 'outside' || kind === 'sync-drift') && !ids.length)
|
|
1268
|
+
return send(res, 400, { error: 'Pick a source.' });
|
|
1269
|
+
const attrs = (Array.isArray(b['attributes']) ? b['attributes'] : []).map(String).map((x) => x.trim()).filter(Boolean);
|
|
1270
|
+
if (kind === 'attr-history' && (!attrs.length || attrs.some((a) => !ATTRIBUTE_NAME.test(a))))
|
|
1271
|
+
return send(res, 400, { error: 'Name one to ten attributes (letters, digits and _).' });
|
|
1272
|
+
const query = typeof b['query'] === 'string' ? b['query'].slice(0, 500) : undefined;
|
|
1273
|
+
const now = opts.now?.() ?? new Date();
|
|
1274
|
+
const key = tenant ?? t.label ?? 'tenant';
|
|
1275
|
+
const work = async (progress) => {
|
|
1276
|
+
switch (kind) {
|
|
1277
|
+
case 'priv-gained': {
|
|
1278
|
+
const before = loadPrivileged(home, key);
|
|
1279
|
+
const o = await privilegedGained(t, { now, previous: before ? { taken: before.taken, keys: before.keys } : undefined, onProgress: progress });
|
|
1280
|
+
// "Look without remembering" compares again with the same earlier look.
|
|
1281
|
+
const findings = b['remember'] === false ? [...o.fresh, ...(before?.findings ?? []).filter((f) => !o.fresh.some((x) => x.key === f.key))] : savePrivileged(home, key, o.taken, o.keys, o.fresh, before?.findings);
|
|
1282
|
+
const rows = findings.map((x) => [x.found.slice(0, 10), x.person, x.personState, x.entitlement, x.source, x.via, x.how, x.when ? x.when.slice(0, 16).replace('T', ' ') : null, x.requestedBy ?? null, x.newPerson ? 'new identity' : null]);
|
|
1283
|
+
return { extra: { ...o, keys: undefined, fresh: undefined, findings: findings.slice(0, 5000), more: Math.max(0, findings.length - 5000), freshKeys: o.fresh.slice(0, 5000).map((f) => f.key), remembered: b['remember'] !== false }, table: tableResult('Privileged access gained', ['Found on', 'Person', 'State', 'Privileged entitlement', 'Source', 'Held', 'How it got there', 'Provisioned at', 'Requested by', 'Note'], rows, Date.now(), o.notes) };
|
|
1284
|
+
}
|
|
1285
|
+
case 'outside-accounts': {
|
|
1286
|
+
const o = await accountsOutsideIsc(t, { now, days: num('days', 1, 90, 7), onProgress: progress });
|
|
1287
|
+
const rows = o.rows.map((x) => [x.created.slice(0, 16).replace('T', ' '), x.account, x.source, x.owner || null, x.ownerState || null, x.hasEntitlements ? 'yes' : 'no', x.disabled ? 'disabled' : 'enabled', x.signals.join('; ') || null, x.nativeIdentity]);
|
|
1288
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: o.more + Math.max(0, o.rows.length - 5000) }, table: tableResult('Accounts created outside ISC', ['Appeared', 'Account', 'Source', 'Owner', 'Owner state', 'Has access', 'Account state', 'Signals', 'Native identity'], rows, Date.now(), o.notes) };
|
|
1289
|
+
}
|
|
1290
|
+
case 'sensitive': {
|
|
1291
|
+
const days = num('days', 1, 365, 7);
|
|
1292
|
+
const history = new ChangeHistory(join(home, 'changes'));
|
|
1293
|
+
const key = tenant ?? 'tenant'; // the same name Change history uses
|
|
1294
|
+
const today = now.toISOString().slice(0, 10);
|
|
1295
|
+
const wanted = new Date(now.getTime() - days * 86_400_000).toISOString().slice(0, 10);
|
|
1296
|
+
const earlier = history.list(key).filter((d) => d < today);
|
|
1297
|
+
// The newest snapshot that is at least `days` old; failing that, the oldest there is.
|
|
1298
|
+
const baseDay = earlier.find((d) => d <= wanted) ?? earlier[earlier.length - 1];
|
|
1299
|
+
const snap = await takeSnapshot(t, key, now, progress);
|
|
1300
|
+
history.save(snap);
|
|
1301
|
+
const notes = [];
|
|
1302
|
+
if (!baseDay) {
|
|
1303
|
+
notes.push('This is the first configuration snapshot of this tenant on this computer, so there is nothing to compare with yet. Run it again tomorrow or later, or schedule a daily snapshot under Tenant > Change history.');
|
|
1304
|
+
return { extra: { baseline: true, rows: [], totals: { high: 0, medium: 0, credentials: 0, areas: 0 }, notes }, table: tableResult('Sensitive changes', ['Severity', 'Area', 'Object', 'Change', 'Why it matters', 'Who (from audit events)', 'When'], [], Date.now(), notes) };
|
|
1305
|
+
}
|
|
1306
|
+
const base = history.load(key, baseDay);
|
|
1307
|
+
progress('Reading API credentials...');
|
|
1308
|
+
const clientId = signedInAs === undefined ? creds?.clientId : undefined;
|
|
1309
|
+
const cr = await credentialsOverview(t, { clientId, onProgress: progress }).catch(() => undefined);
|
|
1310
|
+
if (!cr)
|
|
1311
|
+
notes.push('API credentials could not be read with this sign-in, so new tokens and API clients are not included.');
|
|
1312
|
+
const since = Math.max(1, Math.min(90, Math.ceil((now.getTime() - Date.parse(base.taken)) / 86_400_000)));
|
|
1313
|
+
const ev = await adminActivity(t, { now, days: since, onProgress: progress }).catch(() => undefined);
|
|
1314
|
+
if (!ev)
|
|
1315
|
+
notes.push('Audit events could not be searched with this sign-in, so who made each change is not shown.');
|
|
1316
|
+
const o = sensitiveChanges(diffSnapshots(base, snap), { from: base.taken, to: snap.taken, credentials: cr?.credentials, events: ev?.events });
|
|
1317
|
+
for (const x of o.skipped)
|
|
1318
|
+
notes.push(`Not compared: ${x}`);
|
|
1319
|
+
notes.push(`Configuration now compared with the snapshot of ${baseDay}. “Who” is the last person ISC's audit log names for an object of the same name in that period; it is empty when the log names nobody.`);
|
|
1320
|
+
notes.push('Every other kind of change (roles, access profiles, forms, email templates) is under Tenant > Change history. New ISC admins are under Warnings > ISC admins.');
|
|
1321
|
+
const rows = o.rows.map((x) => [x.severity, x.area, x.object, x.change, x.why, x.who || null, x.when ? x.when.slice(0, 16).replace('T', ' ') : null]);
|
|
1322
|
+
return { extra: { baseline: false, from: baseDay, rows: o.rows.slice(0, 3000), more: Math.max(0, o.rows.length - 3000), totals: o.totals, notes }, table: tableResult('Sensitive changes', ['Severity', 'Area', 'Object', 'Change', 'Why it matters', 'Who (from audit events)', 'When'], rows, Date.now(), notes) };
|
|
1323
|
+
}
|
|
1324
|
+
case 'risk': {
|
|
1325
|
+
const days = num('days', 1, 30, 7);
|
|
1326
|
+
const sig = [];
|
|
1327
|
+
const notes = [];
|
|
1328
|
+
const part = async (label, work) => {
|
|
1329
|
+
try {
|
|
1330
|
+
await work();
|
|
1331
|
+
}
|
|
1332
|
+
catch (e) {
|
|
1333
|
+
notes.push(`${label} could not be read: ${e.status === 403 ? 'no permission with this sign-in' : e.message}`);
|
|
1334
|
+
}
|
|
1335
|
+
};
|
|
1336
|
+
await part('Sign-in signals', async () => {
|
|
1337
|
+
for (const r of (await signInSignals(t, { now, days, onProgress: progress })).rows)
|
|
1338
|
+
for (const s of r.signals)
|
|
1339
|
+
sig.push({ person: r.person, signal: s, from: 'Sign-in', weight: /left|after/i.test(s) ? 5 : 2 });
|
|
1340
|
+
});
|
|
1341
|
+
await part('Self-approvals', async () => {
|
|
1342
|
+
for (const r of (await selfApprovals(t, { now, days: Math.max(days, 30), onProgress: progress })).rows)
|
|
1343
|
+
sig.push({ person: r.approver, signal: `${r.kind}: ${r.access}`, from: 'Self-approval', weight: 3 });
|
|
1344
|
+
});
|
|
1345
|
+
await part('Admin activity', async () => {
|
|
1346
|
+
for (const a of (await adminActivity(t, { now, days, onProgress: progress })).actors)
|
|
1347
|
+
for (const s of a.signals)
|
|
1348
|
+
if (/left/i.test(s))
|
|
1349
|
+
sig.push({ person: a.actor, signal: `${s}; ${a.changes} changes`, from: 'Admin activity', weight: 5 });
|
|
1350
|
+
});
|
|
1351
|
+
await part('Access spikes', async () => {
|
|
1352
|
+
for (const r of (await accessSpikes(t, { now, days, onProgress: progress })).rows)
|
|
1353
|
+
sig.push({ person: r.person, signal: `${r.added} access items on ${r.day}`, from: 'Access spike', weight: 2 });
|
|
1354
|
+
});
|
|
1355
|
+
await part('Accounts created outside ISC', async () => {
|
|
1356
|
+
for (const r of (await accountsOutsideIsc(t, { now, days, onProgress: progress })).rows)
|
|
1357
|
+
if (r.owner && !r.signals.includes('Source newly connected'))
|
|
1358
|
+
sig.push({ person: r.owner, signal: `${r.account} on ${r.source}${r.hasEntitlements ? ', already has access' : ''}`, from: 'Account created outside ISC', weight: r.hasEntitlements ? 3 : 2 });
|
|
1359
|
+
});
|
|
1360
|
+
const seen = loadPrivileged(home, key);
|
|
1361
|
+
const cutoff = new Date(now.getTime() - Math.max(days, 30) * 86_400_000).toISOString();
|
|
1362
|
+
for (const f of seen?.findings ?? [])
|
|
1363
|
+
if (f.how === 'No ISC record' && f.found >= cutoff && !f.newPerson)
|
|
1364
|
+
sig.push({ person: f.person, signal: `${f.entitlement} on ${f.source}`, from: 'Privileged access outside ISC', weight: 5 });
|
|
1365
|
+
if (!seen)
|
|
1366
|
+
notes.push('Privileged access gained has not been run on this computer yet, so it is not part of the score.');
|
|
1367
|
+
const all = riskByPerson(sig);
|
|
1368
|
+
notes.push(`Signals of the last ${days} days (self-approvals and privileged access: at least 30) from the threat screens, added up per person by display name. A person on several screens comes first. The score orders the list; it is not a measure of guilt, and two people with the same name are counted as one.`);
|
|
1369
|
+
const rows = all.map((x) => [x.person, x.score, x.screens, x.signals.join(' | ')]);
|
|
1370
|
+
return { extra: { days, rows: all.slice(0, 3000), more: Math.max(0, all.length - 3000), totals: { people: all.length, several: all.filter((x) => x.screens > 1).length, signals: sig.length }, notes }, table: tableResult('Risk by person', ['Person', 'Score', 'Screens', 'Signals'], rows, Date.now(), notes) };
|
|
1371
|
+
}
|
|
1372
|
+
case 'jml-preview': {
|
|
1373
|
+
const a = (k) => (typeof b[k] === 'string' && ATTRIBUTE_NAME.test(String(b[k])) ? String(b[k]) : undefined);
|
|
1374
|
+
const o = await jmlPreview(t, { now, days: num('days', 1, 90, 14), startDateAttribute: a('startDateAttribute'), endDateAttribute: a('endDateAttribute'), query, onProgress: progress });
|
|
1375
|
+
const rows = o.rows.map((x) => [x.date, x.inDays === 0 ? 'today' : `in ${x.inDays} day${x.inDays === 1 ? '' : 's'}`, x.kind, x.person, x.email ?? null, x.manager ?? null, x.profile, x.lifecycle || null, x.stateNow || null, x.accounts, x.access, x.findings.join('; ') || null]);
|
|
1376
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Joiners and leavers coming up', ['Date', 'When', 'Starts or ends', 'Person', 'Email', 'Manager', 'Identity profile', 'Lifecycle state now', 'What that state does', 'Accounts', 'Access items', 'To check'], rows, Date.now(), o.notes) };
|
|
1377
|
+
}
|
|
1378
|
+
case 'stuck-requests': {
|
|
1379
|
+
const o = await stuckRequests(t, { now, hours: num('hours', 1, 24 * 90, 24), onProgress: progress });
|
|
1380
|
+
const rows = o.rows.map((x) => [x.submitted.slice(0, 16).replace('T', ' '), x.hours, x.access, x.type, x.requestedFor, x.requestedBy, x.phase, x.phaseHours, x.waitingOn || null, x.reason, x.errors || null]);
|
|
1381
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Stuck access requests', ['Submitted', 'Hours running', 'Access', 'Type', 'Requested for', 'Requested by', 'Phase', 'Hours in phase', 'Waiting on', 'Why', 'Errors'], rows, Date.now(), o.notes) };
|
|
1382
|
+
}
|
|
1383
|
+
case 'source-log': {
|
|
1384
|
+
const source = typeof b['source'] === 'string' ? b['source'].trim().slice(0, 200) : '';
|
|
1385
|
+
const o = await sourceLog(t, { now, days: num('days', 1, 30, 2), source: source || undefined, failedOnly: b['failedOnly'] === true, onProgress: progress });
|
|
1386
|
+
const rows = o.rows.map((x) => [x.when.slice(0, 19).replace('T', ' '), x.source, x.kind, x.status, x.what, x.detail || null, x.who || null]);
|
|
1387
|
+
return { extra: { ...o, rows: o.rows.slice(0, 3000), more: o.more + Math.max(0, o.rows.length - 3000) }, table: tableResult('What ISC recorded about sources', ['When', 'Source', 'Kind', 'Status', 'What', 'Detail', 'Who'], rows, Date.now(), o.notes) };
|
|
1388
|
+
}
|
|
1389
|
+
case 'signins': {
|
|
1390
|
+
const o = await signInSignals(t, { now, days: num('days', 1, 90, 7), minFailed: num('minFailed', 3, 1000, 10), onProgress: progress });
|
|
1391
|
+
const rows = o.rows.map((x) => [x.person, x.username, x.state, x.failed, x.passed, x.worstDay, x.worstDayFailed, x.addresses, x.lastFailed ? x.lastFailed.slice(0, 16).replace('T', ' ') : null, x.signals.join('; ')]);
|
|
1392
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Sign-in signals', ['Person', 'Username', 'State', 'Failed sign-ins', 'Successful sign-ins', 'Worst day', 'Failed that day', 'Network addresses', 'Last failure', 'Signals'], rows, Date.now(), o.notes) };
|
|
1393
|
+
}
|
|
1394
|
+
case 'self-approvals': {
|
|
1395
|
+
const o = await selfApprovals(t, { now, days: num('days', 1, 730, 90), onProgress: progress });
|
|
1396
|
+
const rows = o.rows.map((x) => [x.when.slice(0, 16).replace('T', ' '), x.access, x.requestedFor, x.requestedBy, x.approver, x.kind, x.state]);
|
|
1397
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Self-approvals', ['Approved at', 'Access', 'Requested for', 'Requested by', 'Approved by', 'Finding', 'Request state'], rows, Date.now(), o.notes) };
|
|
1398
|
+
}
|
|
1399
|
+
case 'admin-activity': {
|
|
1400
|
+
const o = await adminActivity(t, { now, days: num('days', 1, 90, 7), onProgress: progress });
|
|
1401
|
+
const rows = o.events.map((x) => [x.when.slice(0, 16).replace('T', ' '), x.actor, x.event, x.target, x.type]);
|
|
1402
|
+
return { extra: { ...o, events: o.events.slice(0, 3000), more: o.more + Math.max(0, o.events.length - 3000) }, table: tableResult('Administration changes by people', ['When', 'Who', 'Event', 'On', 'Kind'], rows, Date.now(), o.notes) };
|
|
1403
|
+
}
|
|
1404
|
+
case 'access-spikes': {
|
|
1405
|
+
const o = await accessSpikes(t, { now, days: num('days', 1, 30, 7), min: num('min', 3, 1000, 15), onProgress: progress });
|
|
1406
|
+
const rows = o.rows.map((x) => [x.person, x.personState || null, x.day, x.added, x.sources, x.requestedBy, x.examples]);
|
|
1407
|
+
return { extra: o, table: tableResult('Access spikes per person', ['Person', 'State', 'Day', 'Access items added', 'Sources', 'Requested by', 'Examples'], rows, Date.now(), o.notes) };
|
|
1408
|
+
}
|
|
1409
|
+
case 'lifecycle-settings': {
|
|
1410
|
+
const o = await lifecycleSettings(t, { onProgress: progress });
|
|
1411
|
+
const rows = o.rows.map((x) => [x.profile, x.state, x.kind === 'leaver' ? 'leaver state' : 'active state', x.enabled ? 'on' : 'off', x.people, x.accounts, x.removesAccess ? 'yes' : 'no', x.grants, x.findings.join('; ') || null]);
|
|
1412
|
+
return { extra: o, table: tableResult('What each lifecycle state does', ['Identity profile', 'Lifecycle state', 'Kind', 'State is', 'People', 'Accounts', 'Removes all access', 'Access profiles granted', 'Findings'], rows, Date.now(), o.notes) };
|
|
1413
|
+
}
|
|
1414
|
+
case 'gov-groups': {
|
|
1415
|
+
const o = await governanceGroups(t, { onProgress: progress });
|
|
1416
|
+
const rows = o.rows.map((x) => [x.group, x.owner || null, x.ownerState, x.members, x.activeMembers, x.left.join(', ') || null, x.usedIn, x.findings.join('; ') || null]);
|
|
1417
|
+
return { extra: o, table: tableResult('Governance groups', ['Group', 'Owner', 'Owner state', 'Members', 'Active members', 'Members who left', 'Used in', 'Findings'], rows, Date.now(), o.notes) };
|
|
1418
|
+
}
|
|
1419
|
+
case 'outside-model': {
|
|
1420
|
+
const o = await accessOutsideModel(t, { query, onProgress: progress });
|
|
1421
|
+
const rows = o.people.map((x) => [x.person, x.entitlement, x.source, x.privileged ? 'yes' : null]);
|
|
1422
|
+
return { extra: { ...o, people: o.people.slice(0, 5000), entitlements: o.entitlements.slice(0, 5000), morePeople: Math.max(0, o.people.length - 5000) + o.more }, table: tableResult('Access held directly (outside roles and access profiles)', ['Person', 'Entitlement', 'Source', 'Privileged'], rows, Date.now(), o.notes) };
|
|
1423
|
+
}
|
|
1424
|
+
case 'composition': {
|
|
1425
|
+
const o = await roleComposition(t, { onProgress: progress });
|
|
1426
|
+
const rows = o.rows.map((x) => [x.role, x.roleOwner ?? null, x.roleState, x.assignment, x.accessProfile ?? null, x.entitlement ?? null, x.source ?? null, x.note ?? null]);
|
|
1427
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('What is in every role', ['Role', 'Role owner', 'Role state', 'Assigned', 'Access profile', 'Entitlement', 'Source', 'Note'], rows, Date.now(), o.notes) };
|
|
1428
|
+
}
|
|
1429
|
+
case 'agg-safety': {
|
|
1430
|
+
const o = await aggregationSafety(t, { now, days: num('days', 1, 90, 14), onProgress: progress });
|
|
1431
|
+
const rows = o.rows.map((x) => [x.source, x.type, x.authoritative ? 'yes' : null, x.deleteThreshold, x.runs, x.failed, x.lastOk ? x.lastOk.slice(0, 16).replace('T', ' ') : null, x.findings.join('; ') || null]);
|
|
1432
|
+
return { extra: o, table: tableResult('Aggregation safety', ['Source', 'Type', 'Authoritative', 'Delete threshold (%)', 'Aggregations', 'Failed', 'Last good aggregation', 'Findings'], rows, Date.now(), o.notes) };
|
|
1433
|
+
}
|
|
1434
|
+
case 'service-accounts': {
|
|
1435
|
+
const o = await serviceAccounts(t, { now, unusedDays: num('unusedDays', 7, 730, 90), onProgress: progress });
|
|
1436
|
+
const rows = o.rows.map((x) => [x.account, x.source, x.subtype ?? null, x.owner ?? null, x.ownerState ?? null, x.enabled ? 'enabled' : 'disabled', x.hasAccess === null ? null : x.hasAccess ? 'yes' : 'no', x.lastUsed ? x.lastUsed.slice(0, 10) : null, x.findings.join('; ') || null]);
|
|
1437
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Service and machine accounts: ownership', ['Account', 'Source', 'Kind', 'Owner', 'Owner state', 'Account', 'Has access', 'Last used', 'Findings'], rows, Date.now(), o.notes) };
|
|
1438
|
+
}
|
|
1439
|
+
case 'multi-accounts': {
|
|
1440
|
+
const o = await multipleAccounts(t, { activeOnly: b['activeOnly'] !== false, onProgress: progress });
|
|
1441
|
+
const rows = o.rows.map((x) => [x.person, x.personState, x.source, x.authoritative ? 'yes' : null, x.accounts, x.enabled, x.names]);
|
|
1442
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('People with several accounts on one source', ['Person', 'Lifecycle state', 'Source', 'Authoritative source', 'Accounts', 'Enabled', 'Account names'], rows, Date.now(), o.notes) };
|
|
1443
|
+
}
|
|
1444
|
+
case 'password-failures': {
|
|
1445
|
+
const o = await passwordFailures(t, { now, days: num('days', 1, 90, 14), onProgress: progress });
|
|
1446
|
+
const rows = o.rows.map((x) => [x.when.slice(0, 16).replace('T', ' '), x.person, x.source, x.event, x.by || null, x.error || null]);
|
|
1447
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Password changes and syncs that failed', ['When', 'Person', 'Source', 'Event', 'Started by', 'Error'], rows, Date.now(), o.notes) };
|
|
1448
|
+
}
|
|
1449
|
+
case 'reassigned': {
|
|
1450
|
+
const o = await reassignedReviews(t, { now, days: num('days', 7, 730, 180), onProgress: progress });
|
|
1451
|
+
const rows = o.rows.map((x) => [x.campaign, x.certification, x.from, x.to, x.toState || null, x.comment || null, x.decisions, x.signed || null]);
|
|
1452
|
+
return { extra: o, table: tableResult('Reassigned reviews', ['Campaign', 'Certification', 'Reassigned from', 'Now with', 'Their state', 'Reason given', 'Decisions made', 'Signed off'], rows, Date.now(), o.notes) };
|
|
1453
|
+
}
|
|
1454
|
+
case 'mass-change': {
|
|
1455
|
+
const o = await massChange(t, { now, days: num('days', 7, 90, 30), factor: num('factor', 2, 20, 3), min: num('min', 5, 100_000, 50), onProgress: progress });
|
|
1456
|
+
const rows = o.series.flatMap((x) => x.daily.map((d) => [x.label, d.day, d.count]));
|
|
1457
|
+
return { extra: o, table: tableResult('Provisioning per day', ['Kind', 'Day', 'Changes'], rows, Date.now(), o.notes) };
|
|
1458
|
+
}
|
|
1459
|
+
case 'loops': {
|
|
1460
|
+
const o = await provisioningLoops(t, { now, days: num('days', 1, 30, 7), min: num('min', 3, 1000, 5), onProgress: progress });
|
|
1461
|
+
const rows = o.rows.map((x) => [x.person, x.source, x.op, x.change, x.times, x.first.slice(0, 16).replace('T', ' '), x.last.slice(0, 16).replace('T', ' '), x.lastStatus ?? null]);
|
|
1462
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Provisioning loops', ['Person', 'Source', 'Operation', 'Change', 'Times', 'First', 'Last', 'Last result'], rows, Date.now(), o.notes) };
|
|
1463
|
+
}
|
|
1464
|
+
case 'outside': {
|
|
1465
|
+
const o = await changesOutsideIsc(t, { now, days: num('days', 0, 3650, 0), sourceIds: ids, onProgress: progress });
|
|
1466
|
+
const rows = o.rows.map((x) => [x.person, x.personState, x.account, x.source, x.finding, x.lastIsc]);
|
|
1467
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Changes made outside ISC', ['Person', 'Person state', 'Account', 'Source', 'Finding', 'Last disable or enable ISC sent'], rows, Date.now(), o.notes) };
|
|
1468
|
+
}
|
|
1469
|
+
case 'leaver-times': {
|
|
1470
|
+
const o = await leaverRemovalTimes(t, { now, days: num('days', 1, 90, 30), limitHours: num('limitHours', 1, 720, 24), onProgress: progress });
|
|
1471
|
+
const rows = o.rows.map((x) => [x.person, x.lifecycle ?? null, x.started ? x.started.slice(0, 16).replace('T', ' ') : null, x.startedBy, x.accounts, x.slowestHours, x.stillEnabled.join(', ') || null, x.late ? 'late' : 'on time']);
|
|
1472
|
+
return { extra: o, table: tableResult('Leaver removal times', ['Person', 'Lifecycle state', 'Started', 'Started by', 'Accounts', 'Slowest removal (hours)', 'Still enabled on', 'Result'], rows, Date.now(), o.notes) };
|
|
1473
|
+
}
|
|
1474
|
+
case 'rules': {
|
|
1475
|
+
const o = await ruleUsage(t, { cloudRules: b['cloudRules'] === true, onProgress: progress });
|
|
1476
|
+
const rows = o.rows.map((x) => [x.rule, x.kind, x.usedBy.join('; ') || null, x.finding ?? null]);
|
|
1477
|
+
return { extra: o, table: tableResult('Where rules are used', ['Rule', 'Kind', 'Used by', 'Finding'], rows, Date.now(), o.notes) };
|
|
1478
|
+
}
|
|
1479
|
+
case 'sync-drift': {
|
|
1480
|
+
const o = await attributeSyncDrift(t, { sourceId: ids[0], now, days: num('days', 1, 90, 14), onProgress: progress });
|
|
1481
|
+
const rows = o.rows.map((x) => [x.person, x.account, x.identityAttribute, x.accountAttribute, x.inIsc, x.onAccount]);
|
|
1482
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult(`Attribute sync drift: ${o.source}`, ['Person', 'Account', 'Identity attribute', 'Account attribute', 'Value in ISC', 'Value on the account'], rows, Date.now(), o.notes) };
|
|
1483
|
+
}
|
|
1484
|
+
case 'group-approvals': {
|
|
1485
|
+
const o = await groupApprovals(t, { now, onProgress: progress });
|
|
1486
|
+
const rows = o.rows.map((x) => [x.group, x.request, x.requestedFor, x.waitingDays, x.members, x.activeMembers, x.leftMembers.join(', ') || null]);
|
|
1487
|
+
return { extra: o, table: tableResult('Approvals waiting on governance groups', ['Group', 'Access', 'Requested for', 'Waiting (days)', 'Members', 'Active members', 'Members who left'], rows, Date.now(), o.notes) };
|
|
1488
|
+
}
|
|
1489
|
+
case 'owners': {
|
|
1490
|
+
const o = await entitlementOwners(t, { onProgress: progress });
|
|
1491
|
+
const rows = o.rows.map((x) => [x.owner, x.entitlement, x.source, x.privileged ? 'yes' : null, x.holders]);
|
|
1492
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Entitlements by owner', ['Owner', 'Entitlement', 'Source', 'Privileged', 'Holders'], rows, Date.now(), o.notes) };
|
|
1493
|
+
}
|
|
1494
|
+
case 'manager-left': {
|
|
1495
|
+
const o = await managerLeft(t, { query, onProgress: progress });
|
|
1496
|
+
const rows = o.rows.map((x) => [x.person, x.lifecycle ?? null, x.profile ?? null, x.manager, x.managerState]);
|
|
1497
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('People whose manager left', ['Person', 'Lifecycle state', 'Identity profile', 'Manager', 'Manager state'], rows, Date.now(), o.notes) };
|
|
1498
|
+
}
|
|
1499
|
+
default: {
|
|
1500
|
+
const o = await attributeChanges(t, home, key, { attributes: attrs, now, onProgress: progress });
|
|
1501
|
+
const rows = o.changes.map((x) => [x.at.slice(0, 16).replace('T', ' '), x.person, x.attribute, x.from, x.to]);
|
|
1502
|
+
return { extra: { ...o, changes: o.changes.slice(0, 5000), more: Math.max(0, o.changes.length - 5000) }, table: tableResult('Attribute changes', ['Seen at', 'Person', 'Attribute', 'From', 'To'], rows, Date.now(), o.notes) };
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
};
|
|
1506
|
+
return send(res, 202, { job: background('reading ' + kind.replace('-', ' '), work) });
|
|
1507
|
+
}
|
|
1508
|
+
// ---------- 0.23.0: Non-Employee Risk Management (read-only) ----------
|
|
1509
|
+
const nermFile = join(home, 'nerm.json');
|
|
1510
|
+
const nermAddress = () => {
|
|
1511
|
+
// The demo tenant comes with a made-up NERM of its own; no other address is used with it.
|
|
1512
|
+
if (demo)
|
|
1513
|
+
return `${demo.url}/nerm`;
|
|
1514
|
+
const e = env()['ISC_NERM_URL'];
|
|
1515
|
+
if (e)
|
|
1516
|
+
return e;
|
|
1517
|
+
try {
|
|
1518
|
+
return JSON.parse(readFileSync(nermFile, 'utf8'))[tenant ?? ''];
|
|
1519
|
+
}
|
|
1520
|
+
catch {
|
|
1521
|
+
return undefined;
|
|
1522
|
+
}
|
|
1523
|
+
};
|
|
1524
|
+
if (route === 'GET /api/nerm/settings') {
|
|
1525
|
+
const a = nermAddress();
|
|
1526
|
+
return send(res, 200, { address: a ?? null, base: a ? nermBaseUrl(a) : null });
|
|
1527
|
+
}
|
|
1528
|
+
if (route === 'PUT /api/nerm/settings') {
|
|
1529
|
+
need();
|
|
1530
|
+
if (demo)
|
|
1531
|
+
throw new HttpProblem(400, 'The demo tenant comes with its own made-up NERM. Connect to your own tenant to set a NERM address.');
|
|
1532
|
+
const b = await readJson(req);
|
|
1533
|
+
const a = typeof b['address'] === 'string' ? b['address'].trim() : '';
|
|
1534
|
+
if (a) {
|
|
1535
|
+
try {
|
|
1536
|
+
nermBaseUrl(a);
|
|
1537
|
+
}
|
|
1538
|
+
catch (e) {
|
|
1539
|
+
return send(res, 400, { error: e.message });
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
let all = {};
|
|
1543
|
+
try {
|
|
1544
|
+
all = JSON.parse(readFileSync(nermFile, 'utf8'));
|
|
1545
|
+
}
|
|
1546
|
+
catch {
|
|
1547
|
+
/* first save */
|
|
1548
|
+
}
|
|
1549
|
+
if (a)
|
|
1550
|
+
all[tenant ?? ''] = a;
|
|
1551
|
+
else
|
|
1552
|
+
delete all[tenant ?? ''];
|
|
1553
|
+
writeFileSync(nermFile, JSON.stringify(all, null, 2), { mode: 0o600 });
|
|
1554
|
+
return send(res, 200, { address: a || null, base: a ? nermBaseUrl(a) : null });
|
|
1555
|
+
}
|
|
1556
|
+
const nm = /^POST \/api\/nerm\/(overview|sync|sessions|risk|users)\/run$/.exec(route);
|
|
1557
|
+
if (nm) {
|
|
1558
|
+
const t = need();
|
|
1559
|
+
const a = nermAddress();
|
|
1560
|
+
if (!a)
|
|
1561
|
+
return send(res, 400, { error: 'Enter your NERM address first (for example acme, or https://acme.nonemployee.com).' });
|
|
1562
|
+
if (!rawIsc)
|
|
1563
|
+
return send(res, 400, { error: 'NERM needs a sign-in with an API client or personal access token.' });
|
|
1564
|
+
const isc = rawIsc;
|
|
1565
|
+
const nerm = counted(new HttpTransport({ baseUrl: nermBaseUrl(a), tokenProvider: (force) => isc.accessToken(force), allow: assertNermReadOnly }));
|
|
1566
|
+
const b = await readJson(req);
|
|
1567
|
+
const now = opts.now?.() ?? new Date();
|
|
1568
|
+
const kind = nm[1];
|
|
1569
|
+
const work = async (progress) => {
|
|
1570
|
+
switch (kind) {
|
|
1571
|
+
case 'overview': {
|
|
1572
|
+
const days = Math.min(365, Math.max(1, Math.round(Number(b['days'])) || 30));
|
|
1573
|
+
const endAttribute = typeof b['endAttribute'] === 'string' ? b['endAttribute'].slice(0, 100) : undefined;
|
|
1574
|
+
const o = await nermOverview(nerm, t, { now, days, endAttribute, onProgress: progress });
|
|
1575
|
+
const row = (g, x) => [g, x.name, x.type, x.status, x.endDate ?? null, x.daysLeft ?? null, x.sponsors || null, x.sponsorProblem ?? null];
|
|
1576
|
+
const rows = [...o.pastEnd.map((x) => row('Past end date', x)), ...o.ending.map((x) => row('Ending soon', x)), ...o.sponsorIssues.map((x) => row('Sponsor', x))];
|
|
1577
|
+
return { extra: o, table: tableResult('Non-employees: end dates and sponsors', ['Finding', 'Profile', 'Type', 'Status', 'End date', 'Days left', 'Sponsor', 'Sponsor problem'], rows, Date.now(), o.notes) };
|
|
1578
|
+
}
|
|
1579
|
+
case 'sync': {
|
|
1580
|
+
const o = await nermSync(nerm, t, { onProgress: progress });
|
|
1581
|
+
const rows = o.rows.map((x) => [x.profile, x.type, x.nermStatus, x.iscPerson ?? null, x.iscState ?? null, x.problem]);
|
|
1582
|
+
return { extra: o, table: tableResult('NERM and ISC out of step', ['Profile', 'Type', 'Status in NERM', 'Identity in ISC', 'State in ISC', 'Problem'], rows, Date.now(), o.notes) };
|
|
1583
|
+
}
|
|
1584
|
+
case 'sessions': {
|
|
1585
|
+
const o = await nermSessions(nerm, { now, minDays: Math.max(0, Math.round(Number(b['minDays'])) || 0), onProgress: progress });
|
|
1586
|
+
const rows = o.waiting.map((x) => [x.workflow, x.status, x.profile ?? null, x.age ?? null, x.id]);
|
|
1587
|
+
return { extra: o, table: tableResult('NERM workflow sessions waiting', ['Workflow', 'Status', 'Profile', 'Age (days)', 'Session ID'], rows, Date.now(), o.notes) };
|
|
1588
|
+
}
|
|
1589
|
+
case 'risk': {
|
|
1590
|
+
const o = await nermRisk(nerm, { onProgress: progress });
|
|
1591
|
+
const rows = o.rows.map((x) => [x.profile, x.type, x.status, x.level, x.score]);
|
|
1592
|
+
return { extra: o, table: tableResult('High-risk non-employees', ['Profile', 'Type', 'Status', 'Risk level', 'Score'], rows, Date.now(), o.notes) };
|
|
1593
|
+
}
|
|
1594
|
+
default: {
|
|
1595
|
+
const o = await nermUsers(nerm, t, { onProgress: progress });
|
|
1596
|
+
const rows = o.rows.map((x) => [x.user, x.email ?? null, x.type, x.nermStatus, x.lastLogin ?? null, x.iscState]);
|
|
1597
|
+
return { extra: o, table: tableResult('NERM users who left', ['User', 'Email', 'Type', 'Status in NERM', 'Last login', 'State in ISC'], rows, Date.now(), o.notes) };
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
return send(res, 202, { job: background('reading NERM ' + kind, work) });
|
|
1602
|
+
}
|
|
1603
|
+
// ---------- joiner, mover and leaver gaps ----------
|
|
1604
|
+
const lm = /^POST \/api\/lifecycle\/(joiners|leavers|movers|accounts)\/run$/.exec(route);
|
|
1605
|
+
if (lm) {
|
|
1606
|
+
const t = need();
|
|
1607
|
+
const b = await readJson(req);
|
|
1608
|
+
const num = (k, min, max, dflt) => {
|
|
1609
|
+
const v = Number(b[k]);
|
|
1610
|
+
return Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : dflt;
|
|
1611
|
+
};
|
|
1612
|
+
const attr = (k) => (typeof b[k] === 'string' && /^[A-Za-z0-9_]{1,100}$/.test(String(b[k])) ? String(b[k]) : undefined);
|
|
1613
|
+
const now = opts.now?.() ?? new Date();
|
|
1614
|
+
const kind = lm[1];
|
|
1615
|
+
return send(res, 202, {
|
|
1616
|
+
job: background('lifecycle: ' + kind, async (progress) => {
|
|
1617
|
+
if (kind === 'movers') {
|
|
1618
|
+
// Two passes over ISC instead of holding everyone's entitlements in memory.
|
|
1619
|
+
const o = await moverLeftoversStreamed(t, { groupBy: attr('groupBy'), maxShare: num('maxShare', 1, 25, 5) / 100, maxHolders: num('maxHolders', 1, 50, 3), onProgress: progress });
|
|
1620
|
+
const rows = o.rows.map((x) => [x.person, x.email ?? null, x.group, x.access, x.type, x.source ?? null, `${x.holders} of ${x.groupSize}`, x.privileged ? 'yes' : null]);
|
|
1621
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Unusual access for the group', ['Person', 'Email', `Group (${o.groupBy})`, 'Access', 'Type', 'Source', 'Holders in group', 'Privileged'], rows, Date.now(), o.notes) };
|
|
1622
|
+
}
|
|
1623
|
+
if (kind === 'leavers') {
|
|
1624
|
+
// One person at a time: nobody is kept in memory.
|
|
1625
|
+
const lw = leaverWork();
|
|
1626
|
+
for await (const p of eachPerson(t, { access: 'model', attributes: [], onProgress: progress }))
|
|
1627
|
+
lw.add(p);
|
|
1628
|
+
const o = lw.done();
|
|
1629
|
+
const rows = o.rows.map((x) => [x.person, x.email ?? null, x.lifecycle ?? null, x.kind, x.detail, x.source ?? null, x.lastChanged ? x.lastChanged.slice(0, 10) : null]);
|
|
1630
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Missed leavers', ['Person', 'Email', 'Lifecycle state', 'Gap', 'Detail', 'Source', 'Identity last changed'], rows, Date.now(), o.notes) };
|
|
1631
|
+
}
|
|
1632
|
+
// Joiners and leavers need accounts, roles and access profiles, and at most one identity attribute.
|
|
1633
|
+
const startAttr = attr('startDateAttribute');
|
|
1634
|
+
const people = await readPeople(t, { access: 'model', attributes: startAttr ? [startAttr] : [], onProgress: progress });
|
|
1635
|
+
progress('Comparing...');
|
|
1636
|
+
if (kind === 'joiners') {
|
|
1637
|
+
const graceDays = num('graceDays', 0, 90, 3);
|
|
1638
|
+
const o = missedJoiners(people, { now, share: num('share', 50, 100, 90) / 100, graceDays, startDateAttribute: attr('startDateAttribute') });
|
|
1639
|
+
if (b['verify'] === false) {
|
|
1640
|
+
const rows = o.rows.map((x) => [x.person, x.email ?? null, x.profile, x.lifecycle ?? null, x.created ? x.created.slice(0, 10) : null, x.reason, x.missing.join(', ') || null]);
|
|
1641
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Missed joiners', ['Person', 'Email', 'Identity profile', 'Lifecycle state', 'Created', 'Why', 'Missing accounts on'], rows, Date.now(), o.notes) };
|
|
1642
|
+
}
|
|
1643
|
+
// Check each finding against ISC's own records: lifecycle state configuration, joiner criteria and recorded activity.
|
|
1644
|
+
const ev = await joinerEvidence(t, people, { now, graceDays, recentDays: num('recentDays', 1, 365, 30), max: num('maxChecks', 1, 1000, 200), also: o.rows.map((x) => ({ id: x.id, reason: x.reason })), onProgress: progress });
|
|
1645
|
+
const rows = ev.rows.map((x) => [x.person, x.email ?? null, x.profile, x.lifecycle ?? null, x.criteria ?? x.criteriaNote ?? null, x.created ? x.created.slice(0, 10) : null, x.verdict, x.why, x.missing.join(', ') || null, x.evidence.map((e) => `${e.when ? e.when.slice(0, 10) + ' ' : ''}${e.what}${e.status ? ` [${e.status}]` : ''}${e.detail ? `: ${e.detail}` : ''}`).join(' | ') || null, x.reason]);
|
|
1646
|
+
return {
|
|
1647
|
+
extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000), evidence: ev },
|
|
1648
|
+
table: tableResult('Joiner check', ['Person', 'Email', 'Identity profile', 'Lifecycle state in ISC', 'Lifecycle state by the criteria', 'Created', 'Verdict', 'Why', 'Missing', 'Recorded by ISC', 'Checked because'], rows, Date.now(), [...ev.notes, ...o.notes]),
|
|
1649
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
const words = Array.isArray(b['words']) ? b['words'].map(String).filter((w) => /^[A-Za-z0-9]{1,20}$/.test(w)).slice(0, 30) : undefined;
|
|
1652
|
+
const o = linkedAdminAccounts(people, { words: words?.length ? words : undefined });
|
|
1653
|
+
const rows = o.rows.map((x) => [x.person, x.email ?? null, x.left ? 'left' : 'active', x.account, x.source, x.word, x.privileged ? 'yes' : null, x.disabled ? 'disabled' : 'enabled']);
|
|
1654
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000) }, table: tableResult('Admin and service accounts linked to people', ['Person', 'Email', 'Person status', 'Account', 'Source', 'Matched', 'Privileged', 'Account state'], rows, Date.now(), o.notes) };
|
|
1655
|
+
}),
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
// ---------- accepted exceptions ----------
|
|
1659
|
+
if (route === 'GET /api/exceptions') {
|
|
1660
|
+
const now = opts.now?.() ?? new Date();
|
|
1661
|
+
return send(res, 200, { tenant: tenant ?? null, exceptions: readExceptions(home).map((e) => ({ ...e, state: stateOf(e, now) })).reverse() });
|
|
1662
|
+
}
|
|
1663
|
+
if (route === 'POST /api/exceptions') {
|
|
1664
|
+
need();
|
|
1665
|
+
const now = opts.now?.() ?? new Date();
|
|
1666
|
+
const v = validateException(await readJson(req), CHECKS, now);
|
|
1667
|
+
if (!v.value)
|
|
1668
|
+
throw new DefinitionError('The exception was not saved', v.problems);
|
|
1669
|
+
const e = addException(home, tenant ?? 'tenant', v.value, now);
|
|
1670
|
+
log(`exception accepted on ${tenant}: ${e.checkLabel} / ${e.key} until ${e.until}`);
|
|
1671
|
+
return send(res, 200, { exception: { ...e, state: stateOf(e, now) } });
|
|
1672
|
+
}
|
|
1673
|
+
const em = /^POST \/api\/exceptions\/([0-9a-f-]{36})\/end$/.exec(route);
|
|
1674
|
+
if (em) {
|
|
1675
|
+
const b = await readJson(req);
|
|
1676
|
+
const e = endException(home, em[1], String(b['by'] ?? '').trim(), opts.now?.() ?? new Date());
|
|
1677
|
+
if (!e)
|
|
1678
|
+
throw new HttpProblem(404, 'No such exception.');
|
|
1679
|
+
return send(res, 200, { exception: { ...e, state: stateOf(e) } });
|
|
1680
|
+
}
|
|
1681
|
+
// ---------- audit readiness ----------
|
|
1682
|
+
const am = /^POST \/api\/audit\/(outliers|coverage|speed|quality)\/run$/.exec(route);
|
|
1683
|
+
if (am) {
|
|
1684
|
+
const t = need();
|
|
1685
|
+
const b = await readJson(req);
|
|
1686
|
+
const num = (k, min, max, dflt) => {
|
|
1687
|
+
const v = Number(b[k]);
|
|
1688
|
+
return Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : dflt;
|
|
1689
|
+
};
|
|
1690
|
+
const attr = (k) => (typeof b[k] === 'string' && /^[A-Za-z0-9_]{1,100}$/.test(String(b[k])) ? String(b[k]) : undefined);
|
|
1691
|
+
const now = opts.now?.() ?? new Date();
|
|
1692
|
+
const kind = am[1];
|
|
1693
|
+
const work = async (progress) => {
|
|
1694
|
+
switch (kind) {
|
|
1695
|
+
case 'outliers': {
|
|
1696
|
+
const o = await accessOutliers(t, { groupBy: attr('groupBy'), factor: num('factor', 1.5, 20, 3), minExtra: num('minExtra', 0, 10_000, 10), minGroup: num('minGroup', 3, 1000, 5), onProgress: progress });
|
|
1697
|
+
const rows = o.rows.map((x) => [x.person, x.email ?? null, x.group, x.access, x.groupMedian, x.times, x.entitlements, x.roles]);
|
|
1698
|
+
return { extra: o, table: tableResult('Access outliers', ['Person', 'Email', `Group (${o.groupBy})`, 'Access items', 'Group median', 'Times the median', 'Entitlements', 'Roles'], rows, Date.now(), o.notes) };
|
|
1699
|
+
}
|
|
1700
|
+
case 'coverage': {
|
|
1701
|
+
const o = await reviewCoverage(t, { now, months: num('months', 1, 36, 12), onProgress: progress });
|
|
1702
|
+
const rows = [
|
|
1703
|
+
...o.notReviewedSources.map((x) => ['Source not reviewed', x, null, null]),
|
|
1704
|
+
...o.privileged.notReviewed.map((x) => ['Privileged entitlement not reviewed', x.name, x.source ?? null, null]),
|
|
1705
|
+
...o.sources.map((x) => ['Source reviewed', x.source, x.reviewedItems, x.lastReviewed ? x.lastReviewed.slice(0, 10) : null]),
|
|
1706
|
+
];
|
|
1707
|
+
return { extra: o, table: tableResult('Certification coverage', ['Finding', 'Name', 'Source / items reviewed', 'Latest review'], rows, Date.now(), o.notes) };
|
|
1708
|
+
}
|
|
1709
|
+
case 'speed': {
|
|
1710
|
+
const o = await provisioningSpeed(t, { now, days: num('days', 1, 90, 30), removalLimitHours: num('removalLimitHours', 1, 720, 24), otherLimitHours: num('otherLimitHours', 1, 720, 72), onProgress: progress });
|
|
1711
|
+
const rows = o.slow.map((x) => [x.person, x.source, x.op, x.started.slice(0, 16).replace('T', ' '), x.state, x.hours, x.status ?? null]);
|
|
1712
|
+
return { extra: o, table: tableResult('Slow or open access removals', ['Person', 'Source', 'Change', 'Started (UTC)', 'State', 'Hours', 'Status'], rows, Date.now(), o.notes) };
|
|
1713
|
+
}
|
|
1714
|
+
default: {
|
|
1715
|
+
const o = await identityDataQuality(t, { attribute: attr('attribute'), onProgress: progress });
|
|
1716
|
+
const rows = o.rows.map((x) => [x.person, x.email ?? null, x.lifecycle ?? null, x.issue]);
|
|
1717
|
+
return { extra: { ...o, rows: o.rows.slice(0, 5000), more: Math.max(0, o.rows.length - 5000), sharedEmails: o.sharedEmails.slice(0, 500) }, table: tableResult('Identity data quality', ['Person', 'Email', 'Lifecycle state', 'Issue'], rows, Date.now(), o.notes) };
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
};
|
|
1721
|
+
return send(res, 202, { job: background('audit: ' + kind, work) });
|
|
1722
|
+
}
|
|
1723
|
+
// ---------- API credentials ----------
|
|
1724
|
+
if (route === 'GET /api/credentials/mine') {
|
|
1725
|
+
const t = need();
|
|
1726
|
+
// Signed in with SailPoint: there is no token of ours to expire.
|
|
1727
|
+
if (!creds || signedInAs !== undefined)
|
|
1728
|
+
return send(res, 200, { kind: 'sign-in' });
|
|
1729
|
+
try {
|
|
1730
|
+
const mine = await ownTokenExpiry(t, creds.clientId);
|
|
1731
|
+
return send(res, 200, mine ? { kind: 'token', ...mine } : { kind: 'unknown' });
|
|
1732
|
+
}
|
|
1733
|
+
catch {
|
|
1734
|
+
return send(res, 200, { kind: 'unknown' });
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
if (route === 'POST /api/credentials/run') {
|
|
1738
|
+
const t = need();
|
|
1739
|
+
const b = await readJson(req);
|
|
1740
|
+
const expiringDays = Math.min(365, Math.max(1, Number(b['expiringDays']) || 30));
|
|
1741
|
+
const unusedDays = Math.min(730, Math.max(7, Number(b['unusedDays']) || 90));
|
|
1742
|
+
const clientId = signedInAs === undefined ? creds?.clientId : undefined;
|
|
1743
|
+
return send(res, 202, {
|
|
1744
|
+
job: background('reading API credentials', async (progress) => {
|
|
1745
|
+
const o = await credentialsOverview(t, { expiringDays, unusedDays, clientId, onProgress: progress });
|
|
1746
|
+
const rows = o.credentials.map((c) => [c.kind, c.name, c.owner ?? null, c.ownerStatus ?? null, c.expires === undefined ? null : c.expires === null ? 'never' : c.expires.slice(0, 10), c.lastUsed ? c.lastUsed.slice(0, 10) : null, c.created ? c.created.slice(0, 10) : null, c.scopes.join(' ') || '(all of the owner\'s rights)', c.flags.join('; ')]);
|
|
1747
|
+
return { extra: o, table: tableResult('API credentials', ['Type', 'Name', 'Owner', 'Owner status', 'Expires', 'Last used', 'Created', 'Scopes', 'Needs attention'], rows, Date.now(), o.notes) };
|
|
1748
|
+
}),
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
// ---------- insights: license reclaim, separation of duties, requests, role mining ----------
|
|
1752
|
+
const extraSettings = () => readSettings();
|
|
1753
|
+
if (route === 'GET /api/insights/settings') {
|
|
1754
|
+
const st = extraSettings();
|
|
1755
|
+
return send(res, 200, { reclaim: st.reclaim ?? {}, sod: st.sod ?? [] });
|
|
1756
|
+
}
|
|
1757
|
+
if (route === 'PUT /api/reclaim/settings') {
|
|
1758
|
+
const b = await readJson(req);
|
|
1759
|
+
const problems = [];
|
|
1760
|
+
const out = {};
|
|
1761
|
+
if (b['dormantDays'] !== undefined) {
|
|
1762
|
+
const d = Number(b['dormantDays']);
|
|
1763
|
+
Number.isInteger(d) && d >= 7 && d <= 3650 ? (out.dormantDays = d) : problems.push('Days without sign-in must be a whole number from 7 to 3650');
|
|
1764
|
+
}
|
|
1765
|
+
if (Array.isArray(b['leaverStates']))
|
|
1766
|
+
out.leaverStates = b['leaverStates'].map((x) => String(x).trim()).filter(Boolean).slice(0, 20);
|
|
1767
|
+
if (typeof b['currency'] === 'string')
|
|
1768
|
+
out.currency = b['currency'].trim().slice(0, 8);
|
|
1769
|
+
const srcs = (b['sources'] && typeof b['sources'] === 'object' ? b['sources'] : {});
|
|
1770
|
+
out.sources = {};
|
|
1771
|
+
for (const [name, v] of Object.entries(srcs).slice(0, 2000)) {
|
|
1772
|
+
const one = {};
|
|
1773
|
+
if (v['cost'] !== undefined && v['cost'] !== null && v['cost'] !== '') {
|
|
1774
|
+
const c = Number(v['cost']);
|
|
1775
|
+
Number.isFinite(c) && c >= 0 && c <= 1e6 ? (one.cost = c) : problems.push(`${name}: the cost must be a number of 0 or more`);
|
|
1776
|
+
}
|
|
1777
|
+
if (typeof v['lastLogin'] === 'string' && v['lastLogin'].trim()) {
|
|
1778
|
+
/^[A-Za-z0-9_.:-]{1,100}$/.test(v['lastLogin'].trim()) ? (one.lastLogin = v['lastLogin'].trim()) : problems.push(`${name}: the sign-in attribute name has characters that are not allowed`);
|
|
1779
|
+
}
|
|
1780
|
+
if (one.cost !== undefined || one.lastLogin)
|
|
1781
|
+
out.sources[name] = one;
|
|
1782
|
+
}
|
|
1783
|
+
if (problems.length)
|
|
1784
|
+
throw new DefinitionError('Some settings are not valid', problems);
|
|
1785
|
+
writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), reclaim: out }, null, 2));
|
|
1786
|
+
return send(res, 200, { saved: true });
|
|
1787
|
+
}
|
|
1788
|
+
if (route === 'POST /api/reclaim/run') {
|
|
1789
|
+
const t = need();
|
|
1790
|
+
const st = extraSettings().reclaim ?? {};
|
|
1791
|
+
return send(res, 202, {
|
|
1792
|
+
job: background('looking for licenses to reclaim', async (progress) => {
|
|
1793
|
+
const o = await reclaimOverview(t, st, { onProgress: progress });
|
|
1794
|
+
const rows = o.rows.map((r) => [r.source, r.account, r.person ?? null, r.lifecycleState ?? null, r.reason, r.lastLogin ? r.lastLogin.slice(0, 10) : null, r.daysSince, r.privileged, r.monthlyCost]);
|
|
1795
|
+
return { extra: o, table: tableResult('Accounts to reclaim', ['Source', 'Account', 'Person', 'Lifecycle state', 'Why', 'Last sign-in', 'Days since sign-in', 'Privileged', 'Monthly cost'], rows, Date.now(), o.notes) };
|
|
1796
|
+
}),
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
if (route === 'PUT /api/sod/rules') {
|
|
1800
|
+
const b = await readJson(req);
|
|
1801
|
+
const { rules, problems } = validateSodRules(b['rules']);
|
|
1802
|
+
if (problems.length)
|
|
1803
|
+
throw new DefinitionError('Some rules are not valid', problems);
|
|
1804
|
+
writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), sod: rules }, null, 2));
|
|
1805
|
+
return send(res, 200, { saved: rules.length });
|
|
1806
|
+
}
|
|
1807
|
+
if (route === 'POST /api/sod/run') {
|
|
1808
|
+
const t = need();
|
|
1809
|
+
const rules = extraSettings().sod ?? [];
|
|
1810
|
+
if (!rules.length)
|
|
1811
|
+
throw new HttpProblem(400, 'Add a rule first.');
|
|
1812
|
+
return send(res, 202, {
|
|
1813
|
+
job: background('checking separation of duties', async (progress) => {
|
|
1814
|
+
const o = await sodOverview(t, rules, { onProgress: progress });
|
|
1815
|
+
const rows = o.violations.map((v) => [v.rule, v.person, v.username ?? null, v.email ?? null, v.lifecycleState ?? null, v.heldA.join('; '), v.heldB.join('; ')]);
|
|
1816
|
+
return { extra: o, table: tableResult('Separation of duties violations', ['Rule', 'Person', 'Username', 'Email', 'Lifecycle state', 'Holds (side A)', 'Holds (side B)'], rows, Date.now()) };
|
|
1817
|
+
}),
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
if (route === 'POST /api/requests/run') {
|
|
1821
|
+
const t = need();
|
|
1822
|
+
const b = await readJson(req);
|
|
1823
|
+
const days = Math.min(365, Math.max(7, Number(b['days']) || 90));
|
|
1824
|
+
return send(res, 202, {
|
|
1825
|
+
job: background('reading access requests', async (progress) => {
|
|
1826
|
+
const o = await requestInsights(t, { days, onProgress: progress });
|
|
1827
|
+
const rows = o.approvers.map((a) => [a.name, a.decisions, a.approved, a.rejected, a.medianHours, a.pending, a.oldestPendingDays]);
|
|
1828
|
+
return { extra: o, table: tableResult('Access request approvers', ['Approver', 'Decisions', 'Approved', 'Rejected', 'Median hours to decide', 'Waiting now', 'Oldest waiting (days)'], rows, Date.now(), o.notes) };
|
|
1829
|
+
}),
|
|
1830
|
+
});
|
|
1831
|
+
}
|
|
1832
|
+
if (route === 'POST /api/mining/run') {
|
|
1833
|
+
const t = need();
|
|
1834
|
+
const b = await readJson(req);
|
|
1835
|
+
const attribute = String(b['attribute'] ?? 'department').trim();
|
|
1836
|
+
if (!/^[A-Za-z0-9_.-]{1,100}$/.test(attribute))
|
|
1837
|
+
throw new HttpProblem(400, 'Pick an identity attribute.');
|
|
1838
|
+
const minGroup = Math.min(10_000, Math.max(1, Math.floor(Number(b['minGroup']) || 5)));
|
|
1839
|
+
const minShare = Math.min(100, Math.max(50, Math.floor(Number(b['minShare']) || 80)));
|
|
1840
|
+
return send(res, 202, {
|
|
1841
|
+
job: background('looking for candidate roles', async (progress) => {
|
|
1842
|
+
const o = await roleMining(t, { attribute, minGroup, minShare, onProgress: progress });
|
|
1843
|
+
const rows = [];
|
|
1844
|
+
for (const c of o.candidates)
|
|
1845
|
+
for (const i of c.items)
|
|
1846
|
+
rows.push([c.value, c.members, i.name, i.source ?? null, i.holders, i.share, i.covered]);
|
|
1847
|
+
return { extra: o, table: tableResult(`Candidate roles by ${attribute}`, [attribute, 'People in group', 'Entitlement', 'Source', 'Holders', 'Share %', 'Already in a role'], rows, Date.now(), o.notes) };
|
|
1848
|
+
}),
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
// ---------- configuration change history ----------
|
|
1852
|
+
const changeHistory = () => new ChangeHistory(join(home, 'changes'));
|
|
1853
|
+
if (route === 'GET /api/changes') {
|
|
1854
|
+
if (!tenant)
|
|
1855
|
+
throw new HttpProblem(400, 'Connect to a tenant first.');
|
|
1856
|
+
return send(res, 200, { tenant, days: changeHistory().list(tenant) });
|
|
1857
|
+
}
|
|
1858
|
+
if (route === 'POST /api/changes/snapshot') {
|
|
1859
|
+
const t = need();
|
|
1860
|
+
const tk = tenant ?? 'tenant';
|
|
1861
|
+
return send(res, 202, {
|
|
1862
|
+
job: background('taking a configuration snapshot', async (progress) => {
|
|
1863
|
+
const snap = await takeSnapshot(t, tk, new Date(), progress);
|
|
1864
|
+
const day = changeHistory().save(snap);
|
|
1865
|
+
const rows = Object.entries(snap.kinds).map(([k, v]) => [k, Object.keys(v ?? {}).length]);
|
|
1866
|
+
return { extra: { day, errors: snap.errors }, table: tableResult('Configuration snapshot', ['Type', 'Objects'], rows, Date.now()) };
|
|
1867
|
+
}),
|
|
1868
|
+
});
|
|
1869
|
+
}
|
|
1870
|
+
if (route === 'GET /api/changes/diff') {
|
|
1871
|
+
if (!tenant)
|
|
1872
|
+
throw new HttpProblem(400, 'Connect to a tenant first.');
|
|
1873
|
+
const h = changeHistory();
|
|
1874
|
+
const [from, to] = [url.searchParams.get('from') ?? '', url.searchParams.get('to') ?? ''];
|
|
1875
|
+
const a = h.load(tenant, from);
|
|
1876
|
+
const b2 = h.load(tenant, to);
|
|
1877
|
+
if (!a || !b2)
|
|
1878
|
+
throw new HttpProblem(404, 'Pick two days that have a snapshot.');
|
|
1879
|
+
const [older, newer] = a.taken <= b2.taken ? [a, b2] : [b2, a];
|
|
1880
|
+
return send(res, 200, { from: older.taken.slice(0, 10), to: newer.taken.slice(0, 10), kinds: diffSnapshots(older, newer) });
|
|
1881
|
+
}
|
|
1882
|
+
// ---------- Build & test: impact, policy preview, workflow health, drift ----------
|
|
1883
|
+
if (route === 'POST /api/build/impact/run') {
|
|
1884
|
+
const t = need();
|
|
1885
|
+
return send(res, 202, {
|
|
1886
|
+
job: background('finding where transforms are used', async (progress) => {
|
|
1887
|
+
const o = await transformImpact(t, progress);
|
|
1888
|
+
const rows = o.transforms.flatMap((x) => (x.uses.length ? x.uses.map((u) => [x.name, u.kind, u.where, u.detail ?? null, u.via.length ? u.via.join(' → ') : 'directly']) : [[x.name, 'Not used', null, null, null]]));
|
|
1889
|
+
return { extra: o, table: tableResult('Where transforms are used', ['Transform', 'Used by', 'Where', 'Attribute or field', 'How'], rows, Date.now(), o.notes) };
|
|
1890
|
+
}),
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
if (route === 'GET /api/build/sources') {
|
|
1894
|
+
const t = need();
|
|
1895
|
+
const list = [];
|
|
1896
|
+
for await (const x of pageList(t, '/sources/v1', {}))
|
|
1897
|
+
list.push({ id: x['id'], name: x['name'], type: x['type'] ?? x['connectorName'] });
|
|
1898
|
+
return send(res, 200, list);
|
|
1899
|
+
}
|
|
1900
|
+
if (route === 'POST /api/build/policy/run') {
|
|
1901
|
+
const t = need();
|
|
1902
|
+
const b = await readJson(req);
|
|
1903
|
+
const sourceId = String(b['sourceId'] ?? '');
|
|
1904
|
+
const person = String(b['person'] ?? '').trim();
|
|
1905
|
+
if (!/^[A-Za-z0-9-]+$/.test(sourceId))
|
|
1906
|
+
throw new HttpProblem(400, 'Pick a source.');
|
|
1907
|
+
if (!person)
|
|
1908
|
+
throw new HttpProblem(400, 'Name the person (username, email or display name).');
|
|
1909
|
+
const usageType = /^[A-Z_]{2,40}$/.test(String(b['usageType'] ?? '')) ? String(b['usageType']) : 'CREATE';
|
|
1910
|
+
return send(res, 202, {
|
|
1911
|
+
job: background('previewing an account', async (progress) => {
|
|
1912
|
+
const o = await policyPreview(t, { sourceId, usageType, person, now: opts.now?.() ?? new Date(), onProgress: progress });
|
|
1913
|
+
const rows = o.fields.map((f) => [f.field, f.required ? 'yes' : null, f.value === undefined || f.value === null ? null : typeof f.value === 'string' ? f.value : JSON.stringify(f.value), f.status, f.error ?? f.note ?? null]);
|
|
1914
|
+
return { extra: o, table: tableResult(`${o.source} ${o.usageType} preview${o.person ? `: ${o.person.name}` : ''}`, ['Field', 'Required', 'Value', 'Result', 'Note'], rows, Date.now(), [...o.warnings, ...o.assumptions]) };
|
|
1915
|
+
}),
|
|
1916
|
+
});
|
|
1917
|
+
}
|
|
1918
|
+
if (route === 'POST /api/build/health/run') {
|
|
1919
|
+
const t = need();
|
|
1920
|
+
const b = await readJson(req);
|
|
1921
|
+
return send(res, 202, {
|
|
1922
|
+
job: background('reading workflow health', async (progress) => {
|
|
1923
|
+
const o = await workflowHealth(t, { days: Number(b['days']) || 30, now: opts.now?.() ?? new Date(), onProgress: progress });
|
|
1924
|
+
const rows = o.workflows.map((w) => [w.name, w.enabled ? 'yes' : 'no', w.trigger ?? null, w.owner ?? null, w.failedOnly ? null : w.runs, w.failed, w.rate, w.weeks.map((x) => `${x.failed}/${x.runs}`).join(' '), w.lastRun ?? null, w.flags.join('; ') || null, w.topCause ?? null]);
|
|
1925
|
+
return { extra: o, table: tableResult(`Workflow health, last ${o.days} days`, ['Workflow', 'Enabled', 'Trigger', 'Owner', 'Runs', 'Failed', 'Failure %', 'Failed/runs per week', 'Last run', 'Flags', 'Most common cause'], rows, Date.now(), o.notes) };
|
|
1926
|
+
}),
|
|
1927
|
+
});
|
|
1928
|
+
}
|
|
1929
|
+
const baselines = () => new Baselines(join(home, 'baselines'));
|
|
1930
|
+
if (route === 'GET /api/build/drift') {
|
|
1931
|
+
if (!tenant)
|
|
1932
|
+
throw new HttpProblem(400, 'Connect to a tenant first.');
|
|
1933
|
+
return send(res, 200, { baseline: baselines().get(tenant)?.baseline ?? null, days: changeHistory().list(tenant) });
|
|
1934
|
+
}
|
|
1935
|
+
if (route === 'POST /api/build/drift/baseline') {
|
|
1936
|
+
if (!tenant)
|
|
1937
|
+
throw new HttpProblem(400, 'Connect to a tenant first.');
|
|
1938
|
+
const b = await readJson(req);
|
|
1939
|
+
const day = String(b['day'] ?? '');
|
|
1940
|
+
if (!day) {
|
|
1941
|
+
baselines().clear(tenant);
|
|
1942
|
+
return send(res, 200, { baseline: null });
|
|
1943
|
+
}
|
|
1944
|
+
const snap = changeHistory().load(tenant, day);
|
|
1945
|
+
if (!snap)
|
|
1946
|
+
throw new HttpProblem(404, 'Pick a day that has a snapshot.');
|
|
1947
|
+
const baseline = { day, note: String(b['note'] ?? '').slice(0, 300), by: signedInAs ?? 'this computer', approvedAt: new Date().toISOString() };
|
|
1948
|
+
baselines().set(tenant, baseline, snap);
|
|
1949
|
+
return send(res, 200, { baseline });
|
|
1950
|
+
}
|
|
1951
|
+
if (route === 'POST /api/build/drift/run') {
|
|
1952
|
+
const t = need();
|
|
1953
|
+
const tk = tenant ?? 'tenant';
|
|
1954
|
+
const saved = baselines().get(tk);
|
|
1955
|
+
if (!saved)
|
|
1956
|
+
throw new HttpProblem(400, 'Approve a baseline first.');
|
|
1957
|
+
return send(res, 202, {
|
|
1958
|
+
job: background('checking for drift', async (progress) => {
|
|
1959
|
+
const now = await takeSnapshot(t, tk, opts.now?.() ?? new Date(), progress);
|
|
1960
|
+
const d = drift(saved.baseline, saved.snapshot, now);
|
|
1961
|
+
const rows = d.kinds.flatMap((k) => [
|
|
1962
|
+
...k.onlyB.map((n) => [k.label, 'Added since the baseline', n, null]),
|
|
1963
|
+
...k.onlyA.map((n) => [k.label, 'Removed since the baseline', n, null]),
|
|
1964
|
+
...k.different.map((x) => [k.label, 'Changed', x.name, x.differences.slice(0, 5).map((f) => `${f.path}: ${f.a} → ${f.b}`).join('; ')]),
|
|
1965
|
+
]);
|
|
1966
|
+
const notes = d.kinds.filter((k) => k.error).map((k) => `${k.label}: ${k.error}`);
|
|
1967
|
+
return { extra: d, table: tableResult(`Drift since ${saved.baseline.day}`, ['Type', 'Change', 'Name', 'What changed'], rows, Date.now(), notes) };
|
|
1968
|
+
}),
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1971
|
+
// ---------- audit evidence pack ----------
|
|
1972
|
+
if (route === 'GET /api/evidence')
|
|
1973
|
+
return send(res, 200, { sections: EVIDENCE_SECTIONS.map(({ id, label, description }) => ({ id, label, description })) });
|
|
1974
|
+
if (route === 'POST /api/evidence/run') {
|
|
1975
|
+
const t = need();
|
|
1976
|
+
const b = await readJson(req);
|
|
1977
|
+
const sections = Array.isArray(b['sections']) ? b['sections'].map(String) : [];
|
|
1978
|
+
const days = Math.min(730, Math.max(7, Number(b['days']) || 365));
|
|
1979
|
+
const tk = tenant ?? 'tenant';
|
|
1980
|
+
const by = signedInAs;
|
|
1981
|
+
let jobId = '';
|
|
1982
|
+
jobId = background('building the audit evidence pack', async (progress) => {
|
|
1983
|
+
const pack = await buildEvidencePack({
|
|
1984
|
+
transport: t,
|
|
1985
|
+
tenant: tk,
|
|
1986
|
+
loadReport: (rid) => {
|
|
1987
|
+
const r = findReport(rid);
|
|
1988
|
+
if (!r)
|
|
1989
|
+
throw new Error(`Report ${rid} is missing`);
|
|
1990
|
+
return r.definition;
|
|
1991
|
+
},
|
|
1992
|
+
sections,
|
|
1993
|
+
days,
|
|
1994
|
+
sodRules: extraSettings().sod ?? [],
|
|
1995
|
+
exceptions: readExceptions(home).filter((e) => e.tenant === tk),
|
|
1996
|
+
version: opts.version ?? '',
|
|
1997
|
+
generatedBy: by,
|
|
1998
|
+
onProgress: progress,
|
|
1999
|
+
});
|
|
2000
|
+
evidencePacks.set(jobId, pack);
|
|
2001
|
+
while (evidencePacks.size > 3)
|
|
2002
|
+
evidencePacks.delete(evidencePacks.keys().next().value);
|
|
2003
|
+
const rows = pack.files.map((f) => [f.section, f.error ? 'not included' : f.name, f.rows, f.error ?? f.sha256]);
|
|
2004
|
+
return { extra: { files: pack.files, fileName: pack.fileName }, table: tableResult('Audit evidence pack', ['Part', 'File', 'Rows', 'SHA-256 or problem'], rows, Date.now()) };
|
|
2005
|
+
});
|
|
2006
|
+
return send(res, 202, { job: jobId });
|
|
2007
|
+
}
|
|
2008
|
+
const evDl = /^GET \/api\/evidence\/([0-9a-f]{16})\/download$/.exec(route);
|
|
2009
|
+
if (evDl) {
|
|
2010
|
+
const pack = evidencePacks.get(evDl[1]);
|
|
2011
|
+
if (!pack)
|
|
2012
|
+
throw new HttpProblem(404, 'The pack is no longer available. Build it again.');
|
|
2013
|
+
res.writeHead(200, {
|
|
2014
|
+
'content-type': 'application/zip',
|
|
2015
|
+
'content-disposition': `attachment; filename="${pack.fileName}"`,
|
|
2016
|
+
'cache-control': 'no-store',
|
|
2017
|
+
'x-content-type-options': 'nosniff',
|
|
2018
|
+
});
|
|
2019
|
+
res.end(Buffer.from(pack.zip));
|
|
2020
|
+
return;
|
|
2021
|
+
}
|
|
2022
|
+
// ---------- report packs ----------
|
|
2023
|
+
if (route === 'GET /api/packs/download') {
|
|
2024
|
+
const ids = (url.searchParams.get('ids') ?? '').split(',').filter(Boolean);
|
|
2025
|
+
const chosen = allReports().filter((r) => ids.includes(r.definition.id));
|
|
2026
|
+
if (!chosen.length)
|
|
2027
|
+
throw new HttpProblem(400, 'Choose at least one report.');
|
|
2028
|
+
const pack = makePack(chosen.map((r) => ({ id: r.definition.id, name: r.definition.name, yaml: r.yaml })), url.searchParams.get('name') ?? undefined);
|
|
2029
|
+
res.writeHead(200, {
|
|
2030
|
+
'content-type': 'application/json; charset=utf-8',
|
|
2031
|
+
'content-disposition': `attachment; filename="identityscope-reports-${new Date().toISOString().slice(0, 10)}.json"`,
|
|
2032
|
+
'cache-control': 'no-store',
|
|
2033
|
+
'x-content-type-options': 'nosniff',
|
|
2034
|
+
});
|
|
2035
|
+
res.end(JSON.stringify(pack, null, 2));
|
|
2036
|
+
return;
|
|
2037
|
+
}
|
|
2038
|
+
const packExisting = () => ({ builtin: new Set(builtinReports().map((d) => d.id)), custom: new Set(listCustom(reportsDir).map((r) => r.definition.id)) });
|
|
2039
|
+
if (route === 'POST /api/packs/preview') {
|
|
2040
|
+
const b = await readJson(req);
|
|
2041
|
+
return send(res, 200, readPack(String(b['text'] ?? ''), packExisting()));
|
|
2042
|
+
}
|
|
2043
|
+
if (route === 'POST /api/packs/import') {
|
|
2044
|
+
const b = await readJson(req);
|
|
2045
|
+
const wanted = new Set(Array.isArray(b['ids']) ? b['ids'].map(String) : []);
|
|
2046
|
+
const p = readPack(String(b['text'] ?? ''), packExisting());
|
|
2047
|
+
const saved = [];
|
|
2048
|
+
mkdirSync(reportsDir, { recursive: true });
|
|
2049
|
+
for (const e of p.entries) {
|
|
2050
|
+
if (!wanted.has(e.id) || e.status === 'built in' || e.status === 'problem')
|
|
2051
|
+
continue;
|
|
2052
|
+
writeFileSync(join(reportsDir, `${e.id}.yaml`), e.yaml);
|
|
2053
|
+
saved.push(e.id);
|
|
2054
|
+
}
|
|
2055
|
+
return send(res, 200, { saved });
|
|
2056
|
+
}
|
|
2057
|
+
if (route === 'GET /api/monthly' || route === 'GET /api/monthly/download') {
|
|
2058
|
+
if (!tenant)
|
|
2059
|
+
throw new HttpProblem(400, 'Connect to a tenant first.');
|
|
2060
|
+
let snapshot;
|
|
2061
|
+
if (transport) {
|
|
2062
|
+
const t = transport;
|
|
2063
|
+
snapshot = await cached('tenant:overview', () => tenantOverview(t)).then((o) => o.counts).catch(() => undefined);
|
|
2064
|
+
}
|
|
2065
|
+
const data = monthlyData(new History(join(home, 'history.json')), tenant, url.searchParams.get('month') ?? undefined, snapshot);
|
|
2066
|
+
if (route === 'GET /api/monthly')
|
|
2067
|
+
return send(res, 200, data);
|
|
2068
|
+
const html = monthlyHtml(data);
|
|
2069
|
+
res.writeHead(200, {
|
|
2070
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2071
|
+
'content-disposition': `attachment; filename="identity-operations-${data.month}.html"`,
|
|
2072
|
+
'cache-control': 'no-store',
|
|
2073
|
+
'x-content-type-options': 'nosniff',
|
|
2074
|
+
});
|
|
2075
|
+
res.end(html);
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
// ---------- tenant ----------
|
|
2079
|
+
const tenantRoute = /^GET \/api\/tenant\/(overview|clusters)$/.exec(route);
|
|
2080
|
+
if (tenantRoute) {
|
|
2081
|
+
const t = need();
|
|
2082
|
+
const what = tenantRoute[1];
|
|
2083
|
+
try {
|
|
2084
|
+
if (what === 'overview')
|
|
2085
|
+
return send(res, 200, await cached('tenant:overview', () => tenantOverview(t)));
|
|
2086
|
+
return send(res, 200, { clusters: await clusterHealth(t) });
|
|
2087
|
+
}
|
|
2088
|
+
catch (e) {
|
|
2089
|
+
const st = e.status;
|
|
2090
|
+
throw new HttpProblem(st === 403 ? 403 : 502, `Could not read ${what}: ${e.message}`);
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
const configRoute = /^GET \/api\/sources\/([A-Za-z0-9-]+)\/config$/.exec(route);
|
|
2094
|
+
if (configRoute) {
|
|
2095
|
+
const t = need();
|
|
2096
|
+
try {
|
|
2097
|
+
return send(res, 200, { config: await sourceConfiguration(t, configRoute[1]) });
|
|
2098
|
+
}
|
|
2099
|
+
catch (e) {
|
|
2100
|
+
const st = e.status;
|
|
2101
|
+
throw new HttpProblem(st === 404 ? 404 : st === 403 ? 403 : 502, `Could not read the configuration: ${e.message}`);
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
if (route === 'PUT /api/settings/diagnostics') {
|
|
2105
|
+
const b = await readJson(req);
|
|
2106
|
+
writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), diagnostics: b['enabled'] === true }, null, 2));
|
|
2107
|
+
log(`connector diagnostics turned ${b['enabled'] === true ? 'on' : 'off'}`);
|
|
2108
|
+
return send(res, 200, { diagnostics: diagnosticsOn() });
|
|
2109
|
+
}
|
|
2110
|
+
const diagRoute = /^POST \/api\/sources\/([A-Za-z0-9-]+)\/diagnostics$/.exec(route);
|
|
2111
|
+
if (diagRoute) {
|
|
2112
|
+
const t = need();
|
|
2113
|
+
const b = await readJson(req);
|
|
2114
|
+
if (!diagnosticsOn())
|
|
2115
|
+
throw new HttpProblem(403, 'Connector diagnostics are off. Turn them on first.');
|
|
2116
|
+
if (b['confirm'] !== true)
|
|
2117
|
+
throw new HttpProblem(400, 'Confirm the action first.');
|
|
2118
|
+
const action = String(b['action'] ?? '');
|
|
2119
|
+
if (!['test', 'ping', 'peek'].includes(action))
|
|
2120
|
+
throw new HttpProblem(400, 'Unknown diagnostic.');
|
|
2121
|
+
const entry = { time: new Date().toISOString(), tenant, user: signedInAs ?? 'token', source: diagRoute[1], action };
|
|
2122
|
+
try {
|
|
2123
|
+
mkdirSync(join(home, 'logs'), { recursive: true });
|
|
2124
|
+
appendFileSync(join(home, 'logs', 'diagnostics.log'), JSON.stringify(entry) + '\n');
|
|
2125
|
+
}
|
|
2126
|
+
catch {
|
|
2127
|
+
/* the action itself is what matters; the log is best effort */
|
|
2128
|
+
}
|
|
2129
|
+
log(`diagnostic "${action}" on source ${diagRoute[1]}`);
|
|
2130
|
+
try {
|
|
2131
|
+
const result = await sourceDiagnostic(t, diagRoute[1], action, { objectType: typeof b['objectType'] === 'string' ? b['objectType'] : undefined, maxCount: typeof b['maxCount'] === 'number' ? b['maxCount'] : undefined });
|
|
2132
|
+
return send(res, 200, { result });
|
|
2133
|
+
}
|
|
2134
|
+
catch (e) {
|
|
2135
|
+
const st = e.status;
|
|
2136
|
+
throw new HttpProblem(st === 403 ? 403 : 502, `${action === 'test' ? 'Test connection' : action === 'ping' ? 'Ping cluster' : 'Peek'} failed: ${e.message}`);
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
// ---------- lookups ----------
|
|
2140
|
+
if (route === 'GET /api/people') {
|
|
2141
|
+
const t = need();
|
|
2142
|
+
return send(res, 200, { people: await findPeople(t, url.searchParams.get('q') ?? '') });
|
|
2143
|
+
}
|
|
2144
|
+
const personRoute = /^GET \/api\/people\/([A-Za-z0-9-]+)$/.exec(route);
|
|
2145
|
+
if (personRoute) {
|
|
2146
|
+
const t = need();
|
|
2147
|
+
try {
|
|
2148
|
+
const d = await personDetail(t, personRoute[1]);
|
|
2149
|
+
return send(res, 200, { ...d, timeline: personTimeline(d) });
|
|
2150
|
+
}
|
|
2151
|
+
catch (e) {
|
|
2152
|
+
const st = e.status;
|
|
2153
|
+
throw new HttpProblem(st === 404 ? 404 : st === 403 ? 403 : 502, `Could not read this person: ${e.message}`);
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
if (route === 'GET /api/sources') {
|
|
2157
|
+
const t = need();
|
|
2158
|
+
return send(res, 200, await sourcesOverview(t));
|
|
2159
|
+
}
|
|
2160
|
+
const sourceRoute = /^GET \/api\/sources\/([A-Za-z0-9-]+)$/.exec(route);
|
|
2161
|
+
if (sourceRoute) {
|
|
2162
|
+
const t = need();
|
|
2163
|
+
try {
|
|
2164
|
+
return send(res, 200, await sourceDetail(t, sourceRoute[1]));
|
|
2165
|
+
}
|
|
2166
|
+
catch (e) {
|
|
2167
|
+
const st = e.status;
|
|
2168
|
+
throw new HttpProblem(st === 404 ? 404 : st === 403 ? 403 : 502, `Could not read this source: ${e.message}`);
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
const roleGet = /^GET \/api\/roles\/([A-Za-z0-9-]+)$/.exec(route);
|
|
2172
|
+
if (roleGet) {
|
|
2173
|
+
const t = need();
|
|
2174
|
+
try {
|
|
2175
|
+
const names = await cached('sourceNames', () => sourceNameMap(t));
|
|
2176
|
+
return send(res, 200, await getRole(t, roleGet[1], names));
|
|
2177
|
+
}
|
|
2178
|
+
catch (e) {
|
|
2179
|
+
throw new HttpProblem(e instanceof HttpError ? (e.status === 404 ? 404 : e.status === 403 ? 403 : 502) : 400, `Could not read the role: ${e.message}`);
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
if (route === 'POST /api/roles/compare' || route === 'POST /api/roles/impact') {
|
|
2183
|
+
const t = need();
|
|
2184
|
+
const b = await readJson(req);
|
|
2185
|
+
const compare = route.endsWith('compare');
|
|
2186
|
+
if (!compare) {
|
|
2187
|
+
const problems = criteriaProblems(b['criteria']);
|
|
2188
|
+
if (problems.length)
|
|
2189
|
+
throw new DefinitionError('The criteria are not complete', problems);
|
|
2190
|
+
}
|
|
2191
|
+
const id = randomBytes(8).toString('hex');
|
|
2192
|
+
const job = { id, state: 'running', progress: 'Starting...', started: Date.now() };
|
|
2193
|
+
jobs.set(id, job);
|
|
2194
|
+
while (jobs.size > 20)
|
|
2195
|
+
jobs.delete(jobs.keys().next().value);
|
|
2196
|
+
const onProgress = (m) => (job.progress = m);
|
|
2197
|
+
const work = jobContext.run(job, () => compare
|
|
2198
|
+
? compareRoles(t, (Array.isArray(b['roles']) ? b['roles'] : []).map(String), onProgress)
|
|
2199
|
+
: roleImpact(t, { roleId: typeof b['roleId'] === 'string' && b['roleId'] ? b['roleId'] : undefined, criteria: b['criteria'] }, onProgress));
|
|
2200
|
+
log(compare ? 'comparing roles' : 'previewing a role change');
|
|
2201
|
+
work.then((out) => {
|
|
2202
|
+
const { table, ...rest } = out;
|
|
2203
|
+
job.result = table;
|
|
2204
|
+
job.extra = rest;
|
|
2205
|
+
job.state = 'done';
|
|
2206
|
+
}, (e) => {
|
|
2207
|
+
job.error = e.problems ? `${e.message}\n${e.problems.join('\n')}` : e.message;
|
|
2208
|
+
job.state = 'error';
|
|
2209
|
+
});
|
|
2210
|
+
return send(res, 202, { job: id });
|
|
2211
|
+
}
|
|
2212
|
+
if (route === 'GET /api/support/download') {
|
|
2213
|
+
const text = supportFile({
|
|
2214
|
+
home,
|
|
2215
|
+
version: opts.version ?? '',
|
|
2216
|
+
edition: IS_EXE ? 'Windows program' : IS_NODE_BUNDLE ? 'Node.js edition' : 'npm install',
|
|
2217
|
+
connected: Boolean(transport),
|
|
2218
|
+
signedIn: signedInAs !== undefined,
|
|
2219
|
+
apiCalls,
|
|
2220
|
+
tenantHosts: [tenant ?? '', tenantB ?? '', apiBase ? new URL(apiBase).host : ''].filter(Boolean),
|
|
2221
|
+
recentErrors,
|
|
2222
|
+
});
|
|
2223
|
+
res.writeHead(200, {
|
|
2224
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
2225
|
+
'content-disposition': `attachment; filename="identityscope-support-${new Date().toISOString().slice(0, 10)}.txt"`,
|
|
2226
|
+
'cache-control': 'no-store',
|
|
2227
|
+
'x-content-type-options': 'nosniff',
|
|
2228
|
+
});
|
|
2229
|
+
res.end(text);
|
|
2230
|
+
return;
|
|
2231
|
+
}
|
|
2232
|
+
// ---------- new version notice (off unless turned on, and only where the build names a release address) ----------
|
|
2233
|
+
if (route === 'GET /api/updates') {
|
|
2234
|
+
const url = opts.updateUrl ?? UPDATE_URL;
|
|
2235
|
+
const on = readSettings().updateCheck === true;
|
|
2236
|
+
if (!url)
|
|
2237
|
+
return send(res, 200, { available: false, enabled: false, current: opts.version });
|
|
2238
|
+
if (!on && !reqWantsNow(req))
|
|
2239
|
+
return send(res, 200, { available: true, enabled: false, current: opts.version });
|
|
2240
|
+
try {
|
|
2241
|
+
const r = await (opts.fetch ?? fetch)(url, { headers: { accept: 'application/vnd.github+json', 'user-agent': 'IdentityScope' }, signal: AbortSignal.timeout(5000) });
|
|
2242
|
+
if (!r.ok)
|
|
2243
|
+
throw new Error(`HTTP ${r.status}`);
|
|
2244
|
+
const d = (await r.json());
|
|
2245
|
+
const latest = String(d.tag_name ?? d.version ?? '').replace(/^v/i, '');
|
|
2246
|
+
const page = String(d.html_url ?? d.url ?? '');
|
|
2247
|
+
if (!/^\d+\.\d+\.\d+$/.test(latest))
|
|
2248
|
+
throw new Error('unexpected answer');
|
|
2249
|
+
return send(res, 200, { available: true, enabled: on, current: opts.version, latest, newer: newerVersion(latest, opts.version ?? '0.0.0'), page: /^https:\/\//.test(page) ? page : undefined });
|
|
2250
|
+
}
|
|
2251
|
+
catch (e) {
|
|
2252
|
+
return send(res, 200, { available: true, enabled: on, current: opts.version, error: `Could not check for a new version (${e.message}).` });
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
if (route === 'PUT /api/updates') {
|
|
2256
|
+
const b = await readJson(req);
|
|
2257
|
+
writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), updateCheck: b['enabled'] === true }, null, 2));
|
|
2258
|
+
return send(res, 200, { enabled: b['enabled'] === true });
|
|
2259
|
+
}
|
|
2260
|
+
const stopRoute = /^POST \/api\/jobs\/([a-f0-9]+)\/stop$/.exec(route);
|
|
2261
|
+
if (stopRoute) {
|
|
2262
|
+
const job = jobs.get(stopRoute[1]);
|
|
2263
|
+
if (!job)
|
|
2264
|
+
throw new HttpProblem(404, 'Unknown job');
|
|
2265
|
+
if (job.state === 'running') {
|
|
2266
|
+
job.stopped = true;
|
|
2267
|
+
job.progress = 'Stopping...';
|
|
2268
|
+
job.abort?.abort();
|
|
2269
|
+
log('a job was stopped from the screen');
|
|
2270
|
+
}
|
|
2271
|
+
return send(res, 200, { stopping: job.state === 'running' });
|
|
2272
|
+
}
|
|
2273
|
+
const jobRoute = /^GET \/api\/jobs\/([a-f0-9]+)$/.exec(route);
|
|
2274
|
+
if (jobRoute) {
|
|
2275
|
+
const job = jobs.get(jobRoute[1]);
|
|
2276
|
+
if (!job)
|
|
2277
|
+
throw new HttpProblem(404, 'Unknown run');
|
|
2278
|
+
if (job.state === 'error' && !job.noted) {
|
|
2279
|
+
job.noted = true;
|
|
2280
|
+
noteError(`a job ended with: ${job.error ?? '?'}`);
|
|
2281
|
+
}
|
|
2282
|
+
const r = job.result;
|
|
2283
|
+
return send(res, 200, {
|
|
2284
|
+
state: job.state,
|
|
2285
|
+
progress: job.progress,
|
|
2286
|
+
error: job.memoryStop && job.state === "error" ? MEMORY_STOP : job.error,
|
|
2287
|
+
seconds: Math.round((Date.now() - job.started) / 100) / 10,
|
|
2288
|
+
extra: job.state === 'done' ? job.extra : undefined,
|
|
2289
|
+
warnings: job.warnings,
|
|
2290
|
+
result: r && {
|
|
2291
|
+
name: r.definition.name,
|
|
2292
|
+
columns: r.columns,
|
|
2293
|
+
rows: r.rows.slice(0, SHOWN_ROWS),
|
|
2294
|
+
total: r.rows.length,
|
|
2295
|
+
shown: Math.min(SHOWN_ROWS, r.rows.length),
|
|
2296
|
+
warnings: r.warnings,
|
|
2297
|
+
durationMs: r.stats.durationMs,
|
|
2298
|
+
generatedAt: r.generatedAt,
|
|
2299
|
+
},
|
|
2300
|
+
});
|
|
2301
|
+
}
|
|
2302
|
+
const dl = /^GET \/api\/jobs\/([a-f0-9]+)\/download$/.exec(route);
|
|
2303
|
+
if (dl) {
|
|
2304
|
+
const job = jobs.get(dl[1]);
|
|
2305
|
+
if (!job?.result)
|
|
2306
|
+
throw new HttpProblem(404, 'Run the report first.');
|
|
2307
|
+
const format = (url.searchParams.get('format') ?? 'xlsx');
|
|
2308
|
+
if (!['xlsx', 'csv', 'html', 'json'].includes(format))
|
|
2309
|
+
throw new HttpProblem(400, 'Unknown format');
|
|
2310
|
+
const bytes = render(job.result, format);
|
|
2311
|
+
res.writeHead(200, {
|
|
2312
|
+
'content-type': MIME[format],
|
|
2313
|
+
'content-disposition': `attachment; filename="${fileName(job.result.definition.id, job.result.generatedAt, format)}"`,
|
|
2314
|
+
'cache-control': 'no-store',
|
|
2315
|
+
'x-content-type-options': 'nosniff',
|
|
2316
|
+
});
|
|
2317
|
+
res.end(Buffer.from(bytes));
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2320
|
+
if (route === 'POST /api/doctor') {
|
|
2321
|
+
const t = need();
|
|
2322
|
+
const sec = secretsStatus(home);
|
|
2323
|
+
const how = sec.protection === 'windows-user' ? 'encrypted, key protected by Windows for this user on this computer' : sec.protection === 'file-permissions' ? 'encrypted, key protected by owner-only file permissions' : sec.protection === 'none' ? 'none saved' : 'NOT encrypted yet';
|
|
2324
|
+
const secLine = `Saved secrets on this computer: ${sec.count} (${how})${sec.problem ? `\n Problem: ${sec.problem}` : ''}`;
|
|
2325
|
+
return send(res, 200, { text: `${await runDoctor(t, opts.version ?? '', signedInAs === undefined ? creds?.clientId : undefined)}\n\n${secLine}` });
|
|
2326
|
+
}
|
|
2327
|
+
throw new HttpProblem(404, 'Not found');
|
|
2328
|
+
};
|
|
2329
|
+
// ---------- schedules ----------
|
|
2330
|
+
const jobView = async (j) => {
|
|
2331
|
+
const when = cronToWhen(j.schedule);
|
|
2332
|
+
const secretName = webhookSecret(j.name);
|
|
2333
|
+
return {
|
|
2334
|
+
name: j.name,
|
|
2335
|
+
report: j.report,
|
|
2336
|
+
reportName: j.report === INSTANT_CHECK ? 'Instant check (all checks)' : j.report === ALL_TENANTS_CHECK ? 'All tenants (partner overview)' : findReport(j.report)?.definition.name ?? j.report,
|
|
2337
|
+
params: j.params ?? {},
|
|
2338
|
+
formats: j.formats ?? ['xlsx'],
|
|
2339
|
+
skipWhenEmpty: j.skipWhenEmpty === true,
|
|
2340
|
+
sendWhen: j.sendWhen ?? (j.skipWhenEmpty ? 'rows' : 'always'),
|
|
2341
|
+
when,
|
|
2342
|
+
whenText: describeWhen(when, j.schedule),
|
|
2343
|
+
emailTo: j.email?.to ?? [],
|
|
2344
|
+
allowUnverified: j.email?.allowUnverified ?? [],
|
|
2345
|
+
webhookKind: j.webhook?.kind ?? null,
|
|
2346
|
+
webhookSaved: Boolean(j.webhook && readSecrets(home)[secretName]),
|
|
2347
|
+
automatic: await queryTask(j.name, exec, home).catch(() => null),
|
|
2348
|
+
lastLog: readLogTail(j.name, home, 12),
|
|
2349
|
+
};
|
|
2350
|
+
};
|
|
2351
|
+
const schedulesApi = async (req, res, route) => {
|
|
2352
|
+
const cfg = readSchedules(home);
|
|
2353
|
+
if (route === 'GET /api/schedules') {
|
|
2354
|
+
const secrets = readSecrets(home);
|
|
2355
|
+
return send(res, 200, {
|
|
2356
|
+
file: schedulesPath(home),
|
|
2357
|
+
outputDir: join(home, 'output'),
|
|
2358
|
+
email: cfg.email ? { host: cfg.email.host, port: cfg.email.port, user: cfg.email.user ?? '', from: cfg.email.from, passwordSaved: Boolean(secrets[SMTP_SECRET]) } : null,
|
|
2359
|
+
jobs: await Promise.all(cfg.jobs.map(jobView)),
|
|
2360
|
+
remembered: Boolean(secrets['ISC_CLIENT_SECRET']),
|
|
2361
|
+
});
|
|
2362
|
+
}
|
|
2363
|
+
if (route === 'PUT /api/schedules/email') {
|
|
2364
|
+
const b = await readJson(req);
|
|
2365
|
+
const host = String(b['host'] ?? '').trim();
|
|
2366
|
+
const from = String(b['from'] ?? '').trim();
|
|
2367
|
+
const port = Number(b['port'] ?? 587);
|
|
2368
|
+
if (!host || !from)
|
|
2369
|
+
throw new HttpProblem(400, 'Enter the mail server and the "from" address.');
|
|
2370
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
2371
|
+
throw new HttpProblem(400, 'The port must be a number such as 587.');
|
|
2372
|
+
const user = String(b['user'] ?? '').trim();
|
|
2373
|
+
cfg.email = { host, port, from, ...(user ? { user } : {}), password: `env:${SMTP_SECRET}` };
|
|
2374
|
+
writeSchedules(cfg, home);
|
|
2375
|
+
if (typeof b['password'] === 'string' && b['password'] !== '')
|
|
2376
|
+
writeSecrets({ [SMTP_SECRET]: b['password'] }, home);
|
|
2377
|
+
return send(res, 200, { saved: true });
|
|
2378
|
+
}
|
|
2379
|
+
if (route === 'POST /api/schedules/recipients') {
|
|
2380
|
+
const b = await readJson(req);
|
|
2381
|
+
if (!transport)
|
|
2382
|
+
throw new HttpProblem(409, 'Connect to a tenant first, so recipients can be checked against ISC.');
|
|
2383
|
+
const emails = (Array.isArray(b['emails']) ? b['emails'] : String(b['emails'] ?? '').split(/[,;\s]+/)).map((x) => String(x).trim()).filter(Boolean);
|
|
2384
|
+
const allow = Array.isArray(b['allowUnverified']) ? b['allowUnverified'].map(String) : [];
|
|
2385
|
+
return send(res, 200, { recipients: await checkRecipients(transport, emails, allow) });
|
|
2386
|
+
}
|
|
2387
|
+
if (route === 'POST /api/schedules/email/test') {
|
|
2388
|
+
const b = await readJson(req);
|
|
2389
|
+
const to = String(b['to'] ?? '').trim();
|
|
2390
|
+
if (!/^[^\s@]+@[^\s@]+$/.test(to))
|
|
2391
|
+
throw new HttpProblem(400, 'Enter an email address to send the test to.');
|
|
2392
|
+
if (!cfg.email)
|
|
2393
|
+
throw new HttpProblem(400, 'Save the email settings first.');
|
|
2394
|
+
if (!transport)
|
|
2395
|
+
throw new HttpProblem(409, 'Connect to a tenant first, so the address can be checked against ISC.');
|
|
2396
|
+
const [check] = await checkRecipients(transport, [to]);
|
|
2397
|
+
if (!check.ok)
|
|
2398
|
+
throw new HttpProblem(400, `${to}: ${check.reason}. Test emails only go to active identities in ISC.`);
|
|
2399
|
+
const pw = readSecrets(home)[SMTP_SECRET] ?? env()[SMTP_SECRET];
|
|
2400
|
+
const server = { host: cfg.email.host, port: cfg.email.port, secure: cfg.email.port === 465, user: cfg.email.user, password: pw, from: cfg.email.from };
|
|
2401
|
+
try {
|
|
2402
|
+
await (opts.mailer ?? createMailer(server)).sendMail({
|
|
2403
|
+
from: server.from,
|
|
2404
|
+
to,
|
|
2405
|
+
subject: 'identityscope test email',
|
|
2406
|
+
text: 'Email delivery from identityscope works.',
|
|
2407
|
+
});
|
|
2408
|
+
}
|
|
2409
|
+
catch (e) {
|
|
2410
|
+
throw new HttpProblem(502, `The mail server refused: ${e.message}`);
|
|
2411
|
+
}
|
|
2412
|
+
return send(res, 200, { sent: true });
|
|
2413
|
+
}
|
|
2414
|
+
if (route === 'POST /api/schedules/jobs') {
|
|
2415
|
+
const b = await readJson(req);
|
|
2416
|
+
const name = String(b['name'] ?? '').trim();
|
|
2417
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,60}$/.test(name))
|
|
2418
|
+
throw new HttpProblem(400, 'Name: letters, digits, dot, dash or underscore, no spaces.');
|
|
2419
|
+
const report = String(b['report'] ?? '');
|
|
2420
|
+
if (!isSpecialJob(report) && !findReport(report))
|
|
2421
|
+
throw new HttpProblem(400, 'Choose a report.');
|
|
2422
|
+
const when = b['when'];
|
|
2423
|
+
const problems = when ? validateWhen(when) : ['Choose when it runs.'];
|
|
2424
|
+
if (problems.length)
|
|
2425
|
+
throw new HttpProblem(400, problems.join(' '));
|
|
2426
|
+
const formats = (Array.isArray(b['formats']) ? b['formats'] : ['xlsx']).map(String).filter((f) => ['xlsx', 'csv', 'html', 'json'].includes(f));
|
|
2427
|
+
if (!formats.length)
|
|
2428
|
+
throw new HttpProblem(400, 'Choose at least one file type.');
|
|
2429
|
+
const to = (Array.isArray(b['emailTo']) ? b['emailTo'] : String(b['emailTo'] ?? '').split(/[,;\s]+/)).map((x) => String(x).trim()).filter(Boolean);
|
|
2430
|
+
for (const a of to)
|
|
2431
|
+
if (!/^[^\s@]+@[^\s@]+$/.test(a))
|
|
2432
|
+
throw new HttpProblem(400, `"${a}" is not an email address.`);
|
|
2433
|
+
if (to.length && !cfg.email)
|
|
2434
|
+
throw new HttpProblem(400, 'Save the email settings first, or leave the recipients empty.');
|
|
2435
|
+
const lowerTo = to.map((a) => a.toLowerCase());
|
|
2436
|
+
const allowUnverified = (Array.isArray(b['allowUnverified']) ? b['allowUnverified'].map(String) : []).filter((a) => lowerTo.includes(a.toLowerCase()));
|
|
2437
|
+
if (to.length) {
|
|
2438
|
+
if (!transport)
|
|
2439
|
+
throw new HttpProblem(409, 'Connect to a tenant first, so the recipients can be checked against ISC.');
|
|
2440
|
+
const checks = await checkRecipients(transport, to, allowUnverified);
|
|
2441
|
+
const refused = checks.filter((c) => !c.ok);
|
|
2442
|
+
if (refused.length) {
|
|
2443
|
+
return send(res, 400, {
|
|
2444
|
+
error: 'Report files only go to active identities in ISC. Fix these addresses, or mark a shared mailbox or distribution list as allowed.',
|
|
2445
|
+
problems: refused.map((r) => `${r.email}: ${r.reason}`),
|
|
2446
|
+
recipients: checks,
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
const kind = b['webhookKind'] ? String(b['webhookKind']) : '';
|
|
2451
|
+
const hookUrl = typeof b['webhookUrl'] === 'string' ? b['webhookUrl'].trim() : '';
|
|
2452
|
+
if (kind && !['teams', 'slack', 'json'].includes(kind))
|
|
2453
|
+
throw new HttpProblem(400, 'Unknown chat type.');
|
|
2454
|
+
if (hookUrl && !/^https:\/\//i.test(hookUrl))
|
|
2455
|
+
throw new HttpProblem(400, 'The webhook address must start with https://');
|
|
2456
|
+
const previous = typeof b['previousName'] === 'string' ? b['previousName'] : undefined;
|
|
2457
|
+
const others = cfg.jobs.filter((j) => j.name !== (previous ?? name));
|
|
2458
|
+
if (others.some((j) => j.name === name))
|
|
2459
|
+
throw new HttpProblem(400, `A schedule named "${name}" already exists.`);
|
|
2460
|
+
const params = (b['params'] && typeof b['params'] === 'object' ? b['params'] : {});
|
|
2461
|
+
for (const k of Object.keys(params))
|
|
2462
|
+
if (params[k] === '' || params[k] === null)
|
|
2463
|
+
delete params[k];
|
|
2464
|
+
const job = {
|
|
2465
|
+
name,
|
|
2466
|
+
report,
|
|
2467
|
+
schedule: whenToCron(when),
|
|
2468
|
+
...(Object.keys(params).length ? { params } : {}),
|
|
2469
|
+
formats,
|
|
2470
|
+
...(['rows', 'new'].includes(b['sendWhen']) ? { sendWhen: b['sendWhen'] } : b['skipWhenEmpty'] === true ? { sendWhen: 'rows' } : {}),
|
|
2471
|
+
...(to.length ? { email: { to, ...(allowUnverified.length ? { allowUnverified } : {}) } } : {}),
|
|
2472
|
+
...(kind ? { webhook: { url: `env:${webhookSecret(name)}`, kind: kind } } : {}),
|
|
2473
|
+
};
|
|
2474
|
+
const secrets = readSecrets(home);
|
|
2475
|
+
if (kind && !hookUrl && !secrets[webhookSecret(previous ?? name)])
|
|
2476
|
+
throw new HttpProblem(400, 'Paste the Teams or Slack webhook address.');
|
|
2477
|
+
if (!to.length && !kind)
|
|
2478
|
+
throw new HttpProblem(400, 'Add at least one email recipient or a Teams/Slack webhook, so the report goes somewhere.');
|
|
2479
|
+
// Move or set the webhook secret.
|
|
2480
|
+
const changes = {};
|
|
2481
|
+
if (previous && previous !== name)
|
|
2482
|
+
changes[webhookSecret(previous)] = undefined;
|
|
2483
|
+
if (kind)
|
|
2484
|
+
changes[webhookSecret(name)] = hookUrl || secrets[webhookSecret(previous ?? name)];
|
|
2485
|
+
else
|
|
2486
|
+
changes[webhookSecret(name)] = undefined;
|
|
2487
|
+
writeSecrets(changes, home);
|
|
2488
|
+
cfg.jobs = previous ? cfg.jobs.map((j) => (j.name === previous ? job : j)) : [...cfg.jobs, job];
|
|
2489
|
+
writeSchedules(cfg, home);
|
|
2490
|
+
// Keep an existing automatic run in step with the new time or name.
|
|
2491
|
+
if (previous && (await queryTask(previous, exec, home).catch(() => null))) {
|
|
2492
|
+
await disableTask(previous, exec, home);
|
|
2493
|
+
await enableTask(name, when, exec, home);
|
|
2494
|
+
}
|
|
2495
|
+
return send(res, 200, { saved: name });
|
|
2496
|
+
}
|
|
2497
|
+
const named = /^(DELETE|POST) \/api\/schedules\/jobs\/([A-Za-z0-9._-]+)(\/run|\/automatic|\/run-status)?$/.exec(route);
|
|
2498
|
+
if (named) {
|
|
2499
|
+
const [, method, name, action] = named;
|
|
2500
|
+
const job = cfg.jobs.find((j) => j.name === name);
|
|
2501
|
+
if (!job)
|
|
2502
|
+
throw new HttpProblem(404, 'Unknown schedule');
|
|
2503
|
+
if (method === 'DELETE' && !action) {
|
|
2504
|
+
await disableTask(name, exec, home).catch(() => undefined);
|
|
2505
|
+
cfg.jobs = cfg.jobs.filter((j) => j.name !== name);
|
|
2506
|
+
writeSchedules(cfg, home);
|
|
2507
|
+
writeSecrets({ [webhookSecret(name)]: undefined }, home);
|
|
2508
|
+
return send(res, 200, { deleted: name });
|
|
2509
|
+
}
|
|
2510
|
+
if (method === 'POST' && action === '/automatic') {
|
|
2511
|
+
const b = await readJson(req);
|
|
2512
|
+
if (b['on'] === false) {
|
|
2513
|
+
await disableTask(name, exec, home);
|
|
2514
|
+
return send(res, 200, { automatic: null });
|
|
2515
|
+
}
|
|
2516
|
+
if (!readSecrets(home)['ISC_CLIENT_SECRET'] && !baseEnv['ISC_CLIENT_SECRET']) {
|
|
2517
|
+
throw new HttpProblem(400, 'Automatic runs need your tenant details saved on this computer. Click "Remember my tenant" first.');
|
|
2518
|
+
}
|
|
2519
|
+
const when = cronToWhen(job.schedule);
|
|
2520
|
+
if (!when)
|
|
2521
|
+
throw new HttpProblem(400, 'Edit the schedule and choose daily, weekly or monthly first.');
|
|
2522
|
+
await enableTask(name, when, exec, home);
|
|
2523
|
+
return send(res, 200, { automatic: await queryTask(name, exec, home) });
|
|
2524
|
+
}
|
|
2525
|
+
if (method === 'POST' && action === '/run') {
|
|
2526
|
+
const t = transport;
|
|
2527
|
+
if (!t)
|
|
2528
|
+
throw new HttpProblem(409, 'Connect to a tenant first.');
|
|
2529
|
+
const runId = randomBytes(6).toString('hex');
|
|
2530
|
+
scheduleRuns.set(runId, { state: 'running' });
|
|
2531
|
+
const e = { ...env(), ISC_BASE_URL: 'screen', ISC_CLIENT_ID: 'screen', ISC_CLIENT_SECRET: 'screen' };
|
|
2532
|
+
const config = parseConfig({ ...cfg, jobs: [job], tenant: undefined }, schedulesPath(home), e);
|
|
2533
|
+
runJob(config, config.jobs[0], { transport: t, mailer: opts.mailer, fetch: opts.fetch, log: (l) => log(l) }).then((outcome) => {
|
|
2534
|
+
scheduleRuns.set(runId, { state: 'done', outcome });
|
|
2535
|
+
});
|
|
2536
|
+
return send(res, 202, { run: runId });
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
const status = /^GET \/api\/schedules\/runs\/([a-f0-9]+)$/.exec(route);
|
|
2540
|
+
if (status) {
|
|
2541
|
+
const r = scheduleRuns.get(status[1]);
|
|
2542
|
+
if (!r)
|
|
2543
|
+
throw new HttpProblem(404, 'Unknown run');
|
|
2544
|
+
return send(res, 200, r);
|
|
2545
|
+
}
|
|
2546
|
+
throw new HttpProblem(404, 'Not found');
|
|
2547
|
+
};
|
|
2548
|
+
const page = (res, status, title, text) => {
|
|
2549
|
+
res.writeHead(status, {
|
|
2550
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2551
|
+
'cache-control': 'no-store',
|
|
2552
|
+
'referrer-policy': 'no-referrer',
|
|
2553
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'",
|
|
2554
|
+
});
|
|
2555
|
+
const esc = (x) => x.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
2556
|
+
res.end(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${esc(title)}</title>` +
|
|
2557
|
+
'<style>body{font:15px -apple-system,Segoe UI,Roboto,Arial,sans-serif;background:#f6f7fb;color:#1f2937;display:flex;align-items:center;justify-content:center;height:90vh}div{background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:28px 32px;max-width:520px}h1{font-size:19px;margin:0 0 8px}</style>' +
|
|
2558
|
+
`</head><body><div><h1>${esc(title)}</h1><p>${esc(text)}</p></div>` +
|
|
2559
|
+
(status === 200 ? '<script>setTimeout(function(){window.close()},1500)</script>' : '') +
|
|
2560
|
+
'</body></html>');
|
|
2561
|
+
};
|
|
2562
|
+
/** ISC sends the user back here after sign-in. The one-time state proves the request came from this screen. */
|
|
2563
|
+
const callback = async (url, res) => {
|
|
2564
|
+
const state = url.searchParams.get('state') ?? '';
|
|
2565
|
+
const pending = pendingLogins.get(state);
|
|
2566
|
+
pendingLogins.delete(state);
|
|
2567
|
+
if (!pending || Date.now() - pending.created > 10 * 60_000) {
|
|
2568
|
+
return page(res, 400, 'Sign-in not completed', 'This sign-in link is unknown or expired. Go back to IdentityScope and click "Sign in with SailPoint" again.');
|
|
2569
|
+
}
|
|
2570
|
+
const error = url.searchParams.get('error');
|
|
2571
|
+
if (error)
|
|
2572
|
+
return page(res, 400, 'Sign-in not completed', `ISC answered: ${url.searchParams.get('error_description') ?? error}`);
|
|
2573
|
+
const code = url.searchParams.get('code');
|
|
2574
|
+
if (!code)
|
|
2575
|
+
return page(res, 400, 'Sign-in not completed', 'ISC did not send a sign-in code.');
|
|
2576
|
+
try {
|
|
2577
|
+
const tokens = await exchangeCode(pending, code, opts.fetch);
|
|
2578
|
+
const session = new SignInSession(pending, tokens, opts.fetch);
|
|
2579
|
+
const t = opts.transportFactory
|
|
2580
|
+
? opts.transportFactory({ baseUrl: pending.baseUrl, clientId: '', clientSecret: '', tokenProvider: session.token })
|
|
2581
|
+
: new HttpTransport({ baseUrl: pending.baseUrl, tokenProvider: session.token, onWait: noteWait });
|
|
2582
|
+
await stopDemo();
|
|
2583
|
+
transport = counted(t);
|
|
2584
|
+
rawIsc = t instanceof HttpTransport ? t : undefined;
|
|
2585
|
+
tenant = t.label;
|
|
2586
|
+
apiBase = normalizeBaseUrl(pending.baseUrl);
|
|
2587
|
+
creds = undefined;
|
|
2588
|
+
signedInAs = session.user ?? '';
|
|
2589
|
+
lookups.clear();
|
|
2590
|
+
log(`signed in to ${tenant}${signedInAs ? ` as ${signedInAs}` : ''}`);
|
|
2591
|
+
return page(res, 200, 'Signed in', 'You are signed in to IdentityScope. This tab closes by itself; if it does not, close it and go back to the IdentityScope tab.');
|
|
2592
|
+
}
|
|
2593
|
+
catch (e) {
|
|
2594
|
+
return page(res, 400, 'Sign-in not completed', e.message);
|
|
2595
|
+
}
|
|
2596
|
+
};
|
|
2597
|
+
const server = createServer((req, res) => {
|
|
2598
|
+
void (async () => {
|
|
2599
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
2600
|
+
try {
|
|
2601
|
+
// Refuse other host names (protects against DNS rebinding) and other origins.
|
|
2602
|
+
const host = req.headers.host ?? '';
|
|
2603
|
+
if (host !== `127.0.0.1:${port}` && host !== `localhost:${port}`)
|
|
2604
|
+
throw new HttpProblem(403, 'Forbidden');
|
|
2605
|
+
const origin = req.headers.origin;
|
|
2606
|
+
if (origin && origin !== `http://127.0.0.1:${port}` && origin !== `http://localhost:${port}`)
|
|
2607
|
+
throw new HttpProblem(403, 'Forbidden');
|
|
2608
|
+
if (url.pathname === '/callback' && req.method === 'GET') {
|
|
2609
|
+
await callback(url, res);
|
|
2610
|
+
return;
|
|
2611
|
+
}
|
|
2612
|
+
if (url.pathname === '/' && req.method === 'GET') {
|
|
2613
|
+
res.writeHead(200, {
|
|
2614
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2615
|
+
'cache-control': 'no-store',
|
|
2616
|
+
'x-content-type-options': 'nosniff',
|
|
2617
|
+
'x-frame-options': 'DENY',
|
|
2618
|
+
'referrer-policy': 'no-referrer',
|
|
2619
|
+
'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; form-action 'none'; frame-ancestors 'none'; base-uri 'none'",
|
|
2620
|
+
});
|
|
2621
|
+
res.end(UI_PAGE);
|
|
2622
|
+
return;
|
|
2623
|
+
}
|
|
2624
|
+
if (!url.pathname.startsWith('/api/'))
|
|
2625
|
+
throw new HttpProblem(404, 'Not found');
|
|
2626
|
+
const key = req.headers['x-isc-reports-key'] ?? (url.pathname.endsWith('/download') ? url.searchParams.get('k') ?? undefined : undefined);
|
|
2627
|
+
if (!keyOk(key))
|
|
2628
|
+
throw new HttpProblem(401, 'This page is out of date. Open the address printed by "identityscope ui" again.');
|
|
2629
|
+
await api(req, res, url);
|
|
2630
|
+
}
|
|
2631
|
+
catch (e) {
|
|
2632
|
+
const err = e;
|
|
2633
|
+
const status = e instanceof HttpProblem ? e.status : e instanceof DefinitionError ? 400 : 500;
|
|
2634
|
+
if (status !== 401 && status !== 404)
|
|
2635
|
+
noteError(`${status} ${url.pathname}: ${err.message.split('\n')[0]}`);
|
|
2636
|
+
if (!res.headersSent)
|
|
2637
|
+
send(res, status, { error: err.message.split('\n')[0], problems: err.problems ?? [] });
|
|
2638
|
+
}
|
|
2639
|
+
})();
|
|
2640
|
+
});
|
|
2641
|
+
await new Promise((resolve, reject) => {
|
|
2642
|
+
server.once('error', reject);
|
|
2643
|
+
server.listen(opts.port ?? 0, '127.0.0.1', () => resolve());
|
|
2644
|
+
});
|
|
2645
|
+
port = server.address().port;
|
|
2646
|
+
if (opts.demo)
|
|
2647
|
+
await startDemo();
|
|
2648
|
+
return {
|
|
2649
|
+
url: `http://127.0.0.1:${port}/#k=${token}`,
|
|
2650
|
+
token,
|
|
2651
|
+
close: () => new Promise((r) => {
|
|
2652
|
+
void stopDemo();
|
|
2653
|
+
clearInterval(guard);
|
|
2654
|
+
try {
|
|
2655
|
+
unlinkSync(activityFile);
|
|
2656
|
+
}
|
|
2657
|
+
catch {
|
|
2658
|
+
/* nothing was running */
|
|
2659
|
+
}
|
|
2660
|
+
server.closeAllConnections?.();
|
|
2661
|
+
server.close(() => r());
|
|
2662
|
+
}),
|
|
2663
|
+
};
|
|
2664
|
+
}
|
|
2665
|
+
//# sourceMappingURL=ui-server.js.map
|