-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCircleCIRequester.ts
237 lines (199 loc) · 6.94 KB
/
CircleCIRequester.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
import { Octokit } from '@octokit/rest';
import axios from 'axios';
import { Request, Response } from 'express';
import * as Joi from 'joi';
import type * as jwt from 'jsonwebtoken';
import { Requester, AllowedState } from './Requester';
import { Project, CircleCIRequesterConfig, OTPRequest } from '../db/models';
import { getGitHubAppInstallationToken } from '../helpers/auth';
import { RequestInformation } from '../responders/Responder';
export type CircleCIOTPRequestMetadata = {
buildNumber: number;
};
export const getAxiosForConfig = (config: CircleCIRequesterConfig) =>
axios.create({
baseURL: 'https://circleci.com/api/v1.1',
auth: {
username: config.accessToken,
password: '',
},
validateStatus: () => true,
});
// Unauthenticated
export const getAxiosForConfigV2 = (config: CircleCIRequesterConfig) =>
axios.create({
baseURL: 'https://circleci.com/api/v2',
validateStatus: () => true,
});
const validateMetadataObject = (object: any) => {
return Joi.validate(object, {
buildNumber: Joi.number().min(1).integer().required(),
});
};
export class CircleCIRequester
implements Requester<CircleCIRequesterConfig, CircleCIOTPRequestMetadata>
{
readonly slug = 'circleci';
getConfigForProject(project: Project) {
return project.requester_circleCI || null;
}
async getOpenIDConnectDiscoveryURL(project: Project, config: CircleCIRequesterConfig) {
const projectResponse = await getAxiosForConfigV2(config).get(
`/project/gh/${project.repoOwner}/${project.repoName}`,
);
if (projectResponse.status !== 200) {
return null;
}
const orgId = projectResponse.data.organization_id;
return `https://oidc.circleci.com/org/${orgId}`;
}
async doOpenIDConnectClaimsMatchProject(
claims: jwt.JwtPayload,
project: Project,
config: CircleCIRequesterConfig,
) {
const projectResponse = await getAxiosForConfigV2(config).get(
`/project/gh/${project.repoOwner}/${project.repoName}`,
);
if (projectResponse.status !== 200) {
return false;
}
return projectResponse.data.id === claims['oidc.circleci.com/project-id'];
}
async metadataForInitialRequest(
req: Request,
res: Response,
): Promise<CircleCIOTPRequestMetadata | null> {
const result = validateMetadataObject(req.body);
if (result.error) {
res.status(400).json({
error: 'Request Validation Error',
message: result.error.message,
});
return null;
}
return {
buildNumber: result.value.buildNumber,
};
}
async validateActiveRequest(
request: OTPRequest<CircleCIOTPRequestMetadata, unknown>,
config: CircleCIRequesterConfig,
): Promise<AllowedState> {
const { project } = request;
const buildResponse = await getAxiosForConfig(config).get(
`/project/github/${project.repoOwner}/${project.repoName}/${request.requestMetadata.buildNumber}`,
);
// Build clearly does not exist
if (buildResponse.status !== 200)
return {
ok: false,
error: 'CircleCI build does not exist',
};
const build = buildResponse.data;
// Must be on the default branch
if (build.vcs_tag) {
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,
basehead: `${build.vcs_tag}...${project.defaultBranch}`,
});
if (
comparison.status !== 200 ||
!(comparison.data.behind_by === 0 && comparison.data.ahead_by >= 0)
) {
return {
ok: false,
error: 'CircleCI build is for a tag not on the default branch',
};
}
} else if (build.branch !== project.defaultBranch) {
return {
ok: false,
error: 'CircleCI build is not for the default branch',
};
}
// Trigger must be GitHub
if (build.why !== 'github')
return {
ok: false,
error: 'CircleCI build was triggered manually, not by GitHub',
};
// Build must be currently running
if (build.status !== 'running')
return {
ok: false,
error: 'CircleCI build is not running',
};
// SSH must be disabled for safety
if (!build.ssh_disabled)
return {
ok: false,
error: 'CircleCI build had SSH enabled, this is not allowed',
};
return {
ok: true,
needsLogBasedProof: true,
};
}
async validateProofForRequest(
request: OTPRequest<CircleCIOTPRequestMetadata, unknown>,
config: CircleCIRequesterConfig,
): Promise<boolean> {
const { project, proof } = request;
const { buildNumber } = request.requestMetadata;
async function attemptToValidateProof(attempts: number): Promise<boolean> {
if (attempts <= 0) return false;
const again = async () => {
await new Promise((r) => setTimeout(r, 5000));
return attemptToValidateProof(attempts - 1);
};
const buildUrl = `/project/github/${project.repoOwner}/${project.repoName}/${buildNumber}`;
const buildResponse = await getAxiosForConfig(config).get(buildUrl, {
validateStatus: () => true,
});
// Build clearly does not exist
if (buildResponse.status !== 200) return again();
const build = buildResponse.data;
if (!build.steps || !build.steps.length) return again();
const finalStep = build.steps[build.steps.length - 1];
if (!finalStep || !finalStep.actions.length) return again();
const finalAction = finalStep.actions[finalStep.actions.length - 1];
const outputResponse = await getAxiosForConfig(config).get(
`${buildUrl}/output/${finalAction.step}/${finalAction.index}`,
{
validateStatus: () => true,
},
);
// Output clearly does not exist
if (outputResponse.status !== 200) return again();
const outputData = outputResponse.data;
if (!outputData.length) return again();
const output = outputData[0].message.trim();
if (new RegExp(`Proof:(\r?\n)${proof}$`).test(output)) return true;
return again();
}
return attemptToValidateProof(3);
}
async isOTPRequestValidForRequester(
request: OTPRequest<unknown, unknown>,
): Promise<OTPRequest<CircleCIOTPRequestMetadata> | null> {
const result = validateMetadataObject(request.requestMetadata);
if (result.error) return null;
return request as any;
}
async getRequestInformationToPassOn(
request: OTPRequest<CircleCIOTPRequestMetadata, unknown>,
): Promise<RequestInformation> {
const { project } = request;
return {
description: `Circle CI Build for ${project.repoOwner}/${project.repoName}#${request.requestMetadata.buildNumber}`,
url: `https://circleci.com/gh/${project.repoOwner}/${project.repoName}/${request.requestMetadata.buildNumber}`,
};
}
}