This repository has been archived by the owner on Jan 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathv1.js
556 lines (494 loc) · 17 KB
/
v1.js
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
var parser = require('cron-parser');
var debug = require('debug')('hooks:routes:v1');
var Promise = require('promise');
var taskcluster = require('taskcluster-client');
var API = require('taskcluster-lib-api');
var nextDate = require('../src/nextdate');
var _ = require('lodash');
var Ajv = require('ajv');
var api = new API({
title: 'Hooks API Documentation',
description: [
'Hooks are a mechanism for creating tasks in response to events.',
'',
'Hooks are identified with a `hookGroupId` and a `hookId`.',
'',
'When an event occurs, the resulting task is automatically created. The',
'task is created using the scope `assume:hook-id:<hookGroupId>/<hookId>`,',
'which must have scopes to make the createTask call, including satisfying all',
'scopes in `task.scopes`. The new task has a `taskGroupId` equal to its',
'`taskId`, as is the convention for decision tasks.',
'',
'Hooks can have a "schedule" indicating specific times that new tasks should',
'be created. Each schedule is in a simple cron format, per ',
'https://www.npmjs.com/package/cron-parser. For example:',
' * `[\'0 0 1 * * *\']` -- daily at 1:00 UTC',
' * `[\'0 0 9,21 * * 1-5\', \'0 0 12 * * 0,6\']` -- weekdays at 9:00 and 21:00 UTC, weekends at noon',
'',
'The task definition is used as a JSON-e template, with a context depending on how it is fired. See',
'https://docs.taskcluster.net/reference/core/taskcluster-hooks/docs/firing-hooks',
'for more information.',
].join('\n'),
name: 'hooks',
context: ['Hook', 'taskcreator'],
schemaPrefix: 'http://schemas.taskcluster.net/hooks/v1/',
});
// Export api
module.exports = api;
/** Get hook groups **/
api.declare({
method: 'get',
route: '/hooks',
name: 'listHookGroups',
idempotent: true,
output: 'list-hook-groups-response.json',
title: 'List hook groups',
stability: 'experimental',
description: [
'This endpoint will return a list of all hook groups with at least one hook.',
].join('\n'),
}, async function(req, res) {
var groups = new Set();
await this.Hook.scan({}, {
handler: (item) => {
groups.add(item.hookGroupId);
},
});
return res.reply({groups: Array.from(groups)});
});
/** Get hooks in a given group **/
api.declare({
method: 'get',
route: '/hooks/:hookGroupId',
name: 'listHooks',
idempotent: true,
output: 'list-hooks-response.json',
title: 'List hooks in a given group',
stability: 'experimental',
description: [
'This endpoint will return a list of all the hook definitions within a',
'given hook group.',
].join('\n'),
}, async function(req, res) {
var hooks = [];
await this.Hook.query({
hookGroupId: req.params.hookGroupId,
}, {
handler: async (hook) => {
hooks.push(await hook.definition());
},
});
if (hooks.length == 0) {
return res.reportError('ResourceNotFound', 'No such group', {});
}
return res.reply({hooks: hooks});
});
/** Get hook definition **/
api.declare({
method: 'get',
route: '/hooks/:hookGroupId/:hookId',
name: 'hook',
idempotent: true,
output: 'hook-definition.json',
title: 'Get hook definition',
stability: 'experimental',
description: [
'This endpoint will return the hook definition for the given `hookGroupId`',
'and hookId.',
].join('\n'),
}, async function(req, res) {
let hook = await this.Hook.load({
hookGroupId: req.params.hookGroupId,
hookId: req.params.hookId,
}, true);
// Handle the case where the hook doesn't exist
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
// Reply with the hook definition
let definition = await hook.definition();
return res.reply(definition);
});
/** Get hook's current status */
api.declare({
method: 'get',
route: '/hooks/:hookGroupId/:hookId/status',
name: 'getHookStatus',
output: 'hook-status.json',
title: 'Get hook status',
stability: 'experimental',
description: [
'This endpoint will return the current status of the hook. This represents a',
'snapshot in time and may vary from one call to the next.',
].join('\n'),
}, async function(req, res) {
let hook = await this.Hook.load({
hookGroupId: req.params.hookGroupId,
hookId: req.params.hookId,
}, true);
// Handle the case where the hook doesn't exist
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
let reply = {lastFire: hook.lastFire};
// Return a schedule only if a schedule is defined
if (hook.schedule.length > 0) {
reply.nextScheduledDate = hook.nextScheduledDate.toJSON();
// Remark: nextTaskId cannot be exposed here, it's a secret.
// If someone could predict the taskId they could use it, breaking this
// service at best, at worst maybe exploit it to elevate from defineTask
// to createTask without scope to schedule a task.
}
return res.reply(reply);
});
/** Get next scheduled hook date */
api.declare({
method: 'get',
route: '/hooks/:hookGroupId/:hookId/schedule',
name: 'getHookSchedule',
output: 'hook-schedule.json',
title: 'Get hook schedule',
stability: 'deprecated',
description: [
'This endpoint will return the schedule and next scheduled creation time',
'for the given hook.',
].join('\n'),
}, async function(req, res) {
let hook = await this.Hook.load({
hookGroupId: req.params.hookGroupId,
hookId: req.params.hookId,
}, true);
// Handle the case where the hook doesn't exist
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
// Return a schedule only if a schedule is defined
if (hook.schedule.length > 0) {
return res.reply({
schedule: hook.schedule,
nextScheduledDate: hook.nextScheduledDate.toJSON(),
// Remark: nextTaskId cannot be exposed here, it's a secret.
// If someone could predict the taskId they could use it, breaking this
// service at best, at worst maybe exploit it to elevate from defineTask
// to createTask without scope to schedule a task.
});
}
return res.reply({
schedule: hook.schedule,
});
});
/** Create a hook **/
api.declare({
method: 'put',
route: '/hooks/:hookGroupId/:hookId',
name: 'createHook',
idempotent: true,
scopes: {AllOf:
['hooks:modify-hook:<hookGroupId>/<hookId>', 'assume:hook-id:<hookGroupId>/<hookId>'],
},
input: 'create-hook-request.json',
output: 'hook-definition.json',
title: 'Create a hook',
stability: 'experimental',
description: [
'This endpoint will create a new hook.',
'',
'The caller\'s credentials must include the role that will be used to',
'create the task. That role must satisfy task.scopes as well as the',
'necessary scopes to add the task to the queue.',,
].join('\n'),
}, async function(req, res) {
var hookGroupId = req.params.hookGroupId;
var hookId = req.params.hookId;
var hookDef = req.body;
if (req.body.hookGroupId && hookGroupId !== req.body.hookGroupId) {
return res.reportError('InputError', 'Hook Group Ids do not match', {});
}
if (req.body.hookId && hookId !== req.body.hookId) {
return res.reportError('InputError', 'Hook Ids do not match', {});
}
hookDef.hookGroupId = hookGroupId;
hookDef.hookId = hookId;
await req.authorize({hookGroupId, hookId});
// Validate cron-parser expressions
_.forEach(hookDef.schedule, function(schedule) {
try {
parser.parseExpression(schedule);
} catch (err) {
return res.reportError('InputError',
'{{message}} in {{schedule}}', {message: err.message, schedule});
}
});
// Try to create a Hook entity
try {
var hook = await this.Hook.create(
_.defaults({}, hookDef, {
bindings: [], // TODO
triggerToken: taskcluster.slugid(),
lastFire: {result: 'no-fire'},
nextTaskId: taskcluster.slugid(),
nextScheduledDate: nextDate(hookDef.schedule),
}));
} catch (err) {
if (!err || err.code !== 'EntityAlreadyExists') {
throw err;
}
let existingHook = await this.Hook.load({hookGroupId, hookId}, true);
if (!_.isEqual(hookDef, await existingHook.definition())) {
return res.reportError('RequestConflict',
'hook `' + hookGroupId + '/' + hookId + '` already exists.',
{});
}
}
// Reply with the hook definition
return res.reply(hookDef);
});
/** Update hook definition**/
api.declare({
method: 'post',
route: '/hooks/:hookGroupId/:hookId',
name: 'updateHook',
idempotent: true,
scopes: {AllOf:
['hooks:modify-hook:<hookGroupId>/<hookId>', 'assume:hook-id:<hookGroupId>/<hookId>'],
},
input: 'create-hook-request.json',
output: 'hook-definition.json',
title: 'Update a hook',
stability: 'experimental',
description: [
'This endpoint will update an existing hook. All fields except',
'`hookGroupId` and `hookId` can be modified.',
].join('\n'),
}, async function(req, res) {
var hookGroupId = req.params.hookGroupId;
var hookId = req.params.hookId;
var hookDef = req.body;
if (req.body.hookGroupId && hookGroupId !== req.body.hookGroupId) {
return res.reportError('InputError', 'Hook Group Ids do not match', {});
}
if (req.body.hookId && hookId !== req.body.hookId) {
return res.reportError('InputError', 'Hook Ids do not match', {});
}
hookDef.hookGroupId = hookGroupId;
hookDef.hookId = hookId;
await req.authorize({hookGroupId, hookId});
var hook = await this.Hook.load({hookGroupId, hookId}, true);
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
// Attempt to modify properties of the hook
var schedule = hookDef.schedule ? hookDef.schedule : [];
_.forEach(schedule, function(schedule) {
try {
parser.parseExpression(schedule);
} catch (err) {
return res.reportError('InputError',
'{{message}} in {{schedule}}', {message: err.message, schedule});
}
});
await hook.modify((hook) => {
hook.metadata = hookDef.metadata;
hook.task = hookDef.task;
hook.triggerSchema = hookDef.triggerSchema;
hook.deadline = hookDef.deadline;
hook.expires = hookDef.expires ? hookDef.expires : '';
hook.schedule = schedule;
hook.nextTaskId = taskcluster.slugid();
hook.nextScheduledDate = nextDate(schedule);
});
let definition = await hook.definition();
return res.reply(definition);
});
/** Delete hook definition**/
api.declare({
method: 'delete',
route: '/hooks/:hookGroupId/:hookId',
name: 'removeHook',
idempotent: true,
scopes: 'hooks:modify-hook:<hookGroupId>/<hookId>',
title: 'Delete a hook',
stability: 'experimental',
description: [
'This endpoint will remove a hook definition.',
].join('\n'),
}, async function(req, res) {
var hookGroupId = req.params.hookGroupId;
var hookId = req.params.hookId;
await req.authorize({hookGroupId, hookId});
// Remove the resource if it exists
await this.Hook.remove({hookGroupId, hookId}, true);
return res.status(200).json({});
});
/** Trigger a hook **/
api.declare({
method: 'post',
route: '/hooks/:hookGroupId/:hookId/trigger',
name: 'triggerHook',
scopes: 'hooks:trigger-hook:<hookGroupId>/<hookId>',
input: 'trigger-context.json',
output: 'task-status.json',
title: 'Trigger a hook',
stability: 'experimental',
description: [
'This endpoint will trigger the creation of a task from a hook definition.',
'',
'The HTTP payload must match the hook\s `triggerSchema`. If it does, it is',
'provided as the `payload` property of the JSON-e context used to render the',
'task template.',
].join('\n'),
}, async function(req, res) {
var hookGroupId = req.params.hookGroupId;
var hookId = req.params.hookId;
await req.authorize({hookGroupId, hookId});
var lastFire;
var resp;
var payload = req.body;
var hook = await this.Hook.load({hookGroupId, hookId}, true);
var error = null;
const ajv = new Ajv({format: 'full', verbose: true, allErrors: true});
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
//Using ajv lib to check if the context respect the triggerSchema
var validate = ajv.compile(hook.triggerSchema);
if (validate && payload) {
let valid = validate(payload);
if (!valid) {
return res.reportError('InputError', '{{message}}', {
message: ajv.errorsText(validate.errors, {separator: '; '}
)});
}
}
// build the context for the task creation
let context = {
firedBy: 'triggerHook',
payload: payload,
};
try {
resp = await this.taskcreator.fire(hook, context);
lastFire = {
result: 'success',
taskId: resp.status.taskId,
time: new Date(),
};
} catch (err) {
error = err;
lastFire = {
result: 'error',
error: err,
time: new Date(),
};
}
await hook.modify((hook) => {
hook.lastFire = lastFire;
});
if (resp) {
return res.reply(resp);
} else {
return res.reportError('InputError', 'Could not create task: {{error}}',
{error: (error || 'unknown').toString()});
}
});
/** Get secret token for a trigger **/
api.declare({
method: 'get',
route: '/hooks/:hookGroupId/:hookId/token',
name: 'getTriggerToken',
scopes: 'hooks:get-trigger-token:<hookGroupId>/<hookId>',
input: undefined,
output: 'trigger-token-response.json',
title: 'Get a trigger token',
stability: 'experimental',
description: [
'Retrieve a unique secret token for triggering the specified hook. This',
'token can be deactivated with `resetTriggerToken`.',
].join('\n'),
}, async function(req, res) {
var hookGroupId = req.params.hookGroupId;
var hookId = req.params.hookId;
await req.authorize({hookGroupId, hookId});
let hook = await this.Hook.load({hookGroupId, hookId}, true);
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
return res.reply({
token: hook.triggerToken,
});
});
/** Reset a trigger token **/
api.declare({
method: 'post',
route: '/hooks/:hookGroupId/:hookId/token',
name: 'resetTriggerToken',
scopes: 'hooks:reset-trigger-token:<hookGroupId>/<hookId>',
input: undefined,
output: 'trigger-token-response.json',
title: 'Reset a trigger token',
stability: 'experimental',
description: [
'Reset the token for triggering a given hook. This invalidates token that',
'may have been issued via getTriggerToken with a new token.',
].join('\n'),
}, async function(req, res) {
var hookGroupId = req.params.hookGroupId;
var hookId = req.params.hookId;
await req.authorize({hookGroupId, hookId});
let hook = await this.Hook.load({hookGroupId, hookId}, true);
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
await hook.modify((hook) => {
hook.triggerToken = taskcluster.slugid();
});
return res.reply({
token: hook.triggerToken,
});
});
/** Trigger hook from a webhook with a token **/
api.declare({
method: 'post',
route: '/hooks/:hookGroupId/:hookId/trigger/:token',
name: 'triggerHookWithToken',
input: 'trigger-context.json',
output: 'task-status.json',
title: 'Trigger a hook with a token',
stability: 'experimental',
description: [
'This endpoint triggers a defined hook with a valid token.',
'',
'The HTTP payload must match the hook\s `triggerSchema`. If it does, it is',
'provided as the `payload` property of the JSON-e context used to render the',
'task template.',
].join('\n'),
}, async function(req, res) {
var payload = req.body;
const ajv = new Ajv({format: 'full', verbose: true, allErrors: true});
var hook = await this.Hook.load({
hookGroupId: req.params.hookGroupId,
hookId: req.params.hookId,
}, true);
// Return a 404 if the hook entity doesn't exist
if (!hook) {
return res.reportError('ResourceNotFound', 'No such hook', {});
}
// Return 401 if the token doesn't exist or doesn't match
if (req.params.token !== hook.triggerToken) {
return res.reportError('AuthenticationFailed', 'invalid hook token', {});
}
//Using ajv lib to check if the context respect the triggerSchema
var validate = ajv.compile(hook.triggerSchema);
if (validate && payload) {
let valid = validate(payload);
if (!valid) {
return res.reportError('InputError', '{{message}}', {message: validate.errors[0].message});
}
}
// build the context for the task creation
let context = {
firedBy: 'triggerHookWithToken',
payload: payload,
};
let resp = await this.taskcreator.fire(hook, context);
return res.reply(resp);
});