@nsshunt/stsappframework 2.19.173 → 2.19.175

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.
@@ -1,326 +0,0 @@
1
- import debugModule from 'debug'
2
- const debug = debugModule(`proc:${process.pid}:testHelper`);
3
-
4
- import * as tough from 'tough-cookie'
5
-
6
- import https from 'https'
7
- import crypto from 'crypto';
8
-
9
- import 'jest-date'
10
-
11
- import axios from 'axios';
12
-
13
- import { GenericContainer, Network, Wait } from "testcontainers";
14
-
15
- import { $Options, $ResetOptions } from '@nsshunt/stsconfig'
16
- let goptions = $Options()
17
-
18
- import { Sleep } from '@nsshunt/stsutils'
19
-
20
- import { AuthUtilsNode, STSClientID } from './authutilsnode'
21
-
22
- export class TestHelper {
23
- //#regexBase64URL = /^[A-Za-z0-9_-]+$/ // Base64URL - https://base64.guru/standards/base64url
24
- #regexURLSafeStringComponent = /[-a-zA-Z0-9@:%._+~#=]{1,256}/ // URL safe string component
25
- //#regexBase64 = /(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?/ // Base64 - https://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data
26
- #regexSTSBase64 = /SES_(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?/ // Base64
27
- #regexJWT = /[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+/ // JWT (Base64URL.Base64URL.Base64URL)
28
-
29
- #authUtilsNode = new AuthUtilsNode();
30
-
31
- #databaseContainer: any;
32
- #stsAuthContainer: any;
33
- #network: any;
34
- #authEndpoint = '';
35
- #authPort = '';
36
- #authHost = '';
37
- #httpsAgent: https.Agent | null = null;
38
-
39
- constructor() {
40
- this.#authEndpoint = 'https://localhost:3002'; //@@
41
- }
42
-
43
- #GetHttpsAgent = () =>
44
- {
45
- if (this.#httpsAgent === null) {
46
- // https://nodejs.org/api/http.html#class-httpagent
47
- this.#httpsAgent = new https.Agent({
48
- keepAlive: goptions.keepAlive,
49
- maxSockets: goptions.maxSockets,
50
- maxTotalSockets: goptions.maxTotalSockets,
51
- maxFreeSockets: goptions.maxFreeSockets,
52
- timeout: goptions.timeout,
53
- rejectUnauthorized: false
54
- });
55
- }
56
- return this.#httpsAgent;
57
- }
58
-
59
- StartNetwork = async () => {
60
- this.#network = await new Network().start();
61
- }
62
-
63
- StopNetwork = async () => {
64
- await this.#network.stop();
65
- }
66
-
67
- get network() {
68
- return this.#network;
69
- }
70
-
71
- get authPort() {
72
- return this.#authPort;
73
- }
74
-
75
- get authHost() {
76
- return this.#authHost;
77
- }
78
-
79
- get authEndpoint() {
80
- return this.#authEndpoint;
81
- }
82
-
83
- get getHttpsAgent() {
84
- return this.#GetHttpsAgent();
85
- }
86
-
87
- CreateRandomString = () => {
88
- const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.'; // /[0-9A-Za-z\-_~.]/
89
- let random = '';
90
- const randomValues: number[] = Array.from(crypto.getRandomValues(new Uint8Array(43)));
91
- randomValues.forEach(v => (random += charset[v % charset.length]));
92
- return random;
93
- }
94
-
95
- Login = async (username: string, password: string) => {
96
- const client_id = process.env.CLIENT_ID as string;
97
- const nonce = crypto.randomBytes(43).toString('base64'); //CreateRandomString();
98
- const response_type = 'code';
99
- const redirect_uri = process.env.REDIRECT_URI as string;
100
- const response_mode = 'query';
101
- const scope = process.env.SCOPE as string;
102
- const state = crypto.randomBytes(43).toString('base64'); // CreateRandomString();
103
- const code_verifier = this.CreateRandomString();
104
- const code_challenge = crypto.createHash('sha256').update(code_verifier).digest('base64');
105
- const code_challenge_method = 'S256';
106
-
107
- const authoriseOptions: any = {
108
- email: username,
109
- password,
110
- client_id,
111
- nonce,
112
- response_type,
113
- redirect_uri,
114
- response_mode,
115
- scope,
116
- state,
117
- code_challenge,
118
- code_challenge_method
119
- }
120
-
121
-
122
- const url = `${this.#authEndpoint}${goptions.asapiroot}/login`;
123
- const headers = { 'Content-Type': 'application/json'};
124
-
125
- const retVal = await axios({
126
- url
127
- ,method: 'post'
128
- ,data: authoriseOptions
129
- ,headers: headers
130
- ,httpsAgent: this.#GetHttpsAgent()
131
- });
132
-
133
- //const cookieString = retVal.headers['set-cookie'];
134
-
135
- /*
136
- const api = request(this.#endpoint);
137
- const retVal: any = await (api as any)
138
- .post(`${goptions.asapiroot}/login`)
139
- .send(authoriseOptions)
140
- //.expect('set-cookie', /consent_cookie=.*; Max-Age=86; Path=\/; Expires=.*; HttpOnly; Secure; SameSite=Strict/);
141
-
142
- const cookieString = retVal.header['set-cookie'];
143
-
144
- if (cookieString) {
145
- retVal.cookie = new Cookie(cookieString[0]);
146
- }
147
- */
148
-
149
- return retVal;
150
- }
151
-
152
- GetAuthServerAPITokenFromServer = async (): Promise<string> => {
153
- return await this.#authUtilsNode.GetAPITokenFromAuthServer(STSClientID.STSTestingService,
154
- "eN9u0mHZLGWZrdnE1zit2vL6xwUFW466sTZcbkXDml5KWxlvKaZ1uiOZmA==",
155
- goptions.asapiidentifier, this.#authEndpoint)
156
- }
157
-
158
- ValidateJWT = async (token: string): Promise<string> => {
159
- return await this.#authUtilsNode.ValidateJWT(token, goptions.asapiidentifier, this.#authEndpoint);
160
- }
161
-
162
- StartDatabase = async () => {
163
- this.#databaseContainer = await new GenericContainer("postgres")
164
- .withExposedPorts(5432)
165
- .withEnvironment({
166
- POSTGRES_PASSWORD: "postgres",
167
- //UV_THREADPOOL_SIZE: "64"
168
- })
169
- .withNetwork(this.#network)
170
- .withNetworkAliases("database")
171
- .start();
172
-
173
- const httpPort = this.#databaseContainer.getMappedPort(5432);
174
- const host = this.#databaseContainer.getHost();
175
- const networkIpAddress = this.#databaseContainer.getIpAddress(this.#network.getName());
176
-
177
- process.env.DB_PORT = httpPort;
178
- process.env.DB_HOST = host;
179
-
180
- $ResetOptions();
181
- goptions = $Options()
182
-
183
- debug(`httpPort: [${httpPort}]`.green)
184
- debug(`host: [${host}]`.green)
185
- debug(`networkIpAddress: [${networkIpAddress}]`.green)
186
- debug(`connectionString: [${goptions.connectionString}]`.green)
187
- debug(`defaultDatabaseConnectionString: [${goptions.defaultDatabaseConnectionString }]`.green)
188
- }
189
-
190
- StopDatabase = async () => {
191
- if (this.#databaseContainer) {
192
- await this.#databaseContainer.stop();
193
-
194
- debug(`Used the following parameters for the database during testing:`.yellow);
195
- debug(`connectionString: [${goptions.connectionString}]`.yellow);
196
- debug(`defaultDatabaseConnectionString: [${goptions.defaultDatabaseConnectionString }]`.yellow);
197
- }
198
- }
199
-
200
- // Note: .withCopyFilesToContainer and .withCopyContentToContainer have a defect in that Jest will not close. A file handle/stream is left open
201
- // within the underlying code.
202
- InitializeDatabase = async () => {
203
- const stsAuthContainerInit = await new GenericContainer("serza/stsauth:latest")
204
- .withEnvironment({
205
- DB_USER: "postgres",
206
- DB_PASSWORD: "postgres",
207
- DB_HOST: "database", // "192.168.14.101",
208
- DB_PORT: "5432",
209
- POOL_SIZE: "50",
210
- MAX_CPU: "2",
211
- DEBUG: "proc*",
212
- HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
213
- HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
214
- AS_CLIENT_ID: "q6a9F0kksXDDcrsCUKRwHKDnTNh7yZfxCShAgIJqfGg=",
215
- AS_CLIENT_SECRET: "eN9u0mHZLGWZrdnE1zit2vL6xwUFW466sTZcbkXDml5KWxlvKaZ1uiOZmA==",
216
- AS_ENDPOINT: "https://stscore.stsmda.org"
217
- })
218
- .withCommand(["node", "dist/app", "create"])
219
- .withNetwork(this.#network)
220
- .withNetworkAliases("stsauthrunnerinit")
221
- .withWaitStrategy(Wait.forLogMessage(`User Permissions: {"status":200,"detail":["STSREST01ReadPermission","STSREST01CreatePermission","STSREST01UpdatePermission","STSREST01DeletePermission"]}`))
222
- .start();
223
-
224
- await Sleep(200);
225
-
226
- await stsAuthContainerInit.stop();
227
- }
228
-
229
- StartAuthService = async () => {
230
- this.#stsAuthContainer = await new GenericContainer("serza/stsauth:latest")
231
- .withExposedPorts(3002)
232
- .withEnvironment({
233
- DB_USER: "postgres",
234
- DB_PASSWORD: "postgres",
235
- DB_HOST: "database",
236
- DB_PORT: "5432",
237
- POOL_SIZE: "50",
238
- MAX_CPU: "2",
239
- DEBUG: "proc*",
240
- HTTPS_SERVER_KEY_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.key",
241
- HTTPS_SERVER_CERT_PATH: "/var/lib/sts/stsglobalresources/keys-tmp/server.cert",
242
- AS_CLIENT_ID: "q6a9F0kksXDDcrsCUKRwHKDnTNh7yZfxCShAgIJqfGg=",
243
- AS_CLIENT_SECRET: "eN9u0mHZLGWZrdnE1zit2vL6xwUFW466sTZcbkXDml5KWxlvKaZ1uiOZmA==",
244
- AS_ENDPOINT: "https://stscore.stsmda.org"
245
- })
246
- .withNetwork(this.#network)
247
- .withNetworkAliases("stsauthrunner")
248
- .withWaitStrategy(Wait.forHttp("/stsauth/v1.0/latency", 3002).usingTls().allowInsecure())
249
- .start();
250
-
251
- const httpAuthPort = this.#stsAuthContainer.getMappedPort(3002);
252
-
253
- await Sleep(200);
254
- debug(`-------------------------------------------------------------------------------------------`.green)
255
- debug(` *** STSAuth Started ***: [${httpAuthPort}]`.green)
256
- debug(`-------------------------------------------------------------------------------------------`.green)
257
-
258
- this.#authHost = 'https://localhost'
259
- this.#authPort = httpAuthPort;
260
- this.#authEndpoint = `${this.#authHost}:${this.#authPort}`;
261
- }
262
-
263
- StopAuthService = async () => {
264
- if (this.#stsAuthContainer) {
265
- await this.#stsAuthContainer.stop();
266
- await Sleep(200);
267
- }
268
- }
269
-
270
- TestLoginAndVerify = async () => {
271
- expect.assertions(4);
272
-
273
- const retVal = await this.Login('user01@stsmda.com.au', 'user01password');
274
- expect(retVal.status).toEqual(200);
275
-
276
- debug(`${JSON.stringify(retVal.data)}`.red);
277
- debug(`${JSON.stringify(retVal.headers)}`.magenta);
278
- debug(`${JSON.stringify(retVal.headers['set-cookie'])}`.yellow);
279
-
280
- const cookies = retVal.headers['set-cookie'] as string[];
281
- debug(`${cookies[0]}`.yellow);
282
- debug(`${JSON.stringify(tough.Cookie.parse(cookies[0]))}`.green);
283
-
284
- const cookie = tough.Cookie.parse(cookies[0]) as tough.Cookie;
285
-
286
- const desiredCookieResultAxios = {
287
- key: 'consent_cookie',
288
- value: expect.stringMatching(this.#regexURLSafeStringComponent),
289
- path: '/',
290
- secure: true,
291
- httpOnly: true,
292
- sameSite: 'strict',
293
- }
294
-
295
- const cookieResult = JSON.parse(JSON.stringify(cookie));
296
- expect(cookieResult).toMatchObject(desiredCookieResultAxios);
297
-
298
- const cookieExpireDate = new Date(cookie.expires);
299
- expect(cookieExpireDate).toBeAfter(new Date());
300
-
301
- const desiredResult = {
302
- sessionId: expect.stringMatching(this.#regexSTSBase64),
303
- id_token: expect.stringMatching(this.#regexJWT),
304
- consentRequired: [ 'res01.create', 'res01.read', 'res01.update', 'res01.delete' ]
305
- }
306
- expect(retVal.data.detail).toMatchObject(desiredResult);
307
- }
308
-
309
- TestValidateJWT = async () => {
310
- expect.assertions(1);
311
-
312
- const access_token = await this.GetAuthServerAPITokenFromServer();
313
- debug(`access_token: [${access_token}]`.green);
314
-
315
- const retVal = await this.ValidateJWT(access_token);
316
- // https://jestjs.io/docs/expect#tomatchobjectobject
317
- const desiredJWT = {
318
- scope: 'offline_access session.read session.update',
319
- iss: 'https://stsmda.com.au/stsauth/',
320
- aud: 'https://stsmda.com.au/stsauthapi/v1.0/',
321
- sub: 'session'
322
- };
323
-
324
- expect(retVal).toMatchObject(desiredJWT);
325
- }
326
- }
@@ -1,26 +0,0 @@
1
- /// <reference types="node" />
2
- import https from 'https';
3
- import 'jest-date';
4
- export declare class TestHelper {
5
- #private;
6
- constructor();
7
- StartNetwork: () => Promise<void>;
8
- StopNetwork: () => Promise<void>;
9
- get network(): any;
10
- get authPort(): string;
11
- get authHost(): string;
12
- get authEndpoint(): string;
13
- get getHttpsAgent(): https.Agent;
14
- CreateRandomString: () => string;
15
- Login: (username: string, password: string) => Promise<import("axios").AxiosResponse<any, any>>;
16
- GetAuthServerAPITokenFromServer: () => Promise<string>;
17
- ValidateJWT: (token: string) => Promise<string>;
18
- StartDatabase: () => Promise<void>;
19
- StopDatabase: () => Promise<void>;
20
- InitializeDatabase: () => Promise<void>;
21
- StartAuthService: () => Promise<void>;
22
- StopAuthService: () => Promise<void>;
23
- TestLoginAndVerify: () => Promise<void>;
24
- TestValidateJWT: () => Promise<void>;
25
- }
26
- //# sourceMappingURL=testHelpers.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testHelpers.d.ts","sourceRoot":"","sources":["../src/testHelpers.ts"],"names":[],"mappings":";AAKA,OAAO,KAAK,MAAM,OAAO,CAAA;AAGzB,OAAO,WAAW,CAAA;AAalB,qBAAa,UAAU;;;IAqCnB,YAAY,sBAEX;IAED,WAAW,sBAEV;IAED,IAAI,OAAO,QAEV;IAED,IAAI,QAAQ,WAEX;IAED,IAAI,QAAQ,WAEX;IAED,IAAI,YAAY,WAEf;IAED,IAAI,aAAa,gBAEhB;IAED,kBAAkB,eAMjB;IAED,KAAK,aAAoB,MAAM,YAAY,MAAM,sDAuDhD;IAED,+BAA+B,QAAa,QAAQ,MAAM,CAAC,CAI1D;IAED,WAAW,UAAiB,MAAM,KAAG,QAAQ,MAAM,CAAC,CAEnD;IAED,aAAa,sBA0BZ;IAED,YAAY,sBAQX;IAID,kBAAkB,sBAyBjB;IAED,gBAAgB,sBAgCf;IAED,eAAe,sBAKd;IAED,kBAAkB,sBAqCjB;IAED,eAAe,sBAgBd;CACJ"}