17337: Added another edge case handling
[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     keepWebInlineServiceUrl: string;
93     remoteHosts: {
94         [key: string]: string
95     };
96     rootUrl: string;
97     uuidPrefix: string;
98     websocketUrl: string;
99     workbenchUrl: string;
100     workbench2Url: string;
101     vocabularyUrl: string;
102     fileViewersConfigUrl: string;
103     loginCluster: string;
104     clusterConfig: ClusterConfigJSON;
105     apiRevision: number;
106 }
107
108 export const buildConfig = (clusterConfig: ClusterConfigJSON): Config => {
109     const clusterConfigJSON = removeTrailingSlashes(clusterConfig);
110     const config = new Config();
111     config.rootUrl = clusterConfigJSON.Services.Controller.ExternalURL;
112     config.baseUrl = `${config.rootUrl}/${ARVADOS_API_PATH}`;
113     config.uuidPrefix = clusterConfigJSON.ClusterID;
114     config.websocketUrl = clusterConfigJSON.Services.Websocket.ExternalURL;
115     config.workbench2Url = clusterConfigJSON.Services.Workbench2.ExternalURL;
116     config.workbenchUrl = clusterConfigJSON.Services.Workbench1.ExternalURL;
117     config.keepWebServiceUrl = clusterConfigJSON.Services.WebDAVDownload.ExternalURL;
118     config.keepWebInlineServiceUrl = clusterConfigJSON.Services.WebDAV.ExternalURL;
119     config.loginCluster = clusterConfigJSON.Login.LoginCluster;
120     config.clusterConfig = clusterConfigJSON;
121     config.apiRevision = 0;
122     mapRemoteHosts(clusterConfigJSON, config);
123     return config;
124 };
125
126 const getApiRevision = async (apiUrl: string) => {
127     try {
128         const dd = (await Axios.get<any>(`${apiUrl}/${DISCOVERY_DOC_PATH}`)).data;
129         return parseInt(dd.revision, 10) || 0;
130     } catch {
131         console.warn("Unable to get API Revision number, defaulting to zero. Some features may not work properly.");
132         return 0;
133     }
134 };
135
136 const removeTrailingSlashes = (config: ClusterConfigJSON): ClusterConfigJSON => {
137     const svcs: any = {};
138     Object.keys(config.Services).map((s) => {
139         svcs[s] = config.Services[s];
140         if (svcs[s].hasOwnProperty('ExternalURL')) {
141             svcs[s].ExternalURL = svcs[s].ExternalURL.replace(/\/+$/, '');
142         }
143     });
144     return { ...config, Services: svcs };
145 };
146
147 export const fetchConfig = () => {
148     return Axios
149         .get<WorkbenchConfig>(WORKBENCH_CONFIG_URL + "?nocache=" + (new Date()).getTime())
150         .then(response => response.data)
151         .catch(() => {
152             console.warn(`There was an exception getting the Workbench config file at ${WORKBENCH_CONFIG_URL}. Using defaults instead.`);
153             return Promise.resolve(getDefaultConfig());
154         })
155         .then(workbenchConfig => {
156             if (workbenchConfig.API_HOST === undefined) {
157                 throw new Error(`Unable to start Workbench. API_HOST is undefined in ${WORKBENCH_CONFIG_URL} or the environment.`);
158             }
159             return Axios.get<ClusterConfigJSON>(getClusterConfigURL(workbenchConfig.API_HOST)).then(async response => {
160                 const apiRevision = await getApiRevision(response.data.Services.Controller.ExternalURL.replace(/\/+$/, ''));
161                 const config = { ...buildConfig(response.data), apiRevision };
162                 const warnLocalConfig = (varName: string) => console.warn(
163                     `A value for ${varName} was found in ${WORKBENCH_CONFIG_URL}. To use the Arvados centralized configuration instead, \
164 remove the entire ${varName} entry from ${WORKBENCH_CONFIG_URL}`);
165
166                 // Check if the workbench config has an entry for vocabulary and file viewer URLs
167                 // If so, use these values (even if it is an empty string), but print a console warning.
168                 // Otherwise, use the cluster config.
169                 let fileViewerConfigUrl;
170                 if (workbenchConfig.FILE_VIEWERS_CONFIG_URL !== undefined) {
171                     warnLocalConfig("FILE_VIEWERS_CONFIG_URL");
172                     fileViewerConfigUrl = workbenchConfig.FILE_VIEWERS_CONFIG_URL;
173                 }
174                 else {
175                     fileViewerConfigUrl = config.clusterConfig.Workbench.FileViewersConfigURL || "/file-viewers-example.json";
176                 }
177                 config.fileViewersConfigUrl = fileViewerConfigUrl;
178
179                 let vocabularyUrl;
180                 if (workbenchConfig.VOCABULARY_URL !== undefined) {
181                     warnLocalConfig("VOCABULARY_URL");
182                     vocabularyUrl = workbenchConfig.VOCABULARY_URL;
183                 }
184                 else {
185                     vocabularyUrl = config.clusterConfig.Workbench.VocabularyURL || "/vocabulary-example.json";
186                 }
187                 config.vocabularyUrl = vocabularyUrl;
188
189                 return { config, apiHost: workbenchConfig.API_HOST };
190             });
191         });
192 };
193
194 // Maps remote cluster hosts and removes the default RemoteCluster entry
195 export const mapRemoteHosts = (clusterConfigJSON: ClusterConfigJSON, config: Config) => {
196     config.remoteHosts = {};
197     Object.keys(clusterConfigJSON.RemoteClusters).forEach(k => { config.remoteHosts[k] = clusterConfigJSON.RemoteClusters[k].Host; });
198     delete config.remoteHosts["*"];
199 };
200
201 export const mockClusterConfigJSON = (config: Partial<ClusterConfigJSON>): ClusterConfigJSON => ({
202     ClusterID: "",
203     RemoteClusters: {},
204     Services: {
205         Controller: { ExternalURL: "" },
206         Workbench1: { ExternalURL: "" },
207         Workbench2: { ExternalURL: "" },
208         Websocket: { ExternalURL: "" },
209         WebDAV: { ExternalURL: "" },
210         WebDAVDownload: { ExternalURL: "" },
211         WebShell: { ExternalURL: "" },
212     },
213     Workbench: {
214         ArvadosDocsite: "",
215         VocabularyURL: "",
216         FileViewersConfigURL: "",
217         WelcomePageHTML: "",
218         InactivePageHTML: "",
219         SSHHelpPageHTML: "",
220         SSHHelpHostSuffix: "",
221         SiteName: "",
222         IdleTimeout: "0s",
223     },
224     Login: {
225         LoginCluster: "",
226         Google: {
227             Enable: false,
228         },
229         LDAP: {
230             Enable: false,
231         },
232         OpenIDConnect: {
233             Enable: false,
234         },
235         PAM: {
236             Enable: false,
237         },
238         SSO: {
239             Enable: false,
240         },
241         Test: {
242             Enable: false,
243         },
244     },
245     Collections: {
246         ForwardSlashNameSubstitution: "",
247     },
248     ...config
249 });
250
251 export const mockConfig = (config: Partial<Config>): Config => ({
252     baseUrl: "",
253     keepWebServiceUrl: "",
254     keepWebInlineServiceUrl: "",
255     remoteHosts: {},
256     rootUrl: "",
257     uuidPrefix: "",
258     websocketUrl: "",
259     workbenchUrl: "",
260     workbench2Url: "",
261     vocabularyUrl: "",
262     fileViewersConfigUrl: "",
263     loginCluster: "",
264     clusterConfig: mockClusterConfigJSON({}),
265     apiRevision: 0,
266     ...config
267 });
268
269 const getDefaultConfig = (): WorkbenchConfig => {
270     let apiHost = "";
271     const envHost = process.env.REACT_APP_ARVADOS_API_HOST;
272     if (envHost !== undefined) {
273         console.warn(`Using default API host ${envHost}.`);
274         apiHost = envHost;
275     }
276     else {
277         console.warn(`No API host was found in the environment. Workbench may not be able to communicate with Arvados components.`);
278     }
279     return {
280         API_HOST: apiHost,
281         VOCABULARY_URL: undefined,
282         FILE_VIEWERS_CONFIG_URL: undefined,
283     };
284 };
285
286 export const ARVADOS_API_PATH = "arvados/v1";
287 export const CLUSTER_CONFIG_PATH = "arvados/v1/config";
288 export const DISCOVERY_DOC_PATH = "discovery/v1/apis/arvados/v1/rest";
289 export const getClusterConfigURL = (apiHost: string) => `${window.location.protocol}//${apiHost}/${CLUSTER_CONFIG_PATH}?nocache=${(new Date()).getTime()}`;