@tenonhq/dovetail-core 0.0.130 → 0.0.131
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/README.md +38 -0
- package/dist/authFailure.js +243 -0
- package/dist/bootstrap.js +4 -0
- package/dist/index.js +4 -0
- package/dist/reconcileCommand.js +1 -0
- package/dist/snClient.js +77 -5
- package/dist/tests/authExitCode.process.test.js +81 -0
- package/dist/tests/authFailure.test.js +227 -0
- package/dist/tests/retryOnHttpErr.test.js +37 -2
- package/dist/tests/snClient.authInterceptor.test.js +250 -0
- package/package.json +2 -2
- package/release-manifest.json +546 -734
package/README.md
CHANGED
|
@@ -49,6 +49,44 @@ See [`UPDATE_SET_COMMANDS.md`](UPDATE_SET_COMMANDS.md) for the full update-set C
|
|
|
49
49
|
- An in-progress set with the same name already in that scope is refused (exit 1) rather than duplicated.
|
|
50
50
|
- The set is created, not activated — the success line prints its sys_id; use `npx dove switchUpdateSet --sysId <sys_id> -s <scope>` (or `npx dove createUpdateSet`, which creates and activates in one step).
|
|
51
51
|
|
|
52
|
+
### Exit codes
|
|
53
|
+
|
|
54
|
+
| Code | Meaning |
|
|
55
|
+
| ---- | ------- |
|
|
56
|
+
| `0` | The command finished. |
|
|
57
|
+
| `1` | The command failed (any reason not listed below). |
|
|
58
|
+
| `77` | ServiceNow rejected the credentials or refused the request. A write got HTTP 401 or 403, or a failing command got HTTP 401 on a read. |
|
|
59
|
+
|
|
60
|
+
A write is any request that changes the instance, whichever command sends it: `push`,
|
|
61
|
+
`reconcile --apply` (create and delete), `create`, `delete`, `createUpdateSet`, the
|
|
62
|
+
update-set and scope switches that save a user preference, and so on. The check runs
|
|
63
|
+
on every request `dove` makes, so a new command is covered without extra wiring.
|
|
64
|
+
|
|
65
|
+
On a 401, or a 403 on a write, `dove` names the instance host, the request, and the
|
|
66
|
+
env file the credentials were loaded from. That message prints once per run, not once
|
|
67
|
+
per record. It never prints a credential. The next step depends on the status:
|
|
68
|
+
|
|
69
|
+
- **401**: the credentials were rejected. `dove` prints the command that
|
|
70
|
+
re-authenticates: `dove login`, or `dove login --env <name>` when the command ran
|
|
71
|
+
with `--env`.
|
|
72
|
+
- **403 on a write**: the sign-in worked and the instance refused the write for this
|
|
73
|
+
user. `dove` names the table when it can and says to check the role or ACL for it.
|
|
74
|
+
It does not suggest `dove login`, because signing in again as the same user changes
|
|
75
|
+
nothing.
|
|
76
|
+
|
|
77
|
+
Exit codes:
|
|
78
|
+
|
|
79
|
+
- A write that was turned away exits `77` even when the command itself reports
|
|
80
|
+
per-record results and would otherwise exit `0` (`push`) or `1` (`reconcile --apply`).
|
|
81
|
+
- A 401 on a read changes the exit code only when the command then fails: `1` becomes
|
|
82
|
+
`77`. A command that tolerated it and succeeded still exits `0`.
|
|
83
|
+
- A 403 on a read does not change the exit code, because it is usually one table's
|
|
84
|
+
ACL. The manifest and file downloads behind `refresh` count as reads.
|
|
85
|
+
- Every other exit code is unchanged.
|
|
86
|
+
|
|
87
|
+
Exit code `77` and the credential-failure message are in `@tenonhq/dovetail-core` 0.0.131
|
|
88
|
+
and later.
|
|
89
|
+
|
|
52
90
|
## Plugins
|
|
53
91
|
|
|
54
92
|
Dovetail's build pipeline is plugin-driven. Each plugin is an npm package implementing `run(context, content, options) => Promise<PluginResults>`. Shipped plugins live in sibling packages (`@tenonhq/dovetail-typescript-plugin`, `-babel-plugin`, `-webpack-plugin`, `-sass-plugin`, `-eslint-plugin`, `-prettier-plugin`, `-babel-preset-servicenow`, `-babel-plugin-remove-modules`).
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* What `dove` says and how it exits when ServiceNow rejects its credentials (#185).
|
|
4
|
+
*
|
|
5
|
+
* A 401 or 403 used to surface as a generic "verify your credentials" line and the
|
|
6
|
+
* same exit code as every other failure, so a script could not tell "the instance
|
|
7
|
+
* turned us away" from "a record failed to build". This module owns the two halves
|
|
8
|
+
* of the fix:
|
|
9
|
+
*
|
|
10
|
+
* 1. The MESSAGE — which instance, which env file the credentials came from, and
|
|
11
|
+
* the next step. For a 401: the exact command that re-authenticates
|
|
12
|
+
* (`dove login`, with `--env <name>` when one was used). For a 403 on a write:
|
|
13
|
+
* check the role or ACL for the table, since signing in again changes nothing.
|
|
14
|
+
* 2. The EXIT CODE — AUTH_EXIT_CODE, distinct from the generic 1.
|
|
15
|
+
*
|
|
16
|
+
* NEVER A CREDENTIAL. The message is built only from the instance host, the env
|
|
17
|
+
* file's PATH and the `--env` selector the user typed. Nothing is read out of the
|
|
18
|
+
* env file, and the host is reduced to a bare hostname first, so a value that
|
|
19
|
+
* carries userinfo (`user:pass@host`) cannot leak through it.
|
|
20
|
+
*
|
|
21
|
+
* No imports from the rest of core: snClient.ts must be able to use this without
|
|
22
|
+
* a circular dependency on config.ts. bootstrap.ts pushes the context in.
|
|
23
|
+
*/
|
|
24
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
25
|
+
exports.AUTH_EXIT_CODE = void 0;
|
|
26
|
+
exports.setAuthContext = setAuthContext;
|
|
27
|
+
exports.resetAuthFailureState = resetAuthFailureState;
|
|
28
|
+
exports.isAuthStatus = isAuthStatus;
|
|
29
|
+
exports.requestPath = requestPath;
|
|
30
|
+
exports.classifyAuthRejection = classifyAuthRejection;
|
|
31
|
+
exports.firstRejectionOfKind = firstRejectionOfKind;
|
|
32
|
+
exports.instanceHost = instanceHost;
|
|
33
|
+
exports.reauthCommand = reauthCommand;
|
|
34
|
+
exports.buildAuthFailureMessage = buildAuthFailureMessage;
|
|
35
|
+
exports.recordAuthFailure = recordAuthFailure;
|
|
36
|
+
exports.resolveExitCode = resolveExitCode;
|
|
37
|
+
exports.installAuthExitCode = installAuthExitCode;
|
|
38
|
+
/**
|
|
39
|
+
* Exit code for "ServiceNow rejected the credentials" (HTTP 401 or 403).
|
|
40
|
+
* 77 is EX_NOPERM in sysexits.h — "permission denied". Every other failure keeps
|
|
41
|
+
* the exit code it had (1).
|
|
42
|
+
*/
|
|
43
|
+
exports.AUTH_EXIT_CODE = 77;
|
|
44
|
+
var context = { envPath: "", envArg: "" };
|
|
45
|
+
/** A failed WRITE was rejected (forces the auth exit code, even over a clean exit). */
|
|
46
|
+
var writeRejected = false;
|
|
47
|
+
/** Any request was rejected (re-maps a generic failure exit to the auth exit code). */
|
|
48
|
+
var anyRejected = false;
|
|
49
|
+
/** Called once by bootstrap, after the env file is resolved. Values are paths/names only. */
|
|
50
|
+
function setAuthContext(next) {
|
|
51
|
+
var n = next || {};
|
|
52
|
+
context = {
|
|
53
|
+
envPath: typeof n.envPath === "string" ? n.envPath : "",
|
|
54
|
+
envArg: typeof n.envArg === "string" ? n.envArg : "",
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** Which rejection kinds already had their full message printed (see classifyAuthRejection). */
|
|
58
|
+
var announced = {};
|
|
59
|
+
/** Test seam: forget the context and every recorded failure. */
|
|
60
|
+
function resetAuthFailureState() {
|
|
61
|
+
context = { envPath: "", envArg: "" };
|
|
62
|
+
writeRejected = false;
|
|
63
|
+
anyRejected = false;
|
|
64
|
+
announced = {};
|
|
65
|
+
}
|
|
66
|
+
function isAuthStatus(status) {
|
|
67
|
+
return status === 401 || status === 403;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* POST endpoints that only READ. Everything else that is not a GET changes the
|
|
71
|
+
* instance. A 403 on one of these is treated like a 403 on a GET.
|
|
72
|
+
*/
|
|
73
|
+
var READ_ONLY_POST_ENDPOINTS = [
|
|
74
|
+
"api/cadso/dovetail_sync/getManifest",
|
|
75
|
+
"api/cadso/dovetail_sync/bulkDownload",
|
|
76
|
+
];
|
|
77
|
+
/**
|
|
78
|
+
* The request path, safe to echo: no scheme, host, userinfo, query or fragment,
|
|
79
|
+
* and only ordinary path characters. Returns "" for anything else.
|
|
80
|
+
*/
|
|
81
|
+
function requestPath(rawUrl) {
|
|
82
|
+
if (typeof rawUrl !== "string")
|
|
83
|
+
return "";
|
|
84
|
+
var path = rawUrl.trim().replace(/^[a-z][a-z0-9+.-]*:\/\/[^\/?#]*/i, "");
|
|
85
|
+
var cut = path.search(/[?#]/);
|
|
86
|
+
if (cut !== -1)
|
|
87
|
+
path = path.slice(0, cut);
|
|
88
|
+
path = path.replace(/^\/+/, "");
|
|
89
|
+
if (path.length === 0 || path.length > 200)
|
|
90
|
+
return "";
|
|
91
|
+
if (!/^[A-Za-z0-9._\/-]+$/.test(path))
|
|
92
|
+
return "";
|
|
93
|
+
return path;
|
|
94
|
+
}
|
|
95
|
+
function isReadOnlyPost(method, path) {
|
|
96
|
+
if (method !== "POST")
|
|
97
|
+
return false;
|
|
98
|
+
for (var i = 0; i < READ_ONLY_POST_ENDPOINTS.length; i += 1) {
|
|
99
|
+
var endpoint = READ_ONLY_POST_ENDPOINTS[i];
|
|
100
|
+
if (path === endpoint || path.indexOf(endpoint + "/") === 0)
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Decide what a rejected HTTP request means for the exit code. Pure.
|
|
107
|
+
*
|
|
108
|
+
* - 401 on any request: the credentials were rejected
|
|
109
|
+
* - 403 on a write (any method but GET, bar the read-only POSTs above): the
|
|
110
|
+
* instance refused the change
|
|
111
|
+
* - 403 on a read: null. It is usually one table's ACL, and callers probe and
|
|
112
|
+
* fall back, so it changes nothing
|
|
113
|
+
* - any other status: null
|
|
114
|
+
*
|
|
115
|
+
* An unknown method counts as a read, so a malformed error can never force the
|
|
116
|
+
* auth exit code on its own.
|
|
117
|
+
*/
|
|
118
|
+
function classifyAuthRejection(input) {
|
|
119
|
+
var i = input || { status: undefined, method: undefined };
|
|
120
|
+
if (!isAuthStatus(i.status))
|
|
121
|
+
return null;
|
|
122
|
+
var method = typeof i.method === "string" ? i.method.toUpperCase() : "";
|
|
123
|
+
var write = method !== "" && method !== "GET" && !isReadOnlyPost(method, requestPath(i.url));
|
|
124
|
+
if (i.status === 403 && !write)
|
|
125
|
+
return null;
|
|
126
|
+
return { status: i.status, write: write };
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* True the first time a rejection of this kind is seen in the process, so the full
|
|
130
|
+
* message prints once instead of once per record on a large push.
|
|
131
|
+
*/
|
|
132
|
+
function firstRejectionOfKind(rejection) {
|
|
133
|
+
var kind = rejection.status + (rejection.write ? ":write" : ":read");
|
|
134
|
+
if (announced[kind] === true)
|
|
135
|
+
return false;
|
|
136
|
+
announced[kind] = true;
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Reduce an SN_INSTANCE value to a bare hostname: no scheme, no userinfo, no path,
|
|
141
|
+
* no query. Returns "" for anything that is not a plain host, so the caller falls
|
|
142
|
+
* back to a neutral phrase instead of echoing an unexpected value.
|
|
143
|
+
*/
|
|
144
|
+
function instanceHost(raw) {
|
|
145
|
+
if (typeof raw !== "string")
|
|
146
|
+
return "";
|
|
147
|
+
var host = raw.trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i, "");
|
|
148
|
+
var at = host.lastIndexOf("@");
|
|
149
|
+
if (at !== -1)
|
|
150
|
+
host = host.slice(at + 1);
|
|
151
|
+
var cut = host.search(/[\/?#]/);
|
|
152
|
+
if (cut !== -1)
|
|
153
|
+
host = host.slice(0, cut);
|
|
154
|
+
if (!/^[A-Za-z0-9.-]+(:[0-9]{1,5})?$/.test(host))
|
|
155
|
+
return "";
|
|
156
|
+
return host;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* The `--env` selector, when it is safe to echo into a suggested command: a bare
|
|
160
|
+
* name or a path made of ordinary filename characters. Anything else (spaces, shell
|
|
161
|
+
* metacharacters) yields "" and the suggestion uses a placeholder instead.
|
|
162
|
+
*/
|
|
163
|
+
function echoableEnvArg(envArg) {
|
|
164
|
+
return /^[A-Za-z0-9._\/~-]+$/.test(envArg) ? envArg : "";
|
|
165
|
+
}
|
|
166
|
+
/** The command that re-authenticates this invocation's instance. */
|
|
167
|
+
function reauthCommand(envArg) {
|
|
168
|
+
var arg = typeof envArg === "string" ? envArg : context.envArg;
|
|
169
|
+
if (!arg)
|
|
170
|
+
return "dove login";
|
|
171
|
+
var safe = echoableEnvArg(arg);
|
|
172
|
+
return "dove login --env " + (safe ? safe : "<name>");
|
|
173
|
+
}
|
|
174
|
+
/** A table name safe to echo, or "". */
|
|
175
|
+
function echoableTable(table) {
|
|
176
|
+
return typeof table === "string" && /^[A-Za-z0-9_]{1,80}$/.test(table) ? table : "";
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The actionable message for a 401/403. Pure: reads the module context and its
|
|
180
|
+
* arguments, nothing else. Contains no credential.
|
|
181
|
+
*
|
|
182
|
+
* The two statuses need different remedies. A 401 means the credentials were
|
|
183
|
+
* rejected, so the fix is to sign in again. A 403 means the sign-in worked and the
|
|
184
|
+
* instance refused the write for this user: signing in again as the same user
|
|
185
|
+
* changes nothing, so the message points at the role or ACL instead.
|
|
186
|
+
*/
|
|
187
|
+
function buildAuthFailureMessage(input) {
|
|
188
|
+
var host = instanceHost(input.instance);
|
|
189
|
+
var where = host ? host : "the ServiceNow instance";
|
|
190
|
+
if (input.status === 401) {
|
|
191
|
+
var source = context.envPath
|
|
192
|
+
? "the credentials loaded from " + context.envPath
|
|
193
|
+
: "the credentials in the loaded env file";
|
|
194
|
+
return ("Unauthorized (401) " + input.action + ". " +
|
|
195
|
+
where + " rejected " + source + " — the user, password or API key is wrong or expired." +
|
|
196
|
+
" Re-authenticate with: " + reauthCommand() +
|
|
197
|
+
" — then re-run. (dove exits " + exports.AUTH_EXIT_CODE + " for a credential failure.)");
|
|
198
|
+
}
|
|
199
|
+
var table = echoableTable(input.table);
|
|
200
|
+
return ("Forbidden (403) " + input.action + ". " +
|
|
201
|
+
where + " accepted the sign-in but refused the write for this user." +
|
|
202
|
+
" Check the role or ACL for " + (table ? "table " + table : "the table") +
|
|
203
|
+
" for the user in " + (context.envPath ? context.envPath : "the loaded env file") +
|
|
204
|
+
", then re-run. (dove exits " + exports.AUTH_EXIT_CODE + " for a refused write.)");
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Record that the instance rejected a request. `write: true` is a rejected WRITE —
|
|
208
|
+
* the command did not do what it was asked, so it must not exit clean.
|
|
209
|
+
*/
|
|
210
|
+
function recordAuthFailure(opts) {
|
|
211
|
+
anyRejected = true;
|
|
212
|
+
if (opts && opts.write === true)
|
|
213
|
+
writeRejected = true;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The exit code the process should finish with, given the code it was about to use.
|
|
217
|
+
*
|
|
218
|
+
* - a rejected WRITE: 0 or 1 becomes AUTH_EXIT_CODE (a push that was turned away
|
|
219
|
+
* is not a success, even though the push command itself exits 0 after reporting)
|
|
220
|
+
* - any other rejection: only a generic failure (1) becomes AUTH_EXIT_CODE — a
|
|
221
|
+
* command that tolerated the rejection and succeeded still exits 0
|
|
222
|
+
* - every other code is left exactly as it was
|
|
223
|
+
*/
|
|
224
|
+
function resolveExitCode(code) {
|
|
225
|
+
var current = typeof code === "number" && !isNaN(code) ? code : 0;
|
|
226
|
+
if (writeRejected && (current === 0 || current === 1))
|
|
227
|
+
return exports.AUTH_EXIT_CODE;
|
|
228
|
+
if (anyRejected && current === 1)
|
|
229
|
+
return exports.AUTH_EXIT_CODE;
|
|
230
|
+
return current;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Install the process `exit` hook that applies resolveExitCode. Called only from the
|
|
234
|
+
* CLI entry point — importing dovetail-core as a library never touches exit codes.
|
|
235
|
+
*/
|
|
236
|
+
function installAuthExitCode(proc) {
|
|
237
|
+
proc.on("exit", function (code) {
|
|
238
|
+
var next = resolveExitCode(code);
|
|
239
|
+
if (next !== code) {
|
|
240
|
+
proc.exitCode = next;
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
package/dist/bootstrap.js
CHANGED
|
@@ -41,6 +41,7 @@ const dotenv_1 = __importDefault(require("dotenv"));
|
|
|
41
41
|
const ConfigManager = __importStar(require("./config"));
|
|
42
42
|
const Logger_1 = require("./Logger");
|
|
43
43
|
const envArg_1 = require("./envArg");
|
|
44
|
+
const authFailure_1 = require("./authFailure");
|
|
44
45
|
async function init() {
|
|
45
46
|
// Honor a per-command `--env <path>` override before config/env load so
|
|
46
47
|
// dotenv reads the requested file. Resolved here (not in loadConfigs) because
|
|
@@ -71,6 +72,9 @@ async function init() {
|
|
|
71
72
|
try {
|
|
72
73
|
let path = ConfigManager.getEnvPath();
|
|
73
74
|
dotenv_1.default.config({ path });
|
|
75
|
+
// Only the file's PATH and the selector the user typed — never its contents.
|
|
76
|
+
// Lets a 401/403 name the env file and the exact re-auth command (#185).
|
|
77
|
+
(0, authFailure_1.setAuthContext)({ envPath: path, envArg: envArg || "" });
|
|
74
78
|
}
|
|
75
79
|
catch (e) {
|
|
76
80
|
Logger_1.logger.error("Failed to load environment: " + String(e));
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,7 @@ exports.encodeV2Values = exports.decodeV2Values = void 0;
|
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
9
|
const bootstrap_1 = require("./bootstrap");
|
|
10
10
|
const FileLogger_1 = require("./FileLogger");
|
|
11
|
+
const authFailure_1 = require("./authFailure");
|
|
11
12
|
// Library exports — consumers can `import { decodeV2Values } from "@tenonhq/dovetail-core"`.
|
|
12
13
|
// Keep exports above the CLI entry so bundlers/TS can tree-shake and require() consumers
|
|
13
14
|
// never accidentally invoke main().
|
|
@@ -28,6 +29,9 @@ async function main() {
|
|
|
28
29
|
// Only run the CLI when this file is executed directly (e.g. `npx dove`, `node dist/index.js`).
|
|
29
30
|
// When imported as a library, require.main !== module and main() is skipped.
|
|
30
31
|
if (require.main === module) {
|
|
32
|
+
// A run the instance turned away (HTTP 401/403) exits AUTH_EXIT_CODE (77), not the
|
|
33
|
+
// generic 1 — see authFailure.ts. Every other exit code is left as it was.
|
|
34
|
+
(0, authFailure_1.installAuthExitCode)(process);
|
|
31
35
|
main().catch(function (e) {
|
|
32
36
|
FileLogger_1.fileLogger.error("Fatal error: " + String(e));
|
|
33
37
|
process.exit(1);
|
package/dist/reconcileCommand.js
CHANGED
|
@@ -53,6 +53,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
53
53
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
54
54
|
};
|
|
55
55
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
56
|
+
exports.applyDeletes = applyDeletes;
|
|
56
57
|
exports.applyCreates = applyCreates;
|
|
57
58
|
exports.reconcileCommand = reconcileCommand;
|
|
58
59
|
const path_1 = __importDefault(require("path"));
|
package/dist/snClient.js
CHANGED
|
@@ -8,6 +8,7 @@ exports.setBenchmarkSink = setBenchmarkSink;
|
|
|
8
8
|
exports._resetDovetailApiFallback = _resetDovetailApiFallback;
|
|
9
9
|
exports._isUsingLegacyPath = _isUsingLegacyPath;
|
|
10
10
|
exports._callDovetailApi = _callDovetailApi;
|
|
11
|
+
exports._noteAuthRejection = _noteAuthRejection;
|
|
11
12
|
exports.unwrapTableAPIFirstItem = unwrapTableAPIFirstItem;
|
|
12
13
|
const axios_1 = __importDefault(require("axios"));
|
|
13
14
|
const axios_cookiejar_support_1 = require("axios-cookiejar-support");
|
|
@@ -16,6 +17,7 @@ const tough_cookie_1 = require("tough-cookie");
|
|
|
16
17
|
const genericUtils_1 = require("./genericUtils");
|
|
17
18
|
const Logger_1 = require("./Logger");
|
|
18
19
|
const FileLogger_1 = require("./FileLogger");
|
|
20
|
+
const authFailure_1 = require("./authFailure");
|
|
19
21
|
// Benchmark sink. Null when --benchmark is off; zero overhead in that case.
|
|
20
22
|
let _benchmarkSink = null;
|
|
21
23
|
function setBenchmarkSink(sink) {
|
|
@@ -149,6 +151,67 @@ async function _callDovetailApi(op, call) {
|
|
|
149
151
|
throw _enrichDovetailApiError(e, endpoint);
|
|
150
152
|
}
|
|
151
153
|
}
|
|
154
|
+
// The table a request targeted: the Table API path segment, or the `table` field
|
|
155
|
+
// of a Dovetail REST body. "" when neither is present. Only used to name the table
|
|
156
|
+
// in the 403 message, which echoes it only when it is a plain table name.
|
|
157
|
+
function _requestTable(path, data) {
|
|
158
|
+
var match = /^api\/now\/table\/([A-Za-z0-9_]+)(\/|$)/.exec(path);
|
|
159
|
+
if (match)
|
|
160
|
+
return match[1];
|
|
161
|
+
var body = data;
|
|
162
|
+
if (typeof body === "string") {
|
|
163
|
+
try {
|
|
164
|
+
body = JSON.parse(body);
|
|
165
|
+
}
|
|
166
|
+
catch (_) {
|
|
167
|
+
return "";
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (body && typeof body === "object") {
|
|
171
|
+
var table = body.table;
|
|
172
|
+
if (typeof table === "string")
|
|
173
|
+
return table;
|
|
174
|
+
}
|
|
175
|
+
return "";
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* The ONE place an HTTP 401/403 is recorded (#185). Every request an snClient
|
|
179
|
+
* makes passes its response interceptor, which calls this, so `push`,
|
|
180
|
+
* `reconcile --apply`, `create-record`, `delete-record`, `createUpdateSet` and any
|
|
181
|
+
* future verb get the same message and exit code without wiring a call site.
|
|
182
|
+
*
|
|
183
|
+
* Never throws: the caller must still see the original HTTP error.
|
|
184
|
+
*/
|
|
185
|
+
function _noteAuthRejection(e) {
|
|
186
|
+
try {
|
|
187
|
+
if (!axios_1.default.isAxiosError(e) || !e.response)
|
|
188
|
+
return;
|
|
189
|
+
var config = e.config;
|
|
190
|
+
var method = config && typeof config.method === "string" ? config.method.toUpperCase() : "";
|
|
191
|
+
var url = config ? config.url : undefined;
|
|
192
|
+
var rejection = (0, authFailure_1.classifyAuthRejection)({
|
|
193
|
+
status: e.response.status,
|
|
194
|
+
method: method,
|
|
195
|
+
url: url,
|
|
196
|
+
});
|
|
197
|
+
if (!rejection)
|
|
198
|
+
return;
|
|
199
|
+
(0, authFailure_1.recordAuthFailure)({ write: rejection.write });
|
|
200
|
+
if (!(0, authFailure_1.firstRejectionOfKind)(rejection))
|
|
201
|
+
return;
|
|
202
|
+
var path = (0, authFailure_1.requestPath)(url);
|
|
203
|
+
var baseURL = config && typeof config.baseURL === "string" ? config.baseURL : "";
|
|
204
|
+
Logger_1.logger.error((0, authFailure_1.buildAuthFailureMessage)({
|
|
205
|
+
status: rejection.status,
|
|
206
|
+
action: "calling " + (method ? method + " " : "") + (path ? path : "the instance"),
|
|
207
|
+
instance: baseURL ? baseURL : process.env.SN_INSTANCE,
|
|
208
|
+
table: _requestTable(path, config ? config.data : undefined),
|
|
209
|
+
}));
|
|
210
|
+
}
|
|
211
|
+
catch (_) {
|
|
212
|
+
// Reporting must never mask the HTTP error itself.
|
|
213
|
+
}
|
|
214
|
+
}
|
|
152
215
|
function _getRetryAfterMs(e) {
|
|
153
216
|
if (axios_1.default.isAxiosError(e) && e.response && e.response.headers) {
|
|
154
217
|
var retryAfter = e.response.headers["retry-after"];
|
|
@@ -172,11 +235,16 @@ const retryOnHttpErr = async (f, recSummary) => {
|
|
|
172
235
|
catch (e) {
|
|
173
236
|
var status = _getHttpStatus(e);
|
|
174
237
|
attempt++;
|
|
175
|
-
// 401/403: Auth failure — fail immediately
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
238
|
+
// 401/403: Auth failure — fail immediately. The snClient response
|
|
239
|
+
// interceptor (_noteAuthRejection) has already recorded it and printed the
|
|
240
|
+
// instance, env file and next step once; this line names the record.
|
|
241
|
+
if ((0, authFailure_1.isAuthStatus)(status)) {
|
|
242
|
+
Logger_1.logger.error((status === 401 ? "Unauthorized (401)" : "Forbidden (403)") +
|
|
243
|
+
" pushing " + recSummary + ". " +
|
|
244
|
+
(status === 401
|
|
245
|
+
? "ServiceNow rejected the credentials."
|
|
246
|
+
: "ServiceNow refused the write for this user.") +
|
|
247
|
+
" See the message above for the instance, env file and next step.");
|
|
180
248
|
throw e;
|
|
181
249
|
}
|
|
182
250
|
// 404: Record not found — fail immediately
|
|
@@ -311,6 +379,8 @@ const snClient = (baseURL, username, password, apiKey) => {
|
|
|
311
379
|
}, function (error) {
|
|
312
380
|
// Preserve original rejection; don't record errored requests (they skew
|
|
313
381
|
// latency tails without adding signal for the "scales the same" question).
|
|
382
|
+
// A 401/403 is noted here, the one place every request passes (#185).
|
|
383
|
+
_noteAuthRejection(error);
|
|
314
384
|
return Promise.reject(error);
|
|
315
385
|
});
|
|
316
386
|
const client = (0, axios_rate_limit_1.default)(rawAxios, { maxRPS: 20 });
|
|
@@ -687,6 +757,8 @@ const unwrapSNResponse = async (clientPromise) => {
|
|
|
687
757
|
scope = manifestMatch[1];
|
|
688
758
|
Logger_1.logger.error("Error from " + instance + ": HTTP " + status + " " +
|
|
689
759
|
method + " " + url + snMessage);
|
|
760
|
+
// A 401/403 was already recorded, with its next step, by the snClient
|
|
761
|
+
// response interceptor (_noteAuthRejection).
|
|
690
762
|
FileLogger_1.fileLogger.debug("REST error detail", {
|
|
691
763
|
instance: instance,
|
|
692
764
|
scope: scope,
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The exit hook in a REAL Node process (#185).
|
|
3
|
+
//
|
|
4
|
+
// authFailure.test.ts checks installAuthExitCode against a hand-built fake `proc`,
|
|
5
|
+
// which would still pass if Node ignored an `exitCode` set inside an `exit`
|
|
6
|
+
// listener. These tests spawn `node`, install the hook on the real `process`, and
|
|
7
|
+
// assert the status the parent actually sees.
|
|
8
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
9
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
const child_process_1 = require("child_process");
|
|
13
|
+
const fs_1 = __importDefault(require("fs"));
|
|
14
|
+
const os_1 = __importDefault(require("os"));
|
|
15
|
+
const path_1 = __importDefault(require("path"));
|
|
16
|
+
const typescript_1 = __importDefault(require("typescript"));
|
|
17
|
+
var RUNNER = [
|
|
18
|
+
'"use strict";',
|
|
19
|
+
'var auth = require("./authFailure.js");',
|
|
20
|
+
"auth.installAuthExitCode(process);",
|
|
21
|
+
"var mode = process.argv[2];",
|
|
22
|
+
"var exitWith = process.argv[3];",
|
|
23
|
+
'if (mode === "write") auth.recordAuthFailure({ write: true });',
|
|
24
|
+
'if (mode === "read") auth.recordAuthFailure();',
|
|
25
|
+
'if (exitWith !== "natural") process.exit(Number(exitWith));',
|
|
26
|
+
"",
|
|
27
|
+
].join("\n");
|
|
28
|
+
describe("installAuthExitCode in a child process (#185)", function () {
|
|
29
|
+
var dir = "";
|
|
30
|
+
var runner = "";
|
|
31
|
+
beforeAll(function () {
|
|
32
|
+
dir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), "dove-auth-exit-"));
|
|
33
|
+
// authFailure.ts imports nothing, so one transpiled file is the whole module.
|
|
34
|
+
var source = fs_1.default.readFileSync(path_1.default.join(__dirname, "..", "authFailure.ts"), "utf8");
|
|
35
|
+
var compiled = typescript_1.default.transpileModule(source, {
|
|
36
|
+
compilerOptions: {
|
|
37
|
+
module: typescript_1.default.ModuleKind.CommonJS,
|
|
38
|
+
target: typescript_1.default.ScriptTarget.ES2019,
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
fs_1.default.writeFileSync(path_1.default.join(dir, "authFailure.js"), compiled.outputText);
|
|
42
|
+
runner = path_1.default.join(dir, "runner.js");
|
|
43
|
+
fs_1.default.writeFileSync(runner, RUNNER);
|
|
44
|
+
});
|
|
45
|
+
afterAll(function () {
|
|
46
|
+
if (dir)
|
|
47
|
+
fs_1.default.rmSync(dir, { recursive: true, force: true });
|
|
48
|
+
});
|
|
49
|
+
function exitStatus(mode, exitWith) {
|
|
50
|
+
var result = (0, child_process_1.spawnSync)(process.execPath, [runner, mode, exitWith], {
|
|
51
|
+
encoding: "utf8",
|
|
52
|
+
timeout: 20000,
|
|
53
|
+
});
|
|
54
|
+
if (result.error)
|
|
55
|
+
throw result.error;
|
|
56
|
+
return result.status;
|
|
57
|
+
}
|
|
58
|
+
it("a rejected write turns process.exit(0) into 77", function () {
|
|
59
|
+
expect(exitStatus("write", "0")).toBe(77);
|
|
60
|
+
});
|
|
61
|
+
it("nothing recorded leaves process.exit(0) at 0", function () {
|
|
62
|
+
expect(exitStatus("none", "0")).toBe(0);
|
|
63
|
+
});
|
|
64
|
+
it("a tolerated 401 read turns process.exit(1) into 77", function () {
|
|
65
|
+
expect(exitStatus("read", "1")).toBe(77);
|
|
66
|
+
});
|
|
67
|
+
it("a tolerated 401 read leaves a clean exit at 0", function () {
|
|
68
|
+
expect(exitStatus("read", "0")).toBe(0);
|
|
69
|
+
});
|
|
70
|
+
it("a rejected write turns process.exit(1) and a natural end into 77", function () {
|
|
71
|
+
expect(exitStatus("write", "1")).toBe(77);
|
|
72
|
+
expect(exitStatus("write", "natural")).toBe(77);
|
|
73
|
+
});
|
|
74
|
+
it("nothing recorded leaves process.exit(1) at 1", function () {
|
|
75
|
+
expect(exitStatus("none", "1")).toBe(1);
|
|
76
|
+
});
|
|
77
|
+
it("any other exit code is left alone, even after a rejected write", function () {
|
|
78
|
+
expect(exitStatus("write", "2")).toBe(2);
|
|
79
|
+
expect(exitStatus("read", "130")).toBe(130);
|
|
80
|
+
});
|
|
81
|
+
});
|