forked from opensearch-project/OpenSearch-Dashboards
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rendering_service.tsx
415 lines (371 loc) · 13.9 KB
/
rendering_service.tsx
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Any modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { first, take } from 'rxjs/operators';
import { i18n } from '@osd/i18n';
import { Agent as HttpsAgent } from 'https';
import Axios from 'axios';
import { UiPlugins } from '../plugins';
import { CoreContext } from '../core_context';
import { Template } from './views';
import {
IRenderOptions,
RenderingSetupDeps,
InternalRenderingServiceSetup,
RenderingMetadata,
BrandingValidation,
BrandingAssignment,
} from './types';
import { OpenSearchDashboardsConfigType } from '../opensearch_dashboards_config';
import { HttpConfigType } from '../http/http_config';
import { SslConfig } from '../http/ssl_config';
import { LoggerFactory } from '../logging';
const DEFAULT_TITLE = 'OpenSearch Dashboards';
/** @internal */
export class RenderingService {
constructor(private readonly coreContext: CoreContext) {
this.logger = this.coreContext.logger;
}
private logger: LoggerFactory;
private httpsAgent?: HttpsAgent;
public async setup({
http,
status,
uiPlugins,
}: RenderingSetupDeps): Promise<InternalRenderingServiceSetup> {
const [opensearchDashboardsConfig, serverConfig] = await Promise.all([
this.coreContext.configService
.atPath<OpenSearchDashboardsConfigType>('opensearchDashboards')
.pipe(first())
.toPromise(),
this.coreContext.configService.atPath<HttpConfigType>('server').pipe(first()).toPromise(),
]);
this.setupHttpAgent(serverConfig as HttpConfigType);
return {
render: async (
request,
uiSettings,
{ includeUserSettings = true, vars }: IRenderOptions = {}
) => {
const env = {
mode: this.coreContext.env.mode,
packageInfo: this.coreContext.env.packageInfo,
};
const basePath = http.basePath.get(request);
const uiPublicUrl = `${basePath}/ui`;
const serverBasePath = http.basePath.serverBasePath;
const settings = {
defaults: uiSettings.getRegistered(),
user: includeUserSettings ? await uiSettings.getUserProvided() : {},
};
// Cannot use `uiSettings.get()` since a user might not be authenticated
const darkMode =
(settings.user?.['theme:darkMode']?.userValue ??
uiSettings.getOverrideOrDefault('theme:darkMode')) ||
false;
// At the very least, the schema should define a default theme; the '' will be unreachable
const themeVersion =
(settings.user?.['theme:version']?.userValue ??
uiSettings.getOverrideOrDefault('theme:version')) ||
'';
const brandingAssignment = await this.assignBrandingConfig(
darkMode,
opensearchDashboardsConfig as OpenSearchDashboardsConfigType
);
const metadata: RenderingMetadata = {
strictCsp: http.csp.strict,
uiPublicUrl,
bootstrapScriptUrl: `${basePath}/bootstrap.js`,
i18n: i18n.translate,
locale: i18n.getLocale(),
darkMode,
themeVersion,
injectedMetadata: {
version: env.packageInfo.version,
buildNumber: env.packageInfo.buildNum,
branch: env.packageInfo.branch,
basePath,
serverBasePath,
env,
anonymousStatusPage: status.isStatusPageAnonymous(),
i18n: {
translationsUrl: `${basePath}/translations/${i18n.getLocale()}.json`,
},
csp: { warnLegacyBrowsers: http.csp.warnLegacyBrowsers },
vars: vars ?? {},
uiPlugins: await Promise.all(
[...uiPlugins.public].map(async ([id, plugin]) => ({
id,
plugin,
config: await this.getUiConfig(uiPlugins, id),
}))
),
legacyMetadata: {
uiSettings: settings,
},
branding: {
darkMode,
assetFolderUrl: `${uiPublicUrl}/default_branding`,
logo: {
defaultUrl: brandingAssignment.logoDefault,
darkModeUrl: brandingAssignment.logoDarkmode,
},
mark: {
defaultUrl: brandingAssignment.markDefault,
darkModeUrl: brandingAssignment.markDarkmode,
},
loadingLogo: {
defaultUrl: brandingAssignment.loadingLogoDefault,
darkModeUrl: brandingAssignment.loadingLogoDarkmode,
},
faviconUrl: brandingAssignment.favicon,
applicationTitle: brandingAssignment.applicationTitle,
useExpandedHeader: brandingAssignment.useExpandedHeader,
},
survey: opensearchDashboardsConfig.survey.url,
},
};
return `<!DOCTYPE html>${renderToStaticMarkup(<Template metadata={metadata} />)}`;
},
};
}
public async stop() {}
/**
* Setups HTTP Agent if SSL is enabled to pass SSL config
* values to Axios to make requests in while validating
* resources.
*
* @param {Readonly<HttpConfigType>} httpConfig
*/
private setupHttpAgent(httpConfig: Readonly<HttpConfigType>) {
if (!httpConfig.ssl?.enabled) return;
try {
const sslConfig = new SslConfig(httpConfig.ssl);
this.httpsAgent = new HttpsAgent({
ca: sslConfig.certificateAuthorities,
cert: sslConfig.certificate,
key: sslConfig.key,
passphrase: sslConfig.keyPassphrase,
rejectUnauthorized: false,
});
} catch (e) {
this.logger.get('branding').error('HTTP agent failed to setup for SSL.');
}
}
/**
* Assign values for branding related configurations based on branding validation
* by calling checkBrandingValid(). For dark mode URLs, add additional validation
* to see if there is a valid default mode URL exist first. If URL is valid, pass in
* the actual URL; if not, pass in undefined.
*
* @param {boolean} darkMode
* @param {Readonly<OpenSearchDashboardsConfigType>} opensearchDashboardsConfig
* @returns {BrandingAssignment} valid URLs or undefined assigned for each branding configs
*/
private assignBrandingConfig = async (
darkMode: boolean,
opensearchDashboardsConfig: Readonly<OpenSearchDashboardsConfigType>
): Promise<BrandingAssignment> => {
const brandingValidation: BrandingValidation = await this.checkBrandingValid(
darkMode,
opensearchDashboardsConfig
);
const branding = opensearchDashboardsConfig.branding;
// assign default mode URL based on the brandingValidation function result
const logoDefault = brandingValidation.isLogoDefaultValid
? branding.logo.defaultUrl
: undefined;
const markDefault = brandingValidation.isMarkDefaultValid
? branding.mark.defaultUrl
: undefined;
const loadingLogoDefault = brandingValidation.isLoadingLogoDefaultValid
? branding.loadingLogo.defaultUrl
: undefined;
// assign dark mode URLs based on brandingValidation function result
let logoDarkmode = brandingValidation.isLogoDarkmodeValid
? branding.logo.darkModeUrl
: undefined;
let markDarkmode = brandingValidation.isMarkDarkmodeValid
? branding.mark.darkModeUrl
: undefined;
let loadingLogoDarkmode = brandingValidation.isLoadingLogoDarkmodeValid
? branding.loadingLogo.darkModeUrl
: undefined;
/**
* For dark mode URLs, we added another validation:
* user can only provide a dark mode URL after providing a valid default mode URL,
* If user provides a valid dark mode URL but fails to provide a valid default mode URL,
* return undefined for the dark mode URL
*/
if (logoDarkmode && !logoDefault) {
this.logger
.get('branding')
.error('Must provide a valid logo default mode URL before providing a logo dark mode URL');
logoDarkmode = undefined;
}
if (markDarkmode && !markDefault) {
this.logger
.get('branding')
.error('Must provide a valid mark default mode URL before providing a mark dark mode URL');
markDarkmode = undefined;
}
if (loadingLogoDarkmode && !loadingLogoDefault) {
this.logger
.get('branding')
.error(
'Must provide a valid loading logo default mode URL before providing a loading logo dark mode URL'
);
loadingLogoDarkmode = undefined;
}
// assign favicon based on brandingValidation function result
const favicon = brandingValidation.isFaviconValid ? branding.faviconUrl : undefined;
// assign application title based on brandingValidation function result
const applicationTitle = brandingValidation.isTitleValid
? branding.applicationTitle
: DEFAULT_TITLE;
// use expanded menu by default unless explicitly set to false
const { useExpandedHeader = true } = branding;
const brandingAssignment: BrandingAssignment = {
logoDefault,
logoDarkmode,
markDefault,
markDarkmode,
loadingLogoDefault,
loadingLogoDarkmode,
favicon,
applicationTitle,
useExpandedHeader,
};
return brandingAssignment;
};
/**
* Assign boolean values for branding related configurations to indicate if
* user inputs valid or invalid URLs by calling isUrlValid() function. Also
* check if title is valid by calling isTitleValid() function.
*
* @param {boolean} darkMode
* @param {Readonly<OpenSearchDashboardsConfigType>} opensearchDashboardsConfig
* @returns {BrandingValidation} indicate valid/invalid URL for each branding config
*/
private checkBrandingValid = async (
darkMode: boolean,
opensearchDashboardsConfig: Readonly<OpenSearchDashboardsConfigType>
): Promise<BrandingValidation> => {
const branding = opensearchDashboardsConfig.branding;
const isLogoDefaultValid = await this.isUrlValid(branding.logo.defaultUrl, 'logo default');
const isLogoDarkmodeValid = darkMode
? await this.isUrlValid(branding.logo.darkModeUrl, 'logo darkMode')
: false;
const isMarkDefaultValid = await this.isUrlValid(branding.mark.defaultUrl, 'mark default');
const isMarkDarkmodeValid = darkMode
? await this.isUrlValid(branding.mark.darkModeUrl, 'mark darkMode')
: false;
const isLoadingLogoDefaultValid = await this.isUrlValid(
branding.loadingLogo.defaultUrl,
'loadingLogo default'
);
const isLoadingLogoDarkmodeValid = darkMode
? await this.isUrlValid(branding.loadingLogo.darkModeUrl, 'loadingLogo darkMode')
: false;
const isFaviconValid = await this.isUrlValid(branding.faviconUrl, 'favicon');
const isTitleValid = this.isTitleValid(branding.applicationTitle, 'applicationTitle');
const brandingValidation: BrandingValidation = {
isLogoDefaultValid,
isLogoDarkmodeValid,
isMarkDefaultValid,
isMarkDarkmodeValid,
isLoadingLogoDefaultValid,
isLoadingLogoDarkmodeValid,
isFaviconValid,
isTitleValid,
};
return brandingValidation;
};
private async getUiConfig(uiPlugins: UiPlugins, pluginId: string) {
const browserConfig = uiPlugins.browserConfigs.get(pluginId);
return ((await browserConfig?.pipe(take(1)).toPromise()) ?? {}) as Record<string, any>;
}
/**
* Validation function for URLs. Use Axios to call URL and check validity.
* Also needs to be ended with png, svg, gif, PNG, SVG and GIF.
*
* @param {string} url
* @param {string} configName
* @returns {boolean} indicate if the URL is valid/invalid
*/
public isUrlValid = async (url: string, configName?: string): Promise<boolean> => {
if (url === '/') {
return false;
}
if (url.match(/\.(png|svg|gif|PNG|SVG|GIF)$/) === null) {
this.logger.get('branding').error(`${configName} config is invalid. Using default branding.`);
return false;
}
if (url.startsWith('/')) {
return true;
}
return await Axios.get(url, {
httpsAgent: this.httpsAgent,
adapter: 'http',
maxRedirects: 0,
})
.then(() => {
return true;
})
.catch(() => {
this.logger
.get('branding')
.error(`${configName} URL was not found or invalid. Using default branding.`);
return false;
});
};
/**
* Validation function for applicationTitle config.
* Title length needs to be between 1 to 36 letters.
*
* @param {string} title
* @param {string} configName
* @returns {boolean} indicate if user input title is valid/invalid
*/
public isTitleValid = (title: string, configName?: string): boolean => {
if (!title) {
return false;
}
if (title.length > 36) {
this.logger
.get('branding')
.error(
`${configName} config is not found or invalid. Title length should be between 1 to 36 characters. Using default title.`
);
return false;
}
return true;
};
}