-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
router.ts
497 lines (448 loc) · 14.2 KB
/
router.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
* Copyright 2020 The Backstage Authors
*
* Licensed 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 { PluginDatabaseManager, UrlReader } from '@backstage/backend-common';
import { CatalogApi } from '@backstage/catalog-client';
import {
Entity,
parseEntityRef,
stringifyEntityRef,
UserEntity,
} from '@backstage/catalog-model';
import { Config, JsonObject } from '@backstage/config';
import { InputError, NotFoundError, stringifyError } from '@backstage/errors';
import { ScmIntegrations } from '@backstage/integration';
import {
TaskSpec,
TemplateEntityV1beta3,
templateEntityV1beta3Validator,
} from '@backstage/plugin-scaffolder-common';
import { JsonValue } from '@backstage/types';
import express from 'express';
import Router from 'express-promise-router';
import { validate } from 'jsonschema';
import { Logger } from 'winston';
import { z } from 'zod';
import { TemplateFilter } from '../lib';
import {
createBuiltinActions,
DatabaseTaskStore,
TaskBroker,
TaskWorker,
TemplateAction,
TemplateActionRegistry,
} from '../scaffolder';
import { createDryRunner } from '../scaffolder/dryrun';
import { StorageTaskBroker } from '../scaffolder/tasks/StorageTaskBroker';
import { findTemplate, getEntityBaseUrl, getWorkingDirectory } from './helpers';
/**
* RouterOptions
*
* @public
*/
export interface RouterOptions {
logger: Logger;
config: Config;
reader: UrlReader;
database: PluginDatabaseManager;
catalogClient: CatalogApi;
actions?: TemplateAction<any>[];
taskWorkers?: number;
taskBroker?: TaskBroker;
additionalTemplateFilters?: Record<string, TemplateFilter>;
}
function isSupportedTemplate(entity: TemplateEntityV1beta3) {
return entity.apiVersion === 'scaffolder.backstage.io/v1beta3';
}
/**
* A method to create a router for the scaffolder backend plugin.
* @public
*/
export async function createRouter(
options: RouterOptions,
): Promise<express.Router> {
const router = Router();
router.use(express.json());
const {
logger: parentLogger,
config,
reader,
database,
catalogClient,
actions,
taskWorkers,
additionalTemplateFilters,
} = options;
const logger = parentLogger.child({ plugin: 'scaffolder' });
const workingDirectory = await getWorkingDirectory(config, logger);
const integrations = ScmIntegrations.fromConfig(config);
let taskBroker: TaskBroker;
if (!options.taskBroker) {
const databaseTaskStore = await DatabaseTaskStore.create({ database });
taskBroker = new StorageTaskBroker(databaseTaskStore, logger);
} else {
taskBroker = options.taskBroker;
}
const actionRegistry = new TemplateActionRegistry();
const workers = [];
for (let i = 0; i < (taskWorkers || 1); i++) {
const worker = await TaskWorker.create({
taskBroker,
actionRegistry,
integrations,
logger,
workingDirectory,
additionalTemplateFilters,
});
workers.push(worker);
}
const actionsToRegister = Array.isArray(actions)
? actions
: createBuiltinActions({
integrations,
catalogClient,
reader,
config,
additionalTemplateFilters,
});
actionsToRegister.forEach(action => actionRegistry.register(action));
workers.forEach(worker => worker.start());
const dryRunner = createDryRunner({
actionRegistry,
integrations,
logger,
workingDirectory,
additionalTemplateFilters,
});
router
.get(
'/v2/templates/:namespace/:kind/:name/parameter-schema',
async (req, res) => {
const { namespace, kind, name } = req.params;
const { token } = parseBearerToken({
header: req.headers.authorization,
logger,
});
const template = await findTemplate({
catalogApi: catalogClient,
entityRef: { kind, namespace, name },
token,
});
if (isSupportedTemplate(template)) {
const parameters = [template.spec.parameters ?? []].flat();
res.json({
title: template.metadata.title ?? template.metadata.name,
description: template.metadata.description,
steps: parameters.map(schema => ({
title: schema.title ?? 'Please enter the following information',
description: schema.description,
schema,
})),
});
} else {
throw new InputError(
`Unsupported apiVersion field in schema entity, ${
(template as Entity).apiVersion
}`,
);
}
},
)
.get('/v2/actions', async (_req, res) => {
const actionsList = actionRegistry.list().map(action => {
return {
id: action.id,
description: action.description,
schema: action.schema,
};
});
res.json(actionsList);
})
.post('/v2/tasks', async (req, res) => {
const templateRef: string = req.body.templateRef;
const { kind, namespace, name } = parseEntityRef(templateRef, {
defaultKind: 'template',
});
const { token, entityRef: userEntityRef } = parseBearerToken({
header: req.headers.authorization,
logger,
});
const userEntity = userEntityRef
? await catalogClient.getEntityByRef(userEntityRef, { token })
: undefined;
let auditLog = `Scaffolding task for ${templateRef}`;
if (userEntityRef) {
auditLog += ` created by ${userEntityRef}`;
}
logger.info(auditLog);
const values = req.body.values;
const template = await findTemplate({
catalogApi: catalogClient,
entityRef: { kind, namespace, name },
token,
});
if (!isSupportedTemplate(template)) {
throw new InputError(
`Unsupported apiVersion field in schema entity, ${
(template as Entity).apiVersion
}`,
);
}
for (const parameters of [template.spec.parameters ?? []].flat()) {
const result = validate(values, parameters);
if (!result.valid) {
res.status(400).json({ errors: result.errors });
return;
}
}
const baseUrl = getEntityBaseUrl(template);
const taskSpec: TaskSpec = {
apiVersion: template.apiVersion,
steps: template.spec.steps.map((step, index) => ({
...step,
id: step.id ?? `step-${index + 1}`,
name: step.name ?? step.action,
})),
output: template.spec.output ?? {},
parameters: values,
user: {
entity: userEntity as UserEntity,
ref: userEntityRef,
},
templateInfo: {
entityRef: stringifyEntityRef({
kind,
namespace,
name: template.metadata?.name,
}),
baseUrl,
entity: {
metadata: template.metadata,
},
},
};
const result = await taskBroker.dispatch({
spec: taskSpec,
createdBy: userEntityRef,
secrets: {
...req.body.secrets,
backstageToken: token,
},
});
res.status(201).json({ id: result.taskId });
})
.get('/v2/tasks', async (req, res) => {
const [userEntityRef] = [req.query.createdBy].flat();
if (
typeof userEntityRef !== 'string' &&
typeof userEntityRef !== 'undefined'
) {
throw new InputError('createdBy query parameter must be a string');
}
if (!taskBroker.list) {
throw new Error(
'TaskBroker does not support listing tasks, please implement the list method on the TaskBroker.',
);
}
const tasks = await taskBroker.list({
createdBy: userEntityRef,
});
res.status(200).json(tasks);
})
.get('/v2/tasks/:taskId', async (req, res) => {
const { taskId } = req.params;
const task = await taskBroker.get(taskId);
if (!task) {
throw new NotFoundError(`Task with id ${taskId} does not exist`);
}
// Do not disclose secrets
delete task.secrets;
res.status(200).json(task);
})
.get('/v2/tasks/:taskId/eventstream', async (req, res) => {
const { taskId } = req.params;
const after =
req.query.after !== undefined ? Number(req.query.after) : undefined;
logger.debug(`Event stream observing taskId '${taskId}' opened`);
// Mandatory headers and http status to keep connection open
res.writeHead(200, {
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream',
});
// After client opens connection send all events as string
const subscription = taskBroker.event$({ taskId, after }).subscribe({
error: error => {
logger.error(
`Received error from event stream when observing taskId '${taskId}', ${error}`,
);
res.end();
},
next: ({ events }) => {
let shouldUnsubscribe = false;
for (const event of events) {
res.write(
`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,
);
if (event.type === 'completion') {
shouldUnsubscribe = true;
}
}
// res.flush() is only available with the compression middleware
res.flush?.();
if (shouldUnsubscribe) {
subscription.unsubscribe();
res.end();
}
},
});
// When client closes connection we update the clients list
// avoiding the disconnected one
req.on('close', () => {
subscription.unsubscribe();
logger.debug(`Event stream observing taskId '${taskId}' closed`);
});
})
.get('/v2/tasks/:taskId/events', async (req, res) => {
const { taskId } = req.params;
const after = Number(req.query.after) || undefined;
// cancel the request after 30 seconds. this aligns with the recommendations of RFC 6202.
const timeout = setTimeout(() => {
res.json([]);
}, 30_000);
// Get all known events after an id (always includes the completion event) and return the first callback
const subscription = taskBroker.event$({ taskId, after }).subscribe({
error: error => {
logger.error(
`Received error from event stream when observing taskId '${taskId}', ${error}`,
);
},
next: ({ events }) => {
clearTimeout(timeout);
subscription.unsubscribe();
res.json(events);
},
});
// When client closes connection we update the clients list
// avoiding the disconnected one
req.on('close', () => {
subscription.unsubscribe();
clearTimeout(timeout);
});
})
.post('/v2/dry-run', async (req, res) => {
const bodySchema = z.object({
template: z.unknown(),
values: z.record(z.unknown()),
secrets: z.record(z.string()).optional(),
directoryContents: z.array(
z.object({ path: z.string(), base64Content: z.string() }),
),
});
const body = await bodySchema.parseAsync(req.body).catch(e => {
throw new InputError(`Malformed request: ${e}`);
});
const template = body.template as TemplateEntityV1beta3;
if (!(await templateEntityV1beta3Validator.check(template))) {
throw new InputError('Input template is not a template');
}
const { token } = parseBearerToken({
header: req.headers.authorization,
logger,
});
for (const parameters of [template.spec.parameters ?? []].flat()) {
const result = validate(body.values, parameters);
if (!result.valid) {
res.status(400).json({ errors: result.errors });
return;
}
}
const steps = template.spec.steps.map((step, index) => ({
...step,
id: step.id ?? `step-${index + 1}`,
name: step.name ?? step.action,
}));
const result = await dryRunner({
spec: {
apiVersion: template.apiVersion,
steps,
output: template.spec.output ?? {},
parameters: body.values as JsonObject,
},
directoryContents: (body.directoryContents ?? []).map(file => ({
path: file.path,
content: Buffer.from(file.base64Content, 'base64'),
})),
secrets: {
...body.secrets,
...(token && { backstageToken: token }),
},
});
res.status(200).json({
...result,
steps,
directoryContents: result.directoryContents.map(file => ({
path: file.path,
executable: file.executable,
base64Content: file.content.toString('base64'),
})),
});
});
const app = express();
app.set('logger', logger);
app.use('/', router);
return app;
}
function parseBearerToken({
header,
logger,
}: {
header?: string;
logger: Logger;
}): {
token?: string;
entityRef?: string;
} {
if (!header) {
return {};
}
try {
const token = header.match(/^Bearer\s(\S+\.\S+\.\S+)$/i)?.[1];
if (!token) {
throw new TypeError('Expected Bearer with JWT');
}
const [_header, rawPayload, _signature] = token.split('.');
const payload: JsonValue = JSON.parse(
Buffer.from(rawPayload, 'base64').toString(),
);
if (
typeof payload !== 'object' ||
payload === null ||
Array.isArray(payload)
) {
throw new TypeError('Malformed JWT payload');
}
const sub = payload.sub;
if (typeof sub !== 'string') {
throw new TypeError('Expected string sub claim');
}
// Check that it's a valid ref, otherwise this will throw.
parseEntityRef(sub);
return { entityRef: sub, token };
} catch (e) {
logger.error(`Invalid authorization header: ${stringifyError(e)}`);
return {};
}
}