-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
config-provider.ts
431 lines (393 loc) · 16.8 KB
/
config-provider.ts
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/**
* Copyright (c) 2020 Gitpod GmbH. All rights reserved.
* Licensed under the GNU Affero General Public License (AGPL).
* See License-AGPL.txt in the project root for license information.
*/
import { inject, injectable } from "inversify";
import fetch from "node-fetch";
import * as path from "path";
import { log, LogContext } from "@gitpod/gitpod-protocol/lib/util/logging";
import {
User,
WorkspaceConfig,
CommitContext,
Repository,
ImageConfigString,
ExternalImageConfigFile,
ImageConfigFile,
Commit,
NamedWorkspaceFeatureFlag,
AdditionalContentContext,
WithDefaultConfig,
ProjectConfig,
} from "@gitpod/gitpod-protocol";
import { GitpodFileParser } from "@gitpod/gitpod-protocol/lib/gitpod-file-parser";
import { MaybeContent } from "../repohost/file-provider";
import { ConfigurationService } from "../config/configuration-service";
import { HostContextProvider } from "../auth/host-context-provider";
import { AuthorizationService } from "../user/authorization-service";
import { TraceContext } from "@gitpod/gitpod-protocol/lib/util/tracing";
import { Config } from "../config";
const POD_PATH_WORKSPACE_BASE = "/workspace";
@injectable()
export class ConfigProvider {
static readonly DEFINITELY_GP_REPO: Repository = {
host: "github.com",
owner: "gitpod-io",
name: "definitely-gp",
cloneUrl: "https://github.com/gitpod-io/definitely-gp",
};
@inject(GitpodFileParser) protected readonly gitpodParser: GitpodFileParser;
@inject(HostContextProvider) protected readonly hostContextProvider: HostContextProvider;
@inject(AuthorizationService) protected readonly authService: AuthorizationService;
@inject(Config) protected readonly config: Config;
@inject(ConfigurationService) protected readonly configurationService: ConfigurationService;
public async fetchConfig(
ctx: TraceContext,
user: User,
commit: CommitContext,
): Promise<{ config: WorkspaceConfig; literalConfig?: ProjectConfig }> {
const span = TraceContext.startSpan("fetchConfig", ctx);
span.addTags({
commit,
});
const logContext: LogContext = { userId: user.id };
let configBasePath = "";
try {
let customConfig: WorkspaceConfig | undefined;
let literalConfig: ProjectConfig | undefined;
if (!WithDefaultConfig.is(commit)) {
const cc = await this.fetchCustomConfig(ctx, user, commit);
if (!!cc) {
customConfig = cc.customConfig;
configBasePath = cc.configBasePath;
literalConfig = cc.literalConfig;
}
}
if (!customConfig) {
log.debug(logContext, "Config string undefined, using default config", {
repoCloneUrl: commit.repository.cloneUrl,
revision: commit.revision,
});
const config = this.defaultConfig();
if (!ImageConfigString.is(config.image)) {
throw new Error(`Default config must contain a base image!`);
}
config._origin = "default";
return { config, literalConfig };
}
const config = customConfig;
if (!config.image) {
config.image = this.config.workspaceDefaults.workspaceImage;
} else if (ImageConfigFile.is(config.image)) {
let dockerfilePath = [configBasePath, config.image.file].filter((s) => !!s).join("/");
let repo = commit.repository;
let rev = commit.revision;
let image = config.image!;
if (config._origin === "definitely-gp") {
repo = ConfigProvider.DEFINITELY_GP_REPO;
rev = "master";
image.file = dockerfilePath;
}
if (!(AdditionalContentContext.is(commit) && commit.additionalFiles[dockerfilePath])) {
config.image = <ExternalImageConfigFile>{
...image,
externalSource: await this.fetchWorkspaceImageSourceDocker(
{ span },
repo,
rev,
user,
dockerfilePath,
),
};
}
}
config.vscode = {
extensions: (config && config.vscode && config.vscode.extensions) || [],
};
await this.validateConfig(config, user);
/**
* Some feature flags get attached to any workspace they create - others remain specific to the user.
* Here we attach the workspace-persisted feature flags to the workspace.
*/
delete config._featureFlags;
if (!!user.featureFlags) {
const workspacePersistedFlags: NamedWorkspaceFeatureFlag[] = [
"full_workspace_backup",
"persistent_volume_claim",
];
config._featureFlags = workspacePersistedFlags.filter((f) =>
(user.featureFlags!.permanentWSFeatureFlags || []).includes(f),
);
}
return { config, literalConfig };
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
protected async fetchCustomConfig(
ctx: TraceContext,
user: User,
commit: CommitContext,
): Promise<{ customConfig: WorkspaceConfig; configBasePath: string; literalConfig: ProjectConfig } | undefined> {
const span = TraceContext.startSpan("fetchCustomConfig", ctx);
const logContext: LogContext = { userId: user.id };
let customConfigString: string | undefined;
try {
let customConfig: WorkspaceConfig | undefined;
let configBasePath = "";
if (AdditionalContentContext.is(commit) && commit.additionalFiles[".gitpod.yml"]) {
customConfigString = commit.additionalFiles[".gitpod.yml"];
const parseResult = this.gitpodParser.parse(customConfigString);
customConfig = parseResult.config;
customConfig._origin = "additional-content";
if (parseResult.validationErrors) {
const err = new InvalidGitpodYMLError(parseResult.validationErrors);
// this is not a system error but a user misconfiguration
log.info(logContext, err.message, {
repoCloneUrl: commit.repository.cloneUrl,
revision: commit.revision,
customConfigString,
});
throw err;
}
}
if (!customConfig) {
// try and find config file in the context repo or remote in
const host = commit.repository.host;
const hostContext = this.hostContextProvider.get(host);
if (!hostContext || !hostContext.services) {
throw new Error(`Cannot fetch config for host: ${host}`);
}
const services = hostContext.services;
const contextRepoConfig = services.fileProvider.getGitpodFileContent(commit, user);
customConfigString = await contextRepoConfig;
let origin: WorkspaceConfig["_origin"] = "repo";
if (!customConfigString) {
/* We haven't found a Gitpod configuration file in the context repo - check definitely-gp.
*
* In case we had found a config file here, we'd still be checking the definitely GP repo, just to save some time.
* While all those checks will be in vain, they should not leak memory either as they'll simply
* be resolved and garbage collected.
*/
const definitelyGpConfig = this.fetchExternalGitpodFileContent({ span }, commit.repository);
const { content, basePath } = await definitelyGpConfig;
customConfigString = content;
// We do not only care about the config itself but also where we got it from
configBasePath = basePath;
origin = "definitely-gp";
}
if (!customConfigString) {
const inferredConfig = this.configurationService.guessRepositoryConfiguration(
{ span },
user,
commit,
);
// if there's still no configuration, let's infer one
customConfigString = await inferredConfig;
origin = "derived";
}
if (customConfigString) {
const parseResult = this.gitpodParser.parse(customConfigString);
customConfig = parseResult.config;
if (parseResult.validationErrors) {
const err = new InvalidGitpodYMLError(parseResult.validationErrors);
// this is not a system error but a user misconfiguration
log.info(logContext, err.message, {
repoCloneUrl: commit.repository.cloneUrl,
revision: commit.revision,
customConfigString,
});
throw err;
}
customConfig._origin = origin;
}
}
if (!customConfig) {
return undefined;
}
return { customConfig, configBasePath, literalConfig: { ".gitpod.yml": customConfigString || "" } };
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
public defaultConfig(): WorkspaceConfig {
return {
ports: [
{
port: 3000,
},
],
tasks: [],
image: this.config.workspaceDefaults.workspaceImage,
};
}
protected async fetchWorkspaceImageSourceDocker(
ctx: TraceContext,
repository: Repository,
revisionOrTagOrBranch: string,
user: User,
dockerFilePath: string,
): Promise<Commit> {
const span = TraceContext.startSpan("fetchWorkspaceImageSourceDocker", ctx);
span.addTags({
repository,
revisionOrTagOrBranch,
dockerFilePath,
});
try {
const host = repository.host;
const hostContext = this.hostContextProvider.get(host);
if (!hostContext || !hostContext.services) {
throw new Error(`Cannot fetch workspace image source for host: ${host}`);
}
const repoHost = hostContext.services;
const lastDockerFileSha = await repoHost.fileProvider.getLastChangeRevision(
repository,
revisionOrTagOrBranch,
user,
dockerFilePath,
);
return {
repository,
revision: lastDockerFileSha,
};
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
protected async fillInDefaultLocations(
cfg: WorkspaceConfig | undefined,
inferredConfig: Promise<WorkspaceConfig | undefined>,
): Promise<void> {
if (!cfg) {
// there is no config - return
return;
}
if (!cfg.checkoutLocation) {
let inferredCfg = await inferredConfig;
if (inferredCfg) {
cfg.checkoutLocation = inferredCfg.checkoutLocation;
}
}
if (!cfg.workspaceLocation) {
let inferredCfg = await inferredConfig;
if (inferredCfg) {
cfg.workspaceLocation = inferredCfg.workspaceLocation;
}
}
}
protected async fetchExternalGitpodFileContent(
ctx: TraceContext,
repository: Repository,
): Promise<{ content: MaybeContent; basePath: string }> {
const span = TraceContext.startSpan("fetchExternalGitpodFileContent", ctx);
span.setTag("repo", `${repository.owner}/${repository.name}`);
if (this.config.definitelyGpDisabled) {
span.finish();
return {
content: undefined,
basePath: `${repository.name}`,
};
}
try {
const ownerConfigBasePath = `${repository.name}/${repository.owner}`;
const baseConfigBasePath = `${repository.name}`;
const possibleConfigs = [
[this.fetchDefinitelyGpContent({ span }, `${ownerConfigBasePath}/.gitpod.yml`), ownerConfigBasePath],
[this.fetchDefinitelyGpContent({ span }, `${ownerConfigBasePath}/.gitpod`), ownerConfigBasePath],
[this.fetchDefinitelyGpContent({ span }, `${baseConfigBasePath}/.gitpod.yml`), baseConfigBasePath],
[this.fetchDefinitelyGpContent({ span }, `${baseConfigBasePath}/.gitpod`), baseConfigBasePath],
];
for (const [configPromise, basePath] of possibleConfigs) {
const ownerConfig = await configPromise;
if (ownerConfig !== undefined) {
return {
content: ownerConfig,
basePath: basePath as string,
};
}
}
return {
content: undefined,
basePath: baseConfigBasePath,
};
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
protected async fetchDefinitelyGpContent(ctx: TraceContext, filePath: string) {
const span = TraceContext.startSpan("fetchDefinitelyGpContent", ctx);
span.setTag("filePath", filePath);
try {
const url = `https://raw.githubusercontent.com/gitpod-io/definitely-gp/master/${filePath}`;
const response = await fetch(url, {
timeout: 10000,
method: "GET",
});
let content;
if (response.ok) {
try {
content = await response.text();
} catch {}
}
return content;
} catch (e) {
TraceContext.setError({ span }, e);
throw e;
} finally {
span.finish();
}
}
protected async validateConfig(config: WorkspaceConfig, user: User): Promise<void> {
// Make sure the projectRoot does not leave POD_PATH_WORKSPACE_BASE as that's a common
// assumption throughout the code (e.g. ws-daemon)
const checkoutLocation = config.checkoutLocation;
if (checkoutLocation) {
const normalizedPath = path.join(POD_PATH_WORKSPACE_BASE, checkoutLocation);
if (this.leavesWorkspaceBase(normalizedPath)) {
log.error({ userId: user.id }, `Invalid checkout location. Would end up at ${normalizedPath}`);
throw new Error(
`Checkout location must not leave the ${POD_PATH_WORKSPACE_BASE} folder. Check your .gitpod.yml file.`,
);
}
}
const workspaceLocation = config.workspaceLocation;
if (workspaceLocation) {
const normalizedPath = path.join(POD_PATH_WORKSPACE_BASE, workspaceLocation);
if (this.leavesWorkspaceBase(normalizedPath)) {
log.error({ userId: user.id }, `Invalid workspace location. Would end up at ${normalizedPath}`);
throw new Error(
`Workspace location must not leave the ${POD_PATH_WORKSPACE_BASE} folder. Check your .gitpod.yml file.`,
);
}
}
}
protected leavesWorkspaceBase(normalizedPath: string) {
const pathSegments = normalizedPath.split(path.sep);
return normalizedPath.includes("..") || pathSegments.slice(0, 2).join("/") != POD_PATH_WORKSPACE_BASE;
}
}
export class InvalidGitpodYMLError extends Error {
public readonly errorType = "invalidGitpodYML";
constructor(public readonly validationErrors: string[]) {
super("Invalid gitpod.yml: " + validationErrors.join(","));
}
}
export namespace InvalidGitpodYMLError {
export function is(obj: object): obj is InvalidGitpodYMLError {
return "errorType" in obj && (obj as any).errorType === "invalidGitpodYML" && "validationErrors" in obj;
}
}