-
Notifications
You must be signed in to change notification settings - Fork 500
Expand file tree
/
Copy pathapiClient.ts
More file actions
381 lines (334 loc) · 12.4 KB
/
apiClient.ts
File metadata and controls
381 lines (334 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
import * as Sentry from "@sentry/react";
import {
AppConfig,
appConfig as appConfigSingleton,
CloudAppConfig,
CloudAppMode,
SelfManagedAppConfig,
SelfManagedAppMode,
SelfManagedAuthMode,
} from "~/config/AppConfig";
import { ContextHolder } from "~/external-library-wrappers/frontegg";
import { MzOidcUserManager } from "~/external-library-wrappers/oidc";
import { formatLoginErrorForOIDC, readAuthErrorDetail } from "~/utils/oidcAuth";
import { logoutAndRedirect } from "./materialize/auth";
import {
HttpScheme,
MaterializeAuthConfig,
PasswordAuthConfig,
TokenAuthConfig,
WebsocketScheme,
} from "./types";
export type Fetch = typeof fetch;
export type Middleware = (next: Fetch) => Fetch;
// HACK (SangJunBak): This is a hack to ensure that the fetch function is always the most up to date reference.
// During testing, MSW (Mock Service Worker) intercepts and replaces the global fetch function.
// However, storing a direct reference to fetch would capture the original function, which becomes stale after MSW's replacement.
// By wrapping fetch in an anonymous function, we ensure we always access the current version
// of fetch through closure, allowing MSW to properly intercept and handle requests during tests.
const globalFetch = (...req: Parameters<Fetch>) => fetch(...req);
function buildConsoleVersionHeaders(
currentConsoleVersion: string,
): Record<string, string> {
return currentConsoleVersion && currentConsoleVersion.length > 0
? {
"X-MATERIALIZE-VERSION": currentConsoleVersion,
}
: {};
}
// User and password used to connect to Materialize during flexible deployment mode.
// These are required fields for the Websocket API for self-managed without auth.
export const FLEXIBLE_DEPLOYMENT_USER = {
user: "materialize",
password: "",
};
/**
* Composes multiple middleware functions into a single middleware
* @param middlewares Array of middleware functions to compose
* @returns A single composed middleware function
*/
function composeMiddleware(...middlewares: Middleware[]): Middleware {
return (finalFetch: Fetch): Fetch => {
return middlewares.reduceRight(
(next, middleware) => middleware(next),
finalFetch,
);
};
}
/**
* Creates a new fetch function with the given middlewares applied
* @param fetch The base fetch function to transform
* @param middlewares Array of middleware functions to apply
* @returns A new fetch function with all middlewares applied
*/
export function withMiddleware(
fetch: Fetch,
...middlewares: Middleware[]
): Fetch {
return composeMiddleware(...middlewares)(fetch);
}
/**
* Creates a new Headers object and copies headers from fetch arguments
* @param fetchArgs Original fetch arguments containing input and options
* @returns A new Headers object with copied headers from input and options
*/
function copyHeaders(fetchArgs: Parameters<Fetch>): Headers {
const [input, options = {}] = fetchArgs;
// Start with base headers from input if it's a Request, otherwise empty Headers
const headers = new Headers(
input instanceof Request ? input.headers : undefined,
);
// Copy any headers from options, overriding existing values
if (options.headers) {
Object.entries(options.headers).forEach(([key, value]) => {
headers.set(key, value);
});
}
return headers;
}
function buildTokenAuthConfig(token: string): TokenAuthConfig {
return { token };
}
function buildPasswordAuthConfig(config: {
user: string;
password: string;
}): PasswordAuthConfig {
return config;
}
interface IApiClientBase {
// Fetch function for the Materialize HTTP API
mzApiFetch: Fetch;
// Auth configuration used for the Websocket API.
// When null, we never attach the auth config. This occurs for Impersonation and Self Managed when using password auth.
getWsAuthConfig: () => MaterializeAuthConfig | null;
// The scheme used for the Materialize HTTP API.
mzHttpUrlScheme: HttpScheme;
// The scheme used for the Materialize Websocket API.
mzWebsocketUrlScheme: WebsocketScheme;
}
interface ICloudApiClient {
type: CloudAppMode;
isImpersonating: boolean;
// Fetch function for the Cloud API.
cloudApiFetch: Fetch;
// The base path for the Cloud Global API.
cloudGlobalApiBasePath: string;
}
interface IFronteggApiClient {
isImpersonating: false;
// The base path for the Frontegg API.
fronteggApiBasePath: string;
}
interface IImpersonationApiClient {
isImpersonating: true;
isLocalImpersonation: boolean;
}
interface ISelfManagedApiClient {
type: SelfManagedAppMode;
// The base path for the Password Auth Materialize HTTP API.
authApiBasePath: string;
authMode: SelfManagedAuthMode;
}
export class SelfManagedApiClient
implements IApiClientBase, ISelfManagedApiClient
{
#appConfig: Readonly<SelfManagedAppConfig>;
/** Resolved manager; read synchronously by the auth middleware and WebSocket config. */
oidcManager?: MzOidcUserManager;
/** In-flight init promise; awaited by OidcProviderWrapper to gate rendering. */
oidcManagerInitializationPromise?: Promise<MzOidcUserManager>;
authMode: SelfManagedAuthMode;
authApiBasePath: string;
mzHttpUrlScheme: HttpScheme;
mzWebsocketUrlScheme: WebsocketScheme;
mzApiFetch: Fetch;
getWsAuthConfig: () => MaterializeAuthConfig | null;
type = "self-managed" as const;
#mzApiWithAuthRedirect = async (...req: Parameters<Fetch>) => {
const response = await globalFetch(...req);
if (response.status === 401) {
const reason =
this.authMode === "Oidc"
? formatLoginErrorForOIDC(req[0])
: "session_expired";
const detail =
reason === "auth_rejected"
? await readAuthErrorDetail(response)
: undefined;
const message = reason ? { reason, detail } : undefined;
await logoutAndRedirect({ apiClient: this, message });
}
return response;
};
#oidcAuthMiddleware: Middleware = (next) => {
return async (...fetchArgs) => {
const [input, options = {}] = fetchArgs;
const idToken = this.oidcManager?.getIdToken();
const headers = copyHeaders(fetchArgs);
if (idToken) {
headers.set("Authorization", `Bearer ${idToken}`);
}
const request = new Request(input, { ...options, headers });
return next(request);
};
};
constructor({ appConfig }: { appConfig: Readonly<SelfManagedAppConfig> }) {
this.#appConfig = appConfig;
this.mzHttpUrlScheme = this.#appConfig.environmentdScheme;
this.mzWebsocketUrlScheme = this.#appConfig.environmentdWebsocketScheme;
this.authApiBasePath = `${this.#appConfig.environmentdScheme}://${this.#appConfig.environmentdConfig.environmentdHttpAddress}`;
this.authMode = this.#appConfig.authMode;
if (this.authMode === "Oidc") {
this.oidcManagerInitializationPromise = MzOidcUserManager.create().then(
(manager) => {
this.oidcManager = manager;
return manager;
},
);
// When OIDC is configured, users can authenticate via either OIDC or
// password. The OIDC middleware adds a Bearer token if one exists;
// otherwise no auth header is sent and the session cookie is used
// implicitly. The 401 redirect handles expired/missing sessions.
this.mzApiFetch = withMiddleware(
this.#mzApiWithAuthRedirect,
this.#oidcAuthMiddleware,
);
} else if (this.authMode === "None") {
this.mzApiFetch = globalFetch;
} else {
this.mzApiFetch = this.#mzApiWithAuthRedirect;
}
this.getWsAuthConfig = () => {
if (this.authMode === "Oidc") {
const idToken = this.oidcManager?.getIdToken();
if (idToken) {
return buildTokenAuthConfig(idToken);
}
// No OIDC token — user authenticated via password, session cookie
// is sent implicitly so no explicit auth config is needed.
return null;
}
// Unintuitively, we return an auth config when authMode is "None". This is because
// the authenticated websocket API gets the necessary information via the http-only cookie
// and errors if you try to send a websocket message with the auth config.
if (this.authMode === "None") {
return buildPasswordAuthConfig(FLEXIBLE_DEPLOYMENT_USER);
}
return null;
};
}
}
export class ImpersonationApiClient
implements IApiClientBase, ICloudApiClient, IImpersonationApiClient
{
#appConfig: Readonly<CloudAppConfig>;
cloudGlobalApiBasePath: string;
type = "cloud" as const;
isImpersonating = true as const;
isLocalImpersonation: boolean;
mzHttpUrlScheme: HttpScheme;
mzWebsocketUrlScheme: WebsocketScheme;
constructor({ appConfig }: { appConfig: Readonly<CloudAppConfig> }) {
this.#appConfig = appConfig;
this.cloudGlobalApiBasePath = this.#appConfig.cloudGlobalApiUrl;
this.mzHttpUrlScheme = this.#appConfig.environmentdScheme;
this.mzWebsocketUrlScheme = this.#appConfig.environmentdWebsocketScheme;
this.isLocalImpersonation = this.#appConfig.isLocalImpersonation;
}
#impersonationCloudApiMiddleware: Middleware = (next) => {
return async (...fetchArgs) => {
const [input, options = {}] = fetchArgs;
const headers = copyHeaders(fetchArgs);
if (this.#appConfig.impersonation?.organizationId) {
headers.set("accept", this.#appConfig.impersonation.organizationId);
const request = new Request(input, {
headers,
credentials: "include" as const,
method: "GET",
});
return next(request);
}
const request = new Request(input, { ...options, headers });
return next(request);
};
};
mzApiFetch = globalFetch;
cloudApiFetch = withMiddleware(
globalFetch,
this.#impersonationCloudApiMiddleware,
);
getWsAuthConfig = () => null;
}
export class CloudApiClient
implements IApiClientBase, ICloudApiClient, IFronteggApiClient
{
#appConfig: Readonly<CloudAppConfig>;
cloudGlobalApiBasePath: string;
fronteggApiBasePath: string;
type = "cloud" as const;
isImpersonating = false as const;
mzHttpUrlScheme: HttpScheme;
mzWebsocketUrlScheme: WebsocketScheme;
constructor({ appConfig }: { appConfig: Readonly<CloudAppConfig> }) {
this.#appConfig = appConfig;
this.cloudGlobalApiBasePath = this.#appConfig.cloudGlobalApiUrl;
this.fronteggApiBasePath = this.#appConfig.fronteggUrl;
this.mzHttpUrlScheme = this.#appConfig.environmentdScheme;
this.mzWebsocketUrlScheme = this.#appConfig.environmentdWebsocketScheme;
}
#getAccessToken() {
// Get the access token from Frontegg's context holder
const accessToken = ContextHolder.for("default").getAccessToken();
// The token will most likely always exist since this function
// will be called when logged in. If not, we should alert Sentry.
if (!accessToken) {
Sentry.addBreadcrumb({
level: "error",
category: "auth",
message: "Failed to refresh auth token",
});
}
return accessToken;
}
#authMiddleware: Middleware = (next) => {
return async (...fetchArgs) => {
const [input, options = {}] = fetchArgs;
const accessToken = this.#getAccessToken();
const headers = copyHeaders(fetchArgs);
if (accessToken) {
headers.set("Authorization", `Bearer ${accessToken}`);
if (this.#appConfig.sentryConfig?.release) {
Object.entries(
buildConsoleVersionHeaders(this.#appConfig.sentryConfig?.release),
).forEach(([key, value]) => {
headers.set(key, value);
});
}
}
const request = new Request(input, { ...options, headers });
return next(request);
};
};
mzApiFetch = withMiddleware(globalFetch, this.#authMiddleware);
cloudApiFetch = this.mzApiFetch;
getWsAuthConfig = () => buildTokenAuthConfig(this.#getAccessToken() ?? "");
}
function createApiClient(appConfig: AppConfig) {
if (appConfig.mode === "cloud") {
if (appConfig.isImpersonating) {
return new ImpersonationApiClient({ appConfig });
}
return new CloudApiClient({ appConfig });
} else {
return new SelfManagedApiClient({ appConfig });
}
}
export const apiClient = createApiClient(appConfigSingleton);