16927: Remove clusterConfigJSON local variable
[arvados-workbench2.git] / src / common / config.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import Axios from "axios";
6
7 export const WORKBENCH_CONFIG_URL = process.env.REACT_APP_ARVADOS_CONFIG_URL || "/config.json";
8
9 interface WorkbenchConfig {
10     API_HOST: string;
11     VOCABULARY_URL?: string;
12     FILE_VIEWERS_CONFIG_URL?: string;
13 }
14
15 export interface ClusterConfigJSON {
16     ClusterID: string;
17     RemoteClusters: {
18         [key: string]: {
19             ActivateUsers: boolean
20             Host: string
21             Insecure: boolean
22             Proxy: boolean
23             Scheme: string
24         }
25     };
26     Mail?: {
27         SupportEmailAddress: string;
28     };
29     Services: {
30         Controller: {
31             ExternalURL: string
32         }
33         Workbench1: {
34             ExternalURL: string
35         }
36         Workbench2: {
37             ExternalURL: string
38         }
39         Websocket: {
40             ExternalURL: string
41         }
42         WebDAV: {
43             ExternalURL: string
44         },
45         WebDAVDownload: {
46             ExternalURL: string
47         },
48         WebShell: {
49             ExternalURL: string
50         }
51     };
52     Workbench: {
53         ArvadosDocsite: string;
54         VocabularyURL: string;
55         FileViewersConfigURL: string;
56         WelcomePageHTML: string;
57         InactivePageHTML: string;
58         SSHHelpPageHTML: string;
59         SSHHelpHostSuffix: string;
60         SiteName: string;
61         IdleTimeout: string;
62     };
63     Login: {
64         LoginCluster: string;
65         Google: {
66             Enable: boolean;
67         }
68         LDAP: {
69             Enable: boolean;
70         }
71         OpenIDConnect: {
72             Enable: boolean;
73         }
74         PAM: {
75             Enable: boolean;
76         }
77         SSO: {
78             Enable: boolean;
79         }
80         Test: {
81             Enable: boolean;
82         }
83     };
84     Collections: {
85         ForwardSlashNameSubstitution: string;
86     };
87 }
88
89 export class Config {
90     baseUrl: string;
91     keepWebServiceUrl: string;
92     remoteHosts: {
93         [key: string]: string
94     };
95     rootUrl: string;
96     uuidPrefix: string;
97     websocketUrl: string;
98     workbenchUrl: string;
99     workbench2Url: string;
100     vocabularyUrl: string;
101     fileViewersConfigUrl: string;
102     loginCluster: string;
103     clusterConfig: ClusterConfigJSON;
104     apiRevision: number;
105 }
106
107 export const buildConfig = (clusterConfig: ClusterConfigJSON): Config => {
108     const clusterConfigJSON = removeTrailingSlashes(clusterConfig);
109     const config = new Config();
110     config.rootUrl = clusterConfigJSON.Services.Controller.ExternalURL;
111     config.baseUrl = `${config.rootUrl}/${ARVADOS_API_PATH}`;
112     config.uuidPrefix = clusterConfigJSON.ClusterID;
113     config.websocketUrl = clusterConfigJSON.Services.Websocket.ExternalURL;
114     config.workbench2Url = clusterConfigJSON.Services.Workbench2.ExternalURL;
115     config.workbenchUrl = clusterConfigJSON.Services.Workbench1.ExternalURL;
116     config.keepWebServiceUrl = clusterConfigJSON.Services.WebDAVDownload.ExternalURL;
117     config.loginCluster = clusterConfigJSON.Login.LoginCluster;
118     config.clusterConfig = clusterConfigJSON;
119     config.apiRevision = 0;
120     mapRemoteHosts(clusterConfigJSON, config);
121     return config;
122 };
123
124 const getApiRevision = async (apiUrl: string) => {
125     try {
126         const dd = (await Axios.get<any>(`${apiUrl}/${DISCOVERY_DOC_PATH}`)).data;
127         return parseInt(dd.revision, 10) || 0;
128     } catch {
129         console.warn("Unable to get API Revision number, defaulting to zero. Some features may not work properly.");
130         return 0;
131     }
132 };
133
134 const removeTrailingSlashes = (config: ClusterConfigJSON): ClusterConfigJSON => {
135     const svcs: any = {};
136     Object.keys(config.Services).map((s) => {
137         svcs[s] = config.Services[s];
138         if (svcs[s].hasOwnProperty('ExternalURL')) {
139             svcs[s].ExternalURL = svcs[s].ExternalURL.replace(/\/+$/, '');
140         }
141     });
142     return { ...config, Services: svcs };
143 };
144
145 export const fetchConfig = () => {
146     return Axios
147         .get<WorkbenchConfig>(WORKBENCH_CONFIG_URL + "?nocache=" + (new Date()).getTime())
148         .then(response => response.data)
149         .catch(() => {
150             console.warn(`There was an exception getting the Workbench config file at ${WORKBENCH_CONFIG_URL}. Using defaults instead.`);
151             return Promise.resolve(getDefaultConfig());
152         })
153         .then(workbenchConfig => {
154             if (workbenchConfig.API_HOST === undefined) {
155                 throw new Error(`Unable to start Workbench. API_HOST is undefined in ${WORKBENCH_CONFIG_URL} or the environment.`);
156             }
157             return Axios.get<ClusterConfigJSON>(getClusterConfigURL(workbenchConfig.API_HOST)).then(async response => {
158                 const apiRevision = await getApiRevision(response.data.Services.Controller.ExternalURL.replace(/\/+$/, ''));
159                 const config = { ...buildConfig(response.data), apiRevision };
160                 const warnLocalConfig = (varName: string) => console.warn(
161                     `A value for ${varName} was found in ${WORKBENCH_CONFIG_URL}. To use the Arvados centralized configuration instead, \
162 remove the entire ${varName} entry from ${WORKBENCH_CONFIG_URL}`);
163
164                 // Check if the workbench config has an entry for vocabulary and file viewer URLs
165                 // If so, use these values (even if it is an empty string), but print a console warning.
166                 // Otherwise, use the cluster config.
167                 let fileViewerConfigUrl;
168                 if (workbenchConfig.FILE_VIEWERS_CONFIG_URL !== undefined) {
169                     warnLocalConfig("FILE_VIEWERS_CONFIG_URL");
170                     fileViewerConfigUrl = workbenchConfig.FILE_VIEWERS_CONFIG_URL;
171                 }
172                 else {
173                     fileViewerConfigUrl = config.clusterConfig.Workbench.FileViewersConfigURL || "/file-viewers-example.json";
174                 }
175                 config.fileViewersConfigUrl = fileViewerConfigUrl;
176
177                 let vocabularyUrl;
178                 if (workbenchConfig.VOCABULARY_URL !== undefined) {
179                     warnLocalConfig("VOCABULARY_URL");
180                     vocabularyUrl = workbenchConfig.VOCABULARY_URL;
181                 }
182                 else {
183                     vocabularyUrl = config.clusterConfig.Workbench.VocabularyURL || "/vocabulary-example.json";
184                 }
185                 config.vocabularyUrl = vocabularyUrl;
186
187                 return { config, apiHost: workbenchConfig.API_HOST };
188             });
189         });
190 };
191
192 // Maps remote cluster hosts and removes the default RemoteCluster entry
193 export const mapRemoteHosts = (clusterConfigJSON: ClusterConfigJSON, config: Config) => {
194     config.remoteHosts = {};
195     Object.keys(clusterConfigJSON.RemoteClusters).forEach(k => { config.remoteHosts[k] = clusterConfigJSON.RemoteClusters[k].Host; });
196     delete config.remoteHosts["*"];
197 };
198
199 export const mockClusterConfigJSON = (config: Partial<ClusterConfigJSON>): ClusterConfigJSON => ({
200     ClusterID: "",
201     RemoteClusters: {},
202     Services: {
203         Controller: { ExternalURL: "" },
204         Workbench1: { ExternalURL: "" },
205         Workbench2: { ExternalURL: "" },
206         Websocket: { ExternalURL: "" },
207         WebDAV: { ExternalURL: "" },
208         WebDAVDownload: { ExternalURL: "" },
209         WebShell: { ExternalURL: "" },
210     },
211     Workbench: {
212         ArvadosDocsite: "",
213         VocabularyURL: "",
214         FileViewersConfigURL: "",
215         WelcomePageHTML: "",
216         InactivePageHTML: "",
217         SSHHelpPageHTML: "",
218         SSHHelpHostSuffix: "",
219         SiteName: "",
220         IdleTimeout: "0s",
221     },
222     Login: {
223         LoginCluster: "",
224         Google: {
225             Enable: false,
226         },
227         LDAP: {
228             Enable: false,
229         },
230         OpenIDConnect: {
231             Enable: false,
232         },
233         PAM: {
234             Enable: false,
235         },
236         SSO: {
237             Enable: false,
238         },
239         Test: {
240             Enable: false,
241         },
242     },
243     Collections: {
244         ForwardSlashNameSubstitution: "",
245     },
246     ...config
247 });
248
249 export const mockConfig = (config: Partial<Config>): Config => ({
250     baseUrl: "",
251     keepWebServiceUrl: "",
252     remoteHosts: {},
253     rootUrl: "",
254     uuidPrefix: "",
255     websocketUrl: "",
256     workbenchUrl: "",
257     workbench2Url: "",
258     vocabularyUrl: "",
259     fileViewersConfigUrl: "",
260     loginCluster: "",
261     clusterConfig: mockClusterConfigJSON({}),
262     apiRevision: 0,
263     ...config
264 });
265
266 const getDefaultConfig = (): WorkbenchConfig => {
267     let apiHost = "";
268     const envHost = process.env.REACT_APP_ARVADOS_API_HOST;
269     if (envHost !== undefined) {
270         console.warn(`Using default API host ${envHost}.`);
271         apiHost = envHost;
272     }
273     else {
274         console.warn(`No API host was found in the environment. Workbench may not be able to communicate with Arvados components.`);
275     }
276     return {
277         API_HOST: apiHost,
278         VOCABULARY_URL: undefined,
279         FILE_VIEWERS_CONFIG_URL: undefined,
280     };
281 };
282
283 export const ARVADOS_API_PATH = "arvados/v1";
284 export const CLUSTER_CONFIG_PATH = "arvados/v1/config";
285 export const DISCOVERY_DOC_PATH = "discovery/v1/apis/arvados/v1/rest";
286 export const getClusterConfigURL = (apiHost: string) => `${window.location.protocol}//${apiHost}/${CLUSTER_CONFIG_PATH}?nocache=${(new Date()).getTime()}`;