@sagentix-inc/evidence-collector 0.3.5 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -9
- package/apps/sos-app/src/data/checks/aws.json +12 -0
- package/apps/sos-app/src/data/checks/azure.json +18 -0
- package/apps/sos-app/src/data/checks/bamboohr.json +40 -0
- package/apps/sos-app/src/data/checks/entra.json +1 -1
- package/apps/sos-app/src/data/checks/gcp.json +12 -0
- package/apps/sos-app/src/data/checks/intune.json +7 -1
- package/apps/sos-app/src/data/checks/jamf.json +8 -2
- package/apps/sos-app/src/data/checks/kandji.json +7 -1
- package/apps/sos-app/src/data/checks/rippling.json +40 -0
- package/apps/sos-app/src/data/checks/vulnscan.json +27 -0
- package/apps/sos-app/src/data/checks/web.json +31 -1
- package/collector/package.json +1 -1
- package/collector/src/cli.js +344 -37
- package/collector/src/config.js +12 -0
- package/collector/src/doctor.js +382 -0
- package/collector/src/policies.js +160 -0
- package/collector/src/pool.js +19 -0
- package/collector/src/report.js +88 -16
- package/collector/src/sources/aws/checks.js +64 -0
- package/collector/src/sources/aws.js +6 -1
- package/collector/src/sources/azure/api.js +4 -0
- package/collector/src/sources/azure/checks.js +91 -1
- package/collector/src/sources/azure.js +8 -2
- package/collector/src/sources/bamboohr.js +133 -0
- package/collector/src/sources/cloudflare/api.js +24 -4
- package/collector/src/sources/device_common.js +42 -0
- package/collector/src/sources/directory.js +198 -0
- package/collector/src/sources/engines.js +2 -1
- package/collector/src/sources/entra.js +4 -3
- package/collector/src/sources/gcp/project.js +47 -3
- package/collector/src/sources/gcp.js +5 -2
- package/collector/src/sources/github.js +46 -8
- package/collector/src/sources/google_oauth.js +3 -3
- package/collector/src/sources/google_workspace.js +4 -3
- package/collector/src/sources/hris_common.js +189 -0
- package/collector/src/sources/index.js +3 -0
- package/collector/src/sources/intune.js +40 -3
- package/collector/src/sources/jamf.js +65 -8
- package/collector/src/sources/kandji.js +46 -7
- package/collector/src/sources/oauth.js +22 -0
- package/collector/src/sources/prowler.js +178 -52
- package/collector/src/sources/readonly_http.js +27 -5
- package/collector/src/sources/rippling.js +114 -0
- package/collector/src/sources/shared-cloud.js +14 -6
- package/collector/src/sources/vulnscan.js +386 -0
- package/collector/src/sources/web.js +106 -11
- package/collector/src/sources/web_privacy.js +266 -0
- package/package.json +1 -1
package/collector/src/report.js
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
//
|
|
6
6
|
// Written beside the config as sagentix-run-report.json before it is sent, so the client can read exactly what
|
|
7
7
|
// leaves. A send that fails leaves sagentix-pending-report.json, sent first ("late": true) by the next run.
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
import { subscribe, unsubscribe } from "node:diagnostics_channel";
|
|
8
10
|
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
9
11
|
import { join } from "node:path";
|
|
10
12
|
import { REPORT_PATH, collectorInfo, osInfo, signedPost, writePrivate } from "./channel.js";
|
|
@@ -66,39 +68,88 @@ export function templatePath(path) {
|
|
|
66
68
|
}).join("/");
|
|
67
69
|
}
|
|
68
70
|
// ── Recording ─────────────────────────────────────────────────────────────────────────────────────
|
|
71
|
+
/** Where the HTTP helpers announce a retry (readonly_http.ts, shared-cloud.ts, cloudflare/api.ts); the recorder counts it
|
|
72
|
+
* against the source whose call it was. diagnostics_channel publishes synchronously, so the source is still current. */
|
|
73
|
+
export const RETRY_CHANNEL = "sagentix:collector:retry";
|
|
69
74
|
/** Everything one run does that goes into its report. */
|
|
70
75
|
export class RunRecorder {
|
|
71
76
|
startedAt;
|
|
72
77
|
sources = [];
|
|
73
78
|
pushes = [];
|
|
74
79
|
log = [];
|
|
80
|
+
stats = new Map();
|
|
75
81
|
calls = new Map();
|
|
76
|
-
|
|
82
|
+
/** The source whose work is running, across awaits: sources may run side by side (cli.ts --concurrency). */
|
|
83
|
+
current = new AsyncLocalStorage();
|
|
77
84
|
clock;
|
|
78
|
-
|
|
85
|
+
/** Set once the options are parsed (cli.ts): the timeout and the --verbose hooks. */
|
|
86
|
+
options;
|
|
87
|
+
holds = 0;
|
|
88
|
+
release;
|
|
89
|
+
constructor(now, clock = () => performance.now(), opts = {}) {
|
|
79
90
|
this.startedAt = now();
|
|
80
91
|
this.clock = clock;
|
|
92
|
+
this.options = opts;
|
|
81
93
|
}
|
|
82
94
|
/** An err() that also records each line (and, while a source runs, counts it as that source's warning). */
|
|
83
95
|
tee(err) {
|
|
84
96
|
return (s) => {
|
|
97
|
+
const cur = this.current.getStore();
|
|
85
98
|
for (const line of String(s).split("\n")) {
|
|
86
99
|
this.log.push(line);
|
|
87
|
-
if (
|
|
88
|
-
|
|
100
|
+
if (cur && cur.warnings.length < MAX_WARNINGS)
|
|
101
|
+
cur.warnings.push(line);
|
|
89
102
|
}
|
|
90
103
|
err(s);
|
|
91
104
|
};
|
|
92
105
|
}
|
|
106
|
+
/** The counters of one source, made on first use. */
|
|
107
|
+
statsOf(name) {
|
|
108
|
+
let st = this.stats.get(name);
|
|
109
|
+
if (!st) {
|
|
110
|
+
st = { calls: 0, retries: 0, httpErrors: 0 };
|
|
111
|
+
this.stats.set(name, st);
|
|
112
|
+
}
|
|
113
|
+
return st;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Keeps the fetch instrumentation and the retry counter in place until the returned function is called. Nested holds
|
|
117
|
+
* share one wrapper, so every client built during a run, by any source, sees the same `fetch` (oauth.ts shares a
|
|
118
|
+
* token per fetch function).
|
|
119
|
+
*/
|
|
120
|
+
hold() {
|
|
121
|
+
if (this.holds++ === 0) {
|
|
122
|
+
const restoreFetch = this.instrumentFetch();
|
|
123
|
+
const onRetry = (m) => {
|
|
124
|
+
const cur = this.current.getStore();
|
|
125
|
+
if (!cur)
|
|
126
|
+
return;
|
|
127
|
+
this.statsOf(cur.name).retries++;
|
|
128
|
+
this.options.onRetry?.(cur.name, m);
|
|
129
|
+
};
|
|
130
|
+
subscribe(RETRY_CHANNEL, onRetry);
|
|
131
|
+
this.release = () => { restoreFetch(); unsubscribe(RETRY_CHANNEL, onRetry); };
|
|
132
|
+
}
|
|
133
|
+
let done = false;
|
|
134
|
+
return () => {
|
|
135
|
+
if (done)
|
|
136
|
+
return;
|
|
137
|
+
done = true;
|
|
138
|
+
if (--this.holds === 0) {
|
|
139
|
+
this.release?.();
|
|
140
|
+
this.release = undefined;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
93
144
|
/** Runs one source's work with its outbound HTTP counted, and its time and warnings recorded. */
|
|
94
145
|
async source(name, work) {
|
|
95
146
|
const report = { name, ms: 0, pass: 0, fail: 0, skipped: 0, error: null, warnings: [] };
|
|
96
147
|
this.sources.push(report);
|
|
97
|
-
this.
|
|
148
|
+
this.statsOf(name);
|
|
98
149
|
const t0 = this.clock();
|
|
99
|
-
const
|
|
150
|
+
const release = this.hold();
|
|
100
151
|
try {
|
|
101
|
-
return { value: await work
|
|
152
|
+
return { value: await this.current.run(report, work), report };
|
|
102
153
|
}
|
|
103
154
|
catch (e) {
|
|
104
155
|
const err = e instanceof Error ? e : new Error(String(e));
|
|
@@ -106,9 +157,8 @@ export class RunRecorder {
|
|
|
106
157
|
return { error: e, report };
|
|
107
158
|
}
|
|
108
159
|
finally {
|
|
109
|
-
|
|
160
|
+
release();
|
|
110
161
|
report.ms = Math.round(this.clock() - t0);
|
|
111
|
-
this.current = undefined;
|
|
112
162
|
}
|
|
113
163
|
}
|
|
114
164
|
/** Warnings that belong to no source (the check-in's), as their own entry. */
|
|
@@ -117,7 +167,7 @@ export class RunRecorder {
|
|
|
117
167
|
this.sources.push({ name, ms: 0, pass: 0, fail: 0, skipped: 0, error: null, warnings: warnings.slice(0, MAX_WARNINGS) });
|
|
118
168
|
}
|
|
119
169
|
/** One outbound call, by its shape only. */
|
|
120
|
-
call(source, method, url, status, ms, headers) {
|
|
170
|
+
call(source, method, url, status, ms, headers, error) {
|
|
121
171
|
let host = "", path = "";
|
|
122
172
|
try {
|
|
123
173
|
const u = new URL(url);
|
|
@@ -138,6 +188,11 @@ export class RunRecorder {
|
|
|
138
188
|
if (sun)
|
|
139
189
|
c.sunset = sun.slice(0, 64);
|
|
140
190
|
this.calls.set(key, c);
|
|
191
|
+
const st = this.statsOf(source);
|
|
192
|
+
st.calls++;
|
|
193
|
+
if (status === 0 || status >= 400)
|
|
194
|
+
st.httpErrors++;
|
|
195
|
+
this.options.onCall?.({ source, method, host, path, status, ms: Math.round(ms), ...(error ? { error } : {}) });
|
|
141
196
|
}
|
|
142
197
|
callList() { return [...this.calls.values()]; }
|
|
143
198
|
/** A warning in the source's own list, once per endpoint: the provider retires (410) or plans to retire it. */
|
|
@@ -157,27 +212,44 @@ export class RunRecorder {
|
|
|
157
212
|
}
|
|
158
213
|
/**
|
|
159
214
|
* Every source reaches the network through the global fetch (the default `fetchFn` of each client, read when the
|
|
160
|
-
* client is built), so
|
|
215
|
+
* client is built), so one wrapper in place while sources run counts each call against the source whose work made
|
|
216
|
+
* it (AsyncLocalStorage), and abandons it after `timeoutMs`. A call made outside any source passes through untouched.
|
|
161
217
|
*/
|
|
162
|
-
instrumentFetch(
|
|
218
|
+
instrumentFetch() {
|
|
163
219
|
const original = globalThis.fetch;
|
|
164
220
|
if (typeof original !== "function")
|
|
165
221
|
return () => { };
|
|
166
222
|
const rec = this;
|
|
223
|
+
const timeoutMs = this.options.timeoutMs ?? 0;
|
|
167
224
|
const wrapped = async function (input, init) {
|
|
225
|
+
const cur = rec.current.getStore();
|
|
226
|
+
if (!cur)
|
|
227
|
+
return original(input, init);
|
|
168
228
|
const url = input instanceof Request ? input.url : String(input);
|
|
169
229
|
const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
|
|
230
|
+
let signal = init?.signal ?? undefined;
|
|
231
|
+
if (timeoutMs > 0)
|
|
232
|
+
signal = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
|
|
170
233
|
const t0 = rec.clock();
|
|
171
234
|
try {
|
|
172
|
-
const res = await original(input, init);
|
|
173
|
-
rec.call(
|
|
235
|
+
const res = await original(input, signal ? { ...init, signal } : init);
|
|
236
|
+
rec.call(cur.name, method, url, res.status, rec.clock() - t0, res.headers);
|
|
174
237
|
if (res.headers?.get("deprecation") || res.headers?.get("sunset") || res.status === 410) {
|
|
175
|
-
rec.deprecated(
|
|
238
|
+
rec.deprecated(cur.name, method, url, res.status, res.headers?.get("sunset") ?? null);
|
|
176
239
|
}
|
|
177
240
|
return res;
|
|
178
241
|
}
|
|
179
242
|
catch (e) {
|
|
180
|
-
|
|
243
|
+
const timedOut = e?.name === "TimeoutError";
|
|
244
|
+
let host = "";
|
|
245
|
+
try {
|
|
246
|
+
host = new URL(url).host;
|
|
247
|
+
}
|
|
248
|
+
catch { /* not a URL */ }
|
|
249
|
+
const why = timedOut ? `no answer from ${host} within ${Math.round(timeoutMs / 1000)} s (--http-timeout)` : String(e?.message ?? e);
|
|
250
|
+
rec.call(cur.name, method, url, 0, rec.clock() - t0, undefined, why);
|
|
251
|
+
if (timedOut)
|
|
252
|
+
throw new Error(why, { cause: e });
|
|
181
253
|
throw e;
|
|
182
254
|
}
|
|
183
255
|
};
|
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
// rds DescribeDBInstances rds:DescribeDBInstances
|
|
22
22
|
// kms ListKeys, DescribeKey, GetKeyRotationStatus kms:ListKeys, kms:DescribeKey, kms:GetKeyRotationStatus
|
|
23
23
|
// backup GET /backup/plans/ (ListBackupPlans) backup:ListBackupPlans
|
|
24
|
+
// backup GET /backup-jobs/ (ListBackupJobs) backup:ListBackupJobs
|
|
25
|
+
// backup GET /restore-jobs/ (ListRestoreJobs) backup:ListRestoreJobs
|
|
24
26
|
// access-analyzer GET /analyzer (ListAnalyzers) access-analyzer:ListAnalyzers
|
|
25
27
|
import { ADMIN_PORTS, Results, ageDays, arr, isObj, j, rangeHits, str } from "../shared-cloud.js";
|
|
26
28
|
import { Aws, awsWhy, errorOf, jsonReq, queryReq, restReq } from "./api.js";
|
|
@@ -32,11 +34,16 @@ export const AWS_CHECKS = [
|
|
|
32
34
|
"rds_encrypted", "rds_not_public", "rds_automated_backups", "sg_no_open_admin_ports", "kms_rotation",
|
|
33
35
|
"backup_plans_exist", "vpc_flow_logs", "access_analyzer_enabled",
|
|
34
36
|
"iam_users_inactive", "s3_bucket_not_public", "guardduty_malware_protection", "ssm_patch_compliance",
|
|
37
|
+
"backup_jobs_succeeded", "restore_tested",
|
|
35
38
|
];
|
|
36
39
|
export const DEFAULT_KEY_MAX_AGE_DAYS = 90;
|
|
37
40
|
/** As entra.ts staleDays: 90 days without a sign-in or a key use. */
|
|
38
41
|
export const DEFAULT_INACTIVE_DAYS = 90;
|
|
39
42
|
export const MIN_PASSWORD_LENGTH = 14;
|
|
43
|
+
/** Days of AWS Backup jobs read: a week of daily jobs. */
|
|
44
|
+
export const DEFAULT_BACKUP_WINDOW_DAYS = 7;
|
|
45
|
+
/** A restore test is expected at least once a year (NIST SP 800-53 Rev. 5 CP-4 and CP-9(1) leave the frequency to the organization). */
|
|
46
|
+
export const DEFAULT_RESTORE_TEST_DAYS = 365;
|
|
40
47
|
const IAM_V = "2010-05-08", EC2_V = "2016-11-15", RDS_V = "2014-10-31";
|
|
41
48
|
const MAX_PAGES = 50;
|
|
42
49
|
export async function accountChecks(aws, account, o) {
|
|
@@ -60,6 +67,8 @@ export async function accountChecks(aws, account, o) {
|
|
|
60
67
|
await securityGroups(aws, out, rr, region);
|
|
61
68
|
kmsSeen += await kms(aws, out, rr, region);
|
|
62
69
|
await backupPlans(aws, out, rr, region);
|
|
70
|
+
await backupJobs(aws, out, rr, region, o);
|
|
71
|
+
await restoreJobs(aws, out, rr, region, o);
|
|
63
72
|
await flowLogs(aws, out, rr, region);
|
|
64
73
|
await accessAnalyzer(aws, out, rr, region);
|
|
65
74
|
await patchCompliance(aws, out, rr, region);
|
|
@@ -595,6 +604,61 @@ async function backupPlans(aws, out, rr, region) {
|
|
|
595
604
|
}
|
|
596
605
|
out.add("backup_plans_exist", rr, plans.length ? "pass" : "fail", `${plans.length} AWS Backup plan(s)${plans.length ? ` (${plans.slice(0, 10).map((x) => j(x.BackupPlanName)).join(", ")})` : ""}; at least one required`);
|
|
597
606
|
}
|
|
607
|
+
/** Every item of an AWS Backup list call (REST, NextToken), or why it could not be read. */
|
|
608
|
+
async function backupList(aws, region, path, key, query) {
|
|
609
|
+
const all = [];
|
|
610
|
+
let next;
|
|
611
|
+
for (let p = 0; p < MAX_PAGES; p++) {
|
|
612
|
+
const r = await aws.json(restReq("backup", region, `backup.${region}.amazonaws.com`, path, { maxResults: "1000", ...query, ...(next ? { nextToken: next } : {}) }));
|
|
613
|
+
if (!r.ok)
|
|
614
|
+
return { error: awsWhy(r.r) };
|
|
615
|
+
all.push(...arr(r.o[key]).filter(isObj));
|
|
616
|
+
next = str(r.o.NextToken) || undefined;
|
|
617
|
+
if (!next)
|
|
618
|
+
break;
|
|
619
|
+
}
|
|
620
|
+
return { items: all };
|
|
621
|
+
}
|
|
622
|
+
/** AWS Backup's REST JSON gives timestamps as epoch seconds; accept an ISO string too. */
|
|
623
|
+
const epoch = (v) => (typeof v === "number" ? v * 1000 : typeof v === "string" && Number.isFinite(Date.parse(v)) ? Date.parse(v) : undefined);
|
|
624
|
+
const BAD_JOB = new Set(["FAILED", "ABORTED", "EXPIRED", "PARTIAL"]);
|
|
625
|
+
// ListBackupJobs (GET /backup-jobs/?createdAfter=…, backup:ListBackupJobs): for each resource, the latest job in the
|
|
626
|
+
// window must be COMPLETED. A failure followed by a completed job on the same resource is recovered, not failed.
|
|
627
|
+
async function backupJobs(aws, out, rr, region, o) {
|
|
628
|
+
const since = new Date(o.now.getTime() - o.backupWindowDays * 86_400_000).toISOString();
|
|
629
|
+
const r = await backupList(aws, region, "/backup-jobs/", "BackupJobs", { createdAfter: since });
|
|
630
|
+
if ("error" in r)
|
|
631
|
+
return out.skip("backup_jobs_succeeded", rr, `backup jobs not readable: ${r.error}`);
|
|
632
|
+
const latest = new Map();
|
|
633
|
+
for (const job of r.items) {
|
|
634
|
+
const res = str(job.ResourceArn) ?? str(job.BackupJobId) ?? "?", at = epoch(job.CreationDate) ?? 0, state = String(job.State ?? "");
|
|
635
|
+
if (["CREATED", "PENDING", "RUNNING"].includes(state))
|
|
636
|
+
continue;
|
|
637
|
+
const had = latest.get(res);
|
|
638
|
+
if (!had || at > had.at)
|
|
639
|
+
latest.set(res, { state, at });
|
|
640
|
+
}
|
|
641
|
+
if (!latest.size)
|
|
642
|
+
return out.add("backup_jobs_succeeded", rr, "fail", `no finished AWS Backup job since ${since.slice(0, 10)} (${o.backupWindowDays} days); at least one completed job per protected resource required`);
|
|
643
|
+
const bad = [...latest.entries()].filter(([, v]) => BAD_JOB.has(v.state));
|
|
644
|
+
const counts = new Map();
|
|
645
|
+
for (const v of latest.values())
|
|
646
|
+
counts.set(v.state, (counts.get(v.state) ?? 0) + 1);
|
|
647
|
+
out.add("backup_jobs_succeeded", rr, bad.length ? "fail" : "pass", `${latest.size} resource(s) backed up since ${since.slice(0, 10)}; latest job by state: ${[...counts.entries()].map(([k, n]) => `${k} ${n}`).join(", ")}${bad.length ? `; not completed: ${bad.slice(0, 10).map(([k, v]) => `${k.split(":").slice(-2).join(":")} ${v.state}`).join(", ")}` : ""}; every resource's latest job COMPLETED required`);
|
|
648
|
+
}
|
|
649
|
+
// ListRestoreJobs (GET /restore-jobs/?createdAfter=…, backup:ListRestoreJobs): a restore that completed in the period is
|
|
650
|
+
// a restore test on record. AWS Backup restore testing plans write restore jobs too, so both count.
|
|
651
|
+
async function restoreJobs(aws, out, rr, region, o) {
|
|
652
|
+
const since = new Date(o.now.getTime() - o.restoreTestDays * 86_400_000).toISOString();
|
|
653
|
+
const r = await backupList(aws, region, "/restore-jobs/", "RestoreJobs", { createdAfter: since });
|
|
654
|
+
if ("error" in r)
|
|
655
|
+
return out.skip("restore_tested", rr, `restore jobs not readable: ${r.error}`);
|
|
656
|
+
const done = r.items.filter((x) => x.Status === "COMPLETED");
|
|
657
|
+
const last = done.map((x) => epoch(x.CompletionDate) ?? epoch(x.CreationDate) ?? 0).sort((a, b) => b - a)[0];
|
|
658
|
+
const types = [...new Set(done.map((x) => j(x.ResourceType)).filter(Boolean))].slice(0, 10);
|
|
659
|
+
out.add("restore_tested", rr, done.length ? "pass" : "fail", done.length ? `${done.length} completed restore job(s) since ${since.slice(0, 10)}${types.length ? ` (${types.join(", ")})` : ""}; latest ${last ? new Date(last).toISOString().slice(0, 10) : "undated"}; ${r.items.length - done.length} other(s)`
|
|
660
|
+
: `no completed restore job since ${since.slice(0, 10)} (${o.restoreTestDays} days; ${r.items.length} restore job(s) in other states); a restore test in the period required, or record one done outside AWS Backup`);
|
|
661
|
+
}
|
|
598
662
|
// ── Network ─────────────────────────────────────────────────────────────────────────────────────
|
|
599
663
|
/** Every item of an EC2 Describe call that pages with NextToken. */
|
|
600
664
|
async function ec2List(aws, region, action, set, params = {}) {
|
|
@@ -2,13 +2,15 @@
|
|
|
2
2
|
// from the environment (see aws/api.ts envCredentials) and may assume --aws-role-arn first. Every call
|
|
3
3
|
// is a signed read; no SDK.
|
|
4
4
|
import { AWS_SECRET_ENVS, Aws, assumeRole, callerAccount, envCredentials, fetchAwsTransport } from "./aws/api.js";
|
|
5
|
-
import { AWS_CHECKS, DEFAULT_INACTIVE_DAYS, DEFAULT_KEY_MAX_AGE_DAYS, accountChecks } from "./aws/checks.js";
|
|
5
|
+
import { AWS_CHECKS, DEFAULT_BACKUP_WINDOW_DAYS, DEFAULT_INACTIVE_DAYS, DEFAULT_KEY_MAX_AGE_DAYS, DEFAULT_RESTORE_TEST_DAYS, accountChecks } from "./aws/checks.js";
|
|
6
6
|
import { allSkipped, list, scrub } from "./shared-cloud.js";
|
|
7
7
|
export const DEFAULT_AWS_REGION = "us-east-1";
|
|
8
8
|
const regionsOf = (opts, env) => {
|
|
9
9
|
const r = list(opts["aws-regions"]);
|
|
10
10
|
return r.length ? r : [env.AWS_REGION || env.AWS_DEFAULT_REGION || DEFAULT_AWS_REGION];
|
|
11
11
|
};
|
|
12
|
+
/** A positive number of days from an option, or the default. */
|
|
13
|
+
const posDays = (v, d) => { const n = Number(typeof v === "string" ? v : NaN); return Number.isFinite(n) && n > 0 ? n : d; };
|
|
12
14
|
export const aws = {
|
|
13
15
|
name: "aws",
|
|
14
16
|
options: {
|
|
@@ -17,6 +19,8 @@ export const aws = {
|
|
|
17
19
|
"aws-external-id": { type: "string", help: "external id for --aws-role-arn" },
|
|
18
20
|
"aws-key-max-age-days": { type: "string", help: `oldest an active IAM access key may be (default ${DEFAULT_KEY_MAX_AGE_DAYS})` },
|
|
19
21
|
"aws-inactive-days": { type: "string", help: `days an IAM user's password and active keys may go unused (default ${DEFAULT_INACTIVE_DAYS})` },
|
|
22
|
+
"aws-backup-window-days": { type: "string", help: `days of AWS Backup jobs read; each resource's latest must be COMPLETED (default ${DEFAULT_BACKUP_WINDOW_DAYS})` },
|
|
23
|
+
"aws-restore-test-days": { type: "string", help: `days within which a completed restore job must exist (default ${DEFAULT_RESTORE_TEST_DAYS})` },
|
|
20
24
|
},
|
|
21
25
|
emits: AWS_CHECKS.map((c) => `aws.${c}`),
|
|
22
26
|
describe(opts) {
|
|
@@ -61,6 +65,7 @@ export const aws = {
|
|
|
61
65
|
const results = await accountChecks(api, who.account, {
|
|
62
66
|
regions, keyMaxAgeDays: Number.isFinite(days) && days > 0 ? days : DEFAULT_KEY_MAX_AGE_DAYS,
|
|
63
67
|
inactiveDays: Number.isFinite(idle) && idle > 0 ? idle : DEFAULT_INACTIVE_DAYS, now: ctx.now,
|
|
68
|
+
backupWindowDays: posDays(ctx.opts["aws-backup-window-days"], DEFAULT_BACKUP_WINDOW_DAYS), restoreTestDays: posDays(ctx.opts["aws-restore-test-days"], DEFAULT_RESTORE_TEST_DAYS),
|
|
64
69
|
});
|
|
65
70
|
return scrub(results, secrets);
|
|
66
71
|
},
|
|
@@ -28,6 +28,10 @@ export const API = {
|
|
|
28
28
|
disks: "2023-10-02",
|
|
29
29
|
recoveryServices: "2023-04-01",
|
|
30
30
|
backup: "2023-04-01",
|
|
31
|
+
// Backup Jobs - List (learn.microsoft.com/rest/api/backup/backup-jobs/list, updated 2026-11-03, read 2026-11-07).
|
|
32
|
+
backupJobs: "2026-11-01",
|
|
33
|
+
// Workspaces (learn.microsoft.com/rest/api/loganalytics/workspaces, updated 2026-08-10, read 2026-11-07).
|
|
34
|
+
workspaces: "2026-03-01",
|
|
31
35
|
// Resources - List (learn.microsoft.com/rest/api/resources/resources/list, read 2026-10-26).
|
|
32
36
|
resources: "2021-04-01",
|
|
33
37
|
// Virtual Machines - List All and Instance View (learn.microsoft.com/rest/api/compute/virtual-machines/, read 2026-10-26).
|
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
// GET /providers/Microsoft.Authorization/policyAssignments Reader
|
|
15
15
|
// GET /providers/Microsoft.Compute/disks Reader
|
|
16
16
|
// GET /providers/Microsoft.RecoveryServices/vaults, {vault}/backupProtectedItems Reader
|
|
17
|
+
// GET {vault}/backupJobs?$filter=startTime eq … and endTime eq … Reader (or Backup Reader)
|
|
18
|
+
// GET /providers/Microsoft.OperationalInsights/workspaces Reader
|
|
17
19
|
// GET /resources?$filter=resourceType eq '<type>' Reader (which Defender plans the subscription needs)
|
|
18
20
|
// GET {sql server}/firewallRules Reader
|
|
19
21
|
// GET /providers/Microsoft.Compute/virtualMachines, {vm}/instanceView Reader
|
|
@@ -23,7 +25,7 @@ export const AZURE_CHECKS = [
|
|
|
23
25
|
"defender_plans", "secure_score", "activity_log_export", "keyvault_recoverable",
|
|
24
26
|
"storage_secure_transfer", "storage_no_public_blob", "storage_min_tls", "sql_tde",
|
|
25
27
|
"nsg_no_open_admin_ports", "policy_assignments", "disk_encryption", "backup_protected_items",
|
|
26
|
-
"sql_firewall_not_open", "vm_patches_current",
|
|
28
|
+
"sql_firewall_not_open", "vm_patches_current", "backup_jobs_succeeded", "restore_tested", "log_analytics_retention",
|
|
27
29
|
];
|
|
28
30
|
/** Oldest a VM's patch assessment may be (Azure Update Manager's periodic assessment runs every 24 hours). */
|
|
29
31
|
export const MAX_ASSESSMENT_DAYS = 7;
|
|
@@ -32,6 +34,7 @@ const why = (r) => httpWhy(r.reply, armMessage(r));
|
|
|
32
34
|
const OPEN_SOURCES = new Set(["*", "internet", "any", "0.0.0.0/0", "0.0.0.0", "::/0"]);
|
|
33
35
|
const TLS_OK = new Set(["TLS1_2", "TLS1_3"]);
|
|
34
36
|
const DISK_ENCRYPTION_TYPES = new Set(["EncryptionAtRestWithPlatformKey", "EncryptionAtRestWithCustomerKey", "EncryptionAtRestWithPlatformAndCustomerKeys"]);
|
|
37
|
+
export const DEFAULT_BACKUP_WINDOW_DAYS = 7, DEFAULT_RESTORE_TEST_DAYS = 365, DEFAULT_LOG_RETENTION_DAYS = 365;
|
|
35
38
|
// Which resource types each Defender for Cloud plan protects, so a plan is demanded only where the subscription has
|
|
36
39
|
// something for it to protect (Stéphane, 2026-10-26). Plan names are the pricings API's (Pricings - List,
|
|
37
40
|
// learn.microsoft.com/rest/api/defenderforcloud/pricings/list, read 2026-10-26); what each plan covers is from its
|
|
@@ -260,8 +263,95 @@ export async function subscriptionChecks(t, sub, o) {
|
|
|
260
263
|
}
|
|
261
264
|
out.add("backup_protected_items", res, items.items.length ? "pass" : "fail", `${items.items.length} protected item(s); at least one required`);
|
|
262
265
|
}
|
|
266
|
+
if ("error" in rv)
|
|
267
|
+
for (const c of ["backup_jobs_succeeded", "restore_tested"])
|
|
268
|
+
out.skip(c, subRes, `Recovery Services vaults not readable: ${why(rv.error)}`);
|
|
269
|
+
else
|
|
270
|
+
await backupJobs(t, rv.items, subRes, o, out);
|
|
271
|
+
await logRetention(t, S, subRes, o, out);
|
|
263
272
|
return out.results;
|
|
264
273
|
}
|
|
274
|
+
/** Azure Backup's job filter takes times as "yyyy-MM-dd hh:mm:ss AM" [Unverified: the Backup Jobs - List page read
|
|
275
|
+
* 2026-11-07 shows the $filter parameter but no time format; a refused filter gives "skipped", never "pass"]. */
|
|
276
|
+
export const jobTime = (d) => {
|
|
277
|
+
const h = d.getUTCHours(), p = (n) => String(n).padStart(2, "0");
|
|
278
|
+
return `${d.toISOString().slice(0, 10)} ${p(h % 12 || 12)}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())} ${h < 12 ? "AM" : "PM"}`;
|
|
279
|
+
};
|
|
280
|
+
const JOB_OK = new Set(["Completed", "CompletedWithWarnings"]);
|
|
281
|
+
const JOB_BAD = new Set(["Failed", "Cancelled"]);
|
|
282
|
+
// Backup Jobs - List (GET {vault}/backupJobs, Reader or Backup Reader): per vault, each protected item's latest backup
|
|
283
|
+
// job in the window must have completed; across vaults, a restore job that completed within the restore-test period
|
|
284
|
+
// is a restore test on record. One read per vault over the longer of the two windows serves both checks. Status values:
|
|
285
|
+
// the page's samples show Completed and InProgress; Failed, Cancelled and CompletedWithWarnings are read as well
|
|
286
|
+
// [Unverified]: any other value is neither a success nor a failure. Backup Reader ("Can view backup services, but can't
|
|
287
|
+
// make changes", built-in roles, 2026-07-01) or Reader suffices.
|
|
288
|
+
async function backupJobs(t, vaults, subRes, o, out) {
|
|
289
|
+
if (!vaults.length) {
|
|
290
|
+
out.skip("backup_jobs_succeeded", subRes, "no Recovery Services vault");
|
|
291
|
+
out.skip("restore_tested", subRes, "no Recovery Services vault");
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const backupSince = o.now.getTime() - o.backupWindowDays * 86_400_000, restoreSince = o.now.getTime() - o.restoreTestDays * 86_400_000;
|
|
295
|
+
const from = new Date(Math.min(backupSince, restoreSince));
|
|
296
|
+
const filter = encodeURIComponent(`startTime eq '${jobTime(from)}' and endTime eq '${jobTime(o.now)}'`);
|
|
297
|
+
let restores = 0, read = 0, lastRestore = 0;
|
|
298
|
+
for (const v of vaults) {
|
|
299
|
+
const res = `recovery vault ${rgName(v.id, v.name)}`;
|
|
300
|
+
if (typeof v.id !== "string")
|
|
301
|
+
continue;
|
|
302
|
+
const jobs = await listAll(t, `${ARM}${v.id}/backupJobs?api-version=${API.backupJobs}&$filter=${filter}`);
|
|
303
|
+
if ("error" in jobs) {
|
|
304
|
+
out.skip("backup_jobs_succeeded", res, `backup jobs not readable: ${why(jobs.error)}`);
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
read++;
|
|
308
|
+
const latest = new Map();
|
|
309
|
+
for (const jb of jobs.items) {
|
|
310
|
+
const p = isObj(jb.properties) ? jb.properties : {};
|
|
311
|
+
const at = Date.parse(String(p.startTime ?? "")) || 0, status = String(p.status ?? ""), op = String(p.operation ?? "");
|
|
312
|
+
if (op === "Restore" && status === "Completed" && at >= restoreSince) {
|
|
313
|
+
restores++;
|
|
314
|
+
lastRestore = Math.max(lastRestore, at);
|
|
315
|
+
}
|
|
316
|
+
if (op !== "Backup" || at < backupSince || !(JOB_OK.has(status) || JOB_BAD.has(status)))
|
|
317
|
+
continue;
|
|
318
|
+
const item = String(p.entityFriendlyName ?? jb.name ?? "?"), had = latest.get(item);
|
|
319
|
+
if (!had || at > had.at)
|
|
320
|
+
latest.set(item, { status, at });
|
|
321
|
+
}
|
|
322
|
+
if (!latest.size) {
|
|
323
|
+
out.add("backup_jobs_succeeded", res, "fail", `no finished backup job in the last ${o.backupWindowDays} days; each protected item's latest job Completed required`);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
const bad = [...latest.entries()].filter(([, x]) => JOB_BAD.has(x.status));
|
|
327
|
+
const warn = [...latest.values()].filter((x) => x.status === "CompletedWithWarnings").length;
|
|
328
|
+
out.add("backup_jobs_succeeded", res, bad.length ? "fail" : "pass", `${latest.size} item(s) backed up in the last ${o.backupWindowDays} days; ${latest.size - bad.length} latest job(s) completed${warn ? ` (${warn} with warnings)` : ""}${bad.length ? `; not completed: ${bad.slice(0, 10).map(([k, x]) => `${k} ${x.status}`).join(", ")}` : ""}; every item's latest job Completed required`);
|
|
329
|
+
}
|
|
330
|
+
if (!read)
|
|
331
|
+
out.skip("restore_tested", subRes, "no vault's backup jobs could be read");
|
|
332
|
+
else
|
|
333
|
+
out.add("restore_tested", subRes, restores ? "pass" : "fail", restores
|
|
334
|
+
? `${restores} completed restore job(s) in ${read} vault(s) within ${o.restoreTestDays} days; latest ${new Date(lastRestore).toISOString().slice(0, 10)}`
|
|
335
|
+
: `no completed restore job in ${read} vault(s) within ${o.restoreTestDays} days; a restore test in the period required, or record one done outside Azure Backup`);
|
|
336
|
+
}
|
|
337
|
+
// Workspaces - List (GET /providers/Microsoft.OperationalInsights/workspaces, Reader): properties.retentionInDays, the
|
|
338
|
+
// interactive retention of the workspace's tables by default, must reach the required period.
|
|
339
|
+
async function logRetention(t, S, subRes, o, out) {
|
|
340
|
+
const ws = await listAll(t, `${S}/providers/Microsoft.OperationalInsights/workspaces?api-version=${API.workspaces}`);
|
|
341
|
+
if ("error" in ws)
|
|
342
|
+
return out.skip("log_analytics_retention", subRes, `Log Analytics workspaces not readable: ${why(ws.error)}`);
|
|
343
|
+
if (!ws.items.length)
|
|
344
|
+
return out.skip("log_analytics_retention", subRes, "the subscription has no Log Analytics workspace");
|
|
345
|
+
for (const w of ws.items) {
|
|
346
|
+
const p = isObj(w.properties) ? w.properties : {}, days = Number(p.retentionInDays);
|
|
347
|
+
const res = `log analytics workspace ${rgName(w.id, w.name)}`;
|
|
348
|
+
if (!Number.isFinite(days)) {
|
|
349
|
+
out.skip("log_analytics_retention", res, "retentionInDays not returned");
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
out.add("log_analytics_retention", res, days >= o.logRetentionDays ? "pass" : "fail", `retentionInDays ${days}; at least ${o.logRetentionDays} required (a table may set its own retention; tables are not read)`);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
265
355
|
async function sqlTde(t, S, subRes, out) {
|
|
266
356
|
const servers = await listAll(t, `${S}/providers/Microsoft.Sql/servers?api-version=${API.sql}`);
|
|
267
357
|
if ("error" in servers)
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// at subscription scope. Every ARM call is a GET. Microsoft Entra ID (users, MFA, roles) belongs to
|
|
3
3
|
// the Entra source, not this one.
|
|
4
4
|
import { API, ARM, CREDENTIAL_ENVS, fetchAzure, listAll, armMessage, tokenFromEnv } from "./azure/api.js";
|
|
5
|
-
import { AZURE_CHECKS, subscriptionChecks } from "./azure/checks.js";
|
|
5
|
+
import { AZURE_CHECKS, DEFAULT_BACKUP_WINDOW_DAYS, DEFAULT_LOG_RETENTION_DAYS, DEFAULT_RESTORE_TEST_DAYS, subscriptionChecks } from "./azure/checks.js";
|
|
6
6
|
import { allSkipped, httpWhy, list, scrub, str } from "./shared-cloud.js";
|
|
7
7
|
export const DEFAULT_MIN_SECURE_SCORE = 0;
|
|
8
8
|
export const azure = {
|
|
@@ -10,6 +10,9 @@ export const azure = {
|
|
|
10
10
|
options: {
|
|
11
11
|
"azure-subscription": { type: "string", multiple: true, help: "Azure subscription id; default: every subscription the identity can list" },
|
|
12
12
|
"azure-min-secure-score": { type: "string", help: `lowest Defender for Cloud secure score accepted, in percent (default ${DEFAULT_MIN_SECURE_SCORE})` },
|
|
13
|
+
"azure-backup-window-days": { type: "string", help: `days of Azure Backup jobs read; each item's latest must have completed (default ${DEFAULT_BACKUP_WINDOW_DAYS})` },
|
|
14
|
+
"azure-restore-test-days": { type: "string", help: `days within which a completed restore job must exist (default ${DEFAULT_RESTORE_TEST_DAYS})` },
|
|
15
|
+
"azure-log-retention-days": { type: "string", help: `least Log Analytics workspace retention accepted, in days (default ${DEFAULT_LOG_RETENTION_DAYS})` },
|
|
13
16
|
},
|
|
14
17
|
emits: AZURE_CHECKS.map((c) => `azure.${c}`),
|
|
15
18
|
describe(opts) {
|
|
@@ -44,8 +47,11 @@ export const azure = {
|
|
|
44
47
|
return allSkipped("azure", AZURE_CHECKS, "subscription (list)", "the identity can list no enabled subscription; give --azure-subscription");
|
|
45
48
|
}
|
|
46
49
|
const min = Number(ctx.opts["azure-min-secure-score"] ?? DEFAULT_MIN_SECURE_SCORE);
|
|
50
|
+
const days = (k, d) => { const n = Number(typeof ctx.opts[k] === "string" ? ctx.opts[k] : NaN); return Number.isFinite(n) && n > 0 ? n : d; };
|
|
51
|
+
const o = { minSecureScore: Number.isFinite(min) ? min : DEFAULT_MIN_SECURE_SCORE, now: ctx.now, backupWindowDays: days("azure-backup-window-days", DEFAULT_BACKUP_WINDOW_DAYS),
|
|
52
|
+
restoreTestDays: days("azure-restore-test-days", DEFAULT_RESTORE_TEST_DAYS), logRetentionDays: days("azure-log-retention-days", DEFAULT_LOG_RETENTION_DAYS) };
|
|
47
53
|
for (const s of [...new Set(subs)])
|
|
48
|
-
out.push(...(await subscriptionChecks(t, s,
|
|
54
|
+
out.push(...(await subscriptionChecks(t, s, o)));
|
|
49
55
|
return scrub(out, secrets);
|
|
50
56
|
},
|
|
51
57
|
};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// BambooHR (GET only), with an API key the customer makes under their own user, read as joiners, leavers and the org
|
|
2
|
+
// chart (hris_common.ts). The key is the HTTP Basic user name; the password may be any string.
|
|
3
|
+
//
|
|
4
|
+
// From the BambooHR API documentation (all read 2026-11-07):
|
|
5
|
+
// Requests go to https://{companyDomain}.bamboohr.com/api/; the only version is v1.
|
|
6
|
+
// https://documentation.bamboohr.com/docs/api-details
|
|
7
|
+
// A key carries the access of the user who made it: "The permissions of the user associated with the API request will
|
|
8
|
+
// determine which fields" it can see. No read-only key exists, so the customer makes it under a user whose access level
|
|
9
|
+
// reads the fields below and edits nothing. https://documentation.bamboohr.com/docs/getting-started
|
|
10
|
+
// GET /api/v1/employees?filter[status]=active|inactive&fields=<comma list>&page[limit]=<at most 2500>
|
|
11
|
+
// -> { data: [ { employeeId, status, jobTitleName, _restrictedFields, ...requested fields } ], meta: { total, page },
|
|
12
|
+
// _links: { self, next? } }. Fields the caller cannot read come back null and are named in _restrictedFields;
|
|
13
|
+
// unknown field names are ignored. Both statuses are asked for, so leavers are read as well as current staff.
|
|
14
|
+
// https://documentation.bamboohr.com/reference/list-employees
|
|
15
|
+
// Field names: workEmail, hireDate, terminationDate, supervisorEId (the supervisor's employee id), jobTitle.
|
|
16
|
+
// https://documentation.bamboohr.com/docs/list-of-field-names
|
|
17
|
+
// A 429 carries Retry-After; no rate is published. https://documentation.bamboohr.com/docs/api-details
|
|
18
|
+
// The code of conduct or acceptable-use acknowledgement and the background check have no standard field: the customer
|
|
19
|
+
// names the date field (often a custom field) that records each (--bamboohr-ack-field, --bamboohr-background-field).
|
|
20
|
+
// BambooHR's API has no e-signature endpoint; a signed file is a file in a category (GET /api/v1/employees/{id}/files/view),
|
|
21
|
+
// which shows a file exists, not what it says, so it is not read.
|
|
22
|
+
//
|
|
23
|
+
// Personal data: names, photos and every field not listed are never asked for. A person is named in a result by the
|
|
24
|
+
// employee id; the work email is used only for the identity-provider lookup and the LMS join.
|
|
25
|
+
import { HRIS_CHECKS, hrisChecks, hrisOptionSpecs, hrisOptions, hrisSkipped, isoDay } from "./hris_common.js";
|
|
26
|
+
import { IDP_SECRETS } from "./directory.js";
|
|
27
|
+
import { fetchRest, isObj, ok, realSleep, redact, str, why, withRetry } from "./readonly_http.js";
|
|
28
|
+
export const BAMBOOHR_ENV = { key: "BAMBOOHR_API_KEY" };
|
|
29
|
+
export const SUBDOMAIN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
|
|
30
|
+
/** A field name as BambooHR spells it: letters, digits, underscore (custom fields are named this way too). */
|
|
31
|
+
export const FIELD = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
|
|
32
|
+
const BASE_FIELDS = ["workEmail", "hireDate", "terminationDate", "supervisorEId", "jobTitle"];
|
|
33
|
+
export const PAGE = 1000;
|
|
34
|
+
export const employeesPath = (status, fields) => `/v1/employees?filter%5Bstatus%5D=${status}&fields=${encodeURIComponent(fields.join(","))}&page%5Blimit%5D=${PAGE}`;
|
|
35
|
+
/** A BambooHR client for a company subdomain from BAMBOOHR_API_KEY, or what is missing. */
|
|
36
|
+
export function bamboohrFromEnv(env, company, fetchFn = fetch) {
|
|
37
|
+
const key = env[BAMBOOHR_ENV.key];
|
|
38
|
+
if (!company || !SUBDOMAIN.test(company))
|
|
39
|
+
return "--bamboohr-company must be the BambooHR subdomain (acme for acme.bamboohr.com)";
|
|
40
|
+
if (!key)
|
|
41
|
+
return `${BAMBOOHR_ENV.key} is not set`;
|
|
42
|
+
const basic = `Basic ${Buffer.from(`${key}:x`).toString("base64")}`;
|
|
43
|
+
return fetchRest({ base: `https://${company.toLowerCase()}.bamboohr.com/api`, fetchFn, headers: async () => ({ authorization: basic }) });
|
|
44
|
+
}
|
|
45
|
+
/** Every employee of one status, following _links.next (at most 100 pages). */
|
|
46
|
+
async function listStatus(api, status, fields) {
|
|
47
|
+
const items = [];
|
|
48
|
+
let url = employeesPath(status, fields), pages = 0, total;
|
|
49
|
+
while (url && pages < 100) {
|
|
50
|
+
const r = await api.get(url);
|
|
51
|
+
if (!ok(r) || !isObj(r.body) || !Array.isArray(r.body.data))
|
|
52
|
+
return { error: r };
|
|
53
|
+
pages++;
|
|
54
|
+
items.push(...r.body.data.filter(isObj));
|
|
55
|
+
if (isObj(r.body.meta) && Number.isFinite(Number(r.body.meta.total)))
|
|
56
|
+
total = Number(r.body.meta.total);
|
|
57
|
+
const links = isObj(r.body._links) ? r.body._links : {};
|
|
58
|
+
url = isObj(links.next) ? str(links.next.href) : undefined;
|
|
59
|
+
}
|
|
60
|
+
return { items, pages, truncated: !!url, total };
|
|
61
|
+
}
|
|
62
|
+
const lower = (v) => (typeof v === "string" ? v.trim().toLowerCase() : "");
|
|
63
|
+
export function personOf(e, ackField, backgroundField) {
|
|
64
|
+
const status = lower(e.status) === "active" ? "active" : lower(e.status) === "inactive" ? "terminated" : lower(e.status) || "unknown";
|
|
65
|
+
const title = str(e.jobTitle) ?? str(e.jobTitleName);
|
|
66
|
+
return {
|
|
67
|
+
id: String(e.employeeId ?? e.id ?? "?").slice(0, 40),
|
|
68
|
+
email: str(e.workEmail)?.trim() || undefined,
|
|
69
|
+
status,
|
|
70
|
+
hired: isoDay(e.hireDate),
|
|
71
|
+
left: status === "terminated" ? isoDay(e.terminationDate) : undefined,
|
|
72
|
+
managerId: str(e.supervisorEId)?.trim() || (typeof e.supervisorEId === "number" ? String(e.supervisorEId) : undefined),
|
|
73
|
+
title: title?.trim() || undefined,
|
|
74
|
+
dates: { ack: ackField ? isoDay(e[ackField]) : undefined, background: backgroundField ? isoDay(e[backgroundField]) : undefined },
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export const bamboohr = {
|
|
78
|
+
name: "bamboohr",
|
|
79
|
+
options: {
|
|
80
|
+
"bamboohr-company": { type: "string", help: "the BambooHR company subdomain (acme for acme.bamboohr.com)" },
|
|
81
|
+
...hrisOptionSpecs("bamboohr"),
|
|
82
|
+
},
|
|
83
|
+
emits: HRIS_CHECKS.map((c) => `bamboohr.${c}`),
|
|
84
|
+
describe: (opts) => `BambooHR company ${typeof opts["bamboohr-company"] === "string" ? opts["bamboohr-company"] : "(none)"} (API v1, GET only)`,
|
|
85
|
+
validate(opts) {
|
|
86
|
+
for (const k of ["bamboohr-ack-field", "bamboohr-background-field"]) {
|
|
87
|
+
const v = opts[k];
|
|
88
|
+
if (typeof v === "string" && v.trim() && !FIELD.test(v.trim()))
|
|
89
|
+
return `--${k} must be a BambooHR field name (letters, digits and _)`;
|
|
90
|
+
}
|
|
91
|
+
return undefined;
|
|
92
|
+
},
|
|
93
|
+
async run(ctx) {
|
|
94
|
+
const company = typeof ctx.opts["bamboohr-company"] === "string" ? ctx.opts["bamboohr-company"].trim() : undefined;
|
|
95
|
+
const resource = `bamboohr ${company ?? "(unknown)"}`;
|
|
96
|
+
const o = hrisOptions("bamboohr", ctx);
|
|
97
|
+
if (typeof o === "string")
|
|
98
|
+
return hrisSkipped("bamboohr", resource, o);
|
|
99
|
+
const given = ctx.clients.bamboohr;
|
|
100
|
+
const built = given !== undefined ? given : bamboohrFromEnv(ctx.env, company);
|
|
101
|
+
if (!built || typeof built === "string")
|
|
102
|
+
return hrisSkipped("bamboohr", resource, typeof built === "string" ? built : "no BambooHR client");
|
|
103
|
+
const api = withRetry(built, ctx.clients.sleep ?? realSleep);
|
|
104
|
+
const fields = [...BASE_FIELDS, ...[o.ackField, o.backgroundField].filter((f) => !!f && FIELD.test(f))];
|
|
105
|
+
const people = [];
|
|
106
|
+
let pages = 0, truncated = false;
|
|
107
|
+
const restricted = new Set();
|
|
108
|
+
for (const status of ["active", "inactive"]) {
|
|
109
|
+
const l = await listStatus(api, status, fields);
|
|
110
|
+
if ("error" in l)
|
|
111
|
+
return redact(hrisSkipped("bamboohr", resource, `employees (${status}) not readable: ${why(l.error)}`, l.error), [ctx.env[BAMBOOHR_ENV.key]]);
|
|
112
|
+
pages += l.pages;
|
|
113
|
+
truncated ||= l.truncated;
|
|
114
|
+
for (const e of l.items) {
|
|
115
|
+
for (const f of Array.isArray(e._restrictedFields) ? e._restrictedFields : [])
|
|
116
|
+
if (typeof f === "string")
|
|
117
|
+
restricted.add(f);
|
|
118
|
+
people.push(personOf(e, o.ackField, o.backgroundField));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// A field the key's user cannot read comes back null: say so, rather than fail people for an empty field.
|
|
122
|
+
const hidden = fields.filter((f) => restricted.has(f));
|
|
123
|
+
const read = { method: "config-read", itemsRead: people.length, pagesRead: pages, complete: !truncated && !hidden.length };
|
|
124
|
+
let rs = await hrisChecks("bamboohr", resource, people, read, o, ctx);
|
|
125
|
+
for (const [check, field] of [["bamboohr.hire_acknowledgement", o.ackField], ["bamboohr.hire_background_check", o.backgroundField]]) {
|
|
126
|
+
if (!field || !hidden.includes(field))
|
|
127
|
+
continue;
|
|
128
|
+
rs = rs.filter((r) => r.check !== check);
|
|
129
|
+
rs.push({ check, resource, result: "skipped", detail: `the API key's user cannot read the field ${field} (BambooHR lists it in _restrictedFields); give that user read access to it` });
|
|
130
|
+
}
|
|
131
|
+
return redact(rs, [ctx.env[BAMBOOHR_ENV.key], ...IDP_SECRETS(ctx.env)]);
|
|
132
|
+
},
|
|
133
|
+
};
|