@tenonhq/dovetail-core 0.0.130 → 0.0.132

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.
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ // Fingerprint mode (fingerprint.ts): a configured field is mirrored as a
3
+ // SHA-256 digest instead of its content. Covers the digest format, config
4
+ // validation, request stripping, response rewriting (manifest structure,
5
+ // bulkDownload content, metaData.json), idempotency and the push-side path test.
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ const crypto_1 = __importDefault(require("crypto"));
11
+ const fingerprint_1 = require("../fingerprint");
12
+ const BUNDLE = "!function(){console.log(\"bundle ü\")}();";
13
+ const HEX = crypto_1.default.createHash("sha256").update(BUNDLE, "utf8").digest("hex");
14
+ const OPTIONS = {
15
+ sys_ux_lib_source_script: { fingerprint: ["script"] },
16
+ sys_choice: { nameTemplate: "{name}.{element}.{value}" },
17
+ };
18
+ function metaContent(extra) {
19
+ return JSON.stringify(Object.assign({ _table: "sys_ux_lib_source_script", name: { value: "@tenon/ui-form" } }, extra), null, 2);
20
+ }
21
+ function bulkResult(files) {
22
+ return {
23
+ sys_ux_lib_source_script: {
24
+ records: {
25
+ "@tenon/ui-form": { name: "@tenon/ui-form", sys_id: "f9cd", files: files },
26
+ },
27
+ },
28
+ };
29
+ }
30
+ describe("formatFingerprint", function () {
31
+ it("writes the digest and the UTF-8 byte length", function () {
32
+ expect((0, fingerprint_1.formatFingerprint)(BUNDLE)).toBe("sha256:" + HEX + "\nbytes:" + Buffer.byteLength(BUNDLE, "utf8") + "\n");
33
+ });
34
+ it("is recognized by isFingerprintContent", function () {
35
+ expect((0, fingerprint_1.isFingerprintContent)((0, fingerprint_1.formatFingerprint)(BUNDLE))).toBe(true);
36
+ expect((0, fingerprint_1.isFingerprintContent)(BUNDLE)).toBe(false);
37
+ expect((0, fingerprint_1.isFingerprintContent)(undefined)).toBe(false);
38
+ });
39
+ });
40
+ describe("fingerprintFieldsFor", function () {
41
+ it("returns the configured fields", function () {
42
+ expect((0, fingerprint_1.fingerprintFieldsFor)(OPTIONS, "sys_ux_lib_source_script")).toEqual(["script"]);
43
+ });
44
+ it("returns nothing for an unconfigured table or missing options", function () {
45
+ expect((0, fingerprint_1.fingerprintFieldsFor)(OPTIONS, "sys_choice")).toEqual([]);
46
+ expect((0, fingerprint_1.fingerprintFieldsFor)(OPTIONS, "sys_script")).toEqual([]);
47
+ expect((0, fingerprint_1.fingerprintFieldsFor)(undefined, "sys_ux_lib_source_script")).toEqual([]);
48
+ expect((0, fingerprint_1.fingerprintFieldsFor)(null, "sys_ux_lib_source_script")).toEqual([]);
49
+ });
50
+ it("drops malformed entries instead of throwing", function () {
51
+ var bad = {
52
+ t1: { fingerprint: "script" },
53
+ t2: { fingerprint: ["", " ", 5, "script", "script"] },
54
+ };
55
+ expect((0, fingerprint_1.fingerprintFieldsFor)(bad, "t1")).toEqual([]);
56
+ expect((0, fingerprint_1.fingerprintFieldsFor)(bad, "t2")).toEqual(["script"]);
57
+ });
58
+ });
59
+ describe("stripClientOnlyTableOptions", function () {
60
+ it("removes fingerprint and keeps every other option", function () {
61
+ var out = (0, fingerprint_1.stripClientOnlyTableOptions)(OPTIONS);
62
+ expect(out.sys_ux_lib_source_script).toEqual({});
63
+ expect(out.sys_choice).toEqual({ nameTemplate: "{name}.{element}.{value}" });
64
+ });
65
+ it("never mutates the caller's options", function () {
66
+ (0, fingerprint_1.stripClientOnlyTableOptions)(OPTIONS);
67
+ expect(OPTIONS.sys_ux_lib_source_script.fingerprint).toEqual(["script"]);
68
+ });
69
+ it("returns an empty map for missing options", function () {
70
+ expect((0, fingerprint_1.stripClientOnlyTableOptions)(undefined)).toEqual({});
71
+ });
72
+ });
73
+ describe("applyFingerprints", function () {
74
+ it("renames a structure-only manifest entry to .sha256 without content", function () {
75
+ var tables = bulkResult([{ name: "script", type: "js" }]);
76
+ (0, fingerprint_1.applyFingerprints)(tables, OPTIONS);
77
+ var file = tables.sys_ux_lib_source_script.records["@tenon/ui-form"].files[0];
78
+ expect(file).toEqual({ name: "script", type: "sha256" });
79
+ });
80
+ it("hashes downloaded content, whatever type the server echoed", function () {
81
+ var tables = bulkResult([
82
+ { name: "script", type: "js", content: BUNDLE },
83
+ { name: "script_b", type: "sha256", content: BUNDLE },
84
+ ]);
85
+ (0, fingerprint_1.applyFingerprints)(tables, { sys_ux_lib_source_script: { fingerprint: ["script", "script_b"] } });
86
+ var files = tables.sys_ux_lib_source_script.records["@tenon/ui-form"].files;
87
+ expect(files[0]).toEqual({ name: "script", type: "sha256", content: (0, fingerprint_1.formatFingerprint)(BUNDLE) });
88
+ expect(files[1].content).toBe((0, fingerprint_1.formatFingerprint)(BUNDLE));
89
+ });
90
+ it("replaces the field's metaData.json value with the digest and drops display_value", function () {
91
+ var tables = bulkResult([
92
+ {
93
+ name: "metaData",
94
+ type: "json",
95
+ content: metaContent({ script: { value: BUNDLE, display_value: BUNDLE } }),
96
+ },
97
+ ]);
98
+ (0, fingerprint_1.applyFingerprints)(tables, OPTIONS);
99
+ var meta = JSON.parse(tables.sys_ux_lib_source_script.records["@tenon/ui-form"].files[0].content);
100
+ expect(meta.script).toEqual({ value: "sha256:" + HEX });
101
+ expect(meta.name).toEqual({ value: "@tenon/ui-form" });
102
+ expect(JSON.stringify(meta)).not.toContain("bundle");
103
+ });
104
+ it("is idempotent", function () {
105
+ var tables = bulkResult([
106
+ { name: "script", type: "js", content: BUNDLE },
107
+ { name: "metaData", type: "json", content: metaContent({ script: { value: BUNDLE } }) },
108
+ ]);
109
+ (0, fingerprint_1.applyFingerprints)(tables, OPTIONS);
110
+ var once = JSON.stringify(tables);
111
+ (0, fingerprint_1.applyFingerprints)(tables, OPTIONS);
112
+ expect(JSON.stringify(tables)).toBe(once);
113
+ });
114
+ it("leaves tables without fingerprint config untouched", function () {
115
+ var tables = {
116
+ sys_script_include: {
117
+ records: {
118
+ Foo: { name: "Foo", sys_id: "1", files: [{ name: "script", type: "js", content: "x" }] },
119
+ },
120
+ },
121
+ };
122
+ var before = JSON.stringify(tables);
123
+ (0, fingerprint_1.applyFingerprints)(tables, OPTIONS);
124
+ expect(JSON.stringify(tables)).toBe(before);
125
+ });
126
+ it("tolerates malformed responses", function () {
127
+ expect((0, fingerprint_1.applyFingerprints)(null, OPTIONS)).toBeNull();
128
+ expect((0, fingerprint_1.applyFingerprints)("nope", OPTIONS)).toBe("nope");
129
+ var odd = {
130
+ sys_ux_lib_source_script: { records: { a: null, b: { files: "x" }, c: { files: [null, 7] } } },
131
+ };
132
+ expect(function () { (0, fingerprint_1.applyFingerprints)(odd, OPTIONS); }).not.toThrow();
133
+ var badMeta = bulkResult([{ name: "metaData", type: "json", content: "not json" }]);
134
+ (0, fingerprint_1.applyFingerprints)(badMeta, OPTIONS);
135
+ expect(badMeta.sys_ux_lib_source_script.records["@tenon/ui-form"].files[0].content).toBe("not json");
136
+ });
137
+ });
138
+ describe("isFingerprintFilePath", function () {
139
+ it("matches only a .sha256 extension", function () {
140
+ expect((0, fingerprint_1.isFingerprintFilePath)("/r/src/UIComponents/x/sys_ux_lib_source_script/a/script.sha256")).toBe(true);
141
+ expect((0, fingerprint_1.isFingerprintFilePath)("/r/src/Core/sys_script_include/a/script.js")).toBe(false);
142
+ expect((0, fingerprint_1.isFingerprintFilePath)("/r/a/sha256")).toBe(false);
143
+ });
144
+ });
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ // A fingerprinted field is in the branch as a digest only (fingerprint.ts), and
3
+ // its metaData.json value is the digest too. `dove reconcile --apply` must not
4
+ // create such a record from the branch: it would write the digest over the
5
+ // field's real content. The create is refused per record and nothing is posted.
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ jest.mock("../Logger", function () {
11
+ return {
12
+ logger: {
13
+ info: jest.fn(),
14
+ debug: jest.fn(),
15
+ warn: jest.fn(),
16
+ error: jest.fn(),
17
+ success: jest.fn(),
18
+ getLogLevel: function () { return "debug"; },
19
+ },
20
+ };
21
+ });
22
+ jest.mock("../FileLogger", function () {
23
+ return { fileLogger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() } };
24
+ });
25
+ var mockSourcePath = "";
26
+ jest.mock("../config", function () {
27
+ return {
28
+ getSourcePathForScope: function () {
29
+ return mockSourcePath;
30
+ },
31
+ };
32
+ });
33
+ var mockPost = jest.fn();
34
+ jest.mock("../snClient", function () {
35
+ var actual = jest.requireActual("../snClient");
36
+ var client = actual.snClient("https://x.service-now.com/", "u", "p");
37
+ client.client.post = mockPost;
38
+ return Object.assign({}, actual, {
39
+ defaultClient: function () {
40
+ return client;
41
+ },
42
+ });
43
+ });
44
+ const fs_1 = __importDefault(require("fs"));
45
+ const os_1 = __importDefault(require("os"));
46
+ const path_1 = __importDefault(require("path"));
47
+ const reconcileCommand_1 = require("../reconcileCommand");
48
+ const fingerprint_1 = require("../fingerprint");
49
+ describe("reconcile applyCreates with a fingerprinted record", function () {
50
+ var tmp = "";
51
+ beforeEach(function () {
52
+ mockPost.mockReset();
53
+ tmp = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "dove-fp-create-"));
54
+ mockSourcePath = tmp;
55
+ var recordDir = path_1.default.join(tmp, "sys_ux_lib_source_script", "Bundle");
56
+ fs_1.default.mkdirSync(recordDir, { recursive: true });
57
+ fs_1.default.writeFileSync(path_1.default.join(recordDir, "script.sha256"), (0, fingerprint_1.formatFingerprint)("!function(){}();"));
58
+ fs_1.default.writeFileSync(path_1.default.join(recordDir, "metaData.json"), JSON.stringify({ name: { value: "@tenon/ui-form" }, script: { value: "sha256:" + "0".repeat(64) } }));
59
+ });
60
+ afterEach(function () {
61
+ fs_1.default.rmSync(tmp, { recursive: true, force: true });
62
+ });
63
+ it("refuses the create with a named reason and never posts", async function () {
64
+ var change = {
65
+ kind: "create",
66
+ table: "sys_ux_lib_source_script",
67
+ scope: "x_cadso_ui_form",
68
+ sys_id: "f9cd",
69
+ name: "Bundle",
70
+ fieldDeltas: [],
71
+ };
72
+ var outcomes = await (0, reconcileCommand_1.applyCreates)("x_cadso_ui_form", [change], "us1");
73
+ expect(outcomes).toHaveLength(1);
74
+ expect(outcomes[0].ok).toBe(false);
75
+ expect(outcomes[0].error).toMatch(/fingerprint only/);
76
+ expect(outcomes[0].error).toMatch(/sys_ux_lib_source_script\/Bundle/);
77
+ expect(mockPost).not.toHaveBeenCalled();
78
+ });
79
+ });
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ // resolveScopeFromPath (config.ts) maps a file to the scope whose folder holds
3
+ // it; push relies on it (FileUtils.getFileContextWithSkipReason). With scopes in
4
+ // nested folders (src/UIComponents/<scope>) a plain string prefix is wrong: a
5
+ // folder claims a sibling whose name starts the same. Matching is now on a
6
+ // separator boundary, and the deepest folder wins regardless of declaration order.
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ jest.mock("../Logger", function () {
12
+ return {
13
+ logger: {
14
+ info: jest.fn(),
15
+ debug: jest.fn(),
16
+ warn: jest.fn(),
17
+ error: jest.fn(),
18
+ success: jest.fn(),
19
+ getLogLevel: function () { return "debug"; },
20
+ setLogLevel: jest.fn(),
21
+ },
22
+ };
23
+ });
24
+ jest.mock("../FileLogger", function () {
25
+ return { fileLogger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() } };
26
+ });
27
+ const fs_1 = __importDefault(require("fs"));
28
+ const os_1 = __importDefault(require("os"));
29
+ const path_1 = __importDefault(require("path"));
30
+ const config_1 = require("../config");
31
+ const CONFIG = [
32
+ "module.exports = {",
33
+ " sourceDirectory: 'src',",
34
+ " buildDirectory: 'build',",
35
+ " includes: { _tables: ['sys_script_include'] },",
36
+ " excludes: { _tables: [] },",
37
+ " tableOptions: {},",
38
+ " scopes: {",
39
+ // Declared parent-first on purpose: the old first-match loop returned it for
40
+ // every file below it.
41
+ " x_parent: { sourceDirectory: 'src/UIComponents' },",
42
+ " x_cadso_ui_form: { sourceDirectory: 'src/UIComponents/x_cadso_ui_form' },",
43
+ " x_cadso_ui_form_x: { sourceDirectory: 'src/UIComponents/x_cadso_ui_form_x' },",
44
+ " x_cadso_core: { sourceDirectory: 'src/Core' },",
45
+ " },",
46
+ "};",
47
+ "",
48
+ ].join("\n");
49
+ describe("resolveScopeFromPath", function () {
50
+ var tmp = "";
51
+ var cwd = process.cwd();
52
+ beforeAll(async function () {
53
+ tmp = fs_1.default.realpathSync(fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "dove-scope-path-")));
54
+ fs_1.default.writeFileSync(path_1.default.join(tmp, "dove.config.js"), CONFIG);
55
+ process.chdir(tmp);
56
+ await (0, config_1.loadConfigs)();
57
+ });
58
+ afterAll(function () {
59
+ process.chdir(cwd);
60
+ fs_1.default.rmSync(tmp, { recursive: true, force: true });
61
+ });
62
+ function file(rel) {
63
+ return path_1.default.join(tmp, rel);
64
+ }
65
+ it("resolves each scope's folder from the config", function () {
66
+ expect((0, config_1.getSourcePathForScope)("x_cadso_ui_form")).toBe(file("src/UIComponents/x_cadso_ui_form"));
67
+ });
68
+ it("does not let a folder claim a sibling that shares its prefix", function () {
69
+ expect((0, config_1.resolveScopeFromPath)(file("src/UIComponents/x_cadso_ui_form_x/sys_ux_lib_component/a/metaData.json"))).toBe("x_cadso_ui_form_x");
70
+ expect((0, config_1.resolveScopeFromPath)(file("src/UIComponents/x_cadso_ui_form/sys_ux_lib_component/a/metaData.json"))).toBe("x_cadso_ui_form");
71
+ });
72
+ it("picks the deepest folder when scope folders nest", function () {
73
+ expect((0, config_1.resolveScopeFromPath)(file("src/UIComponents/x_cadso_ui_form/t/r/script.js"))).toBe("x_cadso_ui_form");
74
+ expect((0, config_1.resolveScopeFromPath)(file("src/UIComponents/other/t/r/script.js"))).toBe("x_parent");
75
+ });
76
+ it("still resolves a flat scope folder", function () {
77
+ expect((0, config_1.resolveScopeFromPath)(file("src/Core/sys_script_include/APIUtils/script.js"))).toBe("x_cadso_core");
78
+ });
79
+ it("returns undefined outside every scope folder or for bad input", function () {
80
+ expect((0, config_1.resolveScopeFromPath)(file("src/CoreX/sys_script_include/a/script.js"))).toBeUndefined();
81
+ expect((0, config_1.resolveScopeFromPath)("")).toBeUndefined();
82
+ });
83
+ });
@@ -21,6 +21,7 @@ jest.mock("../genericUtils", function () {
21
21
  });
22
22
  const snClient_1 = require("../snClient");
23
23
  const genericUtils_1 = require("../genericUtils");
24
+ const authFailure_1 = require("../authFailure");
24
25
  function makeAxiosError(status, headers) {
25
26
  var error = new Error("Request failed with status " + status);
26
27
  error.isAxiosError = true;
@@ -49,12 +50,46 @@ describe("retryOnHttpErr", function () {
49
50
  expect(mockLogger.error).toHaveBeenCalledWith(expect.stringContaining("Unauthorized (401)"));
50
51
  expect(mockLogger.error).toHaveBeenCalledWith(expect.stringContaining("credentials"));
51
52
  });
52
- it("fails immediately on 403 with credential message", async function () {
53
+ it("fails immediately on 403 with a refused-write message", async function () {
53
54
  var fn = jest.fn().mockRejectedValue(makeAxiosError(403));
54
55
  await expect((0, snClient_1.retryOnHttpErr)(fn, "test > rec1")).rejects.toThrow();
55
56
  expect(fn).toHaveBeenCalledTimes(1);
56
57
  expect(mockLogger.error).toHaveBeenCalledWith(expect.stringContaining("Forbidden (403)"));
57
- expect(mockLogger.error).toHaveBeenCalledWith(expect.stringContaining("credentials"));
58
+ expect(mockLogger.error).toHaveBeenCalledWith(expect.stringContaining("refused the write"));
59
+ });
60
+ it("401/403: the per-record line names the record and prints no credential; recording is the client interceptor's job (#185)", async function () {
61
+ var saved = { password: process.env.SN_PASSWORD };
62
+ process.env.SN_PASSWORD = "hunter2-do-not-print";
63
+ (0, authFailure_1.resetAuthFailureState)();
64
+ try {
65
+ var statuses = [401, 403];
66
+ for (var i = 0; i < statuses.length; i += 1) {
67
+ mockLogger.error.mockClear();
68
+ var err = makeAxiosError(statuses[i]);
69
+ var fn = jest.fn().mockRejectedValue(err);
70
+ // The original error is still what is thrown — callers keep its status.
71
+ await expect((0, snClient_1.retryOnHttpErr)(fn, "test > rec1")).rejects.toBe(err);
72
+ var logged = String(mockLogger.error.mock.calls[0][0]);
73
+ expect(logged).toContain("pushing test > rec1");
74
+ expect(logged).toContain("See the message above");
75
+ expect(logged).not.toContain("hunter2-do-not-print");
76
+ }
77
+ // A function that never went through an snClient records nothing here;
78
+ // snClient.authInterceptor.test.ts covers the recording.
79
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(0);
80
+ }
81
+ finally {
82
+ (0, authFailure_1.resetAuthFailureState)();
83
+ if (saved.password === undefined)
84
+ delete process.env.SN_PASSWORD;
85
+ else
86
+ process.env.SN_PASSWORD = saved.password;
87
+ }
88
+ });
89
+ it("a 404 does not record an auth failure", async function () {
90
+ (0, authFailure_1.resetAuthFailureState)();
91
+ await expect((0, snClient_1.retryOnHttpErr)(jest.fn().mockRejectedValue(makeAxiosError(404)), "test > rec1")).rejects.toThrow();
92
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(1);
58
93
  });
59
94
  // 404: Fail immediately
60
95
  it("fails immediately on 404 with record not found message", async function () {
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ // Every request an snClient makes passes its response interceptor, which is the
3
+ // ONE place an HTTP 401/403 is recorded (#185). These tests drive real client
4
+ // methods through a stub axios adapter, so the interceptor itself is exercised:
5
+ // a rejected write that is NOT `push` (reconcile CREATE/DELETE, create-record,
6
+ // delete-record, createUpdateSet) must exit 77 like a rejected push does.
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ var mockLogger = {
9
+ info: jest.fn(),
10
+ debug: jest.fn(),
11
+ warn: jest.fn(),
12
+ error: jest.fn(),
13
+ success: jest.fn(),
14
+ getLogLevel: function () {
15
+ return "debug";
16
+ },
17
+ };
18
+ jest.mock("../Logger", function () {
19
+ return { logger: mockLogger };
20
+ });
21
+ jest.mock("../FileLogger", function () {
22
+ return {
23
+ fileLogger: {
24
+ debug: jest.fn(),
25
+ info: jest.fn(),
26
+ warn: jest.fn(),
27
+ error: jest.fn(),
28
+ },
29
+ };
30
+ });
31
+ jest.mock("../genericUtils", function () {
32
+ return { wait: jest.fn().mockResolvedValue(undefined) };
33
+ });
34
+ jest.mock("../config", function () {
35
+ return {
36
+ getSourcePathForScope: function () {
37
+ return "/nonexistent-reconcile-source";
38
+ },
39
+ };
40
+ });
41
+ var mockHolder = { client: undefined };
42
+ jest.mock("../snClient", function () {
43
+ var actual = jest.requireActual("../snClient");
44
+ return Object.assign({}, actual, {
45
+ defaultClient: function () {
46
+ return mockHolder.client;
47
+ },
48
+ });
49
+ });
50
+ const axios_1 = require("axios");
51
+ const snClient_1 = require("../snClient");
52
+ const reconcileCommand_1 = require("../reconcileCommand");
53
+ const authFailure_1 = require("../authFailure");
54
+ var SECRET = "hunter2-do-not-print";
55
+ // A client whose transport answers every request with `status`. Only the adapter
56
+ // is replaced, so the request still runs the client's real interceptors.
57
+ function clientAnswering(status) {
58
+ var seen = [];
59
+ var c = (0, snClient_1.snClient)("https://admin:" + SECRET + "@example.invalid/", "svc-user", SECRET);
60
+ c.client.defaults.adapter = function (config) {
61
+ seen.push({
62
+ method: String(config.method).toUpperCase(),
63
+ url: String(config.url),
64
+ });
65
+ var response = {
66
+ status: status,
67
+ statusText: "",
68
+ headers: {},
69
+ config: config,
70
+ data: { error: { message: "denied" } },
71
+ };
72
+ return Promise.reject(new axios_1.AxiosError("Request failed with status code " + status, "ERR_BAD_REQUEST", config, null, response));
73
+ };
74
+ return { client: c, seen: seen };
75
+ }
76
+ function loggedErrors() {
77
+ return mockLogger.error.mock.calls
78
+ .map(function (c) {
79
+ return String(c[0]);
80
+ })
81
+ .join("\n");
82
+ }
83
+ function change(kind) {
84
+ return {
85
+ kind: kind,
86
+ table: "sys_script_include",
87
+ scope: "x_s",
88
+ sys_id: "abc123",
89
+ name: "Foo",
90
+ fieldDeltas: [],
91
+ };
92
+ }
93
+ describe("snClient auth interceptor (#185)", function () {
94
+ beforeEach(function () {
95
+ jest.clearAllMocks();
96
+ (0, authFailure_1.resetAuthFailureState)();
97
+ (0, snClient_1._resetDovetailApiFallback)();
98
+ (0, authFailure_1.setAuthContext)({ envPath: "/work/.env.loft", envArg: "loft" });
99
+ });
100
+ afterAll(function () {
101
+ (0, authFailure_1.resetAuthFailureState)();
102
+ });
103
+ it("a 403 on createRecord is a rejected write: exit 77 even over a clean exit", async function () {
104
+ var t = clientAnswering(403);
105
+ await expect(t.client.createRecord({
106
+ table: "sys_script_include",
107
+ fields: { name: "Foo" },
108
+ })).rejects.toMatchObject({ response: { status: 403 } });
109
+ expect(t.seen).toEqual([
110
+ { method: "POST", url: "api/cadso/dovetail_core/createRecord" },
111
+ ]);
112
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(authFailure_1.AUTH_EXIT_CODE);
113
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(authFailure_1.AUTH_EXIT_CODE);
114
+ var lines = loggedErrors();
115
+ expect(lines).toContain("Forbidden (403) calling POST api/cadso/dovetail_core/createRecord");
116
+ expect(lines).toContain("example.invalid");
117
+ expect(lines).toContain("/work/.env.loft");
118
+ // The table comes from the request body. A 403 does not send the user to dove login.
119
+ expect(lines).toContain("Check the role or ACL for table sys_script_include");
120
+ expect(lines).not.toContain("dove login");
121
+ expect(lines).not.toContain(SECRET);
122
+ });
123
+ it("a 403 on a Table API write names the table from the path", async function () {
124
+ var t = clientAnswering(403);
125
+ await expect(t.client.updateRecord("sys_script", "abc123", { script: "x" })).rejects.toMatchObject({ response: { status: 403 } });
126
+ expect(loggedErrors()).toContain("Check the role or ACL for table sys_script for the user");
127
+ });
128
+ it("a 403 on deleteRecord is a rejected write", async function () {
129
+ var t = clientAnswering(403);
130
+ await expect(t.client.deleteRecord({ table: "sys_script_include", sys_id: "abc123" })).rejects.toMatchObject({ response: { status: 403 } });
131
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(authFailure_1.AUTH_EXIT_CODE);
132
+ });
133
+ it("a 403 on createUpdateSet through unwrapSNResponse is a rejected write", async function () {
134
+ var t = clientAnswering(403);
135
+ await expect((0, snClient_1.unwrapSNResponse)(t.client.createUpdateSet("My set", "scope1"))).rejects.toMatchObject({
136
+ response: { status: 403 },
137
+ });
138
+ expect(t.seen[0].method).toBe("POST");
139
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(authFailure_1.AUTH_EXIT_CODE);
140
+ });
141
+ it("reconcile --apply: a 403 on CREATE and on DELETE fails the record and exits 77", async function () {
142
+ var t = clientAnswering(403);
143
+ mockHolder.client = t.client;
144
+ var deleted = await (0, reconcileCommand_1.applyDeletes)("x_s", [change("delete")]);
145
+ expect(deleted).toHaveLength(1);
146
+ expect(deleted[0].ok).toBe(false);
147
+ expect(t.seen[t.seen.length - 1].url).toBe("api/cadso/dovetail_core/deleteRecord");
148
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(authFailure_1.AUTH_EXIT_CODE);
149
+ (0, authFailure_1.resetAuthFailureState)();
150
+ var created = await (0, reconcileCommand_1.applyCreates)("x_s", [change("create")], "us1");
151
+ expect(created).toHaveLength(1);
152
+ expect(created[0].ok).toBe(false);
153
+ expect(t.seen[t.seen.length - 1].url).toBe("api/cadso/dovetail_core/createRecord");
154
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(authFailure_1.AUTH_EXIT_CODE);
155
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(authFailure_1.AUTH_EXIT_CODE);
156
+ });
157
+ it("push: a 401 or 403 on updateRecord through retryOnHttpErr is still a rejected write", async function () {
158
+ var statuses = [401, 403];
159
+ for (var i = 0; i < statuses.length; i += 1) {
160
+ (0, authFailure_1.resetAuthFailureState)();
161
+ var t = clientAnswering(statuses[i]);
162
+ await expect((0, snClient_1.retryOnHttpErr)(function () {
163
+ return t.client.updateRecord("sys_script_include", "abc123", {
164
+ script: "x",
165
+ });
166
+ }, "sys_script_include > Foo")).rejects.toMatchObject({ response: { status: statuses[i] } });
167
+ expect(t.seen).toHaveLength(1);
168
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(authFailure_1.AUTH_EXIT_CODE);
169
+ }
170
+ });
171
+ it("a 403 on a GET changes nothing and prints no auth message", async function () {
172
+ var t = clientAnswering(403);
173
+ await expect((0, snClient_1.unwrapSNResponse)(t.client.getAppList())).rejects.toMatchObject({ response: { status: 403 } });
174
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(0);
175
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(1);
176
+ expect(loggedErrors()).not.toContain("Forbidden (403) calling");
177
+ });
178
+ it("a 403 on a read-only POST (getManifest, bulkDownload) is a read, not a rejected write", async function () {
179
+ var t = clientAnswering(403);
180
+ await expect(t.client.getManifest("x_s", {
181
+ sourceDirectory: "src",
182
+ buildDirectory: "build",
183
+ tableOptions: {},
184
+ refreshInterval: 30,
185
+ })).rejects.toMatchObject({
186
+ response: { status: 403 },
187
+ });
188
+ await expect(t.client.getMissingFiles({}, {})).rejects.toMatchObject({
189
+ response: { status: 403 },
190
+ });
191
+ expect(t.seen.map(function (r) {
192
+ return r.method;
193
+ })).toEqual(["POST", "POST"]);
194
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(0);
195
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(1);
196
+ });
197
+ it("a 401 on a GET re-maps only a failing exit and names the re-auth command", async function () {
198
+ var t = clientAnswering(401);
199
+ await expect((0, snClient_1.unwrapSNResponse)(t.client.getAppList())).rejects.toMatchObject({ response: { status: 401 } });
200
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(0);
201
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(authFailure_1.AUTH_EXIT_CODE);
202
+ var lines = loggedErrors();
203
+ expect(lines).toContain("Unauthorized (401) calling GET api/cadso/dovetail_sync/getAppList");
204
+ expect(lines).toContain("dove login --env loft");
205
+ expect(lines).not.toContain(SECRET);
206
+ });
207
+ it("a 401 on a write is a rejected write", async function () {
208
+ var t = clientAnswering(401);
209
+ await expect(t.client.createRecord({
210
+ table: "sys_script_include",
211
+ fields: { name: "Foo" },
212
+ })).rejects.toMatchObject({ response: { status: 401 } });
213
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(authFailure_1.AUTH_EXIT_CODE);
214
+ });
215
+ it("prints the full message once per kind, however many records are rejected", async function () {
216
+ var t = clientAnswering(403);
217
+ for (var i = 0; i < 3; i += 1) {
218
+ await expect(t.client.deleteRecord({
219
+ table: "sys_script_include",
220
+ sys_id: "abc12" + i,
221
+ })).rejects.toBeDefined();
222
+ }
223
+ var full = mockLogger.error.mock.calls.filter(function (c) {
224
+ return String(c[0]).indexOf("Forbidden (403) calling") !== -1;
225
+ });
226
+ expect(full).toHaveLength(1);
227
+ });
228
+ it("a 404 or 500 records nothing", async function () {
229
+ var statuses = [404, 500];
230
+ for (var i = 0; i < statuses.length; i += 1) {
231
+ var t = clientAnswering(statuses[i]);
232
+ await expect(t.client.updateRecord("sys_script_include", "abc123", { script: "x" })).rejects.toBeDefined();
233
+ }
234
+ expect((0, authFailure_1.resolveExitCode)(1)).toBe(1);
235
+ });
236
+ it("_noteAuthRejection never throws on a malformed error", function () {
237
+ expect(function () {
238
+ (0, snClient_1._noteAuthRejection)(undefined);
239
+ (0, snClient_1._noteAuthRejection)(new Error("boom"));
240
+ (0, snClient_1._noteAuthRejection)({ isAxiosError: true, response: { status: 403 } });
241
+ (0, snClient_1._noteAuthRejection)({
242
+ isAxiosError: true,
243
+ response: { status: 401 },
244
+ config: { method: 7, url: {} },
245
+ });
246
+ }).not.toThrow();
247
+ // No method on the 403 means it cannot be called a write.
248
+ expect((0, authFailure_1.resolveExitCode)(0)).toBe(0);
249
+ });
250
+ });