Skip to content

Commit e90d1ee

Browse files
committed
SSP-4252 refactor parse to use regEx & extend unittests
1 parent 58790e9 commit e90d1ee

File tree

2 files changed

+38
-8
lines changed

2 files changed

+38
-8
lines changed

src/parse.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
1-
export function parseVaultKey(vaultKey: string, prefix = "VaultKey--") {
2-
const vaultStr = vaultKey.replace(prefix, "").replace("kv-v2/data/", "");
1+
export function parseVaultKey(vaultKey: string) {
2+
const regex = /(VaultKey--)(kv-v2)\/(data)\/(?<path>.*\/)(?<key>.*)/;
33

4-
const parts = vaultStr.split("/");
5-
const key = parts.pop();
6-
const path = parts.join("/");
4+
const match = vaultKey.match(regex);
5+
6+
if (!match) {
7+
throw new Error("VaultKey not valid: " + vaultKey);
8+
}
9+
10+
const secretPath = trimEnd(match.groups["path"]);
11+
const secretKey = trimEnd(match.groups["key"]);
712

813
return {
914
secretMount: "kv-v2",
10-
secretPath: path,
11-
secretKey: key
15+
secretPath,
16+
secretKey
1217
};
1318
}
19+
20+
function trimEnd(value: string, char = "/") {
21+
if (!value) return "";
22+
return value.endsWith(char) ? value.slice(0, -1) : value;
23+
}

tests/parse.spec.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { parseVaultKey } from "../src/parse";
22

33
describe("parseVaultKey", () => {
4-
it("returns ", () => {
4+
it("returns secret with sub-path ", () => {
55
const result = parseVaultKey("VaultKey--kv-v2/data/global/logstash/Username");
66

77
const expected = {
@@ -12,4 +12,24 @@ describe("parseVaultKey", () => {
1212

1313
expect(result).toStrictEqual(expected);
1414
});
15+
16+
it("returns secret in root-path", () => {
17+
const result = parseVaultKey("VaultKey--kv-v2/data/logstash/Username");
18+
19+
const expected = {
20+
secretMount: "kv-v2",
21+
secretPath: "logstash",
22+
secretKey: "Username"
23+
};
24+
25+
expect(result).toStrictEqual(expected);
26+
});
27+
28+
it("fails for secret without path", () => {
29+
expect(() => parseVaultKey("VaultKey--kv-v2/data/Username")).toThrowError();
30+
});
31+
32+
it("fails for non-secret", () => {
33+
expect(() => parseVaultKey("xyz")).toThrowError();
34+
});
1535
});

0 commit comments

Comments
 (0)