This repository was archived by the owner on Feb 12, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtask.ts
More file actions
341 lines (286 loc) · 15.1 KB
/
task.ts
File metadata and controls
341 lines (286 loc) · 15.1 KB
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
import axios, { AxiosError, AxiosResponse } from 'axios';
import axiosRetry from 'axios-retry';
import * as core from '@actions/core';
import * as moment from 'moment';
import url from 'url';
import { LogEntry, LogLevelDebug, LogLevelError, LogLevelInformation, LogLevelWarning, SubmitSigningRequestResult, ValidationResult } from './dtos/submit-signing-request-result';
import { buildSignPathAuthorizationHeader, executeWithRetries, httpErrorResponseToText } from './utils';
import { SignPathUrlBuilder } from './signpath-url-builder';
import { SigningRequestDto } from './dtos/signing-request';
import { HelperInputOutput } from './helper-input-output';
import { taskVersion } from './version';
import { HelperArtifactDownload } from './helper-artifact-download';
import { Config } from './config';
// output variables
// signingRequestId - the id of the newly created signing request
// signingRequestWebUrl - the url of the signing request in SignPath
// signPathApiUrl - the base API url of the SignPath API
// signingRequestDownloadUrl - the url of the signed artifact in SignPath
export class Task {
urlBuilder: SignPathUrlBuilder;
constructor (
private helperInputOutput: HelperInputOutput,
private helperArtifactDownload: HelperArtifactDownload,
private config: Config) {
this.urlBuilder = new SignPathUrlBuilder(this.helperInputOutput.signPathConnectorUrl);
}
async run() {
this.configureAxios();
try {
const signingRequestId = await this.submitSigningRequest();
if (this.helperInputOutput.waitForCompletion) {
const signingRequest = await this.ensureSigningRequestCompleted(signingRequestId);
this.helperInputOutput.setSignedArtifactDownloadUrl(signingRequest.signedArtifactLink);
if(this.helperInputOutput.outputArtifactDirectory) {
await this.helperArtifactDownload.downloadSignedArtifact(signingRequest.signedArtifactLink);
}
}
else {
await this.ensureSignPathDownloadedUnsignedArtifact(signingRequestId);
}
}
catch (err) {
core.setFailed((err as any).message);
}
}
private async submitSigningRequest (): Promise<string> {
core.info('Submitting the signing request to SignPath CI connector...');
// prepare the payload
const submitRequestPayload = this.buildSigningRequestPayload();
// call the signPath API to submit the signing request
const response = (await axios
.post<SubmitSigningRequestResult>(this.urlBuilder.buildSubmitSigningRequestUrl(),
submitRequestPayload,
{ responseType: "json" })
.catch((e: AxiosError) => {
if(e.code === AxiosError.ERR_BAD_REQUEST) {
const connectorResponse = e.response as AxiosResponse<SubmitSigningRequestResult>;
if(connectorResponse.data.error) {
this.redirectConnectorLogsToActionLogs(connectorResponse.data.logs);
// when an error occurs in the validator the error details are in the validationResult
this.checkCiSystemValidationResult(connectorResponse.data.validationResult);
throw new Error(connectorResponse.data.error);
}
// got validation errors from the connector
return connectorResponse;
}
core.error(`SignPath API call error: ${e.message}`);
throw new Error(httpErrorResponseToText(e));
}))
.data;
this.checkResponseStructure(response);
this.redirectConnectorLogsToActionLogs(response.logs);
this.checkCiSystemValidationResult(response.validationResult);
const signingRequestUrlObj = url.parse(response.signingRequestUrl);
this.urlBuilder.signPathBaseUrl = signingRequestUrlObj.protocol + '//' + signingRequestUrlObj.host;
core.info(`SignPath signing request has been successfully submitted`);
core.info(`The signing request id is ${response.signingRequestId}`);
core.info(`You can view the signing request here: ${response.signingRequestUrl}`);
this.helperInputOutput.setSigningRequestId(response.signingRequestId);
this.helperInputOutput.setSigningRequestWebUrl(response.signingRequestUrl);
this.helperInputOutput.setSignPathApiUrl(this.urlBuilder.signPathBaseUrl + '/API');
return response.signingRequestId;
}
private checkCiSystemValidationResult(validationResult: ValidationResult): void {
if (validationResult && validationResult.errors.length > 0) {
// got validation errors from the connector
core.startGroup('CI system setup validation errors')
core.error(`Build artifact with id \"${this.helperInputOutput.githubArtifactId}\" cannot be signed because of continuous integration system setup validation errors:`);
validationResult.errors.forEach(validationError => {
core.error(`${validationError.error}`);
if (validationError.howToFix)
{
core.info(validationError.howToFix);
}
});
core.endGroup()
throw new Error("CI system validation failed.");
}
}
// if auto-generated GitHub Actions token (secrets.GITHUB_TOKEN) is used for artifact download,
// ensure the workflow continues running until the download is complete.
// The token is valid only for the workflow's duration
private async ensureSignPathDownloadedUnsignedArtifact(signingRequestId: string): Promise<void> {
core.info(`Waiting until SignPath downloaded the unsigned artifact...`);
const requestData = await (executeWithRetries<SigningRequestDto>(
async () => {
const signingRequestDto = await (this.getSigningRequest(signingRequestId)
.then(data => {
if(!data.unsignedArtifactLink && !data.isFinalStatus) {
core.info(`Checking the download status: not yet complete`);
// retry artifact download status check
return { retry: true };
}
return { retry: false, result: data };
}));
return signingRequestDto;
},
this.helperInputOutput.waitForCompletionTimeoutInSeconds * 1000,
this.config.CheckArtifactDownloadStatusIntervalInSeconds * 1000,
this.config.CheckArtifactDownloadStatusIntervalInSeconds * 1000));
if (!requestData.unsignedArtifactLink) {
if(!requestData.isFinalStatus) {
const maxWaitingTime = moment.utc(this.helperInputOutput.waitForCompletionTimeoutInSeconds * 1000).format("hh:mm");
core.error(`We have exceeded the maximum waiting time, which is ${maxWaitingTime}, and the GitHub artifact is still not downloaded by SignPath`);
} else {
core.error(`The signing request is in its final state, but the GitHub artifact has not been downloaded by SignPath.`);
}
throw new Error(`The GitHub artifact is not downloaded by SignPath`);
}
else {
core.info(`The unsigned GitHub artifact has been successfully downloaded by SignPath`);
}
// else continue workflow execution
// artifact already downloaded by SignPath
}
private async ensureSigningRequestCompleted(signingRequestId: string): Promise<SigningRequestDto> {
// check for status update
core.info(`Checking the signing request status...`);
const requestData = await (executeWithRetries<SigningRequestDto>(
async () => {
const signingRequestDto = await (this.getSigningRequest(signingRequestId)
.then(data => {
if(data && !data.isFinalStatus) {
core.info(`The signing request status is ${data.status}, which is not a final status; after a delay, we will check again...`);
return { retry: true };
}
return { retry: false, result: data };
}));
return signingRequestDto;
},
this.helperInputOutput.waitForCompletionTimeoutInSeconds * 1000,
this.config.MinDelayBetweenSigningRequestStatusChecksInSeconds * 1000,
this.config.MaxDelayBetweenSigningRequestStatusChecksInSeconds * 1000));
core.info(`Signing request status is ${requestData.status}`);
if (!requestData.isFinalStatus) {
const maxWaitingTime = moment.utc(this.helperInputOutput.waitForCompletionTimeoutInSeconds * 1000).format("hh:mm");
core.error(`We have exceeded the maximum waiting time, which is ${maxWaitingTime}, and the signing request is still not in a final state`);
throw new Error(`The signing request is not completed. The current status is "${requestData.status}`);
} else {
if (requestData.status !== "Completed") {
throw new Error(`The signing request is not completed. The final status is "${requestData.status}"`);
}
}
return requestData;
}
private async getSigningRequest(signingRequestId: string): Promise<SigningRequestDto> {
const requestStatusUrl = this.urlBuilder.buildGetSigningRequestUrl(
this.helperInputOutput.organizationId, signingRequestId);
const signingRequestDto = await axios
.get<SigningRequestDto>(
requestStatusUrl,
{
responseType: "json",
headers: {
"Authorization": buildSignPathAuthorizationHeader(this.helperInputOutput.signPathApiToken)
}
}
)
.catch((e: AxiosError) => {
core.error(`SignPath API call error: ${e.message}`);
core.error(`Signing request details API URL is: ${requestStatusUrl}`);
throw new Error(httpErrorResponseToText(e));
})
.then(response => response.data);
return signingRequestDto;
}
private configureAxios(): void {
// set user agent
axios.defaults.headers.common['User-Agent'] = this.buildUserAgent();
const timeoutMs = this.helperInputOutput.serviceUnavailableTimeoutInSeconds * 1000
axios.defaults.timeout = timeoutMs;
// original axiosRetry doesn't work for POST requests
// thats why we need to override some functions
axiosRetry.isNetworkOrIdempotentRequestError = (error: AxiosError) => {
return axiosRetry.isNetworkError(error) || axiosRetry.isIdempotentRequestError(error);
};
axiosRetry.isIdempotentRequestError = (error: AxiosError) => {
if (!error.config?.method) {
// Cannot determine if the request can be retried
return false;
}
return axiosRetry.isRetryableError(error);
};
// by default axiosRetry retries on 5xx errors
// we want to change this and retry only 502, 503, 504, 429
axiosRetry.isRetryableError = (error: AxiosError) => {
let retryableHttpErrorCode = false;
if(error.response) {
if(error.response.status === 502
|| error.response.status === 503
|| error.response.status === 504) {
retryableHttpErrorCode = true;
core.info(`SignPath REST API is temporarily unavailable (server responded with ${error.response.status}).`);
}
if(error.response.status === 429) {
retryableHttpErrorCode = true;
core.info('SignPath REST API encountered too many requests.');
}
}
return (error.code !== 'ECONNABORTED' &&
(!error.response || retryableHttpErrorCode));
}
// set retries
// the delays are powers of 2 * 100ms, with 20% jitter
// we want to cover 10 minutes of SignPath service unavailability
// so we need to do 12 retries
// sum of 2^0 + 2^1 + ... + 2^12 = 2^13 - 1 = 8191
// 8191 * 100ms = 819.1 seconds = 13.65 minutes
// 11 retries will not be enough to cover 10 minutes downtime
const maxRetryCount = 12;
axiosRetry(axios, {
retryDelay: axiosRetry.exponentialDelay,
retries: maxRetryCount,
retryCondition: axiosRetry.isNetworkOrIdempotentRequestError
});
}
private buildUserAgent(): string {
const userAgent = `SignPath.SubmitSigningRequestGitHubAction/${taskVersion}(NodeJS/${process.version}; ${process.platform} ${process.arch}})`;
return userAgent;
}
private checkResponseStructure(response: SubmitSigningRequestResult): void {
if (!response.validationResult && !response.signingRequestId) {
// if neither validationResult nor signingRequestId are present,
// then the response might be not from the connector
core.error(`Unexpected response from the SignPath connector: ${JSON.stringify(response)}`);
throw new Error(`SignPath signing request was not created. Please make sure that connector-url is pointing to the SignPath GitHub Actions connector endpoint.`);
}
}
private redirectConnectorLogsToActionLogs(logs: LogEntry[]): void {
if (logs && logs.length > 0) {
logs.forEach(log => {
switch (log.level) {
case LogLevelDebug:
core.debug(log.message);
break;
case LogLevelInformation:
core.info(log.message);
break;
case LogLevelWarning:
core.warning(log.message);
break;
case LogLevelError:
core.error(log.message);
break;
default:
core.info(`${log.level}:${log.message}`);
break;
}
});
}
}
private buildSigningRequestPayload(): any {
return {
signPathApiToken: this.helperInputOutput.signPathApiToken,
artifactId: this.helperInputOutput.githubArtifactId,
gitHubWorkflowRunId: process.env.GITHUB_RUN_ID,
gitHubRepository: process.env.GITHUB_REPOSITORY,
gitHubToken: this.helperInputOutput.gitHubToken,
signPathOrganizationId: this.helperInputOutput.organizationId,
signPathProjectSlug: this.helperInputOutput.projectSlug,
signPathSigningPolicySlug: this.helperInputOutput.signingPolicySlug,
signPathArtifactConfigurationSlug: this.helperInputOutput.artifactConfigurationSlug,
parameters: this.helperInputOutput.parameters
};
}
}