-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathindex.ts
More file actions
370 lines (311 loc) · 11.3 KB
/
index.ts
File metadata and controls
370 lines (311 loc) · 11.3 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
import { existsSync, readFileSync } from 'fs';
import defaultSettings from '../../proxy.config.json';
import { GitProxyConfig, Convert } from './generated/config';
import { ConfigLoader, Configuration } from './ConfigLoader';
import { serverConfig } from './env';
import { configFile } from './file';
// Cache for current configuration
let _currentConfig: GitProxyConfig | null = null;
let _configLoader: ConfigLoader | null = null;
// Function to invalidate cache - useful for testing
export const invalidateCache = () => {
_currentConfig = null;
};
// Compatibility function for old initUserConfig behavior
export const initUserConfig = () => {
invalidateCache();
loadFullConfiguration(); // Force immediate reload
};
// Function to clean undefined values from an object
function cleanUndefinedValues(obj: any): any {
if (obj === null || obj === undefined) return obj;
if (typeof obj !== 'object') return obj;
if (Array.isArray(obj)) return obj.map(cleanUndefinedValues);
const cleaned: any = {};
for (const [key, value] of Object.entries(obj)) {
if (value !== undefined) {
cleaned[key] = cleanUndefinedValues(value);
}
}
return cleaned;
}
/**
* Load and merge default + user configuration with QuickType validation
* @return {GitProxyConfig} The merged and validated configuration
*/
function loadFullConfiguration(): GitProxyConfig {
if (_currentConfig) {
return _currentConfig;
}
const rawDefaultConfig = Convert.toGitProxyConfig(JSON.stringify(defaultSettings));
// Clean undefined values from defaultConfig
const defaultConfig = cleanUndefinedValues(rawDefaultConfig);
let userSettings: Partial<GitProxyConfig> = {};
const userConfigFile = process.env.CONFIG_FILE || configFile;
if (existsSync(userConfigFile)) {
try {
const userConfigContent = readFileSync(userConfigFile, 'utf-8');
// Parse as JSON first, then clean undefined values
// Don't use QuickType validation for partial configurations
const rawUserConfig = JSON.parse(userConfigContent);
userSettings = cleanUndefinedValues(rawUserConfig);
} catch (error) {
console.error(`Error loading user config from ${userConfigFile}:`, error);
throw error;
}
}
_currentConfig = mergeConfigurations(defaultConfig, userSettings);
return _currentConfig;
}
/**
* Merge configurations with environment variable overrides
* @param {GitProxyConfig} defaultConfig - The default configuration
* @param {Partial<GitProxyConfig>} userSettings - User-provided configuration overrides
* @return {GitProxyConfig} The merged configuration
*/
function mergeConfigurations(
defaultConfig: GitProxyConfig,
userSettings: Partial<GitProxyConfig>,
): GitProxyConfig {
// Special handling for TLS configuration when legacy fields are used
let tlsConfig = userSettings.tls || defaultConfig.tls;
// If user doesn't specify tls but has legacy SSL fields, use only legacy fallback
if (!userSettings.tls && (userSettings.sslKeyPemPath || userSettings.sslCertPemPath)) {
tlsConfig = {
enabled: defaultConfig.tls?.enabled || false,
// Use empty strings so legacy fallback works
key: '',
cert: '',
};
}
return {
...defaultConfig,
...userSettings,
// Deep merge for specific objects
api: userSettings.api ? cleanUndefinedValues(userSettings.api) : defaultConfig.api,
domains: { ...defaultConfig.domains, ...userSettings.domains },
commitConfig: { ...defaultConfig.commitConfig, ...userSettings.commitConfig },
attestationConfig: { ...defaultConfig.attestationConfig, ...userSettings.attestationConfig },
rateLimit: userSettings.rateLimit || defaultConfig.rateLimit,
cache: userSettings.cache
? { ...defaultConfig.cache, ...userSettings.cache }
: defaultConfig.cache,
tls: tlsConfig,
tempPassword: { ...defaultConfig.tempPassword, ...userSettings.tempPassword },
// Preserve legacy SSL fields
sslKeyPemPath: userSettings.sslKeyPemPath || defaultConfig.sslKeyPemPath,
sslCertPemPath: userSettings.sslCertPemPath || defaultConfig.sslCertPemPath,
// Environment variable overrides
cookieSecret:
serverConfig.GIT_PROXY_COOKIE_SECRET ||
userSettings.cookieSecret ||
defaultConfig.cookieSecret,
};
}
// Get configured proxy URL
export const getProxyUrl = (): string | undefined => {
const config = loadFullConfiguration();
return config.proxyUrl;
};
// Gets a list of authorised repositories
export const getAuthorisedList = () => {
const config = loadFullConfiguration();
return config.authorisedList || [];
};
// Gets a list of authorised repositories
export const getTempPasswordConfig = () => {
const config = loadFullConfiguration();
return config.tempPassword;
};
// Gets the configured data sink, defaults to filesystem
export const getDatabase = () => {
const config = loadFullConfiguration();
const databases = config.sink || [];
for (const db of databases) {
if (db.enabled) {
// if mongodb is configured and connection string unspecified, fallback to env var
if (db.type === 'mongo' && !db.connectionString) {
db.connectionString = serverConfig.GIT_PROXY_MONGO_CONNECTION_STRING;
}
return db;
}
}
throw Error('No database configured!');
};
/**
* Get the list of enabled authentication methods
*
* At least one authentication method must be enabled.
* @return List of enabled authentication methods
*/
export const getAuthMethods = () => {
const config = loadFullConfiguration();
const authSources = config.authentication || [];
const enabledAuthMethods = authSources.filter((auth) => auth.enabled);
if (enabledAuthMethods.length === 0) {
throw new Error('No authentication method enabled');
}
return enabledAuthMethods;
};
/**
* Get the list of enabled authentication methods for API endpoints
*
* If no API authentication methods are enabled, all endpoints are public.
* @return List of enabled authentication methods
*/
export const getAPIAuthMethods = () => {
const config = loadFullConfiguration();
const apiAuthSources = config.apiAuthentication || [];
return apiAuthSources.filter((auth: { enabled: any }) => auth.enabled);
};
// Gets the configured authentication method, defaults to local (backward compatibility)
export const getAuthentication = () => {
const authMethods = getAuthMethods();
return authMethods[0]; // Return first enabled method for backward compatibility
};
// Log configuration to console
export const logConfiguration = () => {
console.log(`authorisedList = ${JSON.stringify(getAuthorisedList())}`);
console.log(`data sink = ${JSON.stringify(getDatabase())}`);
console.log(`authentication = ${JSON.stringify(getAuthMethods())}`);
console.log(`rateLimit = ${JSON.stringify(getRateLimit())}`);
console.log(`cache = ${JSON.stringify(getCacheConfig())}`);
};
export const getAPIs = () => {
const config = loadFullConfiguration();
return config.api || {};
};
export const getCookieSecret = (): string | undefined => {
const config = loadFullConfiguration();
return config.cookieSecret;
};
export const getSessionMaxAgeHours = (): number | undefined => {
const config = loadFullConfiguration();
return config.sessionMaxAgeHours;
};
// Get commit related configuration
export const getCommitConfig = () => {
const config = loadFullConfiguration();
return config.commitConfig || {};
};
// Get attestation related configuration
export const getAttestationConfig = () => {
const config = loadFullConfiguration();
return config.attestationConfig || {};
};
// Get private organizations related configuration
export const getPrivateOrganizations = () => {
const config = loadFullConfiguration();
return config.privateOrganizations || [];
};
// Get URL shortener
export const getURLShortener = (): string | undefined => {
const config = loadFullConfiguration();
return config.urlShortener;
};
// Get contact e-mail address
export const getContactEmail = (): string | undefined => {
const config = loadFullConfiguration();
return config.contactEmail;
};
// Get CSRF protection flag
export const getCSRFProtection = (): boolean | undefined => {
const config = loadFullConfiguration();
return config.csrfProtection;
};
// Get loadable push plugins
export const getPlugins = () => {
const config = loadFullConfiguration();
return config.plugins || [];
};
export const getTLSKeyPemPath = (): string | undefined => {
const config = loadFullConfiguration();
return config.tls?.key && config.tls.key !== '' ? config.tls.key : config.sslKeyPemPath;
};
export const getTLSCertPemPath = (): string | undefined => {
const config = loadFullConfiguration();
return config.tls?.cert && config.tls.cert !== '' ? config.tls.cert : config.sslCertPemPath;
};
export const getTLSEnabled = (): boolean => {
const config = loadFullConfiguration();
return config.tls?.enabled || false;
};
export const getDomains = () => {
const config = loadFullConfiguration();
return config.domains || {};
};
export const getUIRouteAuth = () => {
const config = loadFullConfiguration();
return config.uiRouteAuth || {};
};
export const getRateLimit = () => {
const config = loadFullConfiguration();
return config.rateLimit;
};
export const getCacheConfig = () => {
const config = loadFullConfiguration();
return (
config.cache || {
maxSizeGB: 2,
maxRepositories: 50,
cacheDir: './.remote/cache',
}
);
};
// Function to handle configuration updates
const handleConfigUpdate = async (newConfig: Configuration) => {
console.log('Configuration updated from external source');
try {
// 1. Validate new configuration using QuickType
const validatedConfig = Convert.toGitProxyConfig(JSON.stringify(newConfig));
// 2. Get proxy module dynamically to avoid circular dependency
const proxy = require('../proxy');
// 3. Stop existing services
await proxy.stop();
// 4. Update config
_currentConfig = validatedConfig;
// 5. Restart services with new config
await proxy.start();
console.log('Services restarted with new configuration');
} catch (error) {
console.error('Failed to apply new configuration:', error);
// Attempt to restart with previous config
try {
const proxy = require('../proxy');
await proxy.start();
} catch (startError) {
console.error('Failed to restart services:', startError);
}
}
};
// Initialize config loader
function initializeConfigLoader() {
const config = loadFullConfiguration() as Configuration;
_configLoader = new ConfigLoader(config);
// Handle configuration updates
_configLoader.on('configurationChanged', handleConfigUpdate);
_configLoader.on('configurationError', (error: Error) => {
console.error('Error loading external configuration:', error);
});
// Start the config loader if external sources are enabled
_configLoader.start().catch((error: Error) => {
console.error('Failed to start configuration loader:', error);
});
}
// Force reload of configuration
export const reloadConfiguration = async () => {
_currentConfig = null;
if (_configLoader) {
await _configLoader.reloadConfiguration();
}
loadFullConfiguration();
};
// Initialize configuration on module load
try {
loadFullConfiguration();
initializeConfigLoader();
console.log('Configuration loaded successfully');
} catch (error) {
console.error('Failed to load configuration:', error);
throw error;
}