@opscompass/opscompass-cli 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/maskValues.js CHANGED
@@ -18,22 +18,7 @@ import path from "path";
18
18
  import Database from "better-sqlite3";
19
19
  import { utilsModule as utils } from "./utils.js";
20
20
  import { opscompassHome } from "../environment/current.js"; // For compatibility with the OpsCompass CLI
21
-
22
- /**
23
- * Function to execute operating system commands
24
- */
25
- import { exec } from "child_process";
26
- function executeCommand(command) {
27
- return new Promise((resolve, reject) => {
28
- exec(command, (error, stdout, stderr) => {
29
- if (error) {
30
- reject(`Error: ${stderr}`);
31
- } else {
32
- resolve(stdout);
33
- }
34
- });
35
- });
36
- }
21
+ import { execFile } from "child_process";
37
22
 
38
23
  // Resources to check for sensitive attributes
39
24
  const maskTypes = {
@@ -41,6 +26,165 @@ const maskTypes = {
41
26
  sha256: "sha256",
42
27
  };
43
28
 
29
+ const ALLOWED_MASK_TABLES = new Set(["mask"]);
30
+ const MASK_TOKEN_REGEX = /^oc\$mask-([^:]+):\{([^{}]+)\}$/;
31
+ const MASK_TYPE_REGEX = /^[A-Za-z0-9._-]+$/;
32
+ const MASK_PROPERTY_REGEX = /^[A-Za-z0-9._-]+$/;
33
+ const SQL_IDENTIFIER_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/;
34
+ const SQL_COLUMN_TYPE_REGEX = /^[A-Z0-9_(),\s]+$/;
35
+ const INVALID_MASK_COMPONENT_REGEX = /[\n\r/\\]/;
36
+ const DEFAULT_KEY_LOOKUP_TIMEOUT_MS = 5000;
37
+ const MASK_DB_COLUMNS = Object.freeze([
38
+ Object.freeze({
39
+ name: "name",
40
+ type: "TEXT NOT NULL UNIQUE",
41
+ index: "mask_name_idx",
42
+ }),
43
+ Object.freeze({
44
+ name: "value",
45
+ type: "TEXT NOT NULL",
46
+ index: "mask_value_idx",
47
+ }),
48
+ ]);
49
+
50
+ function assertPathWithinRoot(rootPath, resolvedPath, label) {
51
+ if (
52
+ resolvedPath !== rootPath &&
53
+ !resolvedPath.startsWith(`${rootPath}${path.sep}`)
54
+ ) {
55
+ throw new Error(`Unsafe ${label} path`);
56
+ }
57
+ }
58
+
59
+ function assertSafeSqlIdentifier(value, label = "identifier") {
60
+ if (typeof value !== "string" || !SQL_IDENTIFIER_REGEX.test(value)) {
61
+ throw new Error(`Invalid SQL ${label}: ${value}`);
62
+ }
63
+ return value;
64
+ }
65
+
66
+ function assertSafeColumnType(columnType) {
67
+ if (
68
+ typeof columnType !== "string" ||
69
+ !SQL_COLUMN_TYPE_REGEX.test(columnType)
70
+ ) {
71
+ throw new Error(`Invalid SQL column type: ${columnType}`);
72
+ }
73
+ return columnType;
74
+ }
75
+
76
+ function assertAllowedMaskTableName(tableName) {
77
+ if (!ALLOWED_MASK_TABLES.has(tableName)) {
78
+ throw new Error(`Unsupported table name: ${tableName}`);
79
+ }
80
+ return tableName;
81
+ }
82
+
83
+ function validateMaskTokenComponent(componentName, value) {
84
+ if (typeof value !== "string" || value.length === 0) {
85
+ throw new Error(`Invalid mask token ${componentName}`);
86
+ }
87
+ if (INVALID_MASK_COMPONENT_REGEX.test(value)) {
88
+ throw new Error(`Invalid mask token ${componentName}`);
89
+ }
90
+ if (componentName === "type" && !MASK_TYPE_REGEX.test(value)) {
91
+ throw new Error(`Invalid mask token ${componentName}`);
92
+ }
93
+ return value;
94
+ }
95
+
96
+ function validateMaskPropertyName(propertyName) {
97
+ if (typeof propertyName !== "string" || propertyName.length === 0) {
98
+ throw new Error("Invalid mask property");
99
+ }
100
+ if (INVALID_MASK_COMPONENT_REGEX.test(propertyName)) {
101
+ throw new Error("Invalid mask property");
102
+ }
103
+ if (!MASK_PROPERTY_REGEX.test(propertyName)) {
104
+ throw new Error("Invalid mask property");
105
+ }
106
+ return propertyName;
107
+ }
108
+
109
+ function resolveMaskDbFilePath(dbFileName, company = "unspecified-company") {
110
+ const configRoot = path.resolve(opscompassHome, "configs");
111
+ const safeCompany = validateMaskPropertyName(company);
112
+ const safeDbFileName = validateMaskPropertyName(dbFileName);
113
+
114
+ const companyPath = path.resolve(configRoot, safeCompany);
115
+ assertPathWithinRoot(configRoot, companyPath, "company");
116
+
117
+ const dbFilePath = path.resolve(companyPath, safeDbFileName);
118
+ assertPathWithinRoot(companyPath, dbFilePath, "database");
119
+
120
+ return {
121
+ company: safeCompany,
122
+ dbFilePath,
123
+ };
124
+ }
125
+
126
+ function parseMaskToken(maskToken) {
127
+ const token = typeof maskToken === "string" ? maskToken.trim() : "";
128
+ const match = token.match(MASK_TOKEN_REGEX);
129
+ if (!match) {
130
+ throw new Error("invalid mask format");
131
+ }
132
+
133
+ const type = validateMaskTokenComponent("type", match[1]);
134
+ const item = validateMaskTokenComponent("item", match[2]);
135
+ return { type, item };
136
+ }
137
+
138
+ function splitPropertyValue(arg) {
139
+ const separatorIdx = arg?.indexOf("=") ?? -1;
140
+ if (separatorIdx < 0) {
141
+ return { prop: arg, value: undefined };
142
+ }
143
+
144
+ return {
145
+ prop: arg.slice(0, separatorIdx),
146
+ value: arg.slice(separatorIdx + 1),
147
+ };
148
+ }
149
+
150
+ function buildMaskDumpQuery(tableName, includeMaskFilter = false) {
151
+ tableName = assertAllowedMaskTableName(tableName);
152
+ const sql = `SELECT * FROM ${tableName}`;
153
+ if (includeMaskFilter) {
154
+ return `${sql} WHERE value = ? ORDER BY name DESC`;
155
+ }
156
+ return `${sql} ORDER BY name DESC`;
157
+ }
158
+
159
+ function executeKeyLookupScript(keyCommand, item, timeoutMs = DEFAULT_KEY_LOOKUP_TIMEOUT_MS) {
160
+ validateMaskTokenComponent("item", item);
161
+
162
+ return new Promise((resolve, reject) => {
163
+ execFile(
164
+ keyCommand,
165
+ [item],
166
+ {
167
+ shell: false,
168
+ timeout: timeoutMs,
169
+ windowsHide: true,
170
+ maxBuffer: 1024 * 1024,
171
+ },
172
+ (error, stdout, stderr) => {
173
+ if (error) {
174
+ if (error.killed) {
175
+ reject(new Error(`lookup timed out after ${timeoutMs}ms`));
176
+ return;
177
+ }
178
+
179
+ reject(new Error(stderr || error.message));
180
+ return;
181
+ }
182
+ resolve(stdout);
183
+ },
184
+ );
185
+ });
186
+ }
187
+
44
188
  /**
45
189
  * Function to find keyCommand for a maskType, and only check
46
190
  * once per maskType
@@ -92,7 +236,7 @@ op item get "${1}" \
92
236
  * @param {*} maskType
93
237
  * @returns the path to the keyCommand (if executable) or undefined
94
238
  */
95
- let keyCmd = [];
239
+ let keyCmd = {};
96
240
  function getKeyCommand(maskType) {
97
241
  if (keyCmd.hasOwnProperty(maskType)) return keyCmd[maskType];
98
242
 
@@ -128,14 +272,18 @@ class MaskDb {
128
272
  return this.dbFilePath;
129
273
  }
130
274
 
131
- maskColumns = [
132
- { name: "name", type: "TEXT NOT NULL UNIQUE", index: "mask_name_idx" },
133
- { name: "value", type: "TEXT NOT NULL", index: "mask_value_idx" },
134
- ];
275
+ maskColumns = MASK_DB_COLUMNS;
135
276
 
136
277
  constructor(dbFileName, company = global?.company || "unspecified-company") {
137
- this.company = company;
138
- this.dbFilePath = path.join(opscompassHome, "configs", company, dbFileName);
278
+ try {
279
+ const safeMaskDbPath = resolveMaskDbFilePath(dbFileName, company);
280
+ this.company = safeMaskDbPath.company;
281
+ this.dbFilePath = safeMaskDbPath.dbFilePath;
282
+ } catch (err) {
283
+ console.error(`Invalid mask database path: ${err}`);
284
+ process.exit(11);
285
+ }
286
+
139
287
  // It is possible that this will be the first time we need that directory
140
288
  try {
141
289
  fs.mkdirSync(path.dirname(this.dbFilePath), { recursive: true });
@@ -166,9 +314,18 @@ class MaskDb {
166
314
 
167
315
  async createTable(tableName, columns) {
168
316
  return new Promise((resolve, reject) => {
317
+ try {
318
+ tableName = assertAllowedMaskTableName(tableName);
319
+ } catch (err) {
320
+ reject(err.message || err);
321
+ return;
322
+ }
323
+
169
324
  const columnsDefinition = columns
170
325
  .map((column) => {
171
- let definition = `${column.name} ${column.type} NOT NULL`;
326
+ const columnName = assertSafeSqlIdentifier(column.name, "column name");
327
+ const columnType = assertSafeColumnType(column.type);
328
+ let definition = `${columnName} ${columnType}`;
172
329
  return definition;
173
330
  })
174
331
  .join(", ");
@@ -185,9 +342,13 @@ class MaskDb {
185
342
  }
186
343
 
187
344
  async createIndexes(tableName, columns) {
345
+ tableName = assertAllowedMaskTableName(tableName);
346
+
188
347
  const indexPromises = columns.map((column) => {
189
348
  if (column.index) {
190
- const indexSql = `CREATE INDEX IF NOT EXISTS idx_${tableName}_${column.name} ON ${tableName} (${column.name})`;
349
+ const columnName = assertSafeSqlIdentifier(column.name, "column name");
350
+ const indexName = assertSafeSqlIdentifier(column.index, "index name");
351
+ const indexSql = `CREATE INDEX IF NOT EXISTS ${indexName} ON ${tableName} (${columnName})`;
191
352
  return new Promise((resolve, reject) => {
192
353
  try {
193
354
  this.db.exec(indexSql);
@@ -203,37 +364,34 @@ class MaskDb {
203
364
  }
204
365
 
205
366
  dumpTable(tableName, mask = undefined) {
367
+ tableName = assertAllowedMaskTableName(tableName);
368
+
206
369
  const maskType = path.basename(this.dbFilePath).split("-")[1];
207
- const sql =
208
- `SELECT * FROM ${tableName}` +
209
- (mask ? ` WHERE value = '${mask}'` : "") +
210
- " ORDER BY name DESC";
370
+ const statement = this.db.prepare(
371
+ buildMaskDumpQuery(tableName, mask !== undefined),
372
+ );
373
+ const rows = mask !== undefined ? statement.all(mask) : statement.all();
211
374
 
212
375
  console.error(`\nContents of ${tableName} table (${this.dbFilePath}):`);
213
376
  console.log(`{\n "${path.basename(this.dbFilePath)}": [`);
214
- this.db
215
- .prepare(sql)
216
- .all()
217
- .forEach((row, idx, arr) => {
218
- row.mask = `oc$mask-${maskType}:{${row.value}}`;
219
- console.log(
220
- process.stdout.isTTY
221
- ? JSON.stringify(row, null, 2).replace(/^/gm, " ")
222
- : JSON.stringify(row),
223
- idx < arr.length - 1 ? "," : "",
224
- );
225
- });
377
+ rows.forEach((row, idx, arr) => {
378
+ row.mask = `oc$mask-${maskType}:{${row.value}}`;
379
+ console.log(
380
+ process.stdout.isTTY
381
+ ? JSON.stringify(row, null, 2).replace(/^/gm, " ")
382
+ : JSON.stringify(row),
383
+ idx < arr.length - 1 ? "," : "",
384
+ );
385
+ });
226
386
  console.log(" ]\n}\n");
227
387
  }
228
388
 
229
389
  close() {
230
- this.db.close((err) => {
231
- if (err) {
232
- console.error("Could not close the database", err);
233
- } else {
234
- // console.log("Database connection closed");
235
- }
236
- });
390
+ try {
391
+ this.db.close();
392
+ } catch (err) {
393
+ console.error("Could not close the database", err);
394
+ }
237
395
  }
238
396
  }
239
397
 
@@ -257,14 +415,21 @@ function processArgs(action, args) {
257
415
  // case "get": // not meant to call directly
258
416
  case "lookup":
259
417
  // The type is after the '-' in oc$mask-{type}
260
- const matchResult = args[0]?.match(/.*-(.+):{(.*)}/);
261
- if (!matchResult) {
262
- return printHelp("invalid mask format");
418
+ const separatorIdx = args[0]?.indexOf("=") ?? -1;
419
+ if (separatorIdx < 0) {
420
+ return printHelp("no property=value provided");
421
+ }
422
+
423
+ let parsedMaskToken = undefined;
424
+ try {
425
+ parsedMaskToken = parseMaskToken(args[0].slice(separatorIdx + 1));
426
+ } catch (err) {
427
+ return printHelp(err.message);
263
428
  }
264
- const testMask = matchResult.splice(1);
265
- maskType = maskTypes[testMask[0]];
429
+
430
+ maskType = maskTypes[parsedMaskToken.type];
266
431
  if (!maskType) {
267
- maskType = testMask[0];
432
+ maskType = parsedMaskToken.type;
268
433
  const keyCommand = getKeyCommand(maskType);
269
434
  if (!keyCommand) {
270
435
  return printHelp(`unknown mask type for lookup (${maskType})`);
@@ -382,7 +547,17 @@ function getServerName(serverSpec) {
382
547
  * @param {Array} args - The arguments for the action
383
548
  */
384
549
  async function dumpMaskTable(maskType, args) {
385
- const [prop, value] = args[0].split("=");
550
+ const { prop } = splitPropertyValue(args[0]);
551
+ if (!prop) {
552
+ return printHelp("no property=value provided");
553
+ }
554
+
555
+ try {
556
+ validateMaskPropertyName(prop);
557
+ } catch (err) {
558
+ return printHelp(err.message);
559
+ }
560
+
386
561
  const dbname = `mask-${maskType}-${prop}`;
387
562
  const maskDb = await new MaskDb(dbname).then((db) => {
388
563
  // console.log("db opened:", db);
@@ -396,7 +571,17 @@ async function dumpMaskTable(maskType, args) {
396
571
  * @param {Array} args - The arguments for the action
397
572
  */
398
573
  async function lookupMask(maskType, args) {
399
- const [prop, value] = args[0].split("=");
574
+ const { prop, value } = splitPropertyValue(args[0]);
575
+ if (!prop) {
576
+ return printHelp("no property=value provided");
577
+ }
578
+
579
+ try {
580
+ validateMaskPropertyName(prop);
581
+ } catch (err) {
582
+ return printHelp(err.message);
583
+ }
584
+
400
585
  const dbname = `mask-${maskType}-${prop}`;
401
586
 
402
587
  if (!value) {
@@ -404,18 +589,25 @@ async function lookupMask(maskType, args) {
404
589
  }
405
590
 
406
591
  // The type is after the '-' in oc$mask-{type} and should match the maskType
407
- const testMask = value.match(/.*-(.+):{(.*)}/).splice(1);
408
- if (testMask.length !== 2 || testMask[0] !== maskType) {
592
+ let maskToken = undefined;
593
+ try {
594
+ maskToken = parseMaskToken(value);
595
+ } catch (err) {
596
+ return printHelp(err.message);
597
+ }
598
+
599
+ if (maskToken.type !== maskType) {
409
600
  return printHelp(`invalid property value (${args[0]})`);
410
601
  }
411
602
 
412
603
  // If keyCmd is set we need to run that command to get the key
413
604
  let keystoreResponse = undefined;
414
605
  if (keyCmd[maskType]) {
415
- // console.log(`We need to lookup ${testMask[1]} using keystore:`, keyCmd);
606
+ // console.log(`We need to lookup ${maskToken.item} using keystore:`, keyCmd);
416
607
  try {
417
- keystoreResponse = await executeCommand(
418
- `${keyCmd[maskType]} ${testMask[1]}`,
608
+ keystoreResponse = await executeKeyLookupScript(
609
+ keyCmd[maskType],
610
+ maskToken.item,
419
611
  );
420
612
  const lookupCreds = JSON.parse(keystoreResponse);
421
613
  console.log("lookupObject:", lookupCreds);
@@ -425,7 +617,7 @@ async function lookupMask(maskType, args) {
425
617
  console.log("lookup:", keystoreResponse.trimEnd());
426
618
  } else {
427
619
  return printHelp(
428
- `Could not retrieve data for ${testMask[1]} from keystore:\n${err}`,
620
+ `Could not retrieve data for ${maskToken.item} from keystore:\n${err?.message || err}`,
429
621
  );
430
622
  }
431
623
  }
@@ -434,7 +626,7 @@ async function lookupMask(maskType, args) {
434
626
  // console.log("db opened:", db);
435
627
  return db;
436
628
  });
437
- maskDb.dumpTable("mask", testMask[1]);
629
+ maskDb.dumpTable("mask", maskToken.item);
438
630
  }
439
631
  }
440
632
 
@@ -446,13 +638,29 @@ async function getMask(maskType, args) {
446
638
  if (args.length === 0 || args[0].indexOf("=") < 0) {
447
639
  return printHelp("no property=value provided");
448
640
  }
449
- const [prop, value] = args[0].split("=");
641
+ const { prop, value } = splitPropertyValue(args[0]);
642
+ if (!prop) {
643
+ return printHelp("no property=value provided");
644
+ }
645
+
646
+ try {
647
+ validateMaskPropertyName(prop);
648
+ } catch (err) {
649
+ return printHelp(err.message);
650
+ }
651
+
450
652
  const dbname = `mask-${maskType}-${prop}`;
451
653
  // console.error(`getMask (${maskType}): ${prop} = ${value}`);
452
654
 
453
655
  // The type is after the '-' in oc$mask-{type} and should match the maskType
454
- const testMask = value.match(/.*-(.+):{(.*)}/).splice(1);
455
- if (testMask.length !== 2 || testMask[0] !== maskType) {
656
+ let maskToken = undefined;
657
+ try {
658
+ maskToken = parseMaskToken(value);
659
+ } catch (err) {
660
+ return printHelp(err.message);
661
+ }
662
+
663
+ if (maskToken.type !== maskType) {
456
664
  return printHelp(`invalid property value (${args[0]})`);
457
665
  }
458
666
 
@@ -463,7 +671,7 @@ async function getMask(maskType, args) {
463
671
  const keyCommand = getKeyCommand(maskType);
464
672
  if (keyCommand) {
465
673
  try {
466
- keystoreResponse = await executeCommand(`${keyCommand} ${testMask[1]}`);
674
+ keystoreResponse = await executeKeyLookupScript(keyCommand, maskToken.item);
467
675
  keystoreObject = JSON.parse(keystoreResponse);
468
676
 
469
677
  // If a username is returned by the keystore, the user is the username
@@ -477,7 +685,7 @@ async function getMask(maskType, args) {
477
685
  unmaskedValue = keystoreResponse.trimEnd();
478
686
  } else {
479
687
  console.error(
480
- `Could not retrieve data for ${testMask[1]} from keystore:\n${err}\n`,
688
+ `Could not retrieve data for ${maskToken.item} from keystore:\n${err?.message || err}\n`,
481
689
  );
482
690
  }
483
691
  }
@@ -496,7 +704,7 @@ async function getMask(maskType, args) {
496
704
  // This only seems to get the first row, not all rows, so we get the longest name match
497
705
  `SELECT name FROM mask WHERE value = ? ORDER BY name DESC`,
498
706
  )
499
- .get(testMask[1]);
707
+ .get(maskToken.item);
500
708
 
501
709
  resolve(row ? row.name : `unknown-${maskType}`);
502
710
  } catch (err) {
@@ -516,7 +724,17 @@ async function getMask(maskType, args) {
516
724
  * @param {Array} args - The arguments for the action
517
725
  */
518
726
  async function setMask(maskType, args) {
519
- const [prop, value] = args[0].split("=");
727
+ const { prop, value } = splitPropertyValue(args[0]);
728
+ if (!prop || value === undefined) {
729
+ return printHelp("no property=value provided");
730
+ }
731
+
732
+ try {
733
+ validateMaskPropertyName(prop);
734
+ } catch (err) {
735
+ return printHelp(err.message);
736
+ }
737
+
520
738
  const dbname = `mask-${maskType}-${prop}`;
521
739
  let maskString = value;
522
740
 
@@ -684,4 +902,20 @@ maskValues.maskObjValues = maskObjValues;
684
902
  maskValues.unmaskObjValues = unmaskObjValues;
685
903
 
686
904
  export default maskValues;
687
- export { maskTypes, printHelp, maskObjValues, unmaskObjValues };
905
+ export {
906
+ maskTypes,
907
+ printHelp,
908
+ maskObjValues,
909
+ unmaskObjValues,
910
+ assertAllowedMaskTableName,
911
+ assertSafeSqlIdentifier,
912
+ assertSafeColumnType,
913
+ validateMaskTokenComponent,
914
+ validateMaskPropertyName,
915
+ resolveMaskDbFilePath,
916
+ parseMaskToken,
917
+ splitPropertyValue,
918
+ buildMaskDumpQuery,
919
+ executeKeyLookupScript,
920
+ DEFAULT_KEY_LOOKUP_TIMEOUT_MS,
921
+ };