@contrail/flexplm 1.7.7 → 1.7.8-alpha.48b253c
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/util/flexplm-connect.d.ts +20 -4
- package/lib/util/flexplm-connect.js +272 -10
- package/lib/util/flexplm-connect.spec.js +537 -0
- package/package.json +1 -1
|
@@ -5,11 +5,27 @@ export declare class FlexPLMConnect {
|
|
|
5
5
|
private staticHeaders;
|
|
6
6
|
payloadSendAsArray: boolean;
|
|
7
7
|
constructor(_config: FCConfig, endPoint?: any, payloadAsArray?: any);
|
|
8
|
+
private get sessionOptions();
|
|
9
|
+
/**
|
|
10
|
+
* Waits until no cold session acquisition is running for this key.
|
|
11
|
+
* Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
|
|
12
|
+
* and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
|
|
13
|
+
*/
|
|
14
|
+
private waitForInFlightAcquisition;
|
|
15
|
+
/** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
|
|
16
|
+
private runColdAcquisition;
|
|
17
|
+
private getSessionKey;
|
|
18
|
+
/** Releases the connection of a rejected response before it is replaced by a retry. */
|
|
19
|
+
private discardBody;
|
|
20
|
+
private getCachedSession;
|
|
21
|
+
private storeSession;
|
|
22
|
+
private clearSession;
|
|
23
|
+
/** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
|
|
24
|
+
private extractSessionCookie;
|
|
25
|
+
private cookieHeader;
|
|
8
26
|
private getRequestOptions;
|
|
9
|
-
getCSRF():
|
|
10
|
-
|
|
11
|
-
nonce: any;
|
|
12
|
-
}>;
|
|
27
|
+
getCSRF(getNewSession?: boolean, rejectedCookie?: string): any;
|
|
28
|
+
private fetchCSRF;
|
|
13
29
|
sendRequest(csrf: any, payload: any): Promise<Response>;
|
|
14
30
|
protected processRequest(payload: any): Promise<FlexPLMResponseData>;
|
|
15
31
|
sendToFlexPLM(payload: PayloadType): Promise<FlexPLMResponseData>;
|
|
@@ -2,6 +2,56 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.FlexPLMConnect = void 0;
|
|
4
4
|
const app_framework_1 = require("@contrail/app-framework");
|
|
5
|
+
// Module-level on purpose: a new FlexPLMConnect is constructed for every event. Declaring for Session reusing use case.
|
|
6
|
+
const sessionCache = new Map();
|
|
7
|
+
// Upper bound so users/option combinations that are never requested again cannot accumulate cookies forever.
|
|
8
|
+
const MAX_CACHED_SESSIONS = 100;
|
|
9
|
+
const pruneSessionCache = () => {
|
|
10
|
+
const now = Date.now();
|
|
11
|
+
for (const [key, session] of sessionCache) {
|
|
12
|
+
if (session.expiresAt <= now)
|
|
13
|
+
sessionCache.delete(key);
|
|
14
|
+
}
|
|
15
|
+
// Still full: drop the oldest entries (Map keeps insertion order).
|
|
16
|
+
while (sessionCache.size >= MAX_CACHED_SESSIONS) {
|
|
17
|
+
sessionCache.delete(sessionCache.keys().next().value);
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
// In-flight cold session acquisitions per key, so concurrent events share one FlexPLM session instead of each creating their own.
|
|
21
|
+
const inFlightAcquisitions = new Map();
|
|
22
|
+
const DEFAULT_SESSION_COOKIE_NAME = 'JSESSIONID';
|
|
23
|
+
const DEFAULT_SESSION_TTL_SECONDS = 900;
|
|
24
|
+
const DEFAULT_RETRY_STATUSES = [401, 403];
|
|
25
|
+
const COOKIE_NAME_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
26
|
+
// Thrown internally when a cached cookie was rejected, so the caller can re-acquire under the lock.
|
|
27
|
+
class SessionRejectedError extends Error {
|
|
28
|
+
}
|
|
29
|
+
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
30
|
+
const parseRetryStatuses = (value) => {
|
|
31
|
+
let list = [];
|
|
32
|
+
if (Array.isArray(value))
|
|
33
|
+
list = value;
|
|
34
|
+
else if (typeof value === 'string')
|
|
35
|
+
list = value.split(',');
|
|
36
|
+
else if (value !== undefined && value !== null)
|
|
37
|
+
list = [value];
|
|
38
|
+
const statuses = list
|
|
39
|
+
.map(status => (typeof status === 'string' ? status.trim() : status))
|
|
40
|
+
.filter(status => status !== '' && status !== null && status !== undefined)
|
|
41
|
+
.map(Number)
|
|
42
|
+
// Only client-error statuses can mean "session rejected". 2xx/5xx would resend events the server already processed.
|
|
43
|
+
.filter(status => Number.isInteger(status) && status >= 400 && status <= 499);
|
|
44
|
+
return statuses.length ? statuses : DEFAULT_RETRY_STATUSES;
|
|
45
|
+
};
|
|
46
|
+
const parseTtlSeconds = (value) => {
|
|
47
|
+
const ttl = Number(value);
|
|
48
|
+
return Number.isFinite(ttl) && ttl > 0 ? ttl : DEFAULT_SESSION_TTL_SECONDS;
|
|
49
|
+
};
|
|
50
|
+
const parseCookieName = (value) => {
|
|
51
|
+
const name = typeof value === 'string' ? value.trim() : '';
|
|
52
|
+
return COOKIE_NAME_TOKEN.test(name) ? name : DEFAULT_SESSION_COOKIE_NAME;
|
|
53
|
+
};
|
|
54
|
+
// Added for Session reuse - ET-390 - Ends
|
|
5
55
|
class FlexPLMConnect {
|
|
6
56
|
constructor(_config, endPoint = undefined, payloadAsArray = undefined) {
|
|
7
57
|
this.vibeEventEndpoint = '';
|
|
@@ -19,9 +69,124 @@ class FlexPLMConnect {
|
|
|
19
69
|
}
|
|
20
70
|
}
|
|
21
71
|
/////////////////////////////////////////////////////////////////////////////
|
|
72
|
+
///////// ET-390 - Session reuse: start
|
|
73
|
+
/////////////////////////////////////////////////////////////////////////////
|
|
74
|
+
get sessionOptions() {
|
|
75
|
+
const sessReuse = this.config?.flexplmConnect?.sessionReuse;
|
|
76
|
+
const enabled = sessReuse?.enabled;
|
|
77
|
+
return {
|
|
78
|
+
enabled: enabled === true || String(enabled).toLowerCase() === 'true',
|
|
79
|
+
ttlMs: parseTtlSeconds(sessReuse?.ttlSeconds) * 1000,
|
|
80
|
+
cookieName: parseCookieName(sessReuse?.cookieName),
|
|
81
|
+
retryStatuses: parseRetryStatuses(sessReuse?.retryStatuses),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Waits until no cold session acquisition is running for this key.
|
|
86
|
+
* Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
|
|
87
|
+
* and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
|
|
88
|
+
*/
|
|
89
|
+
waitForInFlightAcquisition() {
|
|
90
|
+
const key = this.getSessionKey();
|
|
91
|
+
if (!inFlightAcquisitions.has(key))
|
|
92
|
+
return undefined;
|
|
93
|
+
return (async () => {
|
|
94
|
+
let pending = inFlightAcquisitions.get(key);
|
|
95
|
+
while (pending) {
|
|
96
|
+
await pending.catch(() => undefined);
|
|
97
|
+
pending = inFlightAcquisitions.get(key);
|
|
98
|
+
}
|
|
99
|
+
})();
|
|
100
|
+
}
|
|
101
|
+
/** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
|
|
102
|
+
async runColdAcquisition(acquire) {
|
|
103
|
+
const key = this.getSessionKey();
|
|
104
|
+
const acquisition = acquire();
|
|
105
|
+
inFlightAcquisitions.set(key, acquisition);
|
|
106
|
+
try {
|
|
107
|
+
return await acquisition;
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
if (inFlightAcquisitions.get(key) === acquisition)
|
|
111
|
+
inFlightAcquisitions.delete(key);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
getSessionKey() {
|
|
115
|
+
// Options that change the cached value are part of the key; JSON avoids '|' collisions between fields.
|
|
116
|
+
const { cookieName, ttlMs } = this.sessionOptions;
|
|
117
|
+
return JSON.stringify([
|
|
118
|
+
this.config.apiHost, this.config.urlContext, this.config.userName(), this.config.plmEnviornment, cookieName, ttlMs,
|
|
119
|
+
]);
|
|
120
|
+
}
|
|
121
|
+
/** Releases the connection of a rejected response before it is replaced by a retry. */
|
|
122
|
+
async discardBody(response) {
|
|
123
|
+
try {
|
|
124
|
+
if (typeof response?.body?.cancel === 'function')
|
|
125
|
+
await response.body.cancel();
|
|
126
|
+
}
|
|
127
|
+
catch (e) {
|
|
128
|
+
// best effort: nothing to do if the body is already consumed or locked
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
getCachedSession() {
|
|
132
|
+
if (!this.sessionOptions.enabled)
|
|
133
|
+
return undefined;
|
|
134
|
+
const key = this.getSessionKey();
|
|
135
|
+
const cachedSessValue = sessionCache.get(key);
|
|
136
|
+
if (!cachedSessValue)
|
|
137
|
+
return undefined;
|
|
138
|
+
if (cachedSessValue.expiresAt <= Date.now()) {
|
|
139
|
+
sessionCache.delete(key);
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
return cachedSessValue.cookie;
|
|
143
|
+
}
|
|
144
|
+
storeSession(cookie) {
|
|
145
|
+
// sliding expiry: Windchill's session timeout is also sliding
|
|
146
|
+
const key = this.getSessionKey();
|
|
147
|
+
// delete first so a refreshed entry moves to the newest position (oldest-first eviction then acts as LRU)
|
|
148
|
+
sessionCache.delete(key);
|
|
149
|
+
pruneSessionCache();
|
|
150
|
+
sessionCache.set(key, { cookie, expiresAt: Date.now() + this.sessionOptions.ttlMs });
|
|
151
|
+
}
|
|
152
|
+
clearSession() {
|
|
153
|
+
sessionCache.delete(this.getSessionKey());
|
|
154
|
+
}
|
|
155
|
+
/** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
|
|
156
|
+
extractSessionCookie(response) {
|
|
157
|
+
const respHeader = response?.headers;
|
|
158
|
+
if (!respHeader)
|
|
159
|
+
return undefined;
|
|
160
|
+
let raw = [];
|
|
161
|
+
if (typeof respHeader.getSetCookie === 'function') {
|
|
162
|
+
raw = respHeader.getSetCookie();
|
|
163
|
+
}
|
|
164
|
+
else if (typeof respHeader.get === 'function' && respHeader.get('set-cookie')) {
|
|
165
|
+
raw = [respHeader.get('set-cookie')];
|
|
166
|
+
}
|
|
167
|
+
const name = this.sessionOptions.cookieName;
|
|
168
|
+
const regexFilter = new RegExp('(?:^|[,\\s])' + escapeRegExp(name) + '=([^;,\\s]+)', 'g');
|
|
169
|
+
let jSession;
|
|
170
|
+
for (const line of raw) {
|
|
171
|
+
let cookieNameMatcher = regexFilter.exec(line);
|
|
172
|
+
while (cookieNameMatcher !== null) {
|
|
173
|
+
jSession = cookieNameMatcher[1];
|
|
174
|
+
cookieNameMatcher = regexFilter.exec(line);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return jSession;
|
|
178
|
+
}
|
|
179
|
+
cookieHeader(sessionCookie) {
|
|
180
|
+
return sessionCookie ? `${this.sessionOptions.cookieName}=${sessionCookie}` : undefined;
|
|
181
|
+
}
|
|
182
|
+
/////////////////////////////////////////////////////////////////////////////
|
|
183
|
+
///////// ET-390 - Session reuse: end
|
|
184
|
+
/////////////////////////////////////////////////////////////////////////////
|
|
185
|
+
/////////////////////////////////////////////////////////////////////////////
|
|
22
186
|
///////// Custom getRequestOptions: start
|
|
23
187
|
/////////////////////////////////////////////////////////////////////////////
|
|
24
|
-
getRequestOptions
|
|
188
|
+
// ET-390 - adding a new parameter sessionCookie to the getRequestOptions function
|
|
189
|
+
getRequestOptions(method, sessionCookie) {
|
|
25
190
|
const csrfOptions = {
|
|
26
191
|
method,
|
|
27
192
|
headers: {
|
|
@@ -33,9 +198,19 @@ class FlexPLMConnect {
|
|
|
33
198
|
if (this.staticHeaders) {
|
|
34
199
|
Object.assign(csrfOptions.headers, this.staticHeaders);
|
|
35
200
|
}
|
|
201
|
+
// Added for Session reuse - ET-390 - Starts
|
|
202
|
+
const cookie = this.cookieHeader(sessionCookie);
|
|
203
|
+
if (cookie) {
|
|
204
|
+
csrfOptions.headers['Cookie'] = cookie;
|
|
205
|
+
}
|
|
206
|
+
// Added for Session reuse - ET-390 - Ends
|
|
36
207
|
if (app_framework_1.Logger.isInfoOn()) {
|
|
37
208
|
const logOptions = JSON.parse(JSON.stringify(csrfOptions));
|
|
38
209
|
logOptions['headers']['Authorization'] = logOptions?.headers?.Authorization.substring(0, 9);
|
|
210
|
+
// Added for Session reuse - ET-390 - Starts
|
|
211
|
+
if (logOptions.headers['Cookie'])
|
|
212
|
+
logOptions.headers['Cookie'] = '***masked***';
|
|
213
|
+
// Added for Session reuse - ET-390 - Ends
|
|
39
214
|
console.info('csrfOptions: ' + JSON.stringify(logOptions));
|
|
40
215
|
}
|
|
41
216
|
return csrfOptions;
|
|
@@ -43,13 +218,52 @@ class FlexPLMConnect {
|
|
|
43
218
|
/////////////////////////////////////////////////////////////////////////////
|
|
44
219
|
///////// Custom getRequestOptions: end
|
|
45
220
|
/////////////////////////////////////////////////////////////////////////////
|
|
46
|
-
|
|
221
|
+
// ET-390 - adding a new parameter getNewSession to the getCSRF function
|
|
222
|
+
// Whenever a getCSRF is called without getNewSession, the default value of false will be used
|
|
223
|
+
// rejectedCookie: the cookie that was rejected by the caller, so a refresh already done by a concurrent event is not thrown away
|
|
224
|
+
async getCSRF(getNewSession = false, rejectedCookie) {
|
|
225
|
+
// Added for Session reuse - ET-390 - Starts
|
|
226
|
+
if (!this.sessionOptions.enabled)
|
|
227
|
+
return this.fetchCSRF(undefined);
|
|
228
|
+
for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
|
|
229
|
+
await wait;
|
|
230
|
+
if (getNewSession) {
|
|
231
|
+
const current = this.getCachedSession();
|
|
232
|
+
if (rejectedCookie === undefined || !current || current === rejectedCookie)
|
|
233
|
+
this.clearSession();
|
|
234
|
+
}
|
|
235
|
+
const cached = this.getCachedSession();
|
|
236
|
+
if (cached) {
|
|
237
|
+
try {
|
|
238
|
+
return await this.fetchCSRF(cached);
|
|
239
|
+
}
|
|
240
|
+
catch (e) {
|
|
241
|
+
if (!(e instanceof SessionRejectedError))
|
|
242
|
+
throw e;
|
|
243
|
+
// if the cached cookie is rejected (401/403), drop it and acquire a new session (serialized)
|
|
244
|
+
if (this.getCachedSession() === cached)
|
|
245
|
+
this.clearSession();
|
|
246
|
+
return this.getCSRF();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return this.runColdAcquisition(() => this.fetchCSRF(undefined));
|
|
250
|
+
// Added for Session reuse - ET-390 - Ends
|
|
251
|
+
}
|
|
252
|
+
async fetchCSRF(sentCookie) {
|
|
47
253
|
const urlContext = this.config.urlContext;
|
|
48
254
|
const csrfEndpoint = this.config.csrfEndpoint;
|
|
49
255
|
const csrfURL = this.config.apiHost + urlContext + csrfEndpoint;
|
|
50
256
|
console.info('csrfURL: ' + csrfURL);
|
|
51
|
-
|
|
257
|
+
// getRequestOptions will be called with additional sentCookie parameter
|
|
258
|
+
const csrfOptions = this.getRequestOptions('GET', sentCookie);
|
|
52
259
|
const response = await fetch(csrfURL, csrfOptions);
|
|
260
|
+
// Added for Session reuse - ET-390 - Starts
|
|
261
|
+
if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
|
|
262
|
+
console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
|
|
263
|
+
await this.discardBody(response);
|
|
264
|
+
throw new SessionRejectedError();
|
|
265
|
+
}
|
|
266
|
+
// Added for Session reuse - ET-390 - Ends
|
|
53
267
|
if (response.status >= 300) {
|
|
54
268
|
const message = 'Error connecting to FlexPLM:status: ' + response.status;
|
|
55
269
|
console.error(message);
|
|
@@ -58,14 +272,24 @@ class FlexPLMConnect {
|
|
|
58
272
|
e['httpResponseStatus'] = response.status;
|
|
59
273
|
throw e;
|
|
60
274
|
}
|
|
275
|
+
// Added for Session reuse - ET-390 - Starts
|
|
276
|
+
// If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
|
|
277
|
+
let sessionCookie = sentCookie;
|
|
278
|
+
if (this.sessionOptions.enabled) {
|
|
279
|
+
sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
|
|
280
|
+
if (sessionCookie)
|
|
281
|
+
this.storeSession(sessionCookie);
|
|
282
|
+
}
|
|
283
|
+
// Added for Session reuse - ET-390 - Ends
|
|
61
284
|
try {
|
|
62
285
|
const body = await response.json();
|
|
63
286
|
const nonce_key = body.items[0].attributes.nonce_key;
|
|
64
287
|
const nonce = body.items[0].attributes.nonce;
|
|
65
|
-
|
|
288
|
+
// ET-390 - adding sessionCookie to the return
|
|
66
289
|
return {
|
|
67
290
|
nonce_key,
|
|
68
|
-
nonce
|
|
291
|
+
nonce,
|
|
292
|
+
sessionCookie,
|
|
69
293
|
};
|
|
70
294
|
}
|
|
71
295
|
catch (e) {
|
|
@@ -79,7 +303,7 @@ class FlexPLMConnect {
|
|
|
79
303
|
if (this.payloadSendAsArray && !Array.isArray(payload)) {
|
|
80
304
|
payload = [payload];
|
|
81
305
|
}
|
|
82
|
-
const xferOptions = this.getRequestOptions('POST');
|
|
306
|
+
const xferOptions = this.getRequestOptions('POST', csrf?.sessionCookie);
|
|
83
307
|
xferOptions['body'] = JSON.stringify(payload);
|
|
84
308
|
xferOptions.headers[csrf.nonce_key] = csrf.nonce;
|
|
85
309
|
const urlContext = this.config.urlContext;
|
|
@@ -90,6 +314,8 @@ class FlexPLMConnect {
|
|
|
90
314
|
const logOptions = JSON.parse(JSON.stringify(xferOptions));
|
|
91
315
|
if (logOptions?.headers?.Authorization)
|
|
92
316
|
logOptions.headers.Authorization = logOptions?.headers?.Authorization.substring(0, 9);
|
|
317
|
+
if (logOptions?.headers?.Cookie)
|
|
318
|
+
logOptions.headers.Cookie = '***masked***';
|
|
93
319
|
if (csrf?.nonce_key)
|
|
94
320
|
logOptions.headers[csrf.nonce_key] = csrf.nonce ? `***masked(length:${csrf.nonce.length})***` : '***masked(empty)***';
|
|
95
321
|
console.info('csrfOptions: ' + JSON.stringify(logOptions));
|
|
@@ -107,13 +333,22 @@ class FlexPLMConnect {
|
|
|
107
333
|
if (app_framework_1.Logger.isInfoOn()) {
|
|
108
334
|
console.info('payload: ' + JSON.stringify(payload));
|
|
109
335
|
}
|
|
110
|
-
|
|
336
|
+
let csrf = await this.getCSRF();
|
|
111
337
|
if (!csrf) {
|
|
112
338
|
const message = 'Failed to get CSRF nonce';
|
|
113
339
|
console.error(message);
|
|
114
340
|
throw new Error(message);
|
|
115
341
|
}
|
|
116
|
-
|
|
342
|
+
/// Added for Session reuse - ET-390 - Starts
|
|
343
|
+
// const response = await this.sendRequest(csrf, payload);
|
|
344
|
+
let response = await this.sendRequest(csrf, payload);
|
|
345
|
+
if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
|
|
346
|
+
console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
|
|
347
|
+
await this.discardBody(response);
|
|
348
|
+
csrf = await this.getCSRF(true, csrf.sessionCookie);
|
|
349
|
+
response = await this.sendRequest(csrf, payload);
|
|
350
|
+
}
|
|
351
|
+
// Added for Session reuse - ET-390 - Ends
|
|
117
352
|
const status = response.status;
|
|
118
353
|
if (status >= 300) {
|
|
119
354
|
const message = 'Error sending data to FlexPLM:status: ' + response.status;
|
|
@@ -166,8 +401,35 @@ class FlexPLMConnect {
|
|
|
166
401
|
const urlContext = includeUrlContext ? this.config.urlContext : '';
|
|
167
402
|
const path = urlPath || ('/servlet/rest' + this.vibeEventEndpoint);
|
|
168
403
|
const vibeEventsURL = this.config.apiHost + urlContext + path;
|
|
169
|
-
|
|
170
|
-
const
|
|
404
|
+
// Added for Session reuse - ET-390 - Starts
|
|
405
|
+
const attempt = async () => {
|
|
406
|
+
if (!this.sessionOptions.enabled) {
|
|
407
|
+
return { response: await fetch(vibeEventsURL, this.getRequestOptions('GET')), sent: undefined };
|
|
408
|
+
}
|
|
409
|
+
for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
|
|
410
|
+
await wait;
|
|
411
|
+
const sent = this.getCachedSession();
|
|
412
|
+
const call = async () => {
|
|
413
|
+
const res = await fetch(vibeEventsURL, this.getRequestOptions('GET', sent));
|
|
414
|
+
// A rejected cookie must not be stored again; only keep a cookie that was accepted or newly issued.
|
|
415
|
+
if (!(sent && this.sessionOptions.retryStatuses.includes(res.status))) {
|
|
416
|
+
const cookie = this.extractSessionCookie(res) ?? sent;
|
|
417
|
+
if (cookie)
|
|
418
|
+
this.storeSession(cookie);
|
|
419
|
+
}
|
|
420
|
+
return { response: res, sent };
|
|
421
|
+
};
|
|
422
|
+
return sent ? call() : this.runColdAcquisition(call);
|
|
423
|
+
};
|
|
424
|
+
const first = await attempt();
|
|
425
|
+
let response = first.response;
|
|
426
|
+
if (first.sent && this.sessionOptions.retryStatuses.includes(response.status)) {
|
|
427
|
+
await this.discardBody(response);
|
|
428
|
+
if (this.getCachedSession() === first.sent)
|
|
429
|
+
this.clearSession();
|
|
430
|
+
response = (await attempt()).response;
|
|
431
|
+
}
|
|
432
|
+
// Added for Session reuse - ET-390 - Ends
|
|
171
433
|
if (response.status >= 300) {
|
|
172
434
|
const message = 'Error connecting to FlexPLM:status: ' + response.status;
|
|
173
435
|
console.error(message);
|
|
@@ -28,6 +28,23 @@ const createConfig = (overrides) => ({
|
|
|
28
28
|
useDistinctRestEndPointForImages: false,
|
|
29
29
|
...overrides,
|
|
30
30
|
});
|
|
31
|
+
// Added for Session reuse - ET-390 - Starts
|
|
32
|
+
const csrfBody = { items: [{ attributes: { nonce_key: 'CSRF_NONCE', nonce: 'n1' } }] };
|
|
33
|
+
// Response with Set-Cookie support. setCookie = list of raw Set-Cookie header lines.
|
|
34
|
+
const resp = (status, setCookie = [], json = csrfBody) => ({
|
|
35
|
+
status,
|
|
36
|
+
json: jest.fn().mockResolvedValue(json),
|
|
37
|
+
text: jest.fn().mockResolvedValue('error text'),
|
|
38
|
+
headers: { getSetCookie: () => setCookie, get: () => null },
|
|
39
|
+
});
|
|
40
|
+
let userCounter = 0;
|
|
41
|
+
const uniqueUser = () => 'sess-user-' + (++userCounter);
|
|
42
|
+
// The connector config nests the entries: { flexplmConnect: { sessionReuse: { enabled: true, ... } } }
|
|
43
|
+
const sessionConfig = (user, sessionReuse = { enabled: true }) => createConfig({ userName: () => user, flexplmConnect: { sessionReuse } });
|
|
44
|
+
const fetchMock = () => global.fetch;
|
|
45
|
+
const callHeaders = (i) => fetchMock().mock.calls[i][1].headers;
|
|
46
|
+
const callMethod = (i) => fetchMock().mock.calls[i][1].method;
|
|
47
|
+
// Added for Session reuse - ET-390 - Ends
|
|
31
48
|
describe('FlexPLMConnect.getRequest', () => {
|
|
32
49
|
it('should call default URL with urlContext when no params provided', async () => {
|
|
33
50
|
const connect = new flexplm_connect_1.FlexPLMConnect(createConfig());
|
|
@@ -121,3 +138,523 @@ describe('FlexPLMConnect.sendRequest', () => {
|
|
|
121
138
|
consoleInfoSpy.mockRestore();
|
|
122
139
|
});
|
|
123
140
|
});
|
|
141
|
+
// Added for Session reuse - ET-390 - Starts
|
|
142
|
+
describe('FlexPLMConnect session reuse', () => {
|
|
143
|
+
const payload = { id: '123' };
|
|
144
|
+
it('should capture JSESSIONID from the CSRF GET and send it on the POST', async () => {
|
|
145
|
+
const u = uniqueUser();
|
|
146
|
+
fetchMock()
|
|
147
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/; HttpOnly']))
|
|
148
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
149
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
150
|
+
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
151
|
+
expect(callHeaders(0).Cookie).toBeUndefined(); // first ever call: no cached session
|
|
152
|
+
expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
153
|
+
expect(callHeaders(1).CSRF_NONCE).toBe('n1');
|
|
154
|
+
});
|
|
155
|
+
it('should reuse the cached session on the next event (new FlexPLMConnect instance)', async () => {
|
|
156
|
+
const u = uniqueUser();
|
|
157
|
+
fetchMock()
|
|
158
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/'])) // event 1 GET
|
|
159
|
+
.mockResolvedValueOnce(resp(200, [], {})) // event 1 POST
|
|
160
|
+
.mockResolvedValueOnce(resp(200, [])) // event 2 GET (valid session -> no Set-Cookie)
|
|
161
|
+
.mockResolvedValueOnce(resp(200, [], {})); // event 2 POST
|
|
162
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
163
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
164
|
+
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1'); // GET reuses it
|
|
165
|
+
expect(callHeaders(3).Cookie).toBe('JSESSIONID=abc.tomcat1'); // POST reuses it
|
|
166
|
+
});
|
|
167
|
+
it('should replace the cached session when Windchill answers the GET with a new Set-Cookie', async () => {
|
|
168
|
+
const u = uniqueUser();
|
|
169
|
+
fetchMock()
|
|
170
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1; Path=/']))
|
|
171
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
172
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1; Path=/'])) // old one was stale -> new issued
|
|
173
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
174
|
+
.mockResolvedValueOnce(resp(200, []))
|
|
175
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
176
|
+
const connect = () => new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
177
|
+
await connect().sendToFlexPLM(payload);
|
|
178
|
+
await connect().sendToFlexPLM(payload);
|
|
179
|
+
await connect().sendToFlexPLM(payload);
|
|
180
|
+
expect(callHeaders(2).Cookie).toBe('JSESSIONID=old.tomcat1'); // event 2 GET sent the old one
|
|
181
|
+
expect(callHeaders(3).Cookie).toBe('JSESSIONID=new.tomcat1'); // POST uses the replacement
|
|
182
|
+
expect(callHeaders(4).Cookie).toBe('JSESSIONID=new.tomcat1'); // event 3 GET sends the replacement
|
|
183
|
+
});
|
|
184
|
+
it('should retry once with a new session when the POST is rejected with 403', async () => {
|
|
185
|
+
const u = uniqueUser();
|
|
186
|
+
fetchMock()
|
|
187
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1; Path=/'])) // GET
|
|
188
|
+
.mockResolvedValueOnce(resp(403, [], {})) // POST rejected
|
|
189
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1; Path=/'])) // GET again, fresh session
|
|
190
|
+
.mockResolvedValueOnce(resp(200, [], { ok: true })); // POST succeeds
|
|
191
|
+
const result = await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
192
|
+
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
193
|
+
expect(callHeaders(2).Cookie).toBeUndefined(); // retry GET must NOT send the stale cookie
|
|
194
|
+
expect(callHeaders(3).Cookie).toBe('JSESSIONID=new.tomcat1');
|
|
195
|
+
expect(result.status).toBe(200);
|
|
196
|
+
expect(result.data).toEqual({ ok: true });
|
|
197
|
+
});
|
|
198
|
+
it('should also retry on 401', async () => {
|
|
199
|
+
const u = uniqueUser();
|
|
200
|
+
fetchMock()
|
|
201
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
202
|
+
.mockResolvedValueOnce(resp(401, [], {}))
|
|
203
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
204
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
205
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
206
|
+
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
207
|
+
});
|
|
208
|
+
it('should not loop: a second 403 after the retry is surfaced as an error', async () => {
|
|
209
|
+
const u = uniqueUser();
|
|
210
|
+
fetchMock()
|
|
211
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
212
|
+
.mockResolvedValueOnce(resp(403, [], {}))
|
|
213
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
214
|
+
.mockResolvedValueOnce(resp(403, [], {}));
|
|
215
|
+
await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload))
|
|
216
|
+
.rejects.toThrow('Error sending data to FlexPLM:status: 403');
|
|
217
|
+
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
218
|
+
});
|
|
219
|
+
it('should not retry on non-auth errors such as 500 (event may already be processed)', async () => {
|
|
220
|
+
const u = uniqueUser();
|
|
221
|
+
fetchMock()
|
|
222
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
223
|
+
.mockResolvedValueOnce(resp(500, [], {}));
|
|
224
|
+
await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload))
|
|
225
|
+
.rejects.toThrow('Error sending data to FlexPLM:status: 500');
|
|
226
|
+
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
227
|
+
});
|
|
228
|
+
it('should retry the csrf GET without a cookie when the cached session is rejected there', async () => {
|
|
229
|
+
const u = uniqueUser();
|
|
230
|
+
fetchMock()
|
|
231
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1'])) // event 1 GET
|
|
232
|
+
.mockResolvedValueOnce(resp(200, [], {})) // event 1 POST
|
|
233
|
+
.mockResolvedValueOnce(resp(401, [])) // event 2 GET with cached cookie rejected
|
|
234
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1'])) // event 2 GET retry, no cookie
|
|
235
|
+
.mockResolvedValueOnce(resp(200, [], {})); // event 2 POST
|
|
236
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
237
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
238
|
+
expect(callHeaders(2).Cookie).toBe('JSESSIONID=old.tomcat1');
|
|
239
|
+
expect(callHeaders(3).Cookie).toBeUndefined();
|
|
240
|
+
expect(callHeaders(4).Cookie).toBe('JSESSIONID=new.tomcat1');
|
|
241
|
+
});
|
|
242
|
+
it('should expire the cached session after ttlSeconds', async () => {
|
|
243
|
+
const u = uniqueUser();
|
|
244
|
+
const realNow = Date.now();
|
|
245
|
+
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow);
|
|
246
|
+
fetchMock()
|
|
247
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
248
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
249
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=def.tomcat1']))
|
|
250
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
251
|
+
const cfg = sessionConfig(u, { enabled: true, ttlSeconds: 1 });
|
|
252
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
253
|
+
nowSpy.mockReturnValue(realNow + 2000); // 2s later > 1s ttl
|
|
254
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
255
|
+
expect(callHeaders(2).Cookie).toBeUndefined(); // expired -> GET sends no cookie
|
|
256
|
+
expect(callHeaders(3).Cookie).toBe('JSESSIONID=def.tomcat1');
|
|
257
|
+
nowSpy.mockRestore();
|
|
258
|
+
});
|
|
259
|
+
it('should use the last JSESSIONID when several Set-Cookie lines are returned', async () => {
|
|
260
|
+
const u = uniqueUser();
|
|
261
|
+
fetchMock()
|
|
262
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=first.tomcat1; Path=/', 'OTHER=x; Path=/', 'JSESSIONID=second.tomcat1; Path=/']))
|
|
263
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
264
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
265
|
+
expect(callHeaders(1).Cookie).toBe('JSESSIONID=second.tomcat1');
|
|
266
|
+
});
|
|
267
|
+
it('should fall back to headers.get("set-cookie") when getSetCookie is not available', async () => {
|
|
268
|
+
const u = uniqueUser();
|
|
269
|
+
const legacy = {
|
|
270
|
+
status: 200,
|
|
271
|
+
json: jest.fn().mockResolvedValue(csrfBody),
|
|
272
|
+
text: jest.fn(),
|
|
273
|
+
headers: { get: (k) => (k.toLowerCase() === 'set-cookie' ? 'JSESSIONID=legacy.tomcat1; Path=/' : null) },
|
|
274
|
+
};
|
|
275
|
+
fetchMock().mockResolvedValueOnce(legacy).mockResolvedValueOnce(resp(200, [], {}));
|
|
276
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
277
|
+
expect(callHeaders(1).Cookie).toBe('JSESSIONID=legacy.tomcat1');
|
|
278
|
+
});
|
|
279
|
+
it('should honour a custom cookieName', async () => {
|
|
280
|
+
const u = uniqueUser();
|
|
281
|
+
fetchMock()
|
|
282
|
+
.mockResolvedValueOnce(resp(200, ['MYSESSION=zzz; Path=/', 'JSESSIONID=ignored; Path=/']))
|
|
283
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
284
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'MYSESSION' })).sendToFlexPLM(payload);
|
|
285
|
+
expect(callHeaders(1).Cookie).toBe('MYSESSION=zzz');
|
|
286
|
+
});
|
|
287
|
+
it('should accept enabled as the string "true"', async () => {
|
|
288
|
+
const u = uniqueUser();
|
|
289
|
+
fetchMock()
|
|
290
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
291
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
292
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: 'true' })).sendToFlexPLM(payload);
|
|
293
|
+
expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
294
|
+
});
|
|
295
|
+
it('should evict expired sessions of other users when a new session is stored', async () => {
|
|
296
|
+
const userA = uniqueUser();
|
|
297
|
+
const userB = uniqueUser();
|
|
298
|
+
const realNow = Date.now();
|
|
299
|
+
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow);
|
|
300
|
+
fetchMock()
|
|
301
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=a.tomcat1'])) // A GET
|
|
302
|
+
.mockResolvedValueOnce(resp(200, [], {})) // A POST
|
|
303
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=b.tomcat1'])) // B GET
|
|
304
|
+
.mockResolvedValueOnce(resp(200, [], {})) // B POST
|
|
305
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=a2.tomcat1'])) // A GET again
|
|
306
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
307
|
+
const cfg = (u) => sessionConfig(u, { enabled: true, ttlSeconds: 1 });
|
|
308
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg(userA)).sendToFlexPLM(payload);
|
|
309
|
+
nowSpy.mockReturnValue(realNow + 2000); // A has expired
|
|
310
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg(userB)).sendToFlexPLM(payload); // storing B sweeps A
|
|
311
|
+
nowSpy.mockReturnValue(realNow); // rewind: only a swept A has no entry left
|
|
312
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg(userA)).sendToFlexPLM(payload);
|
|
313
|
+
expect(callHeaders(4).Cookie).toBeUndefined();
|
|
314
|
+
nowSpy.mockRestore();
|
|
315
|
+
});
|
|
316
|
+
it('should not hold more than the maximum number of cached sessions', async () => {
|
|
317
|
+
const first = uniqueUser();
|
|
318
|
+
fetchMock().mockImplementation(async () => resp(200, ['JSESSIONID=s.tomcat1']));
|
|
319
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(first)).sendToFlexPLM(payload);
|
|
320
|
+
for (let i = 0; i < 100; i++) {
|
|
321
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(uniqueUser())).sendToFlexPLM(payload);
|
|
322
|
+
}
|
|
323
|
+
fetchMock().mockClear();
|
|
324
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(first)).sendToFlexPLM(payload);
|
|
325
|
+
expect(callHeaders(0).Cookie).toBeUndefined(); // oldest entry was evicted
|
|
326
|
+
});
|
|
327
|
+
it('should keep separate sessions per user', async () => {
|
|
328
|
+
const a = uniqueUser();
|
|
329
|
+
const b = uniqueUser();
|
|
330
|
+
fetchMock()
|
|
331
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=aaa.tomcat1']))
|
|
332
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
333
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=bbb.tomcat1']))
|
|
334
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
335
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(a)).sendToFlexPLM(payload);
|
|
336
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(b)).sendToFlexPLM(payload);
|
|
337
|
+
expect(callHeaders(2).Cookie).toBeUndefined(); // user b must not see user a's cookie
|
|
338
|
+
expect(callHeaders(3).Cookie).toBe('JSESSIONID=bbb.tomcat1');
|
|
339
|
+
});
|
|
340
|
+
it('should never log the cookie value', async () => {
|
|
341
|
+
const isInfoOn = jest.spyOn(app_framework_1.Logger, 'isInfoOn').mockReturnValue(true);
|
|
342
|
+
const info = jest.spyOn(console, 'info').mockImplementation();
|
|
343
|
+
const u = uniqueUser();
|
|
344
|
+
fetchMock()
|
|
345
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=supersecret.tomcat1']))
|
|
346
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
347
|
+
.mockResolvedValueOnce(resp(200, []))
|
|
348
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
349
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
|
|
350
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload); // 2nd event sends Cookie on GET and POST
|
|
351
|
+
const logged = info.mock.calls.map(c => String(c[0] ?? '')).join('\n');
|
|
352
|
+
expect(logged).toContain('"Cookie":"***masked***"');
|
|
353
|
+
expect(logged).not.toContain('supersecret');
|
|
354
|
+
isInfoOn.mockRestore();
|
|
355
|
+
info.mockRestore();
|
|
356
|
+
});
|
|
357
|
+
describe('option normalisation', () => {
|
|
358
|
+
const rejectedOnceThenOk = (u, opts) => {
|
|
359
|
+
fetchMock()
|
|
360
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
361
|
+
.mockResolvedValueOnce(resp(403, [], {}))
|
|
362
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
363
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
364
|
+
return new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, ...opts })).sendToFlexPLM(payload);
|
|
365
|
+
};
|
|
366
|
+
it.each([
|
|
367
|
+
['a scalar number', 403],
|
|
368
|
+
['a comma separated string', '401, 403'],
|
|
369
|
+
['garbage (falls back to 401/403)', 'abc'],
|
|
370
|
+
['an empty array (falls back to 401/403)', []],
|
|
371
|
+
])('should not throw and still retry on 403 when retryStatuses is %s', async (_label, retryStatuses) => {
|
|
372
|
+
await rejectedOnceThenOk(uniqueUser(), { retryStatuses });
|
|
373
|
+
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
374
|
+
});
|
|
375
|
+
it.each([['abc'], [0], [-5]])('should fall back to the 900s default when ttlSeconds is invalid (%p)', async (ttlSeconds) => {
|
|
376
|
+
const u = uniqueUser();
|
|
377
|
+
const realNow = Date.now();
|
|
378
|
+
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow);
|
|
379
|
+
fetchMock()
|
|
380
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
381
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
382
|
+
.mockResolvedValueOnce(resp(200, []))
|
|
383
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
384
|
+
const cfg = sessionConfig(u, { enabled: true, ttlSeconds });
|
|
385
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
386
|
+
nowSpy.mockReturnValue(realNow + 2000);
|
|
387
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
388
|
+
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
389
|
+
nowSpy.mockRestore();
|
|
390
|
+
});
|
|
391
|
+
it('should fall back to JSESSIONID when cookieName is blank', async () => {
|
|
392
|
+
const u = uniqueUser();
|
|
393
|
+
fetchMock()
|
|
394
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
395
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
396
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: ' ' })).sendToFlexPLM(payload);
|
|
397
|
+
expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
398
|
+
});
|
|
399
|
+
});
|
|
400
|
+
describe('retryStatuses restricted to client-error statuses', () => {
|
|
401
|
+
const postFailsWith = async (status, retryStatuses) => {
|
|
402
|
+
const u = uniqueUser();
|
|
403
|
+
fetchMock()
|
|
404
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
405
|
+
.mockResolvedValueOnce(resp(status, [], {}));
|
|
406
|
+
await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, retryStatuses })).sendToFlexPLM({ id: '1' }))
|
|
407
|
+
.rejects.toThrow('Error sending data to FlexPLM:status: ' + status);
|
|
408
|
+
expect(fetchMock()).toHaveBeenCalledTimes(2); // no retry
|
|
409
|
+
};
|
|
410
|
+
it.each([[500], ['500'], [[200, 500]]])('should ignore non-4xx retryStatuses (%p) and not retry a 500', async (retryStatuses) => {
|
|
411
|
+
await postFailsWith(500, retryStatuses);
|
|
412
|
+
});
|
|
413
|
+
it('should keep 4xx entries and drop others from a mixed retryStatuses list', async () => {
|
|
414
|
+
await postFailsWith(500, [401, 500]);
|
|
415
|
+
});
|
|
416
|
+
it('should not resend a successful event when retryStatuses is configured as 200', async () => {
|
|
417
|
+
const u = uniqueUser();
|
|
418
|
+
fetchMock()
|
|
419
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
420
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
421
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, retryStatuses: 200 })).sendToFlexPLM({ id: '1' });
|
|
422
|
+
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
423
|
+
});
|
|
424
|
+
});
|
|
425
|
+
describe('session cache key includes session options', () => {
|
|
426
|
+
it('should not share a cached cookie between different cookieNames for the same user', async () => {
|
|
427
|
+
const u = uniqueUser();
|
|
428
|
+
fetchMock()
|
|
429
|
+
.mockResolvedValueOnce(resp(200, ['AAA=a1; Path=/']))
|
|
430
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
431
|
+
.mockResolvedValueOnce(resp(200, ['BBB=b1; Path=/']))
|
|
432
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
433
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'AAA' })).sendToFlexPLM({ id: '1' });
|
|
434
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'BBB' })).sendToFlexPLM({ id: '1' });
|
|
435
|
+
expect(callHeaders(2).Cookie).toBeUndefined(); // BBB config must not pick up the AAA session
|
|
436
|
+
expect(callHeaders(3).Cookie).toBe('BBB=b1');
|
|
437
|
+
});
|
|
438
|
+
it('should not share a cached session between different ttlSeconds for the same user', async () => {
|
|
439
|
+
const u = uniqueUser();
|
|
440
|
+
fetchMock()
|
|
441
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=short.tomcat1']))
|
|
442
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
443
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=long.tomcat1']))
|
|
444
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
445
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, ttlSeconds: 1 })).sendToFlexPLM({ id: '1' });
|
|
446
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, ttlSeconds: 900 })).sendToFlexPLM({ id: '1' });
|
|
447
|
+
expect(callHeaders(2).Cookie).toBeUndefined();
|
|
448
|
+
expect(callHeaders(3).Cookie).toBe('JSESSIONID=long.tomcat1');
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
describe('rejected response disposal', () => {
|
|
452
|
+
const withBody = (r) => Object.assign(r, { body: { cancel: jest.fn().mockResolvedValue(undefined) } });
|
|
453
|
+
it('should cancel the body of a POST rejected with 403 before retrying', async () => {
|
|
454
|
+
const u = uniqueUser();
|
|
455
|
+
const rejected = withBody(resp(403, [], {}));
|
|
456
|
+
fetchMock()
|
|
457
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
458
|
+
.mockResolvedValueOnce(rejected)
|
|
459
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
460
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
461
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
462
|
+
expect(rejected.body.cancel).toHaveBeenCalledTimes(1);
|
|
463
|
+
});
|
|
464
|
+
it('should cancel the body of a CSRF GET rejected with the cached cookie before retrying', async () => {
|
|
465
|
+
const u = uniqueUser();
|
|
466
|
+
const rejected = withBody(resp(401, []));
|
|
467
|
+
fetchMock()
|
|
468
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
469
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
470
|
+
.mockResolvedValueOnce(rejected)
|
|
471
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
472
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
473
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
474
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
475
|
+
expect(rejected.body.cancel).toHaveBeenCalledTimes(1);
|
|
476
|
+
});
|
|
477
|
+
it('should cancel the body of a getRequest rejected with the cached cookie before retrying', async () => {
|
|
478
|
+
const u = uniqueUser();
|
|
479
|
+
const rejected = withBody(resp(401, []));
|
|
480
|
+
fetchMock()
|
|
481
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
482
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
483
|
+
.mockResolvedValueOnce(rejected)
|
|
484
|
+
.mockResolvedValueOnce(resp(200, [], { items: [] }));
|
|
485
|
+
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
486
|
+
await connect.sendToFlexPLM({ id: '1' });
|
|
487
|
+
await connect.getRequest();
|
|
488
|
+
expect(rejected.body.cancel).toHaveBeenCalledTimes(1);
|
|
489
|
+
});
|
|
490
|
+
it('should still retry when cancelling the body throws', async () => {
|
|
491
|
+
const u = uniqueUser();
|
|
492
|
+
const rejected = resp(403, [], {});
|
|
493
|
+
rejected.body = { cancel: jest.fn().mockRejectedValue(new Error('locked')) };
|
|
494
|
+
fetchMock()
|
|
495
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
|
|
496
|
+
.mockResolvedValueOnce(rejected)
|
|
497
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
|
|
498
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
499
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM({ id: '1' });
|
|
500
|
+
expect(fetchMock()).toHaveBeenCalledTimes(4);
|
|
501
|
+
});
|
|
502
|
+
});
|
|
503
|
+
describe('cookie names containing regex metacharacters', () => {
|
|
504
|
+
it('should extract a cookie whose name contains "+"', async () => {
|
|
505
|
+
const u = uniqueUser();
|
|
506
|
+
fetchMock()
|
|
507
|
+
.mockResolvedValueOnce(resp(200, ['SID+=abc; Path=/']))
|
|
508
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
509
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'SID+' })).sendToFlexPLM(payload);
|
|
510
|
+
expect(callHeaders(1).Cookie).toBe('SID+=abc');
|
|
511
|
+
});
|
|
512
|
+
it('should treat "." literally and not match a look-alike cookie', async () => {
|
|
513
|
+
const u = uniqueUser();
|
|
514
|
+
fetchMock()
|
|
515
|
+
.mockResolvedValueOnce(resp(200, ['AxB=wrong; Path=/']))
|
|
516
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
517
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'A.B' })).sendToFlexPLM(payload);
|
|
518
|
+
expect(callHeaders(1).Cookie).toBeUndefined();
|
|
519
|
+
});
|
|
520
|
+
});
|
|
521
|
+
describe('concurrent session acquisition', () => {
|
|
522
|
+
const flush = () => new Promise(r => setImmediate(r));
|
|
523
|
+
const isColdGet = (call) => call[1].method === 'GET' && !call[1].headers.Cookie;
|
|
524
|
+
it('should share one session across concurrent events on a cold cache', async () => {
|
|
525
|
+
const u = uniqueUser();
|
|
526
|
+
let release;
|
|
527
|
+
const gate = new Promise(r => { release = r; });
|
|
528
|
+
fetchMock().mockImplementation(async (_url, opts) => {
|
|
529
|
+
if (opts.method === 'GET' && !opts.headers.Cookie) {
|
|
530
|
+
await gate;
|
|
531
|
+
return resp(200, ['JSESSIONID=abc.tomcat1']);
|
|
532
|
+
}
|
|
533
|
+
return resp(200, []);
|
|
534
|
+
});
|
|
535
|
+
const all = Promise.all([1, 2, 3].map(() => new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF()));
|
|
536
|
+
await flush();
|
|
537
|
+
expect(fetchMock()).toHaveBeenCalledTimes(1); // the other two are waiting for the first acquisition
|
|
538
|
+
release();
|
|
539
|
+
const results = await all;
|
|
540
|
+
expect(fetchMock().mock.calls.filter(isColdGet)).toHaveLength(1);
|
|
541
|
+
results.forEach(r => expect(r.sessionCookie).toBe('abc.tomcat1'));
|
|
542
|
+
});
|
|
543
|
+
it('should not make a waiter inherit the failure of the first acquisition', async () => {
|
|
544
|
+
const u = uniqueUser();
|
|
545
|
+
let release;
|
|
546
|
+
const gate = new Promise(r => { release = r; });
|
|
547
|
+
fetchMock()
|
|
548
|
+
.mockImplementationOnce(async () => { await gate; return resp(500, []); })
|
|
549
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']));
|
|
550
|
+
const first = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF();
|
|
551
|
+
const firstResult = first.catch(e => e);
|
|
552
|
+
const second = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF();
|
|
553
|
+
await flush();
|
|
554
|
+
release();
|
|
555
|
+
expect(await firstResult).toBeInstanceOf(Error);
|
|
556
|
+
expect((await second).sessionCookie).toBe('abc.tomcat1');
|
|
557
|
+
});
|
|
558
|
+
it('should create only one replacement session for parallel events rejected with 403', async () => {
|
|
559
|
+
const u = uniqueUser();
|
|
560
|
+
fetchMock().mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']));
|
|
561
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).getCSRF(); // prime the cache with the old session
|
|
562
|
+
fetchMock().mockReset();
|
|
563
|
+
fetchMock().mockImplementation(async (_url, opts) => {
|
|
564
|
+
const cookie = opts.headers.Cookie;
|
|
565
|
+
if (opts.method === 'POST')
|
|
566
|
+
return cookie === 'JSESSIONID=new.tomcat1' ? resp(200, [], {}) : resp(403, [], {});
|
|
567
|
+
if (!cookie)
|
|
568
|
+
return resp(200, ['JSESSIONID=new.tomcat1']);
|
|
569
|
+
return resp(200, []);
|
|
570
|
+
});
|
|
571
|
+
await Promise.all([1, 2, 3].map(() => new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload)));
|
|
572
|
+
expect(fetchMock().mock.calls.filter(isColdGet)).toHaveLength(1);
|
|
573
|
+
});
|
|
574
|
+
});
|
|
575
|
+
});
|
|
576
|
+
describe('FlexPLMConnect session reuse - feature disabled (default)', () => {
|
|
577
|
+
const payload = { id: '123' };
|
|
578
|
+
it('should send no Cookie header and make exactly one GET + one POST', async () => {
|
|
579
|
+
const u = uniqueUser();
|
|
580
|
+
fetchMock()
|
|
581
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // Set-Cookie present but must be ignored
|
|
582
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
583
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=def.tomcat1']))
|
|
584
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
585
|
+
const cfg = createConfig({ userName: () => u }); // no flexplmConnect at all
|
|
586
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
587
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
588
|
+
for (let i = 0; i < 4; i++) {
|
|
589
|
+
expect(callHeaders(i).Cookie).toBeUndefined();
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
it('should not retry on 403 (behaves exactly as before)', async () => {
|
|
593
|
+
const u = uniqueUser();
|
|
594
|
+
fetchMock()
|
|
595
|
+
.mockResolvedValueOnce(resp(200))
|
|
596
|
+
.mockResolvedValueOnce(resp(403, [], {}));
|
|
597
|
+
await expect(new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: () => u })).sendToFlexPLM(payload))
|
|
598
|
+
.rejects.toThrow('Error sending data to FlexPLM:status: 403');
|
|
599
|
+
expect(fetchMock()).toHaveBeenCalledTimes(2);
|
|
600
|
+
});
|
|
601
|
+
it('should behave the same as not configured when enabled is false', async () => {
|
|
602
|
+
const u = uniqueUser();
|
|
603
|
+
fetchMock()
|
|
604
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
605
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
606
|
+
await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: false })).sendToFlexPLM(payload);
|
|
607
|
+
expect(callHeaders(1).Cookie).toBeUndefined();
|
|
608
|
+
});
|
|
609
|
+
it('should ignore the legacy flat key form', async () => {
|
|
610
|
+
const u = uniqueUser();
|
|
611
|
+
fetchMock()
|
|
612
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // Set-Cookie present but must be ignored
|
|
613
|
+
.mockResolvedValueOnce(resp(200, [], {}));
|
|
614
|
+
const cfg = createConfig({ userName: () => u, 'flexplmConnect.sessionReuse.enabled': true });
|
|
615
|
+
await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
|
|
616
|
+
expect(callHeaders(1).Cookie).toBeUndefined();
|
|
617
|
+
});
|
|
618
|
+
});
|
|
619
|
+
describe('FlexPLMConnect.getRequest session reuse', () => {
|
|
620
|
+
it('should send the cached cookie on image/GET requests', async () => {
|
|
621
|
+
const u = uniqueUser();
|
|
622
|
+
fetchMock()
|
|
623
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // csrf GET primes the cache
|
|
624
|
+
.mockResolvedValueOnce(resp(200, [], {})) // POST
|
|
625
|
+
.mockResolvedValueOnce(resp(200, [], { items: [] })); // getRequest
|
|
626
|
+
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
627
|
+
await connect.sendToFlexPLM({ id: '1' });
|
|
628
|
+
await connect.getRequest();
|
|
629
|
+
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
630
|
+
});
|
|
631
|
+
it('should retry once without the cookie when the cached session is rejected on getRequest', async () => {
|
|
632
|
+
const u = uniqueUser();
|
|
633
|
+
fetchMock()
|
|
634
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
|
|
635
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
636
|
+
.mockResolvedValueOnce(resp(401, [])) // getRequest with cached cookie
|
|
637
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1'], { items: [] })); // retry, no cookie
|
|
638
|
+
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
639
|
+
await connect.sendToFlexPLM({ id: '1' });
|
|
640
|
+
await connect.getRequest();
|
|
641
|
+
expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
|
|
642
|
+
expect(callHeaders(3).Cookie).toBeUndefined();
|
|
643
|
+
});
|
|
644
|
+
it('should not re-store the rejected cookie when the retry issues no Set-Cookie', async () => {
|
|
645
|
+
const u = uniqueUser();
|
|
646
|
+
fetchMock()
|
|
647
|
+
.mockResolvedValueOnce(resp(200, ['JSESSIONID=stale.tomcat1']))
|
|
648
|
+
.mockResolvedValueOnce(resp(200, [], {}))
|
|
649
|
+
.mockResolvedValueOnce(resp(401, [])) // getRequest with the cached cookie
|
|
650
|
+
.mockResolvedValueOnce(resp(200, [], { items: [] })) // retry succeeds, no Set-Cookie
|
|
651
|
+
.mockResolvedValueOnce(resp(200, [], { items: [] })); // next getRequest
|
|
652
|
+
const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
|
|
653
|
+
await connect.sendToFlexPLM({ id: '1' });
|
|
654
|
+
await connect.getRequest();
|
|
655
|
+
await connect.getRequest();
|
|
656
|
+
expect(callHeaders(3).Cookie).toBeUndefined();
|
|
657
|
+
expect(callHeaders(4).Cookie).toBeUndefined(); // stale cookie must not be sent again
|
|
658
|
+
});
|
|
659
|
+
});
|
|
660
|
+
// Added for Session reuse - ET-390 - Ends
|