-
Notifications
You must be signed in to change notification settings - Fork 6
/
GitHubActionsRequester.ts
256 lines (228 loc) · 7.59 KB
/
GitHubActionsRequester.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
import { Octokit } from '@octokit/rest';
import axios from 'axios';
import { Request, Response } from 'express';
import * as Joi from 'joi';
import * as jwt from 'jsonwebtoken';
import { Requester, AllowedState } from './Requester';
import { Project, GitHubActionsRequesterConfig, OTPRequest } from '../db/models';
import { getGitHubAppInstallationToken } from '../helpers/auth';
import { RequestInformation } from '../responders/Responder';
import { CFA_RELEASE_GITHUB_ENVIRONMENT_NAME } from '../api/project/config';
import { getSignatureValidatedOIDCClaims } from '../helpers/oidc';
type GitHubActionsOTPRequestMetadata = {
oidcToken: string;
buildUrl: string;
};
const validateMetadataObject = (object: any) => {
return Joi.validate(object, {
oidcToken: Joi.string().min(1).required(),
buildUrl: Joi.string()
.uri({
scheme: 'https',
})
.required(),
});
};
export class GitHubActionsRequester
implements Requester<GitHubActionsRequesterConfig, GitHubActionsOTPRequestMetadata>
{
readonly slug = 'github';
getConfigForProject(project: Project) {
return project.requester_gitHub || null;
}
async getOpenIDConnectDiscoveryURL(project: Project, config: GitHubActionsRequesterConfig) {
return 'https://token.actions.githubusercontent.com';
}
async doOpenIDConnectClaimsMatchProject(
claims: jwt.JwtPayload,
project: Project,
config: GitHubActionsRequesterConfig,
) {
const internal = await this.doOpenIDConnectClaimsMatchProjectInternal(claims, project);
if (!internal.ok) {
console.error(
`Failed to match OIDC claims to project(${project.repoOwner}/${project.repoName}):`,
claims,
internal,
);
}
return internal.ok;
}
private async doOpenIDConnectClaimsMatchProjectInternal(
claims: jwt.JwtPayload,
project: Project,
): Promise<AllowedState> {
if (claims.aud !== 'continuousauth.dev') {
return { ok: false, error: 'Token audience is not correct' };
}
// Wrong repository
if (claims.repository_id !== project.id)
return { ok: false, error: 'GitHub Actions build is for incorrect repository id' };
// Wrong repository name (probably out of date)
if (claims.repository_owner !== project.repoOwner)
return { ok: false, error: 'GitHub Actions build is for incorrect repository owner' };
if (claims.repository !== `${project.repoOwner}/${project.repoName}`)
return { ok: false, error: 'GitHub Actions build is for incorrect repository' };
// Must be running int he right environment
if (
claims.sub !==
`repo:${project.repoOwner}/${project.repoName}:environment:${CFA_RELEASE_GITHUB_ENVIRONMENT_NAME}`
)
return { ok: false, error: 'GitHub Actions build is for incorrect environment' };
// Must be on the default branch
if (claims.ref.startsWith('refs/tags/')) {
const token = await getGitHubAppInstallationToken(project, {
metadata: 'read',
contents: 'read',
});
const github = new Octokit({ auth: token });
const comparison = await github.repos.compareCommitsWithBasehead({
owner: project.repoOwner,
repo: project.repoName,
// Use sha instead of ref here to ensure no malicious race between job start and
// ref re-point
basehead: `${claims.sha}...${project.defaultBranch}`,
});
if (
comparison.status !== 200 ||
!(comparison.data.behind_by === 0 && comparison.data.ahead_by >= 0)
) {
return {
ok: false,
error: 'GitHub Actions build is for a tag not on the default branch',
};
}
} else if (claims.ref !== `refs/heads/${project.defaultBranch}`) {
return {
ok: false,
error: 'GitHub Actions build is not for the default branch',
};
}
// Trigger must be GitHub
// Check event_name must be push
// Some repos use workflow_dispatch, those cases can be handled during migration
// as it requires more though
if (claims.event_name !== 'push')
return {
ok: false,
error: 'GitHub Actions build was triggered by not-a-push',
};
// Build must be currently running
// Hit API using claims.run_id, run_number and run_attempt
const token = await getGitHubAppInstallationToken(project, {
metadata: 'read',
contents: 'read',
});
const github = new Octokit({ auth: token });
let isStillRunning = false;
try {
const workflowRunAttempt = await github.actions.getWorkflowRunAttempt({
owner: project.repoOwner,
repo: project.repoName,
run_id: claims.run_id,
attempt_number: claims.run_attempt,
});
isStillRunning = workflowRunAttempt.data.status === 'in_progress';
} catch {
isStillRunning = false;
}
if (!isStillRunning)
return {
ok: false,
error: 'GitHub Actions build is not running',
};
// SSH must be disabled for safety
// We should be able to check this when GitHub releases actions ssh
// for now just checking we're running on github infra is enough
if (claims.runner_environment !== 'github-hosted')
return {
ok: false,
error: 'GitHub Actions build could have SSH enabled, this is not allowed',
};
return { ok: true, needsLogBasedProof: false };
}
async metadataForInitialRequest(
req: Request,
res: Response,
): Promise<GitHubActionsOTPRequestMetadata | null> {
const result = validateMetadataObject(req.body);
if (result.error) {
res.status(400).json({
error: 'Request Validation Error',
message: result.error.message,
});
return null;
}
return {
oidcToken: result.value.oidcToken,
buildUrl: result.value.buildUrl,
};
}
async validateActiveRequest(
request: OTPRequest<GitHubActionsOTPRequestMetadata, unknown>,
config: GitHubActionsRequesterConfig,
): Promise<AllowedState> {
const { project } = request;
// validate and parse claims from request
let claims: jwt.Jwt | null;
try {
claims = await getSignatureValidatedOIDCClaims(
this,
project,
config,
request.requestMetadata.oidcToken,
);
} catch (err) {
if (typeof err === 'string') {
return {
ok: false,
error: err,
};
}
claims = null;
}
if (!claims) {
return {
ok: false,
error: 'Failed to validate OIDC token',
};
}
const claimsEvaluation = await this.doOpenIDConnectClaimsMatchProjectInternal(
claims.payload as jwt.JwtPayload,
project,
);
if (!claimsEvaluation.ok) {
return {
ok: false,
error: claimsEvaluation.error,
};
}
return {
ok: true,
needsLogBasedProof: false,
};
}
async validateProofForRequest(
request: OTPRequest<GitHubActionsOTPRequestMetadata, unknown>,
config: GitHubActionsRequesterConfig,
): Promise<boolean> {
// Not needed, default closed
return false;
}
async isOTPRequestValidForRequester(
request: OTPRequest<unknown, unknown>,
): Promise<OTPRequest<GitHubActionsOTPRequestMetadata> | null> {
const result = validateMetadataObject(request.requestMetadata);
if (result.error) return null;
return request as any;
}
async getRequestInformationToPassOn(
request: OTPRequest<GitHubActionsOTPRequestMetadata, unknown>,
): Promise<RequestInformation> {
const { project } = request;
return {
description: `GitHub Actions Build for ${project.repoOwner}/${project.repoName}`,
url: request.requestMetadata.buildUrl,
};
}
}