@knowttl/tenable-axi 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +347 -2
- package/axi-credential.schema.json +28 -0
- package/bin/tenable-axi-hook.js +13 -0
- package/bin/tenable-axi.js +8 -0
- package/bin/version.js +3 -0
- package/dist/src/attack-catalogue.d.ts +176 -0
- package/dist/src/attack-catalogue.js +71 -0
- package/dist/src/attack-export-catalogue.d.ts +29 -0
- package/dist/src/attack-export-catalogue.js +58 -0
- package/dist/src/attack-export.d.ts +5 -0
- package/dist/src/attack-export.js +151 -0
- package/dist/src/attack.d.ts +3 -0
- package/dist/src/attack.js +287 -0
- package/dist/src/catalogue.d.ts +150 -0
- package/dist/src/catalogue.js +68 -0
- package/dist/src/cli.d.ts +11 -0
- package/dist/src/cli.js +61 -0
- package/dist/src/export-file.d.ts +8 -0
- package/dist/src/export-file.js +157 -0
- package/dist/src/exposure-contracts.d.ts +31 -0
- package/dist/src/exposure-contracts.js +31 -0
- package/dist/src/exposure.d.ts +4 -0
- package/dist/src/exposure.js +323 -0
- package/dist/src/hook-install.d.ts +1 -0
- package/dist/src/hook-install.js +132 -0
- package/dist/src/inventory/schema.d.ts +34 -0
- package/dist/src/inventory/schema.js +18 -0
- package/dist/src/inventory-catalogue.d.ts +55 -0
- package/dist/src/inventory-catalogue.js +62 -0
- package/dist/src/inventory-export-catalogue.d.ts +96 -0
- package/dist/src/inventory-export-catalogue.js +47 -0
- package/dist/src/inventory-export.d.ts +5 -0
- package/dist/src/inventory-export.js +164 -0
- package/dist/src/inventory.d.ts +3 -0
- package/dist/src/inventory.js +285 -0
- package/dist/src/local-commands.d.ts +2 -0
- package/dist/src/local-commands.js +44 -0
- package/dist/src/platform-tag-catalogue.d.ts +101 -0
- package/dist/src/platform-tag-catalogue.js +180 -0
- package/dist/src/platform-tag.d.ts +4 -0
- package/dist/src/platform-tag.js +322 -0
- package/dist/src/private-file.d.ts +18 -0
- package/dist/src/private-file.js +156 -0
- package/dist/src/profiles.d.ts +116 -0
- package/dist/src/profiles.js +147 -0
- package/dist/src/redact.d.ts +7 -0
- package/dist/src/redact.js +41 -0
- package/dist/src/response-catalogue.d.ts +41 -0
- package/dist/src/response-catalogue.js +134 -0
- package/dist/src/response.d.ts +4 -0
- package/dist/src/response.js +227 -0
- package/dist/src/setup.d.ts +1 -0
- package/dist/src/setup.js +39 -0
- package/dist/src/transport-core.d.ts +85 -0
- package/dist/src/transport-core.js +274 -0
- package/dist/src/transport.d.ts +4 -0
- package/dist/src/transport.js +6 -0
- package/dist/src/writes-core.d.ts +112 -0
- package/dist/src/writes-core.js +215 -0
- package/dist/src/writes.d.ts +57 -0
- package/dist/src/writes.js +5 -0
- package/docs/commands.md +1377 -0
- package/inventory/capabilities.json +3728 -0
- package/package.json +55 -4
- package/skills/tenable-axi/SKILL.md +101 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const rows = z.array(z.record(z.string(), z.unknown()));
|
|
3
|
+
export const attackPage = z.object({ data: rows, pagination: z.object({
|
|
4
|
+
total: z.number().int().nonnegative().optional(), offset: z.number().int().nonnegative(),
|
|
5
|
+
limit: z.number().int().positive(),
|
|
6
|
+
}).optional() });
|
|
7
|
+
export const logPage = z.object({ items: rows, total_count: z.number().int().nonnegative().optional() });
|
|
8
|
+
const count = z.number().int().nonnegative();
|
|
9
|
+
const strings = z.array(z.string());
|
|
10
|
+
const objects = z.array(z.record(z.string(), z.json()));
|
|
11
|
+
export const attackFields = {
|
|
12
|
+
vector_id: z.string(), name: z.string(), priority: z.number(), summary: z.string().nullable(),
|
|
13
|
+
is_new: z.boolean(), first_aes: z.number().nullable(), last_acr: z.number(), path_status: z.string(),
|
|
14
|
+
path: z.record(z.string(), z.json()).nullable(), techniques: objects, nodes: objects,
|
|
15
|
+
findings_names: strings, graph_node: z.record(z.string(), z.json()), mitigations: objects,
|
|
16
|
+
};
|
|
17
|
+
export const techniqueFields = {
|
|
18
|
+
serial_id: count, name: z.string(), assets_ids: strings, mitre_id: z.string(), priority: z.string(),
|
|
19
|
+
state: z.string(), status: z.string(), created: z.string(), last_updated_at: z.string(), technique_name: z.string(),
|
|
20
|
+
vector_count: count, total_vector_count: count, critical_assets_count: count, total_critical_assets_count: count,
|
|
21
|
+
tactics: strings, tools: strings, malwares: strings, mitigations: strings, groups: strings,
|
|
22
|
+
detection_ids: strings, weaknesses_ids: strings, source_information: objects, related_nodes: z.record(z.string(), z.json()),
|
|
23
|
+
};
|
|
24
|
+
export const logFields = {
|
|
25
|
+
connector_id: count, status: z.string(), sync_timestamp: z.object({ start: z.string() }).passthrough(),
|
|
26
|
+
sync_uuid: z.string(), type: z.string(), trigger_reason: z.string(), sync_stages_info: objects, sync_logs: objects,
|
|
27
|
+
};
|
|
28
|
+
const permissionHelp = "Attack reads require EXPOSURE_MANAGEMENT.ATTACK_PATH.ATTACK_PATH.READ; check the selected user's access";
|
|
29
|
+
export const attackBindings = Object.freeze({
|
|
30
|
+
"apa-attack-paths-search": { method: "POST", path: "/api/v1/t1/apa/top-attack-paths/search", effect: "read",
|
|
31
|
+
query: ["limit", "offset", "sort", "exclude_resolved", "run_ai_summarization"], paging: ["limit", "offset"],
|
|
32
|
+
decoder: attackPage, permissionHelp, validationHelp: "Run tenable-axi attack-path list --help; check the documented filter body" },
|
|
33
|
+
"apa-attack-techniques-search": { method: "POST", path: "/api/v1/t1/apa/top-attack-techniques/search", effect: "read",
|
|
34
|
+
query: ["limit", "offset", "sort", "exclude_resolved"], paging: ["limit", "offset"], decoder: attackPage,
|
|
35
|
+
permissionHelp, validationHelp: "Run tenable-axi attack-technique list --help; check the documented filter body" },
|
|
36
|
+
"connectors-logs": { method: "GET", path: "/api/v1/t1/connectors/logs", effect: "read",
|
|
37
|
+
query: ["connector_id", "status", "start_date", "end_date"], decoder: logPage,
|
|
38
|
+
permissionHelp: "Connector logs require Administrator [64] or EXPOSURE_MANAGEMENT.CONNECTOR.CONNECTOR.READ; ordinary inventory reads do not require Administrator",
|
|
39
|
+
validationHelp: "Run tenable-axi connector logs --help; use paired YYYY-MM-DD date boundaries" },
|
|
40
|
+
});
|
|
41
|
+
export const attackProperties = ["priority", "name", "summary", "steps", "asset_exposure", "blast_radius", "asset_id", "freetext", "finding_id", "technique", "weakness_id", "critical_asset", "data_source", "apa_aes", "acr", "path_status"];
|
|
42
|
+
export const techniqueProperties = ["priority", "state", "status", "name", "procedureName", "mitre_id", "tactics", "target", "source", "cause", "last_updated_at", "created", "serial_id"];
|
|
43
|
+
export function attackFilterSchema(technique) {
|
|
44
|
+
const single = z.strictObject({ property: z.enum(technique ? techniqueProperties : attackProperties),
|
|
45
|
+
operator: z.enum(["eq", "ne", "gt", "gte", "lt", "lte", "contains", "not_contains", "in", "not_in"]),
|
|
46
|
+
value: z.union([z.string(), z.array(z.string()), z.number().int(), z.array(z.number().int()), z.boolean()]) });
|
|
47
|
+
const operator = technique ? z.enum(["and", "or"]) : z.enum(["AND", "OR"]).default("AND");
|
|
48
|
+
const nested = z.strictObject({ operator, value: z.array(single) });
|
|
49
|
+
return z.union([single, z.strictObject({ operator, value: z.array(z.union([single, nested])) })]);
|
|
50
|
+
}
|
|
51
|
+
const common = { config: "Config path; default credential precedence", profile: "Profile name; default credential precedence",
|
|
52
|
+
fields: "Comma-separated display or wire fields; default compact view", full: "Show full text; default false", help: "Show help",
|
|
53
|
+
limit: "Maximum emitted rows, 1-10000; default 100", all: "Read up to 10000 rows within invocation budgets; excludes --limit",
|
|
54
|
+
cursor: "Bounded resume cursor; retain original selectors, filters, sort and fields" };
|
|
55
|
+
const search = { offset: "Starting record; default 0; excludes --cursor", sort: "Documented wire property:direction",
|
|
56
|
+
filter: "Repeatable: <property> <operator> <JSON-value>; combines with AND (paths) or and (techniques)",
|
|
57
|
+
"filter-file": "Documented single or nested JSON filter, at most two logical levels; '-' reads stdin; excludes --filter",
|
|
58
|
+
"include-resolved": "Include resolved records; default false (exclude_resolved=true)" };
|
|
59
|
+
export const attackCatalogue = {
|
|
60
|
+
"attack-path list": { description: "Search top attack paths using the published specification route", operationId: "apa-attack-paths-search",
|
|
61
|
+
flags: { ...common, ...search, "run-ai-summarization": "true|false; default false" }, defaultFields: ["id", "name", "priority"],
|
|
62
|
+
examples: ["tenable-axi attack-path list --limit 20", "tenable-axi attack-path list --filter 'priority gte 8' --include-resolved"], evidence: "specs/exposure-management.json" },
|
|
63
|
+
"attack-technique list": { description: "Search top attack techniques; affectedAssets counts assets_ids", operationId: "apa-attack-techniques-search",
|
|
64
|
+
flags: { ...common, ...search }, defaultFields: ["id", "name", "affectedAssets"],
|
|
65
|
+
examples: ["tenable-axi attack-technique list --limit 20", "tenable-axi attack-technique list --sort priority:desc --include-resolved"], evidence: "specs/exposure-management.json" },
|
|
66
|
+
"connector logs": { description: "Read connector sync logs; the API has no server paging parameters", operationId: "connectors-logs",
|
|
67
|
+
flags: { ...common, "connector-id": "Nonnegative numeric connector ID", status: "SUCCEEDED|FAILED",
|
|
68
|
+
"start-date": "Inclusive YYYY-MM-DD; requires --end-date", "end-date": "Exclusive YYYY-MM-DD; requires --start-date" },
|
|
69
|
+
defaultFields: ["connectorId", "status", "timestamp"], examples: ["tenable-axi connector logs --connector-id 1 --limit 20",
|
|
70
|
+
"tenable-axi connector logs --status FAILED --start-date 2026-01-01 --end-date 2026-02-01"], evidence: "specs/exposure-management.json" },
|
|
71
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { OperationBinding } from "./transport-core.js";
|
|
3
|
+
import type { MutationOperation } from "./writes-core.js";
|
|
4
|
+
export declare const attackExportInputs: Record<string, z.ZodType>;
|
|
5
|
+
export declare const attackExportCreated: z.ZodObject<{
|
|
6
|
+
export_id: z.ZodString;
|
|
7
|
+
}, z.core.$strip>;
|
|
8
|
+
export declare const attackExportStatus: z.ZodObject<{
|
|
9
|
+
export_id: z.ZodString;
|
|
10
|
+
status: z.ZodEnum<{
|
|
11
|
+
QUEUED: "QUEUED";
|
|
12
|
+
PROCESSING: "PROCESSING";
|
|
13
|
+
FINISHED: "FINISHED";
|
|
14
|
+
ERROR: "ERROR";
|
|
15
|
+
CANCELLED: "CANCELLED";
|
|
16
|
+
}>;
|
|
17
|
+
submitted_at: z.ZodOptional<z.ZodString>;
|
|
18
|
+
last_refreshed_at: z.ZodOptional<z.ZodString>;
|
|
19
|
+
}, z.core.$strip>;
|
|
20
|
+
export declare const attackExportBindings: Readonly<Record<string, OperationBinding>>;
|
|
21
|
+
export declare const attackExportMutations: Readonly<Record<string, MutationOperation>>;
|
|
22
|
+
export declare const attackExportCatalogue: Record<string, {
|
|
23
|
+
description: string;
|
|
24
|
+
operationId: string;
|
|
25
|
+
flags: Record<string, string>;
|
|
26
|
+
defaultFields: string[];
|
|
27
|
+
examples: string[];
|
|
28
|
+
evidence: string;
|
|
29
|
+
}>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { attackProperties, techniqueProperties } from "./attack-catalogue.js";
|
|
3
|
+
function filters(technique) {
|
|
4
|
+
const single = z.strictObject({ property: z.enum(technique ? techniqueProperties : attackProperties).optional(),
|
|
5
|
+
operator: z.enum(["eq", "ne", "gt", "gte", "lt", "lte", "contains", "not_contains", "in", "not_in"]).optional(),
|
|
6
|
+
value: z.union([z.string(), z.array(z.string()), z.number().int(), z.array(z.number().int()), z.boolean()]).optional() });
|
|
7
|
+
const operator = technique ? z.enum(["and", "or"]) : z.enum(["and", "or"]).default("and");
|
|
8
|
+
const nested = z.strictObject({ operator: technique ? operator.optional() : operator, value: z.array(single) });
|
|
9
|
+
return z.union([single, z.strictObject({ operator, value: z.array(z.union([single, nested])) })]);
|
|
10
|
+
}
|
|
11
|
+
const common = { file_format: z.enum(["CSV", "JSON"]), file_name: z.string().max(100).optional() };
|
|
12
|
+
const sort = z.strictObject({ property: z.string(), direction: z.enum(["asc", "desc"]) }).optional();
|
|
13
|
+
export const attackExportInputs = {
|
|
14
|
+
"apa-export-attack-path": z.strictObject({ ...common, filters: filters(false).optional(), vector_ids: z.array(z.string()).optional(),
|
|
15
|
+
columns: z.array(z.enum(["path_name", "priority", "source_nes", "target_acr", "sequence_chain", "enabler_list", "asset_ids"])).optional(), sort }),
|
|
16
|
+
"apa-export-attack-technique": z.strictObject({ ...common, filters: filters(true).optional(), attack_technique_ids: z.array(z.string()).optional(),
|
|
17
|
+
columns: z.array(z.enum(["mitre_id", "technique_name", "priority", "status", "state", "through", "source_names", "source_classes", "source_ids", "target_names", "target_classes", "target_ids", "tactics", "data_sources", "top_attack_path_count", "critical_assets_count"])).optional(), sort }),
|
|
18
|
+
"apa-export-mitre-heatmap": z.strictObject({ ...common,
|
|
19
|
+
filter: z.strictObject({ matrix: z.enum(["enterprise", "ics"]).optional(), platform: z.string().optional(), query: z.string().optional(),
|
|
20
|
+
show_all_techniques: z.boolean().optional(), severities: z.array(z.enum(["info", "low", "medium", "high", "critical"])).optional() }).optional(),
|
|
21
|
+
columns: z.array(z.enum(["technique_id", "tactic", "technique_name", "max_priority", "critical_assets_count", "top_attack_technique_count", "top_attack_path_count", "link"])).optional() }),
|
|
22
|
+
};
|
|
23
|
+
export const attackExportCreated = z.object({ export_id: z.string().uuid() });
|
|
24
|
+
export const attackExportStatus = z.object({ export_id: z.string().uuid(), status: z.enum(["QUEUED", "PROCESSING", "FINISHED", "ERROR", "CANCELLED"]),
|
|
25
|
+
submitted_at: z.string().optional(), last_refreshed_at: z.string().optional() });
|
|
26
|
+
const permissionHelp = "Attack exports require EXPOSURE_MANAGEMENT.ATTACK_PATH.ATTACK_PATH.WRITE; check the selected user's access and export entitlement";
|
|
27
|
+
const validationHelp = "Run tenable-axi export attack-path start --help; use the documented operation-specific JSON body";
|
|
28
|
+
export const attackExportBindings = Object.freeze({
|
|
29
|
+
...Object.fromEntries(Object.keys(attackExportInputs).map((operation) => [operation, { method: "POST", path: `/api/v1/export/${operation.slice(11)}`,
|
|
30
|
+
effect: "write", query: [], decoder: attackExportCreated, permissionHelp, validationHelp }])),
|
|
31
|
+
"apa-export-status": { method: "GET", path: "/api/v1/export/{export_id}/status", effect: "read", query: [],
|
|
32
|
+
decoder: attackExportStatus, permissionHelp, validationHelp: "Run tenable-axi export attack status --id <id>" },
|
|
33
|
+
"apa-export-download": { method: "GET", path: "/api/v1/export/{export_id}/download", effect: "read", query: [],
|
|
34
|
+
responseMode: "file", decoder: z.instanceof(Buffer), permissionHelp, validationHelp: "Run tenable-axi export attack download --id <id> --output <new-file>" },
|
|
35
|
+
});
|
|
36
|
+
export const attackExportMutations = Object.freeze(Object.fromEntries(Object.entries(attackExportInputs).map(([operation, input]) => [operation, { input,
|
|
37
|
+
prepare: (body) => ({ target: { kind: "attack-export", payload: true }, request: { body } }),
|
|
38
|
+
effect: "Create one tenant-side attack export job for the previewed filter and format scope; no server-side dry run or idempotency guarantee",
|
|
39
|
+
readBackHelp: ["Inspect export attack status --id <known-export-id> before any new start; an interrupted create may have succeeded without returning its ID"],
|
|
40
|
+
}])));
|
|
41
|
+
const global = { config: "Config path; default credential precedence", profile: "Profile name; default credential precedence",
|
|
42
|
+
fields: "Comma-separated metadata fields; default compact view", full: "Full metadata text; default false", help: "Show help" };
|
|
43
|
+
const write = { "body-file": "Required strict operation-specific JSON file, at most 1 MiB; '-' reads stdin",
|
|
44
|
+
execute: "Create the previewed job once; default false", "dry-run": "Preview only; excludes --execute",
|
|
45
|
+
confirm: "Exact confirmation string from preview; required with --execute" };
|
|
46
|
+
export const attackExportCatalogue = {
|
|
47
|
+
...Object.fromEntries(["attack-path", "attack-technique", "mitre-heatmap"].map((kind) => [`export ${kind} start`, {
|
|
48
|
+
description: `Preview or start one ${kind} export; requires configured write scope and ATTACK_PATH.WRITE`, operationId: `apa-export-${kind}`,
|
|
49
|
+
flags: { ...global, ...write }, defaultFields: ["id", "state"],
|
|
50
|
+
examples: [`tenable-axi export ${kind} start --body-file export.json`, `tenable-axi export ${kind} start --body-file export.json --execute --confirm '<preview-confirmation>'`], evidence: "specs/exposure-management.json",
|
|
51
|
+
}])),
|
|
52
|
+
"export attack status": { description: "Read an attack export job; no polling by default", operationId: "apa-export-status",
|
|
53
|
+
flags: { ...global, id: "Required attack export UUID", wait: "Poll once per second within 20-second/20-request budgets; default false" }, defaultFields: ["id", "state"],
|
|
54
|
+
examples: ["tenable-axi export attack status --id <id>", "tenable-axi export attack status --id <id> --wait"], evidence: "specs/exposure-management.json" },
|
|
55
|
+
"export attack download": { description: "Download an attack export to a new file, redacting JSON/CSV within 128 MiB", operationId: "apa-export-download",
|
|
56
|
+
flags: { ...global, id: "Required attack export UUID", output: "Required new output file; overwrite refused" }, defaultFields: ["id", "output", "bytes", "format"],
|
|
57
|
+
examples: ["tenable-axi export attack download --id <id> --output attack.json", "tenable-axi export attack download --id <id> --output attack.csv"], evidence: "specs/exposure-management.json" },
|
|
58
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { credentialStore } from "./profiles.js";
|
|
2
|
+
import { type Transport, type TransportOptions } from "./transport.js";
|
|
3
|
+
import { createWriteCoordinator, type WriteCoordinatorOptions } from "./writes.js";
|
|
4
|
+
export type WriteCoordinatorFactory = (options: WriteCoordinatorOptions) => ReturnType<typeof createWriteCoordinator>;
|
|
5
|
+
export declare function attackExportCommand(argv: string[], store: ReturnType<typeof credentialStore>, transportFactory?: (options: TransportOptions) => Transport, writeFactory?: WriteCoordinatorFactory): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { AxiError } from "axi-sdk-js";
|
|
2
|
+
import { closeSync, openSync, readSync } from "node:fs";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { attackExportCatalogue, attackExportCreated, attackExportInputs, attackExportStatus } from "./attack-export-catalogue.js";
|
|
5
|
+
import { exportOutputPath, saveExport } from "./export-file.js";
|
|
6
|
+
import { createTransport, TransportError } from "./transport.js";
|
|
7
|
+
import { createWriteCoordinator } from "./writes.js";
|
|
8
|
+
export async function attackExportCommand(argv, store, transportFactory = createTransport, writeFactory = createWriteCoordinator) {
|
|
9
|
+
const name = argv.slice(0, 3).join(" ");
|
|
10
|
+
const entry = attackExportCatalogue[name];
|
|
11
|
+
const usage = (message) => {
|
|
12
|
+
throw new AxiError(message, "VALIDATION_ERROR", [entry
|
|
13
|
+
? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
|
|
14
|
+
: `Valid commands: ${Object.keys(attackExportCatalogue).join(", ")}`]);
|
|
15
|
+
};
|
|
16
|
+
if (!entry)
|
|
17
|
+
usage("Unknown attack export command");
|
|
18
|
+
const flags = new Map();
|
|
19
|
+
for (let index = 3; index < argv.length; index++) {
|
|
20
|
+
const flag = argv[index];
|
|
21
|
+
if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || flags.has(flag))
|
|
22
|
+
usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
|
|
23
|
+
const value = ["--execute", "--dry-run", "--help", "--full", "--wait"].includes(flag) ? "true" : argv[++index];
|
|
24
|
+
if (!value || value.startsWith("--"))
|
|
25
|
+
usage(`Missing value for ${flag}`);
|
|
26
|
+
flags.set(flag, value);
|
|
27
|
+
}
|
|
28
|
+
const get = (flag) => flags.get(`--${flag}`);
|
|
29
|
+
if (get("help"))
|
|
30
|
+
return { command: name, description: entry.description, flags: entry.flags,
|
|
31
|
+
defaultFields: entry.defaultFields, examples: entry.examples };
|
|
32
|
+
const start = argv[2] === "start", download = argv[2] === "download";
|
|
33
|
+
const available = start ? ["id", "state"] : download ? ["id", "output", "bytes", "format", "compressed"] : ["id", "state", "submittedAt", "lastRefreshedAt"];
|
|
34
|
+
const fields = get("fields")?.split(",") ?? entry.defaultFields;
|
|
35
|
+
if (new Set(fields).size !== fields.length || fields.some((field) => !available.includes(field)))
|
|
36
|
+
usage(`Available fields: ${available.join(", ")}`);
|
|
37
|
+
const project = (value) => Object.fromEntries(fields.filter((key) => value[key] !== undefined).map((key) => [key, value[key]]));
|
|
38
|
+
let body;
|
|
39
|
+
if (start) {
|
|
40
|
+
if (get("execute") && get("dry-run"))
|
|
41
|
+
usage("--execute and --dry-run are mutually exclusive");
|
|
42
|
+
if (get("confirm") && !get("execute"))
|
|
43
|
+
usage("--confirm requires --execute");
|
|
44
|
+
if (!get("body-file"))
|
|
45
|
+
usage("--body-file is required with documented file_format and optional filter/columns/name/sort fields");
|
|
46
|
+
let fd;
|
|
47
|
+
try {
|
|
48
|
+
fd = get("body-file") === "-" ? 0 : openSync(get("body-file"), "r");
|
|
49
|
+
const buffer = Buffer.alloc(1024 * 1024 + 1);
|
|
50
|
+
let size = 0;
|
|
51
|
+
for (;;) {
|
|
52
|
+
const read = readSync(fd, buffer, size, buffer.length - size, null);
|
|
53
|
+
if (!read)
|
|
54
|
+
break;
|
|
55
|
+
size += read;
|
|
56
|
+
if (size === buffer.length)
|
|
57
|
+
throw new Error("Input too large");
|
|
58
|
+
}
|
|
59
|
+
body = JSON.parse(buffer.subarray(0, size).toString("utf8"));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
usage("Cannot read --body-file as JSON within the 1 MiB input limit");
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
if (fd !== undefined && fd !== 0)
|
|
66
|
+
closeSync(fd);
|
|
67
|
+
}
|
|
68
|
+
const parsed = attackExportInputs[entry.operationId].safeParse(body);
|
|
69
|
+
if (!parsed.success)
|
|
70
|
+
usage("Invalid export body; use the operation's documented fields and lowercase and/or filter operators; security fields are forbidden");
|
|
71
|
+
body = parsed.data;
|
|
72
|
+
}
|
|
73
|
+
else if (!z.string().uuid().safeParse(get("id")).success)
|
|
74
|
+
usage("--id must be an attack export UUID");
|
|
75
|
+
let output;
|
|
76
|
+
if (download) {
|
|
77
|
+
if (!get("output"))
|
|
78
|
+
usage("--output is required and must name a new file");
|
|
79
|
+
try {
|
|
80
|
+
output = exportOutputPath(get("output"), entry.operationId);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
usage("--output must name a new file; overwrite is refused");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const operation = entry.operationId;
|
|
87
|
+
if (start) {
|
|
88
|
+
const result = await writeFactory({ config: get("config"), profile: get("profile") }).run(operation, body, { execute: !!get("execute"), dryRun: !!get("dry-run"), confirm: get("confirm") });
|
|
89
|
+
if (result.kind !== "success") {
|
|
90
|
+
let truncated = false;
|
|
91
|
+
const previewText = (value) => {
|
|
92
|
+
if (typeof value === "string" && value.length > 1000 && !get("full")) {
|
|
93
|
+
truncated = true;
|
|
94
|
+
return `${value.slice(0, 1000)}... (truncated, ${value.length} chars total)`;
|
|
95
|
+
}
|
|
96
|
+
if (Array.isArray(value))
|
|
97
|
+
return value.map(previewText);
|
|
98
|
+
if (value && typeof value === "object")
|
|
99
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, previewText(child)]));
|
|
100
|
+
return value;
|
|
101
|
+
};
|
|
102
|
+
const preview = previewText(result.preview);
|
|
103
|
+
return { kind: result.kind, preview, ...(truncated ? { help: [`Run tenable-axi ${name} --body-file ${JSON.stringify(get("body-file"))} --full${get("config") ? ` --config ${JSON.stringify(get("config"))}` : ""}${get("profile") ? ` --profile ${get("profile")}` : ""} to see full preview text`] } : {}) };
|
|
104
|
+
}
|
|
105
|
+
const created = attackExportCreated.parse(result.response);
|
|
106
|
+
return { job: project({ id: created.export_id, state: "SUBMITTED" }), auditId: result.auditId,
|
|
107
|
+
help: [`tenable-axi export attack status --id ${created.export_id}${get("config") ? ` --config ${JSON.stringify(get("config"))}` : ""}${get("profile") ? ` --profile ${get("profile")}` : ""}`] };
|
|
108
|
+
}
|
|
109
|
+
store.readOnly();
|
|
110
|
+
const profile = store.select(store.load(get("config")).config, get("profile"));
|
|
111
|
+
const transport = transportFactory({ origin: profile.origin, keys: store.credentials(profile) });
|
|
112
|
+
const request = { pathParams: { export_id: get("id") } };
|
|
113
|
+
if (download) {
|
|
114
|
+
const response = await transport.request(operation, request).catch((error) => {
|
|
115
|
+
if (error instanceof TransportError && error.error.code === "EXPORT_NOT_READY") {
|
|
116
|
+
throw new TransportError({ code: "JOB_NOT_READY", message: "Attack export is not ready for download", operation }, ["Run tenable-axi export attack status --id <id>"]);
|
|
117
|
+
}
|
|
118
|
+
throw error;
|
|
119
|
+
});
|
|
120
|
+
try {
|
|
121
|
+
return { file: project({ id: get("id"), ...saveExport(response.body, output, store.redactor, operation) }) };
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
throw new TransportError({ code: "EXPORT_FILE_INVALID", message: "Export could not be validated, redacted or saved within 128 MiB to a new file", operation });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const deadline = Date.now() + 19_000;
|
|
128
|
+
let status;
|
|
129
|
+
for (;;) {
|
|
130
|
+
let response;
|
|
131
|
+
try {
|
|
132
|
+
response = await transport.request(operation, request);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (get("wait") && status && error instanceof TransportError && ["REQUEST_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED"].includes(error.error.code))
|
|
136
|
+
break;
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
status = attackExportStatus.parse(response.body);
|
|
140
|
+
if (status.export_id !== get("id"))
|
|
141
|
+
throw new TransportError({ code: "RESPONSE_INVALID", message: "Status belongs to a different attack export", operation });
|
|
142
|
+
const pending = ["QUEUED", "PROCESSING"].includes(status.status);
|
|
143
|
+
if (!get("wait") || !pending || Date.now() + 1000 >= deadline)
|
|
144
|
+
break;
|
|
145
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
job: project({ id: status.export_id, state: status.status, submittedAt: status.submitted_at, lastRefreshedAt: status.last_refreshed_at }),
|
|
149
|
+
...(get("wait") && ["QUEUED", "PROCESSING"].includes(status.status) ? { complete: false, reason: "POLL_BUDGET_EXCEEDED" } : {}),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { credentialStore } from "./profiles.js";
|
|
2
|
+
import { type Transport, type TransportOptions } from "./transport.js";
|
|
3
|
+
export declare function attackCommand(argv: string[], store: ReturnType<typeof credentialStore>, transportFactory?: (options: TransportOptions) => Transport): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { AxiError } from "axi-sdk-js";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, openSync, readSync } from "node:fs";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { attackCatalogue, attackFields, attackFilterSchema, attackPage, logFields, logPage, techniqueFields } from "./attack-catalogue.js";
|
|
6
|
+
import { createTransport, TransportError } from "./transport.js";
|
|
7
|
+
const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
8
|
+
const cursorSchema = z.strictObject({ version: z.literal(1), scope: z.string(), offset: integer,
|
|
9
|
+
pending: z.array(z.record(z.string(), z.unknown())), exhausted: z.boolean(), total: integer.nullable(),
|
|
10
|
+
lastPage: z.string().nullable(), upstreamLimited: z.boolean() });
|
|
11
|
+
const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
12
|
+
const maxCursor = 28 * 1024 * 1024;
|
|
13
|
+
function readFilter(path) {
|
|
14
|
+
const fd = path === "-" ? 0 : openSync(path, "r");
|
|
15
|
+
try {
|
|
16
|
+
const buffer = Buffer.alloc(1024 * 1024 + 1);
|
|
17
|
+
let size = 0;
|
|
18
|
+
for (;;) {
|
|
19
|
+
const read = readSync(fd, buffer, size, buffer.length - size, null);
|
|
20
|
+
if (!read)
|
|
21
|
+
break;
|
|
22
|
+
size += read;
|
|
23
|
+
if (size === buffer.length)
|
|
24
|
+
throw new Error("Input too large");
|
|
25
|
+
}
|
|
26
|
+
return JSON.parse(buffer.subarray(0, size).toString("utf8"));
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
if (path !== "-")
|
|
30
|
+
closeSync(fd);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export async function attackCommand(argv, store, transportFactory = createTransport) {
|
|
34
|
+
const name = argv.slice(0, 2).join(" ");
|
|
35
|
+
const entry = attackCatalogue[name];
|
|
36
|
+
const usage = (message) => {
|
|
37
|
+
throw new AxiError(message, "VALIDATION_ERROR", [entry
|
|
38
|
+
? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
|
|
39
|
+
: "Valid commands: attack-path list, attack-technique list, connector logs"]);
|
|
40
|
+
};
|
|
41
|
+
if (!entry)
|
|
42
|
+
usage("Unknown attack or connector command");
|
|
43
|
+
const logs = name === "connector logs";
|
|
44
|
+
const technique = name === "attack-technique list";
|
|
45
|
+
const flags = new Map();
|
|
46
|
+
const booleans = ["--help", "--full", "--all", "--include-resolved"];
|
|
47
|
+
for (let index = 2; index < argv.length; index++) {
|
|
48
|
+
const flag = argv[index];
|
|
49
|
+
if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || (flags.has(flag) && flag !== "--filter"))
|
|
50
|
+
usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
|
|
51
|
+
const value = booleans.includes(flag) ? "true" : argv[++index];
|
|
52
|
+
if (value === undefined || !value.length || value.startsWith("--"))
|
|
53
|
+
usage(`Missing value for ${flag}`);
|
|
54
|
+
flags.set(flag, [...(flags.get(flag) ?? []), value]);
|
|
55
|
+
}
|
|
56
|
+
const get = (flag) => flags.get(`--${flag}`)?.[0];
|
|
57
|
+
if (get("help"))
|
|
58
|
+
return { command: name, description: entry.description, flags: entry.flags,
|
|
59
|
+
defaultFields: entry.defaultFields, examples: entry.examples };
|
|
60
|
+
if (get("all") && get("limit"))
|
|
61
|
+
usage("--all and --limit are mutually exclusive");
|
|
62
|
+
if (get("cursor") && get("offset"))
|
|
63
|
+
usage("--cursor and --offset are mutually exclusive");
|
|
64
|
+
if (get("filter") && get("filter-file"))
|
|
65
|
+
usage("--filter and --filter-file are mutually exclusive");
|
|
66
|
+
const number = (flag, fallback, min, max) => {
|
|
67
|
+
const raw = get(flag);
|
|
68
|
+
if (raw === undefined)
|
|
69
|
+
return fallback;
|
|
70
|
+
const value = Number(raw);
|
|
71
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < min || value > max)
|
|
72
|
+
usage(`--${flag} must be an integer from ${min} to ${max}`);
|
|
73
|
+
return value;
|
|
74
|
+
};
|
|
75
|
+
const rowLimit = get("all") ? 10000 : number("limit", 100, 1, 10000);
|
|
76
|
+
let offset = number("offset", 0, 0, Number.MAX_SAFE_INTEGER);
|
|
77
|
+
const fields = get("fields")?.split(",") ?? entry.defaultFields;
|
|
78
|
+
if (fields.some((field) => !/^[A-Za-z][A-Za-z0-9_]*$/.test(field)) || new Set(fields).size !== fields.length)
|
|
79
|
+
usage("Fields must be unique comma-separated names");
|
|
80
|
+
const schemas = logs ? logFields : technique ? techniqueFields : attackFields;
|
|
81
|
+
const aliases = logs ? { connectorId: "connector_id", timestamp: "sync_timestamp" }
|
|
82
|
+
: technique ? { id: "serial_id", affectedAssets: "assets_ids" } : { id: "vector_id" };
|
|
83
|
+
const wire = (field) => aliases[field] ?? field;
|
|
84
|
+
if (fields.some((field) => !Object.hasOwn(schemas, wire(field))))
|
|
85
|
+
usage(`Available fields: ${[...Object.keys(aliases), ...Object.keys(schemas)].join(", ")}`);
|
|
86
|
+
const query = {};
|
|
87
|
+
if (!logs) {
|
|
88
|
+
query.exclude_resolved = !get("include-resolved");
|
|
89
|
+
if (!technique) {
|
|
90
|
+
const ai = get("run-ai-summarization") ?? "false";
|
|
91
|
+
if (!["true", "false"].includes(ai))
|
|
92
|
+
usage("--run-ai-summarization must be true or false");
|
|
93
|
+
query.run_ai_summarization = ai;
|
|
94
|
+
}
|
|
95
|
+
if (get("sort")) {
|
|
96
|
+
const pattern = technique ? /^[a-zA-Z_]+:(asc|ASC|ascending|ASCENDING|Ascending|desc|DESC|descending|DESCENDING|Descending)$/ : /^[a-zA-Z_]+:(asc|desc)$/;
|
|
97
|
+
if (!pattern.test(get("sort")))
|
|
98
|
+
usage("--sort must use the documented property:direction format");
|
|
99
|
+
query.sort = get("sort");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
if (get("connector-id"))
|
|
104
|
+
query.connector_id = number("connector-id", 0, 0, Number.MAX_SAFE_INTEGER);
|
|
105
|
+
if (get("status")) {
|
|
106
|
+
if (!["SUCCEEDED", "FAILED"].includes(get("status")))
|
|
107
|
+
usage("--status must be SUCCEEDED or FAILED");
|
|
108
|
+
query.status = get("status");
|
|
109
|
+
}
|
|
110
|
+
if (Boolean(get("start-date")) !== Boolean(get("end-date")))
|
|
111
|
+
usage("--start-date and --end-date must be used together");
|
|
112
|
+
for (const flag of ["start-date", "end-date"])
|
|
113
|
+
if (get(flag)) {
|
|
114
|
+
const value = get(flag);
|
|
115
|
+
if (!z.iso.date().safeParse(value).success)
|
|
116
|
+
usage(`--${flag} must be a valid YYYY-MM-DD date`);
|
|
117
|
+
query[flag.replaceAll("-", "_")] = value;
|
|
118
|
+
}
|
|
119
|
+
if (get("start-date") && get("start-date") >= get("end-date"))
|
|
120
|
+
usage("--start-date must precede the exclusive --end-date");
|
|
121
|
+
}
|
|
122
|
+
let body;
|
|
123
|
+
if (get("filter-file")) {
|
|
124
|
+
try {
|
|
125
|
+
body = readFilter(get("filter-file"));
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
usage("Cannot read --filter-file as JSON within the 1 MiB input limit");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else if (get("filter")) {
|
|
132
|
+
const filters = flags.get("--filter").map((text) => {
|
|
133
|
+
const match = /^(\S+)\s+(\S+)\s+(.+)$/s.exec(text);
|
|
134
|
+
if (!match)
|
|
135
|
+
usage("Use --filter '<property> <operator> <JSON-value>'");
|
|
136
|
+
try {
|
|
137
|
+
return { property: match[1], operator: match[2], value: JSON.parse(match[3]) };
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return usage("Filter values must be JSON strings, integers, booleans or homogeneous arrays");
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
body = filters.length === 1 ? filters[0] : { operator: technique ? "and" : "AND", value: filters };
|
|
144
|
+
}
|
|
145
|
+
if (body !== undefined) {
|
|
146
|
+
const parsed = attackFilterSchema(technique).safeParse(body);
|
|
147
|
+
if (!parsed.success)
|
|
148
|
+
usage(`Invalid documented filter: check properties/operators, homogeneous values and at most two logical levels; logical operators use ${technique ? "and|or" : "AND|OR"}`);
|
|
149
|
+
body = parsed.data;
|
|
150
|
+
}
|
|
151
|
+
let saved;
|
|
152
|
+
if (get("cursor")) {
|
|
153
|
+
try {
|
|
154
|
+
const raw = get("cursor");
|
|
155
|
+
if (raw.length > maxCursor || !/^[A-Za-z0-9_-]+$/.test(raw))
|
|
156
|
+
throw new Error();
|
|
157
|
+
saved = cursorSchema.parse(JSON.parse(Buffer.from(raw, "base64url").toString("utf8")));
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
usage("Invalid resume cursor; retain the cursor exactly as returned");
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
store.readOnly();
|
|
164
|
+
const loaded = store.load(get("config"));
|
|
165
|
+
const profile = store.select(loaded.config, get("profile"));
|
|
166
|
+
const operation = entry.operationId;
|
|
167
|
+
const scope = hash([profile.origin, profile.name, profile.accessKey, profile.secretKey, loaded.path, operation, body, query, fields]);
|
|
168
|
+
if (saved && saved.scope !== scope)
|
|
169
|
+
usage("Cursor belongs to a different profile, operation, filters, sort, or fields");
|
|
170
|
+
const transport = transportFactory({ origin: profile.origin, keys: store.credentials(profile) });
|
|
171
|
+
offset = saved?.offset ?? offset;
|
|
172
|
+
let pending = saved?.pending ?? [];
|
|
173
|
+
let pendingIndex = 0;
|
|
174
|
+
let exhausted = saved?.exhausted ?? false;
|
|
175
|
+
let total = saved?.total ?? null;
|
|
176
|
+
let lastPage = saved?.lastPage ?? null;
|
|
177
|
+
let upstreamLimited = saved?.upstreamLimited ?? false;
|
|
178
|
+
const rows = [];
|
|
179
|
+
let reason;
|
|
180
|
+
let failure;
|
|
181
|
+
let truncated = false;
|
|
182
|
+
const invalid = (message) => { throw new TransportError({ code: "RESPONSE_INVALID", message, operation }); };
|
|
183
|
+
const preview = (value) => {
|
|
184
|
+
if (typeof value === "string" && value.length > 1000 && !get("full")) {
|
|
185
|
+
truncated = true;
|
|
186
|
+
return `${value.slice(0, 1000)}... (truncated, ${value.length} chars total)`;
|
|
187
|
+
}
|
|
188
|
+
if (Array.isArray(value))
|
|
189
|
+
return value.map(preview);
|
|
190
|
+
if (value && typeof value === "object")
|
|
191
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, preview(child)]));
|
|
192
|
+
return value;
|
|
193
|
+
};
|
|
194
|
+
const project = (row) => Object.fromEntries(fields.map((field) => {
|
|
195
|
+
let value = row[wire(field)];
|
|
196
|
+
if (value === undefined || !schemas[wire(field)].safeParse(value).success)
|
|
197
|
+
invalid(`Missing or malformed selected field: ${field}`);
|
|
198
|
+
if (logs && field === "timestamp")
|
|
199
|
+
value = value.start;
|
|
200
|
+
if (technique && field === "affectedAssets")
|
|
201
|
+
value = value.length;
|
|
202
|
+
return [field, preview(store.redactor.payload(value))];
|
|
203
|
+
}));
|
|
204
|
+
try {
|
|
205
|
+
while (rows.length < rowLimit) {
|
|
206
|
+
if (pendingIndex < pending.length) {
|
|
207
|
+
rows.push(project(pending[pendingIndex]));
|
|
208
|
+
pendingIndex++;
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
pending = [];
|
|
212
|
+
pendingIndex = 0;
|
|
213
|
+
if (exhausted)
|
|
214
|
+
break;
|
|
215
|
+
const limit = Math.max(100, Math.min(1000, rowLimit - rows.length));
|
|
216
|
+
const response = await transport.request(operation, { query: logs ? query : { ...query, offset, limit },
|
|
217
|
+
...(body === undefined ? {} : { body }) });
|
|
218
|
+
let data;
|
|
219
|
+
if (logs) {
|
|
220
|
+
const page = logPage.parse(response.body);
|
|
221
|
+
data = page.items;
|
|
222
|
+
total = page.total_count ?? null;
|
|
223
|
+
if (total !== null && total < data.length)
|
|
224
|
+
invalid("Connector total is smaller than the returned collection");
|
|
225
|
+
exhausted = true;
|
|
226
|
+
upstreamLimited = total !== null && total > data.length;
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
const page = attackPage.parse(response.body);
|
|
230
|
+
data = page.data;
|
|
231
|
+
if (data.length > limit)
|
|
232
|
+
invalid("The server exceeded the requested page limit");
|
|
233
|
+
if (page.pagination) {
|
|
234
|
+
if (page.pagination.offset !== offset)
|
|
235
|
+
invalid("The server returned a different or repeated offset");
|
|
236
|
+
total = page.pagination.total ?? total;
|
|
237
|
+
}
|
|
238
|
+
if (total !== null && data.length && offset + data.length > total)
|
|
239
|
+
invalid("The server returned rows beyond its reported total");
|
|
240
|
+
if (!data.length && total !== null && offset < total)
|
|
241
|
+
invalid("The server returned an empty page before the reported total");
|
|
242
|
+
const identity = hash(data);
|
|
243
|
+
if (data.length && identity === lastPage)
|
|
244
|
+
invalid("The server repeated the previous page");
|
|
245
|
+
lastPage = identity;
|
|
246
|
+
exhausted = total !== null ? offset + data.length >= total : data.length < limit;
|
|
247
|
+
}
|
|
248
|
+
offset += data.length;
|
|
249
|
+
if (!Number.isSafeInteger(offset))
|
|
250
|
+
invalid("The server returned an unrepresentable offset");
|
|
251
|
+
// Keep only selected wire fields, redacted before entering a public cursor.
|
|
252
|
+
pending = store.redactor.payload(data.map((row) => Object.fromEntries(fields.flatMap((field) => row[wire(field)] === undefined ? [] : [[wire(field), row[wire(field)]]]))));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
if (!(error instanceof TransportError))
|
|
257
|
+
throw error;
|
|
258
|
+
if (["REQUEST_BUDGET_EXCEEDED", "BYTE_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED"].includes(error.error.code))
|
|
259
|
+
reason = error.error.code;
|
|
260
|
+
else {
|
|
261
|
+
if (!rows.length)
|
|
262
|
+
throw error;
|
|
263
|
+
failure = error;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
pending = pending.slice(pendingIndex);
|
|
267
|
+
const complete = exhausted && !pending.length && !upstreamLimited && !failure && !reason;
|
|
268
|
+
const resume = !complete && (pending.length > 0 || !exhausted);
|
|
269
|
+
const cursor = resume ? Buffer.from(JSON.stringify({ version: 1, scope, offset, pending, exhausted, total, lastPage, upstreamLimited })).toString("base64url") : undefined;
|
|
270
|
+
if (cursor && cursor.length > maxCursor)
|
|
271
|
+
invalid("Continuation exceeds its byte bound; narrow the selected fields or filters");
|
|
272
|
+
const command = (excluded) => ["tenable-axi", name, ...[...flags].flatMap(([flag, values]) => excluded.includes(flag) ? []
|
|
273
|
+
: values.flatMap((value) => [flag, ...(booleans.includes(flag) ? [] : [JSON.stringify(value)])]))].join(" ");
|
|
274
|
+
const help = [];
|
|
275
|
+
if (truncated)
|
|
276
|
+
help.push(`Run ${command(["--full"])} --full to read complete text`);
|
|
277
|
+
if (resume)
|
|
278
|
+
help.push(`Run ${command(["--cursor", "--offset"])} --cursor <cursor> to resume; offset paging does not provide snapshot isolation`);
|
|
279
|
+
if (upstreamLimited)
|
|
280
|
+
help.push("The connector API has no server paging; narrow --connector-id and the paired date range to retrieve missing history");
|
|
281
|
+
const noun = logs ? "logs" : technique ? "attackTechniques" : "attackPaths";
|
|
282
|
+
return { [noun]: rows, count: rows.length, total, complete,
|
|
283
|
+
...(!rows.length && complete ? { message: `0 ${logs ? "connector logs" : technique ? "attack techniques" : "attack paths"} matched the selected filters` } : {}),
|
|
284
|
+
...(!complete ? { reason: reason ?? (failure ? "READ_FAILED" : upstreamLimited && !pending.length ? "UPSTREAM_UNPAGED" : get("all") ? "ROW_BUDGET_EXCEEDED" : "LIMIT") } : {}),
|
|
285
|
+
...(cursor ? { cursor } : {}), ...(failure ? failure.toJSON() : {}),
|
|
286
|
+
...(help.length || failure?.help.length ? { help: [...help, ...(failure?.help ?? [])] } : {}) };
|
|
287
|
+
}
|