@opscompass/opscompass-cli 1.3.2 → 1.3.4

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,174 @@ 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 INVALID_MASK_ITEM_COMPONENT_REGEX = /[\n\r\\]/;
37
+ const DEFAULT_KEY_LOOKUP_TIMEOUT_MS = 5000;
38
+ const MASK_DB_COLUMNS = Object.freeze([
39
+ Object.freeze({
40
+ name: "name",
41
+ type: "TEXT NOT NULL UNIQUE",
42
+ index: "mask_name_idx",
43
+ }),
44
+ Object.freeze({
45
+ name: "value",
46
+ type: "TEXT NOT NULL",
47
+ index: "mask_value_idx",
48
+ }),
49
+ ]);
50
+
51
+ function assertPathWithinRoot(rootPath, resolvedPath, label) {
52
+ if (
53
+ resolvedPath !== rootPath &&
54
+ !resolvedPath.startsWith(`${rootPath}${path.sep}`)
55
+ ) {
56
+ throw new Error(`Unsafe ${label} path`);
57
+ }
58
+ }
59
+
60
+ function assertSafeSqlIdentifier(value, label = "identifier") {
61
+ if (typeof value !== "string" || !SQL_IDENTIFIER_REGEX.test(value)) {
62
+ throw new Error(`Invalid SQL ${label}: ${value}`);
63
+ }
64
+ return value;
65
+ }
66
+
67
+ function assertSafeColumnType(columnType) {
68
+ if (
69
+ typeof columnType !== "string" ||
70
+ !SQL_COLUMN_TYPE_REGEX.test(columnType)
71
+ ) {
72
+ throw new Error(`Invalid SQL column type: ${columnType}`);
73
+ }
74
+ return columnType;
75
+ }
76
+
77
+ function assertAllowedMaskTableName(tableName) {
78
+ if (!ALLOWED_MASK_TABLES.has(tableName)) {
79
+ throw new Error(`Unsupported table name: ${tableName}`);
80
+ }
81
+ return tableName;
82
+ }
83
+
84
+ function validateMaskTokenComponent(componentName, value) {
85
+ if (typeof value !== "string" || value.length === 0) {
86
+ throw new Error(`Invalid mask token ${componentName}`);
87
+ }
88
+ const invalidComponentRegex =
89
+ componentName === "item"
90
+ ? INVALID_MASK_ITEM_COMPONENT_REGEX
91
+ : INVALID_MASK_COMPONENT_REGEX;
92
+ if (invalidComponentRegex.test(value)) {
93
+ throw new Error(`Invalid mask token ${componentName}`);
94
+ }
95
+ if (componentName === "type" && !MASK_TYPE_REGEX.test(value)) {
96
+ throw new Error(`Invalid mask token ${componentName}`);
97
+ }
98
+ return value;
99
+ }
100
+
101
+ function validateMaskPropertyName(propertyName) {
102
+ if (typeof propertyName !== "string" || propertyName.length === 0) {
103
+ throw new Error("Invalid mask property");
104
+ }
105
+ if (INVALID_MASK_COMPONENT_REGEX.test(propertyName)) {
106
+ throw new Error("Invalid mask property");
107
+ }
108
+ if (!MASK_PROPERTY_REGEX.test(propertyName)) {
109
+ throw new Error("Invalid mask property");
110
+ }
111
+ return propertyName;
112
+ }
113
+
114
+ function resolveMaskDbFilePath(dbFileName, company = "unspecified-company") {
115
+ const configRoot = path.resolve(opscompassHome, "configs");
116
+ const safeCompany = validateMaskPropertyName(company);
117
+ const safeDbFileName = validateMaskPropertyName(dbFileName);
118
+
119
+ const companyPath = path.resolve(configRoot, safeCompany);
120
+ assertPathWithinRoot(configRoot, companyPath, "company");
121
+
122
+ const dbFilePath = path.resolve(companyPath, safeDbFileName);
123
+ assertPathWithinRoot(companyPath, dbFilePath, "database");
124
+
125
+ return {
126
+ company: safeCompany,
127
+ dbFilePath,
128
+ };
129
+ }
130
+
131
+ function parseMaskToken(maskToken) {
132
+ const token = typeof maskToken === "string" ? maskToken.trim() : "";
133
+ const match = token.match(MASK_TOKEN_REGEX);
134
+ if (!match) {
135
+ throw new Error("invalid mask format");
136
+ }
137
+
138
+ const type = validateMaskTokenComponent("type", match[1]);
139
+ const item = validateMaskTokenComponent("item", match[2]);
140
+ return { type, item };
141
+ }
142
+
143
+ function splitPropertyValue(arg) {
144
+ const separatorIdx = arg?.indexOf("=") ?? -1;
145
+ if (separatorIdx < 0) {
146
+ return { prop: arg, value: undefined };
147
+ }
148
+
149
+ return {
150
+ prop: arg.slice(0, separatorIdx),
151
+ value: arg.slice(separatorIdx + 1),
152
+ };
153
+ }
154
+
155
+ function buildMaskDumpQuery(tableName, includeMaskFilter = false) {
156
+ tableName = assertAllowedMaskTableName(tableName);
157
+ const sql = `SELECT * FROM ${tableName}`;
158
+ if (includeMaskFilter) {
159
+ return `${sql} WHERE value = ? ORDER BY name DESC`;
160
+ }
161
+ return `${sql} ORDER BY name DESC`;
162
+ }
163
+
164
+ function executeKeyLookupScript(
165
+ keyCommand,
166
+ item,
167
+ timeoutMs = DEFAULT_KEY_LOOKUP_TIMEOUT_MS,
168
+ ) {
169
+ validateMaskTokenComponent("item", item);
170
+
171
+ return new Promise((resolve, reject) => {
172
+ execFile(
173
+ keyCommand,
174
+ [item],
175
+ {
176
+ shell: false,
177
+ timeout: timeoutMs,
178
+ windowsHide: true,
179
+ maxBuffer: 1024 * 1024,
180
+ },
181
+ (error, stdout, stderr) => {
182
+ if (error) {
183
+ if (error.killed) {
184
+ reject(new Error(`lookup timed out after ${timeoutMs}ms`));
185
+ return;
186
+ }
187
+
188
+ reject(new Error(stderr || error.message));
189
+ return;
190
+ }
191
+ resolve(stdout);
192
+ },
193
+ );
194
+ });
195
+ }
196
+
44
197
  /**
45
198
  * Function to find keyCommand for a maskType, and only check
46
199
  * once per maskType
@@ -92,7 +245,7 @@ op item get "${1}" \
92
245
  * @param {*} maskType
93
246
  * @returns the path to the keyCommand (if executable) or undefined
94
247
  */
95
- let keyCmd = [];
248
+ let keyCmd = {};
96
249
  function getKeyCommand(maskType) {
97
250
  if (keyCmd.hasOwnProperty(maskType)) return keyCmd[maskType];
98
251
 
@@ -128,14 +281,18 @@ class MaskDb {
128
281
  return this.dbFilePath;
129
282
  }
130
283
 
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
- ];
284
+ maskColumns = MASK_DB_COLUMNS;
135
285
 
136
286
  constructor(dbFileName, company = global?.company || "unspecified-company") {
137
- this.company = company;
138
- this.dbFilePath = path.join(opscompassHome, "configs", company, dbFileName);
287
+ try {
288
+ const safeMaskDbPath = resolveMaskDbFilePath(dbFileName, company);
289
+ this.company = safeMaskDbPath.company;
290
+ this.dbFilePath = safeMaskDbPath.dbFilePath;
291
+ } catch (err) {
292
+ console.error(`Invalid mask database path: ${err}`);
293
+ process.exit(11);
294
+ }
295
+
139
296
  // It is possible that this will be the first time we need that directory
140
297
  try {
141
298
  fs.mkdirSync(path.dirname(this.dbFilePath), { recursive: true });
@@ -166,9 +323,21 @@ class MaskDb {
166
323
 
167
324
  async createTable(tableName, columns) {
168
325
  return new Promise((resolve, reject) => {
326
+ try {
327
+ tableName = assertAllowedMaskTableName(tableName);
328
+ } catch (err) {
329
+ reject(err.message || err);
330
+ return;
331
+ }
332
+
169
333
  const columnsDefinition = columns
170
334
  .map((column) => {
171
- let definition = `${column.name} ${column.type} NOT NULL`;
335
+ const columnName = assertSafeSqlIdentifier(
336
+ column.name,
337
+ "column name",
338
+ );
339
+ const columnType = assertSafeColumnType(column.type);
340
+ let definition = `${columnName} ${columnType}`;
172
341
  return definition;
173
342
  })
174
343
  .join(", ");
@@ -185,9 +354,13 @@ class MaskDb {
185
354
  }
186
355
 
187
356
  async createIndexes(tableName, columns) {
357
+ tableName = assertAllowedMaskTableName(tableName);
358
+
188
359
  const indexPromises = columns.map((column) => {
189
360
  if (column.index) {
190
- const indexSql = `CREATE INDEX IF NOT EXISTS idx_${tableName}_${column.name} ON ${tableName} (${column.name})`;
361
+ const columnName = assertSafeSqlIdentifier(column.name, "column name");
362
+ const indexName = assertSafeSqlIdentifier(column.index, "index name");
363
+ const indexSql = `CREATE INDEX IF NOT EXISTS ${indexName} ON ${tableName} (${columnName})`;
191
364
  return new Promise((resolve, reject) => {
192
365
  try {
193
366
  this.db.exec(indexSql);
@@ -203,37 +376,34 @@ class MaskDb {
203
376
  }
204
377
 
205
378
  dumpTable(tableName, mask = undefined) {
379
+ tableName = assertAllowedMaskTableName(tableName);
380
+
206
381
  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";
382
+ const statement = this.db.prepare(
383
+ buildMaskDumpQuery(tableName, mask !== undefined),
384
+ );
385
+ const rows = mask !== undefined ? statement.all(mask) : statement.all();
211
386
 
212
387
  console.error(`\nContents of ${tableName} table (${this.dbFilePath}):`);
213
388
  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
- });
389
+ rows.forEach((row, idx, arr) => {
390
+ row.mask = `oc$mask-${maskType}:{${row.value}}`;
391
+ console.log(
392
+ process.stdout.isTTY
393
+ ? JSON.stringify(row, null, 2).replace(/^/gm, " ")
394
+ : JSON.stringify(row),
395
+ idx < arr.length - 1 ? "," : "",
396
+ );
397
+ });
226
398
  console.log(" ]\n}\n");
227
399
  }
228
400
 
229
401
  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
- });
402
+ try {
403
+ this.db.close();
404
+ } catch (err) {
405
+ console.error("Could not close the database", err);
406
+ }
237
407
  }
238
408
  }
239
409
 
@@ -257,14 +427,21 @@ function processArgs(action, args) {
257
427
  // case "get": // not meant to call directly
258
428
  case "lookup":
259
429
  // The type is after the '-' in oc$mask-{type}
260
- const matchResult = args[0]?.match(/.*-(.+):{(.*)}/);
261
- if (!matchResult) {
262
- return printHelp("invalid mask format");
430
+ const separatorIdx = args[0]?.indexOf("=") ?? -1;
431
+ if (separatorIdx < 0) {
432
+ return printHelp("no property=value provided");
263
433
  }
264
- const testMask = matchResult.splice(1);
265
- maskType = maskTypes[testMask[0]];
434
+
435
+ let parsedMaskToken = undefined;
436
+ try {
437
+ parsedMaskToken = parseMaskToken(args[0].slice(separatorIdx + 1));
438
+ } catch (err) {
439
+ return printHelp(err.message);
440
+ }
441
+
442
+ maskType = maskTypes[parsedMaskToken.type];
266
443
  if (!maskType) {
267
- maskType = testMask[0];
444
+ maskType = parsedMaskToken.type;
268
445
  const keyCommand = getKeyCommand(maskType);
269
446
  if (!keyCommand) {
270
447
  return printHelp(`unknown mask type for lookup (${maskType})`);
@@ -382,7 +559,17 @@ function getServerName(serverSpec) {
382
559
  * @param {Array} args - The arguments for the action
383
560
  */
384
561
  async function dumpMaskTable(maskType, args) {
385
- const [prop, value] = args[0].split("=");
562
+ const { prop } = splitPropertyValue(args[0]);
563
+ if (!prop) {
564
+ return printHelp("no property=value provided");
565
+ }
566
+
567
+ try {
568
+ validateMaskPropertyName(prop);
569
+ } catch (err) {
570
+ return printHelp(err.message);
571
+ }
572
+
386
573
  const dbname = `mask-${maskType}-${prop}`;
387
574
  const maskDb = await new MaskDb(dbname).then((db) => {
388
575
  // console.log("db opened:", db);
@@ -396,7 +583,17 @@ async function dumpMaskTable(maskType, args) {
396
583
  * @param {Array} args - The arguments for the action
397
584
  */
398
585
  async function lookupMask(maskType, args) {
399
- const [prop, value] = args[0].split("=");
586
+ const { prop, value } = splitPropertyValue(args[0]);
587
+ if (!prop) {
588
+ return printHelp("no property=value provided");
589
+ }
590
+
591
+ try {
592
+ validateMaskPropertyName(prop);
593
+ } catch (err) {
594
+ return printHelp(err.message);
595
+ }
596
+
400
597
  const dbname = `mask-${maskType}-${prop}`;
401
598
 
402
599
  if (!value) {
@@ -404,18 +601,25 @@ async function lookupMask(maskType, args) {
404
601
  }
405
602
 
406
603
  // 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) {
604
+ let maskToken = undefined;
605
+ try {
606
+ maskToken = parseMaskToken(value);
607
+ } catch (err) {
608
+ return printHelp(err.message);
609
+ }
610
+
611
+ if (maskToken.type !== maskType) {
409
612
  return printHelp(`invalid property value (${args[0]})`);
410
613
  }
411
614
 
412
615
  // If keyCmd is set we need to run that command to get the key
413
616
  let keystoreResponse = undefined;
414
617
  if (keyCmd[maskType]) {
415
- // console.log(`We need to lookup ${testMask[1]} using keystore:`, keyCmd);
618
+ // console.log(`We need to lookup ${maskToken.item} using keystore:`, keyCmd);
416
619
  try {
417
- keystoreResponse = await executeCommand(
418
- `${keyCmd[maskType]} ${testMask[1]}`,
620
+ keystoreResponse = await executeKeyLookupScript(
621
+ keyCmd[maskType],
622
+ maskToken.item,
419
623
  );
420
624
  const lookupCreds = JSON.parse(keystoreResponse);
421
625
  console.log("lookupObject:", lookupCreds);
@@ -425,7 +629,7 @@ async function lookupMask(maskType, args) {
425
629
  console.log("lookup:", keystoreResponse.trimEnd());
426
630
  } else {
427
631
  return printHelp(
428
- `Could not retrieve data for ${testMask[1]} from keystore:\n${err}`,
632
+ `Could not retrieve data for ${maskToken.item} from keystore:\n${err?.message || err}`,
429
633
  );
430
634
  }
431
635
  }
@@ -434,7 +638,7 @@ async function lookupMask(maskType, args) {
434
638
  // console.log("db opened:", db);
435
639
  return db;
436
640
  });
437
- maskDb.dumpTable("mask", testMask[1]);
641
+ maskDb.dumpTable("mask", maskToken.item);
438
642
  }
439
643
  }
440
644
 
@@ -446,13 +650,29 @@ async function getMask(maskType, args) {
446
650
  if (args.length === 0 || args[0].indexOf("=") < 0) {
447
651
  return printHelp("no property=value provided");
448
652
  }
449
- const [prop, value] = args[0].split("=");
653
+ const { prop, value } = splitPropertyValue(args[0]);
654
+ if (!prop) {
655
+ return printHelp("no property=value provided");
656
+ }
657
+
658
+ try {
659
+ validateMaskPropertyName(prop);
660
+ } catch (err) {
661
+ return printHelp(err.message);
662
+ }
663
+
450
664
  const dbname = `mask-${maskType}-${prop}`;
451
665
  // console.error(`getMask (${maskType}): ${prop} = ${value}`);
452
666
 
453
667
  // 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) {
668
+ let maskToken = undefined;
669
+ try {
670
+ maskToken = parseMaskToken(value);
671
+ } catch (err) {
672
+ return printHelp(err.message);
673
+ }
674
+
675
+ if (maskToken.type !== maskType) {
456
676
  return printHelp(`invalid property value (${args[0]})`);
457
677
  }
458
678
 
@@ -463,7 +683,10 @@ async function getMask(maskType, args) {
463
683
  const keyCommand = getKeyCommand(maskType);
464
684
  if (keyCommand) {
465
685
  try {
466
- keystoreResponse = await executeCommand(`${keyCommand} ${testMask[1]}`);
686
+ keystoreResponse = await executeKeyLookupScript(
687
+ keyCommand,
688
+ maskToken.item,
689
+ );
467
690
  keystoreObject = JSON.parse(keystoreResponse);
468
691
 
469
692
  // If a username is returned by the keystore, the user is the username
@@ -477,7 +700,7 @@ async function getMask(maskType, args) {
477
700
  unmaskedValue = keystoreResponse.trimEnd();
478
701
  } else {
479
702
  console.error(
480
- `Could not retrieve data for ${testMask[1]} from keystore:\n${err}\n`,
703
+ `Could not retrieve data for ${maskToken.item} from keystore:\n${err?.message || err}\n`,
481
704
  );
482
705
  }
483
706
  }
@@ -496,7 +719,7 @@ async function getMask(maskType, args) {
496
719
  // This only seems to get the first row, not all rows, so we get the longest name match
497
720
  `SELECT name FROM mask WHERE value = ? ORDER BY name DESC`,
498
721
  )
499
- .get(testMask[1]);
722
+ .get(maskToken.item);
500
723
 
501
724
  resolve(row ? row.name : `unknown-${maskType}`);
502
725
  } catch (err) {
@@ -516,7 +739,17 @@ async function getMask(maskType, args) {
516
739
  * @param {Array} args - The arguments for the action
517
740
  */
518
741
  async function setMask(maskType, args) {
519
- const [prop, value] = args[0].split("=");
742
+ const { prop, value } = splitPropertyValue(args[0]);
743
+ if (!prop || value === undefined) {
744
+ return printHelp("no property=value provided");
745
+ }
746
+
747
+ try {
748
+ validateMaskPropertyName(prop);
749
+ } catch (err) {
750
+ return printHelp(err.message);
751
+ }
752
+
520
753
  const dbname = `mask-${maskType}-${prop}`;
521
754
  let maskString = value;
522
755
 
@@ -684,4 +917,20 @@ maskValues.maskObjValues = maskObjValues;
684
917
  maskValues.unmaskObjValues = unmaskObjValues;
685
918
 
686
919
  export default maskValues;
687
- export { maskTypes, printHelp, maskObjValues, unmaskObjValues };
920
+ export {
921
+ maskTypes,
922
+ printHelp,
923
+ maskObjValues,
924
+ unmaskObjValues,
925
+ assertAllowedMaskTableName,
926
+ assertSafeSqlIdentifier,
927
+ assertSafeColumnType,
928
+ validateMaskTokenComponent,
929
+ validateMaskPropertyName,
930
+ resolveMaskDbFilePath,
931
+ parseMaskToken,
932
+ splitPropertyValue,
933
+ buildMaskDumpQuery,
934
+ executeKeyLookupScript,
935
+ DEFAULT_KEY_LOOKUP_TIMEOUT_MS,
936
+ };