@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,322 @@
|
|
|
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 { platformTagCatalogue, platformTagInputs, tagPagination } from "./platform-tag-catalogue.js";
|
|
6
|
+
import { createTransport, TransportError } from "./transport.js";
|
|
7
|
+
import { createWriteCoordinator } from "./writes.js";
|
|
8
|
+
const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
9
|
+
const cursorSchema = z.strictObject({ version: z.literal(1), scope: z.string(), offset: integer,
|
|
10
|
+
pending: z.array(z.record(z.string(), z.unknown())), exhausted: z.boolean(), total: integer.nullable(), lastPage: z.string().nullable() });
|
|
11
|
+
const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
12
|
+
const uuid = z.string().uuid();
|
|
13
|
+
const fieldTypes = { id: uuid, name: z.string(), reserved: z.boolean(), category: z.string(), value: z.string().nullable(),
|
|
14
|
+
type: z.string().nullable(), assetId: uuid, tagId: uuid, targetId: uuid, targetType: z.literal("assets"), property: z.string(), operators: z.array(z.string()),
|
|
15
|
+
description: z.string(), category_uuid: uuid, category_description: z.string(), created_at: z.string(), updated_at: z.string(),
|
|
16
|
+
created_by: z.string(), updated_by: z.string(), version: z.number().int(), filters: z.object({ asset: z.string() }),
|
|
17
|
+
access_control: z.record(z.string(), z.unknown()), control: z.record(z.string(), z.unknown()), readable_name: z.string(),
|
|
18
|
+
ipv4: z.array(z.string()), sources: z.array(z.string()), product: z.string(), source: z.string(), container_uuid: uuid };
|
|
19
|
+
function inputFile(path) {
|
|
20
|
+
const fd = path === "-" ? 0 : openSync(path, "r");
|
|
21
|
+
try {
|
|
22
|
+
const buffer = Buffer.alloc(1024 * 1024 + 1);
|
|
23
|
+
let size = 0;
|
|
24
|
+
while (size < buffer.length) {
|
|
25
|
+
const count = readSync(fd, buffer, size, buffer.length - size, null);
|
|
26
|
+
if (!count)
|
|
27
|
+
break;
|
|
28
|
+
size += count;
|
|
29
|
+
}
|
|
30
|
+
if (size > 1024 * 1024)
|
|
31
|
+
throw new Error("Input exceeds 1 MiB");
|
|
32
|
+
return JSON.parse(buffer.subarray(0, size).toString("utf8"));
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
if (path !== "-")
|
|
36
|
+
closeSync(fd);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export async function platformTagCommand(argv, store, factory = createTransport, writeFactory = createWriteCoordinator) {
|
|
40
|
+
const name = argv.slice(0, 3).join(" ");
|
|
41
|
+
const entry = platformTagCatalogue[name];
|
|
42
|
+
const usage = (message) => {
|
|
43
|
+
throw new AxiError(message, "VALIDATION_ERROR", [entry
|
|
44
|
+
? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
|
|
45
|
+
: `Valid commands: ${Object.keys(platformTagCatalogue).join(", ")}`]);
|
|
46
|
+
};
|
|
47
|
+
if (!entry)
|
|
48
|
+
usage("Unknown platform tag command");
|
|
49
|
+
const flags = new Map();
|
|
50
|
+
const booleans = ["--help", "--full", "--all", "--execute", "--dry-run"];
|
|
51
|
+
for (let index = 3; index < argv.length; index++) {
|
|
52
|
+
const flag = argv[index];
|
|
53
|
+
if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || flags.has(flag) && flag !== "--filter")
|
|
54
|
+
usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
|
|
55
|
+
const value = booleans.includes(flag) ? "true" : argv[++index];
|
|
56
|
+
if (value === undefined || value.startsWith("--") || !value && flag !== "--description")
|
|
57
|
+
usage(`Missing value for ${flag}`);
|
|
58
|
+
flags.set(flag, [...flags.get(flag) ?? [], value]);
|
|
59
|
+
}
|
|
60
|
+
const get = (key) => flags.get(`--${key}`)?.[0];
|
|
61
|
+
if (get("help"))
|
|
62
|
+
return { command: name, ...entry };
|
|
63
|
+
const operation = entry.operationId, noun = argv[1], verb = argv[2];
|
|
64
|
+
const invalid = (message) => { throw new TransportError({ code: "RESPONSE_INVALID", message, operation }); };
|
|
65
|
+
const category = noun === "category", value = noun === "value", assignment = noun === "assignment", exclusion = noun === "exclusion";
|
|
66
|
+
const mutating = Object.hasOwn(platformTagInputs, operation);
|
|
67
|
+
const available = mutating && ["delete", "bulk-delete"].includes(verb) ? ["kind", "auditId", "status"]
|
|
68
|
+
: mutating && assignment ? ["id", "state"]
|
|
69
|
+
: category ? ["id", "name", "reserved", "description", "created_at", "created_by", "updated_at", "updated_by"]
|
|
70
|
+
: value ? ["id", "category", "value", "type", "description", "category_uuid", "category_description", "created_at", "created_by", "updated_at", "updated_by", "filters", "access_control", "version"]
|
|
71
|
+
: assignment ? ["assetId", "tagId", "value", "category", "category_uuid", "created_at", "created_by", "product", "source", "container_uuid"]
|
|
72
|
+
: exclusion ? ["targetId", "targetType", "tagId", "name", "ipv4", "sources", "container_uuid"] : ["property", "operators", "readable_name", "control"];
|
|
73
|
+
const fields = get("fields")?.split(",") ?? entry.defaultFields;
|
|
74
|
+
if (fields.some((field) => !available.includes(field)) || new Set(fields).size !== fields.length)
|
|
75
|
+
usage(`Output fields: ${available.join(",")}`);
|
|
76
|
+
if (get("execute") && get("dry-run"))
|
|
77
|
+
usage("--execute and --dry-run are mutually exclusive");
|
|
78
|
+
if (get("intent-id") !== undefined && !get("intent-id").trim())
|
|
79
|
+
usage("--intent-id must not be blank");
|
|
80
|
+
if (get("all") && get("limit") || get("cursor") && get("offset"))
|
|
81
|
+
usage("Incompatible paging flags");
|
|
82
|
+
const number = (flag, fallback, min, max) => {
|
|
83
|
+
const raw = get(flag), result = raw === undefined ? fallback : Number(raw);
|
|
84
|
+
if (raw !== undefined && !/^\d+$/.test(raw) || !Number.isSafeInteger(result) || result < min || result > max)
|
|
85
|
+
usage(`Invalid --${flag}`);
|
|
86
|
+
return result;
|
|
87
|
+
};
|
|
88
|
+
const limit = number("limit", get("all") ? 10000 : 100, 1, 10000);
|
|
89
|
+
let offset = number("offset", 0, 0, Number.MAX_SAFE_INTEGER);
|
|
90
|
+
for (const flag of ["id", "asset-id", "tag-id"]) {
|
|
91
|
+
if (Object.hasOwn(entry.flags, flag) && !uuid.safeParse(get(flag)).success)
|
|
92
|
+
usage(`--${flag} requires an exact UUID`);
|
|
93
|
+
}
|
|
94
|
+
const command = (excluded = []) => ["tenable-axi", name, ...[...flags].flatMap(([flag, values]) => excluded.includes(flag) ? []
|
|
95
|
+
: values.flatMap((value) => [flag, ...(booleans.includes(flag) ? [] : [`'${value.replaceAll("'", "'\"'\"'")}'`])]))].join(" ");
|
|
96
|
+
let truncated = false;
|
|
97
|
+
function preview(input, key) {
|
|
98
|
+
if (typeof input === "string" && key !== "confirm" && input.length > 1000 && !get("full")) {
|
|
99
|
+
truncated = true;
|
|
100
|
+
return `${input.slice(0, 1000)}... (truncated, ${input.length} chars total)`;
|
|
101
|
+
}
|
|
102
|
+
if (Array.isArray(input))
|
|
103
|
+
return input.map((child) => preview(child));
|
|
104
|
+
if (input && typeof input === "object")
|
|
105
|
+
return Object.fromEntries(Object.entries(input).map(([key, child]) => [key, preview(child, key)]));
|
|
106
|
+
return input;
|
|
107
|
+
}
|
|
108
|
+
if (mutating) {
|
|
109
|
+
const fileFlags = ["body-file", "ids-file", "asset-ids-file", "tag-ids-file"].filter((flag) => Object.hasOwn(entry.flags, flag));
|
|
110
|
+
if (fileFlags.filter((flag) => get(flag) === "-").length > 1)
|
|
111
|
+
usage("Only one input file may consume stdin");
|
|
112
|
+
const files = {};
|
|
113
|
+
for (const flag of fileFlags) {
|
|
114
|
+
if (!get(flag))
|
|
115
|
+
usage(`--${flag} is required`);
|
|
116
|
+
try {
|
|
117
|
+
files[flag] = inputFile(get(flag));
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
usage(`Cannot read --${flag} as JSON within the 1 MiB limit`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const body = verb === "delete" ? undefined : verb === "bulk-delete" ? { values: files["ids-file"] }
|
|
124
|
+
: assignment ? { action: verb, assets: files["asset-ids-file"], tags: files["tag-ids-file"] }
|
|
125
|
+
: category ? { name: get("name"), ...(get("description") === undefined ? {} : { description: get("description") }) } : files["body-file"];
|
|
126
|
+
const input = platformTagInputs[operation].safeParse({ ...(get("id") ? { id: get("id") } : {}), ...(body === undefined ? {} : { body }) });
|
|
127
|
+
if (!input.success)
|
|
128
|
+
usage("Invalid tag input; use documented fields and UUID arrays, at most 40 dynamic rules and 1024 values per rule; security fields are forbidden");
|
|
129
|
+
const readBack = "The write succeeded; read back the target before retrying";
|
|
130
|
+
const result = await writeFactory({ config: get("config"), profile: get("profile") }).run(operation, input.data, { execute: !!get("execute"), dryRun: !!get("dry-run"), confirm: get("confirm"), intentId: get("intent-id") }).catch((error) => {
|
|
131
|
+
if (!value || !["delete", "bulk-delete"].includes(verb)
|
|
132
|
+
|| !(error instanceof TransportError) || error.error.code !== "RESPONSE_INVALID" || !error.error.auditId
|
|
133
|
+
|| error.error.status === undefined || error.error.status < 200 || error.error.status >= 300)
|
|
134
|
+
throw error;
|
|
135
|
+
return { kind: "success", auditId: error.error.auditId, status: error.error.status,
|
|
136
|
+
warning: "Write succeeded, but its response could not be decoded", help: [readBack] };
|
|
137
|
+
});
|
|
138
|
+
if ("warning" in result)
|
|
139
|
+
return result;
|
|
140
|
+
if (result.kind !== "success") {
|
|
141
|
+
const output = preview(result);
|
|
142
|
+
return { ...output, ...(truncated ? { help: [`Run ${command(["--full"])} --full to read complete text`] } : {}) };
|
|
143
|
+
}
|
|
144
|
+
const response = result.response;
|
|
145
|
+
const metadata = { kind: "success", auditId: result.auditId, status: result.status };
|
|
146
|
+
let selected;
|
|
147
|
+
try {
|
|
148
|
+
if (assignment) {
|
|
149
|
+
const job = { id: response.job_uuid, state: "ACCEPTED" };
|
|
150
|
+
selected = { ...metadata, job: Object.fromEntries(fields.map((field) => [field, job[field]])) };
|
|
151
|
+
}
|
|
152
|
+
else if (["delete", "bulk-delete"].includes(verb))
|
|
153
|
+
selected = Object.fromEntries(fields.map((field) => [field, metadata[field]]));
|
|
154
|
+
else {
|
|
155
|
+
if (get("id") && response.uuid !== get("id"))
|
|
156
|
+
invalid("Mutation response returned another identifier");
|
|
157
|
+
selected = { ...metadata, tag: preview(project(response)) };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (!(error instanceof TransportError))
|
|
162
|
+
throw error;
|
|
163
|
+
throw new TransportError({ ...error.error, auditId: result.auditId, status: result.status }, ["Mutation was accepted; read back its target before retrying"]);
|
|
164
|
+
}
|
|
165
|
+
return { ...selected, help: [`Run tenable-axi tag ${assignment ? "assignment list --asset-id <id>" : ["delete", "bulk-delete"].includes(verb) ? `${noun} list` : `${noun} show --id ${response.uuid}`}${get("config") ? ` --config '${get("config").replaceAll("'", "'\"'\"'")}'` : ""} --profile ${result.preview.profile}`,
|
|
166
|
+
...(truncated ? [`Run ${command(["--full"])} --full to read complete text`] : [])] };
|
|
167
|
+
}
|
|
168
|
+
const query = {};
|
|
169
|
+
const mutableQuery = {};
|
|
170
|
+
const filters = flags.get("--filter") ?? [];
|
|
171
|
+
for (const filter of filters) {
|
|
172
|
+
const match = /^([^:]+):([^:]+):(.+)$/s.exec(filter);
|
|
173
|
+
if (!match)
|
|
174
|
+
usage("--filter requires field:operator:value");
|
|
175
|
+
const [, field, operator, content] = match;
|
|
176
|
+
const dates = category ? ["created_at", "updated_at"] : ["updated_at"];
|
|
177
|
+
const valid = dates.includes(field) ? ["date-eq", "date-gt", "date-lt"].includes(operator) && /^\d+$/.test(content)
|
|
178
|
+
: field === "updated_by" ? operator === "eq" && uuid.safeParse(content).success
|
|
179
|
+
: (category ? ["name", "description"] : ["value", "category_name", "description"]).includes(field) && ["eq", "match"].includes(operator);
|
|
180
|
+
if (!valid)
|
|
181
|
+
usage("Unsupported platform tag filter; use documented fields and operators");
|
|
182
|
+
}
|
|
183
|
+
if (filters.length)
|
|
184
|
+
mutableQuery.f = filters;
|
|
185
|
+
if (get("filter-type")) {
|
|
186
|
+
if (!["and", "or"].includes(get("filter-type")))
|
|
187
|
+
usage("--filter-type requires and or or");
|
|
188
|
+
mutableQuery.ft = get("filter-type");
|
|
189
|
+
}
|
|
190
|
+
if (get("sort")) {
|
|
191
|
+
if (!/^[A-Za-z_]+:(asc|desc)(,[A-Za-z_]+:(asc|desc))*$/.test(get("sort")))
|
|
192
|
+
usage("--sort requires comma-separated field:asc|desc");
|
|
193
|
+
mutableQuery.sort = get("sort");
|
|
194
|
+
}
|
|
195
|
+
if (!!get("with") !== !!get("with-filter"))
|
|
196
|
+
usage("--with and --with-filter must be supplied together");
|
|
197
|
+
if (get("with-filter")) {
|
|
198
|
+
if (get("with-filter").split(",").some((field) => !["category_name", "value", "description"].includes(field)))
|
|
199
|
+
usage("--with-filter fields: category_name,value,description");
|
|
200
|
+
mutableQuery.w = get("with");
|
|
201
|
+
mutableQuery.wf = get("with-filter");
|
|
202
|
+
}
|
|
203
|
+
if (get("target-type") && get("target-type") !== "assets")
|
|
204
|
+
usage("--target-type must be assets");
|
|
205
|
+
if (exclusion)
|
|
206
|
+
mutableQuery.target_type = get("target-type") ?? "assets";
|
|
207
|
+
Object.assign(query, mutableQuery);
|
|
208
|
+
const pathParams = get("id") ? { [category ? "tag_category_uuid" : "tag_value_uuid"]: get("id") }
|
|
209
|
+
: assignment ? { asset_uuid: get("asset-id") } : exclusion ? { tag_value_uuid: get("tag-id") } : undefined;
|
|
210
|
+
let saved;
|
|
211
|
+
if (get("cursor")) {
|
|
212
|
+
try {
|
|
213
|
+
const raw = get("cursor");
|
|
214
|
+
if (raw.length > 28 * 1024 * 1024 || !/^[A-Za-z0-9_-]+$/.test(raw))
|
|
215
|
+
throw new Error();
|
|
216
|
+
saved = cursorSchema.parse(JSON.parse(Buffer.from(raw, "base64url").toString("utf8")));
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
usage("Invalid resume cursor; retain the original scope and cursor");
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
store.readOnly();
|
|
223
|
+
const profile = store.select(store.load(get("config")).config, get("profile"));
|
|
224
|
+
const scope = hash([profile.origin, profile.name, store.configPath(get("config")), operation, pathParams, query, fields, !!get("full")]);
|
|
225
|
+
if (saved && saved.scope !== scope)
|
|
226
|
+
usage("Cursor belongs to a different profile, operation, selector, fields or filters");
|
|
227
|
+
const transport = factory({ keys: store.credentials(profile), origin: profile.origin });
|
|
228
|
+
function project(row) {
|
|
229
|
+
const mapped = { ...row, ...(category ? { id: row.uuid } : value ? { id: row.uuid ?? (row.value === undefined && row.type === undefined ? row.category_uuid : undefined), category: row.category_name,
|
|
230
|
+
value: row.value === undefined && row.type === undefined ? null : row.value, type: row.value === undefined && row.type === undefined ? null : row.type,
|
|
231
|
+
version: row.version ?? row.access_control?.version }
|
|
232
|
+
: assignment ? { assetId: row.asset_uuid, tagId: row.value_uuid, category: row.category_name }
|
|
233
|
+
: exclusion ? { targetId: row.asset_uuid, targetType: "assets", tagId: row.value_uuid } : { property: row.name }) };
|
|
234
|
+
if (assignment && mapped.assetId !== get("asset-id"))
|
|
235
|
+
invalid("Assignment read returned another asset");
|
|
236
|
+
if (exclusion && row.value_uuid !== undefined && row.value_uuid !== get("tag-id"))
|
|
237
|
+
invalid("Exclusion read returned another tag");
|
|
238
|
+
const selected = Object.fromEntries(fields.map((field) => {
|
|
239
|
+
if (!fieldTypes[field].safeParse(mapped[field]).success)
|
|
240
|
+
invalid(`Missing or malformed selected field: ${field}`);
|
|
241
|
+
return [field, mapped[field]];
|
|
242
|
+
}));
|
|
243
|
+
return store.redactor.payload(selected);
|
|
244
|
+
}
|
|
245
|
+
if (verb === "show") {
|
|
246
|
+
const row = (await transport.request(operation, { pathParams })).body;
|
|
247
|
+
if (row.uuid !== get("id"))
|
|
248
|
+
invalid("Tag read returned another identifier");
|
|
249
|
+
const tag = preview(project(row));
|
|
250
|
+
return { tag, ...(truncated ? { help: [`Run ${command(["--full"])} --full to read complete text`] } : {}) };
|
|
251
|
+
}
|
|
252
|
+
const paged = category || value || exclusion;
|
|
253
|
+
const key = category ? "categories" : value ? "values" : assignment ? "tags" : exclusion ? "excluded_targets" : "filters";
|
|
254
|
+
const rows = [];
|
|
255
|
+
let pending = saved?.pending ?? [], exhausted = saved?.exhausted ?? false, total = saved?.total ?? null, lastPage = saved?.lastPage ?? null;
|
|
256
|
+
offset = saved?.offset ?? offset;
|
|
257
|
+
let failure, reason;
|
|
258
|
+
try {
|
|
259
|
+
for (let page = 0; rows.length < limit; page++) {
|
|
260
|
+
while (pending.length && rows.length < limit) {
|
|
261
|
+
const row = pending[0];
|
|
262
|
+
if (fields.some((field) => !fieldTypes[field].safeParse(row[field]).success))
|
|
263
|
+
invalid("Malformed pending tag fields in cursor");
|
|
264
|
+
rows.push(row);
|
|
265
|
+
pending.shift();
|
|
266
|
+
}
|
|
267
|
+
if (rows.length >= limit || exhausted)
|
|
268
|
+
break;
|
|
269
|
+
if (page >= 20) {
|
|
270
|
+
reason = "REQUEST_BUDGET_EXCEEDED";
|
|
271
|
+
break;
|
|
272
|
+
}
|
|
273
|
+
const window = Math.min(1000, limit - rows.length);
|
|
274
|
+
const response = (await transport.request(operation, { pathParams, query: { ...query, ...(paged ? { offset, limit: window } : {}) } })).body;
|
|
275
|
+
const data = response[key];
|
|
276
|
+
let nextTotal = total, nextExhausted = true;
|
|
277
|
+
if (paged) {
|
|
278
|
+
const pagination = tagPagination.parse(response.pagination);
|
|
279
|
+
if (pagination.offset !== offset || data.length > window || pagination.limit !== window || offset + data.length > pagination.total
|
|
280
|
+
|| !data.length && offset < pagination.total)
|
|
281
|
+
invalid("Malformed or non-advancing tag pagination");
|
|
282
|
+
nextTotal = pagination.total;
|
|
283
|
+
nextExhausted = offset + data.length >= nextTotal;
|
|
284
|
+
}
|
|
285
|
+
const identity = hash(data);
|
|
286
|
+
if (data.length && identity === lastPage)
|
|
287
|
+
invalid("Tenable repeated the previous tag page");
|
|
288
|
+
const projected = data.map(project);
|
|
289
|
+
if (!Number.isSafeInteger(offset + data.length))
|
|
290
|
+
invalid("Unrepresentable tag offset");
|
|
291
|
+
pending = projected;
|
|
292
|
+
offset += data.length;
|
|
293
|
+
lastPage = identity;
|
|
294
|
+
total = nextTotal;
|
|
295
|
+
exhausted = nextExhausted;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (!(error instanceof TransportError))
|
|
300
|
+
throw error;
|
|
301
|
+
if (["REQUEST_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED", "BYTE_BUDGET_EXCEEDED"].includes(error.error.code))
|
|
302
|
+
reason = error.error.code;
|
|
303
|
+
else {
|
|
304
|
+
if (!rows.length)
|
|
305
|
+
throw error;
|
|
306
|
+
failure = error;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const complete = exhausted && !pending.length && !failure && !reason;
|
|
310
|
+
const cursor = complete ? undefined : Buffer.from(JSON.stringify({ version: 1, scope, offset, pending, exhausted, total, lastPage })).toString("base64url");
|
|
311
|
+
if (cursor && cursor.length > 28 * 1024 * 1024)
|
|
312
|
+
invalid("Tag continuation exceeds its byte bound; narrow fields or filters");
|
|
313
|
+
if (failure)
|
|
314
|
+
process.exitCode = 1;
|
|
315
|
+
const output = preview(rows);
|
|
316
|
+
const help = [...(cursor ? [`Run ${command(["--cursor", "--offset"])} --cursor <cursor> to resume; offset paging does not provide snapshot isolation`] : []),
|
|
317
|
+
...(truncated ? [`Run ${command(["--full"])} --full to read complete text`] : []), ...(failure?.help ?? []),
|
|
318
|
+
...(noun === "asset-filter" ? ["Resource tag filters cloud.common.resource_tags.key and cloud.common.resource_tags.value also support wc,nwc,exists,nexists; upstream omits them from this list"] : [])];
|
|
319
|
+
return { [key]: output, count: rows.length, total, complete, ...(!rows.length && complete ? { message: `0 tag ${noun} records matched the selected filters` } : {}),
|
|
320
|
+
...(!complete ? { reason: reason ?? (failure ? "READ_FAILED" : get("all") ? "ROW_BUDGET_EXCEEDED" : "LIMIT"), cursor } : {}),
|
|
321
|
+
...(failure ? failure.toJSON() : {}), ...(help.length ? { help } : {}) };
|
|
322
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { renameSync } from "node:fs";
|
|
2
|
+
export type WindowsAcl = (path: string, action: "check" | "verify" | "restrict", directory: boolean) => void;
|
|
3
|
+
export declare const windowsAcl: WindowsAcl;
|
|
4
|
+
export declare function toolDirectory(kind: "config" | "state", env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, home?: string): string;
|
|
5
|
+
export type PrivateFileOptions = {
|
|
6
|
+
platform?: NodeJS.Platform;
|
|
7
|
+
acl?: WindowsAcl;
|
|
8
|
+
uid?: number;
|
|
9
|
+
rename?: typeof renameSync;
|
|
10
|
+
wait?: (ms: number) => void;
|
|
11
|
+
};
|
|
12
|
+
export declare function privateFiles(options?: PrivateFileOptions): {
|
|
13
|
+
check: (path: string, secret?: boolean, verifyAcl?: boolean) => void;
|
|
14
|
+
read: (path: string, secret?: boolean, verifyAcl?: boolean) => string;
|
|
15
|
+
directory: (path: string) => void;
|
|
16
|
+
write: (path: string, content: string) => void;
|
|
17
|
+
lock: (path: string) => () => void;
|
|
18
|
+
};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { chmodSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, isAbsolute, join, win32 } from "node:path";
|
|
6
|
+
import { AxiError } from "axi-sdk-js";
|
|
7
|
+
export const windowsAcl = (path, action, directory) => {
|
|
8
|
+
const quoted = `'${path.replaceAll("'", "''")}'`;
|
|
9
|
+
const script = `$ErrorActionPreference='Stop'; $p=${quoted}; $item=Get-Item -LiteralPath $p -Force; `
|
|
10
|
+
+ `if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Reparse point' }; `
|
|
11
|
+
+ `$sid=[Security.Principal.WindowsIdentity]::GetCurrent().User; $allowed=@($sid.Value,'S-1-5-18','S-1-5-32-544'); `
|
|
12
|
+
+ (action === "check" ? "" : action === "restrict"
|
|
13
|
+
? `$acl=New-Object Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}; $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true,$false); `
|
|
14
|
+
+ `foreach ($s in $allowed) { $id=New-Object Security.Principal.SecurityIdentifier($s); $rule=New-Object Security.AccessControl.FileSystemAccessRule($id,'FullControl','${directory ? "ContainerInherit,ObjectInherit" : "None"}','None','Allow'); $acl.AddAccessRule($rule) }; Set-Acl -LiteralPath $p -AclObject $acl`
|
|
15
|
+
: `$acl=Get-Acl -LiteralPath $p; if (!$acl.AreAccessRulesProtected -or ($acl.Owner -ne $sid.Translate([Security.Principal.NTAccount]).Value -and $acl.Owner -ne $sid.Value)) { throw 'Unprotected ACL' }; `
|
|
16
|
+
+ `$seen=@(); foreach ($r in $acl.Access) { $s=$r.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value; if ($s -notin $allowed -or $r.IsInherited -or $r.AccessControlType -ne 'Allow' -or $r.FileSystemRights -ne [Security.AccessControl.FileSystemRights]::FullControl) { throw 'Unexpected ACL' }; $seen+=$s }; foreach ($s in $allowed) { if ($s -notin $seen) { throw 'Missing ACL' } }`);
|
|
17
|
+
execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], { stdio: "pipe" });
|
|
18
|
+
};
|
|
19
|
+
export function toolDirectory(kind, env = process.env, platform = process.platform, home = homedir()) {
|
|
20
|
+
if (platform === "win32") {
|
|
21
|
+
const base = env[kind === "config" ? "APPDATA" : "LOCALAPPDATA"];
|
|
22
|
+
return win32.join(base && win32.isAbsolute(base) ? base : win32.join(home, "AppData", kind === "config" ? "Roaming" : "Local"), "tenable-axi");
|
|
23
|
+
}
|
|
24
|
+
const xdg = env[kind === "config" ? "XDG_CONFIG_HOME" : "XDG_STATE_HOME"];
|
|
25
|
+
return join(xdg && isAbsolute(xdg) ? xdg : join(home, kind === "config" ? ".config" : ".local/state"), "tenable-axi");
|
|
26
|
+
}
|
|
27
|
+
export function privateFiles(options = {}) {
|
|
28
|
+
const platform = options.platform ?? process.platform;
|
|
29
|
+
const acl = options.acl ?? windowsAcl;
|
|
30
|
+
const insecure = (path) => {
|
|
31
|
+
throw new AxiError(`Insecure private file: ${path}`, "CONFIG_INSECURE", [
|
|
32
|
+
platform === "win32" ? `Apply a protected DACL granting only the current user, SYSTEM and Administrators to ${path}` : `chmod 600 '${path.replaceAll("'", "'\\''")}'`,
|
|
33
|
+
]);
|
|
34
|
+
};
|
|
35
|
+
function validate(stat, path, secret) {
|
|
36
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
37
|
+
insecure(path);
|
|
38
|
+
if (platform !== "win32" && (stat.uid !== (options.uid ?? process.getuid()) || (stat.mode & (secret ? 0o077 : 0o022)) !== 0))
|
|
39
|
+
insecure(path);
|
|
40
|
+
}
|
|
41
|
+
function check(path, secret = false, verifyAcl = false) {
|
|
42
|
+
validate(lstatSync(path), path, secret);
|
|
43
|
+
if (platform === "win32") {
|
|
44
|
+
try {
|
|
45
|
+
acl(path, verifyAcl ? "verify" : "check", false);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
insecure(path);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function read(path, secret = false, verifyAcl = false) {
|
|
53
|
+
check(path, secret, verifyAcl);
|
|
54
|
+
const fd = openSync(path, constants.O_RDONLY | (platform === "win32" ? 0 : constants.O_NOFOLLOW));
|
|
55
|
+
try {
|
|
56
|
+
validate(fstatSync(fd), path, secret);
|
|
57
|
+
return readFileSync(fd, "utf8");
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
closeSync(fd);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function flushDirectory(path) {
|
|
64
|
+
if (platform === "win32")
|
|
65
|
+
return;
|
|
66
|
+
const fd = openSync(path, "r");
|
|
67
|
+
try {
|
|
68
|
+
fsyncSync(fd);
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
closeSync(fd);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function directory(path) {
|
|
75
|
+
const first = mkdirSync(path, { recursive: true, ...(platform === "win32" ? {} : { mode: 0o700 }) });
|
|
76
|
+
let current = path;
|
|
77
|
+
for (;;) {
|
|
78
|
+
const stat = lstatSync(current);
|
|
79
|
+
if (stat.isSymbolicLink() || !stat.isDirectory() || (platform !== "win32" && stat.uid !== (options.uid ?? process.getuid())))
|
|
80
|
+
insecure(current);
|
|
81
|
+
try {
|
|
82
|
+
if (platform === "win32")
|
|
83
|
+
acl(current, "restrict", true);
|
|
84
|
+
else
|
|
85
|
+
chmodSync(current, 0o700);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
insecure(current);
|
|
89
|
+
}
|
|
90
|
+
if (first)
|
|
91
|
+
flushDirectory(current);
|
|
92
|
+
if (!first || current === first)
|
|
93
|
+
break;
|
|
94
|
+
current = dirname(current);
|
|
95
|
+
}
|
|
96
|
+
if (first)
|
|
97
|
+
flushDirectory(dirname(first));
|
|
98
|
+
}
|
|
99
|
+
function write(path, content) {
|
|
100
|
+
directory(dirname(path));
|
|
101
|
+
if (existsSync(path))
|
|
102
|
+
check(path, true);
|
|
103
|
+
const temporary = join(dirname(path), `.${randomUUID()}.tmp`);
|
|
104
|
+
let fd;
|
|
105
|
+
try {
|
|
106
|
+
fd = openSync(temporary, "wx", platform === "win32" ? undefined : 0o600);
|
|
107
|
+
if (platform === "win32") {
|
|
108
|
+
try {
|
|
109
|
+
acl(temporary, "restrict", false);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
insecure(temporary);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
writeFileSync(fd, content, "utf8");
|
|
116
|
+
fsyncSync(fd);
|
|
117
|
+
closeSync(fd);
|
|
118
|
+
fd = undefined;
|
|
119
|
+
for (let attempt = 0;; attempt++) {
|
|
120
|
+
try {
|
|
121
|
+
(options.rename ?? renameSync)(temporary, path);
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (platform !== "win32" || !["EPERM", "EBUSY", "EACCES"].includes(error.code ?? "") || attempt === 5)
|
|
126
|
+
throw error;
|
|
127
|
+
(options.wait ?? ((ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }))(25 * 2 ** attempt);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
flushDirectory(dirname(path));
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
if (fd !== undefined)
|
|
134
|
+
closeSync(fd);
|
|
135
|
+
if (existsSync(temporary))
|
|
136
|
+
unlinkSync(temporary);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function lock(path) {
|
|
140
|
+
directory(dirname(path));
|
|
141
|
+
const fd = openSync(path, "wx", platform === "win32" ? undefined : 0o600);
|
|
142
|
+
try {
|
|
143
|
+
if (platform === "win32")
|
|
144
|
+
acl(path, "restrict", false);
|
|
145
|
+
fsyncSync(fd);
|
|
146
|
+
flushDirectory(dirname(path));
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
closeSync(fd);
|
|
150
|
+
unlinkSync(path);
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
return () => { closeSync(fd); unlinkSync(path); flushDirectory(dirname(path)); };
|
|
154
|
+
}
|
|
155
|
+
return { check, read, directory, write, lock };
|
|
156
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type PrivateFileOptions } from "./private-file.js";
|
|
3
|
+
import { SecretRedactor } from "./redact.js";
|
|
4
|
+
export declare const ORIGIN = "https://cloud.tenable.com";
|
|
5
|
+
export type CredentialContext = PrivateFileOptions & {
|
|
6
|
+
env?: NodeJS.ProcessEnv;
|
|
7
|
+
home?: string;
|
|
8
|
+
};
|
|
9
|
+
declare function schemas(platform: NodeJS.Platform): z.ZodObject<{
|
|
10
|
+
version: z.ZodLiteral<1>;
|
|
11
|
+
defaultProfile: z.ZodOptional<z.ZodString>;
|
|
12
|
+
profiles: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
13
|
+
origin: z.ZodDefault<z.ZodLiteral<"https://cloud.tenable.com">>;
|
|
14
|
+
accessKey: z.ZodDefault<z.ZodUnion<readonly [z.ZodObject<{
|
|
15
|
+
env: z.ZodString;
|
|
16
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
17
|
+
file: z.ZodString;
|
|
18
|
+
}, z.core.$strict>]>>;
|
|
19
|
+
secretKey: z.ZodDefault<z.ZodUnion<readonly [z.ZodObject<{
|
|
20
|
+
env: z.ZodString;
|
|
21
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
22
|
+
file: z.ZodString;
|
|
23
|
+
}, z.core.$strict>]>>;
|
|
24
|
+
writes: z.ZodDefault<z.ZodObject<{
|
|
25
|
+
allowWrites: z.ZodBoolean;
|
|
26
|
+
operations: z.ZodArray<z.ZodString>;
|
|
27
|
+
}, z.core.$strict>>;
|
|
28
|
+
}, z.core.$strict>>;
|
|
29
|
+
}, z.core.$strict>;
|
|
30
|
+
export type Profile = z.infer<ReturnType<typeof schemas>>["profiles"][string];
|
|
31
|
+
export type SelectedProfile = Profile & {
|
|
32
|
+
name: string;
|
|
33
|
+
source: "flag" | "env" | "env-profile" | "config-default" | "sole";
|
|
34
|
+
};
|
|
35
|
+
export declare function credentialStore(options?: CredentialContext, redactor?: SecretRedactor): {
|
|
36
|
+
configPath: (explicit?: string) => string;
|
|
37
|
+
statePath: () => string;
|
|
38
|
+
readOnly: () => boolean;
|
|
39
|
+
load: (explicit?: string, verifyAcl?: boolean) => {
|
|
40
|
+
path: string;
|
|
41
|
+
config: {
|
|
42
|
+
version: 1;
|
|
43
|
+
profiles: Record<string, {
|
|
44
|
+
origin: "https://cloud.tenable.com";
|
|
45
|
+
accessKey: {
|
|
46
|
+
env: string;
|
|
47
|
+
} | {
|
|
48
|
+
file: string;
|
|
49
|
+
};
|
|
50
|
+
secretKey: {
|
|
51
|
+
env: string;
|
|
52
|
+
} | {
|
|
53
|
+
file: string;
|
|
54
|
+
};
|
|
55
|
+
writes: {
|
|
56
|
+
allowWrites: boolean;
|
|
57
|
+
operations: string[];
|
|
58
|
+
};
|
|
59
|
+
}>;
|
|
60
|
+
defaultProfile?: string | undefined;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
select: (config: ReturnType<(explicit?: string, verifyAcl?: boolean) => {
|
|
64
|
+
path: string;
|
|
65
|
+
config: {
|
|
66
|
+
version: 1;
|
|
67
|
+
profiles: Record<string, {
|
|
68
|
+
origin: "https://cloud.tenable.com";
|
|
69
|
+
accessKey: {
|
|
70
|
+
env: string;
|
|
71
|
+
} | {
|
|
72
|
+
file: string;
|
|
73
|
+
};
|
|
74
|
+
secretKey: {
|
|
75
|
+
env: string;
|
|
76
|
+
} | {
|
|
77
|
+
file: string;
|
|
78
|
+
};
|
|
79
|
+
writes: {
|
|
80
|
+
allowWrites: boolean;
|
|
81
|
+
operations: string[];
|
|
82
|
+
};
|
|
83
|
+
}>;
|
|
84
|
+
defaultProfile?: string | undefined;
|
|
85
|
+
};
|
|
86
|
+
}>["config"], flag?: string) => SelectedProfile;
|
|
87
|
+
credentials: (profile: SelectedProfile, verifyAcl?: boolean) => Record<"accessKey" | "secretKey", string>;
|
|
88
|
+
status: (explicit?: string, flag?: string) => {
|
|
89
|
+
profile: string;
|
|
90
|
+
source: "env" | "flag" | "env-profile" | "config-default" | "sole";
|
|
91
|
+
origin: "https://cloud.tenable.com";
|
|
92
|
+
config: string;
|
|
93
|
+
accessKey: {
|
|
94
|
+
env: string;
|
|
95
|
+
} | {
|
|
96
|
+
file: string;
|
|
97
|
+
};
|
|
98
|
+
secretKey: {
|
|
99
|
+
env: string;
|
|
100
|
+
} | {
|
|
101
|
+
file: string;
|
|
102
|
+
};
|
|
103
|
+
readOnly: boolean;
|
|
104
|
+
};
|
|
105
|
+
list: (explicit?: string) => {
|
|
106
|
+
profiles: {
|
|
107
|
+
name: string;
|
|
108
|
+
origin: "https://cloud.tenable.com";
|
|
109
|
+
default: boolean;
|
|
110
|
+
}[];
|
|
111
|
+
count: number;
|
|
112
|
+
config: string;
|
|
113
|
+
};
|
|
114
|
+
redactor: SecretRedactor;
|
|
115
|
+
};
|
|
116
|
+
export {};
|