forked from triggerdotdev/trigger.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetDeploymentImageRef.server.ts
More file actions
565 lines (501 loc) · 14.6 KB
/
getDeploymentImageRef.server.ts
File metadata and controls
565 lines (501 loc) · 14.6 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
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
557
558
559
560
561
562
563
564
565
import {
ECRClient,
CreateRepositoryCommand,
DescribeRepositoriesCommand,
type Repository,
type Tag,
RepositoryNotFoundException,
GetAuthorizationTokenCommand,
PutLifecyclePolicyCommand,
PutImageTagMutabilityCommand,
SetRepositoryPolicyCommand,
} from "@aws-sdk/client-ecr";
import { STSClient, AssumeRoleCommand } from "@aws-sdk/client-sts";
import { tryCatch } from "@trigger.dev/core";
import { logger } from "~/services/logger.server";
import { type RegistryConfig } from "./registryConfig.server";
import type { EnvironmentType } from "@trigger.dev/core/v3";
// Optional configuration for cross-account access
export type AssumeRoleConfig = {
roleArn?: string;
externalId?: string;
};
async function getAssumedRoleCredentials({
region,
assumeRole,
}: {
region: string;
assumeRole?: AssumeRoleConfig;
}): Promise<{
accessKeyId: string;
secretAccessKey: string;
sessionToken: string;
}> {
const sts = new STSClient({ region });
// Generate a unique session name using timestamp and random string
// This helps with debugging but doesn't affect concurrent sessions
const timestamp = Date.now();
const randomSuffix = Math.random().toString(36).substring(2, 8);
const sessionName = `TriggerWebappECRAccess_${timestamp}_${randomSuffix}`;
const [error, response] = await tryCatch(
sts.send(
new AssumeRoleCommand({
RoleArn: assumeRole?.roleArn,
RoleSessionName: sessionName,
// Sessions automatically expire after 1 hour
// AWS allows 5000 concurrent sessions by default
DurationSeconds: 3600,
ExternalId: assumeRole?.externalId,
})
)
);
if (error) {
logger.error("Failed to assume role", {
assumeRole,
sessionName,
error: error.message,
});
throw error;
}
if (!response.Credentials) {
throw new Error("STS: No credentials returned from assumed role");
}
if (
!response.Credentials.AccessKeyId ||
!response.Credentials.SecretAccessKey ||
!response.Credentials.SessionToken
) {
throw new Error("STS: Invalid credentials returned from assumed role");
}
return {
accessKeyId: response.Credentials.AccessKeyId,
secretAccessKey: response.Credentials.SecretAccessKey,
sessionToken: response.Credentials.SessionToken,
};
}
export async function createEcrClient({
region,
assumeRole,
}: {
region: string;
assumeRole?: AssumeRoleConfig;
}) {
if (!assumeRole) {
return new ECRClient({ region });
}
// Get credentials for cross-account access
const credentials = await getAssumedRoleCredentials({ region, assumeRole });
return new ECRClient({
region,
credentials,
});
}
export async function getDeploymentImageRef({
registry,
projectRef,
nextVersion,
environmentType,
deploymentShortCode,
}: {
registry: RegistryConfig;
projectRef: string;
nextVersion: string;
environmentType: EnvironmentType;
deploymentShortCode: string;
}): Promise<{
imageRef: string;
isEcr: boolean;
repoCreated: boolean;
}> {
const repositoryName = `${registry.namespace}/${projectRef}`;
const envType = environmentType.toLowerCase();
const imageRef = `${registry.host}/${repositoryName}:${nextVersion}.${envType}.${deploymentShortCode}`;
if (!isEcrRegistry(registry.host)) {
return {
imageRef,
isEcr: false,
repoCreated: false,
};
}
const [ecrRepoError, ecrData] = await tryCatch(
ensureEcrRepositoryExists({
repositoryName,
registryHost: registry.host,
registryTags: registry.ecrTags,
assumeRole: {
roleArn: registry.ecrAssumeRoleArn,
externalId: registry.ecrAssumeRoleExternalId,
},
defaultRepositoryPolicy: registry.ecrDefaultRepositoryPolicy,
})
);
if (ecrRepoError) {
logger.error("Failed to ensure ECR repository exists", {
repositoryName,
host: registry.host,
ecrRepoError: ecrRepoError.message,
});
throw ecrRepoError;
}
return {
imageRef,
isEcr: true,
repoCreated: ecrData.repoCreated,
};
}
export function isEcrRegistry(registryHost: string) {
try {
parseEcrRegistryDomain(registryHost);
return true;
} catch {
return false;
}
}
export function parseRegistryTags(tags: string): Tag[] {
if (!tags) {
return [];
}
return tags
.split(",")
.map((t) => {
const tag = t.trim();
if (tag.length === 0) {
return null;
}
// If there's no '=' in the tag, treat the whole tag as the key with an empty value
const equalIndex = tag.indexOf("=");
const key = equalIndex === -1 ? tag : tag.slice(0, equalIndex);
const value = equalIndex === -1 ? "" : tag.slice(equalIndex + 1);
if (key.trim().length === 0) {
logger.warn("Invalid ECR tag format (empty key), skipping tag", { tag: t });
return null;
}
return {
Key: key.trim(),
Value: value.trim(),
} as Tag;
})
.filter((tag): tag is Tag => tag !== null);
}
const untaggedImageExpirationPolicy = JSON.stringify({
rules: [
{
rulePriority: 1,
description: "Expire untagged images older than 3 days",
selection: {
tagStatus: "untagged",
countType: "sinceImagePushed",
countUnit: "days",
countNumber: 3,
},
action: { type: "expire" },
},
],
});
async function createEcrRepository({
repositoryName,
region,
accountId,
registryTags,
assumeRole,
defaultRepositoryPolicy,
}: {
repositoryName: string;
region: string;
accountId?: string;
registryTags?: string;
assumeRole?: AssumeRoleConfig;
defaultRepositoryPolicy?: string;
}): Promise<Repository> {
const ecr = await createEcrClient({ region, assumeRole });
const result = await ecr.send(
new CreateRepositoryCommand({
repositoryName,
imageTagMutability: "IMMUTABLE_WITH_EXCLUSION",
imageTagMutabilityExclusionFilters: [
{
// only the `cache` tag will be mutable, all other tags will be immutable
filter: "cache",
filterType: "WILDCARD",
},
],
encryptionConfiguration: {
encryptionType: "AES256",
},
registryId: accountId,
tags: registryTags ? parseRegistryTags(registryTags) : undefined,
})
);
if (!result.repository) {
logger.error("Failed to create ECR repository", { repositoryName, result });
throw new Error(`Failed to create ECR repository: ${repositoryName}`);
}
// When the `cache` tag is mutated, the old cache images are untagged.
// This policy matches those images and expires them to avoid bloating the repository.
await ecr.send(
new PutLifecyclePolicyCommand({
repositoryName: result.repository.repositoryName,
registryId: result.repository.registryId,
lifecyclePolicyText: untaggedImageExpirationPolicy,
})
);
// Apply an operator-provided IAM policy to the new repository. Useful for
// self-hosters whose ECR account is separate from the account running the
// EKS workers — without this the workers get 403 Forbidden when pulling the
// task image (default ECR policy only grants access to the registry owner).
// The existing-repo branch of `ensureEcrRepositoryExists` reconciles this
// same policy on every call, so a partial-create that fails here is
// self-healing on the next deploy.
if (defaultRepositoryPolicy) {
await applyEcrRepositoryPolicy({
repositoryName: result.repository.repositoryName!,
region,
accountId: result.repository.registryId ?? accountId,
assumeRole,
defaultRepositoryPolicy,
});
}
return result.repository;
}
async function applyEcrRepositoryPolicy({
repositoryName,
region,
accountId,
assumeRole,
defaultRepositoryPolicy,
}: {
repositoryName: string;
region: string;
accountId?: string;
assumeRole?: AssumeRoleConfig;
defaultRepositoryPolicy: string;
}): Promise<void> {
const ecr = await createEcrClient({ region, assumeRole });
await ecr.send(
new SetRepositoryPolicyCommand({
repositoryName,
registryId: accountId,
policyText: defaultRepositoryPolicy,
})
);
}
async function updateEcrRepositoryCacheSettings({
repositoryName,
region,
accountId,
assumeRole,
}: {
repositoryName: string;
region: string;
accountId?: string;
assumeRole?: AssumeRoleConfig;
}): Promise<void> {
logger.debug("Updating ECR repository tag mutability to IMMUTABLE_WITH_EXCLUSION", {
repositoryName,
region,
});
const ecr = await createEcrClient({ region, assumeRole });
await ecr.send(
new PutImageTagMutabilityCommand({
repositoryName,
registryId: accountId,
imageTagMutability: "IMMUTABLE_WITH_EXCLUSION",
imageTagMutabilityExclusionFilters: [
{
// only the `cache` tag will be mutable, all other tags will be immutable
filter: "cache",
filterType: "WILDCARD",
},
],
})
);
// When the `cache` tag is mutated, the old cache images are untagged.
// This policy matches those images and expires them to avoid bloating the repository.
await ecr.send(
new PutLifecyclePolicyCommand({
repositoryName,
registryId: accountId,
lifecyclePolicyText: untaggedImageExpirationPolicy,
})
);
logger.debug("Successfully updated ECR repository to IMMUTABLE_WITH_EXCLUSION", {
repositoryName,
region,
});
}
async function getEcrRepository({
repositoryName,
region,
accountId,
assumeRole,
}: {
repositoryName: string;
region: string;
accountId?: string;
assumeRole?: AssumeRoleConfig;
}): Promise<Repository | undefined> {
const ecr = await createEcrClient({ region, assumeRole });
try {
const result = await ecr.send(
new DescribeRepositoriesCommand({
repositoryNames: [repositoryName],
registryId: accountId,
})
);
if (!result.repositories || result.repositories.length === 0) {
logger.debug("ECR repository not found", { repositoryName, region, result });
return undefined;
}
return result.repositories[0];
} catch (error) {
if (
error instanceof RepositoryNotFoundException ||
(error instanceof Error && error.message?.includes("does not exist"))
) {
logger.debug("ECR repository not found: RepositoryNotFoundException", {
repositoryName,
region,
});
return undefined;
}
throw error;
}
}
export type EcrRegistryComponents = {
accountId: string;
region: string;
};
export function parseEcrRegistryDomain(registryHost: string): EcrRegistryComponents {
const parts = registryHost.split(".");
const isValid =
parts.length === 6 &&
parts[1] === "dkr" &&
parts[2] === "ecr" &&
parts[4] === "amazonaws" &&
parts[5] === "com";
if (!isValid) {
throw new Error(`Invalid ECR registry host: ${registryHost}`);
}
return {
accountId: parts[0],
region: parts[3],
};
}
async function ensureEcrRepositoryExists({
repositoryName,
registryHost,
registryTags,
assumeRole,
defaultRepositoryPolicy,
}: {
repositoryName: string;
registryHost: string;
registryTags?: string;
assumeRole?: AssumeRoleConfig;
defaultRepositoryPolicy?: string;
}): Promise<{ repo: Repository; repoCreated: boolean }> {
const { region, accountId } = parseEcrRegistryDomain(registryHost);
const [getRepoError, existingRepo] = await tryCatch(
getEcrRepository({ repositoryName, region, accountId, assumeRole })
);
if (getRepoError) {
logger.error("Failed to get ECR repository", { repositoryName, region, getRepoError });
throw getRepoError;
}
if (existingRepo) {
logger.debug("ECR repository already exists", { repositoryName, region, existingRepo });
// check if the repository is missing the cache settings
if (existingRepo.imageTagMutability === "IMMUTABLE") {
const [updateError] = await tryCatch(
updateEcrRepositoryCacheSettings({ repositoryName, region, accountId, assumeRole })
);
if (updateError) {
logger.error("Failed to update ECR repository cache settings", {
repositoryName,
region,
updateError,
});
}
}
// Reconcile the default repository policy on every call. Idempotent, and
// covers two recovery cases: (1) a previous create succeeded but the
// SetRepositoryPolicy call failed mid-flight, leaving the repo without a
// policy; (2) the operator updated DEPLOY_REGISTRY_ECR_DEFAULT_REPOSITORY_POLICY
// and existing repos need to pick up the new value.
if (defaultRepositoryPolicy) {
const [policyError] = await tryCatch(
applyEcrRepositoryPolicy({
repositoryName,
region,
accountId,
assumeRole,
defaultRepositoryPolicy,
})
);
if (policyError) {
logger.error("Failed to reconcile ECR repository policy on existing repo", {
repositoryName,
region,
policyError,
});
}
}
return {
repo: existingRepo,
repoCreated: false,
};
}
const [createRepoError, newRepo] = await tryCatch(
createEcrRepository({
repositoryName,
region,
accountId,
registryTags,
assumeRole,
defaultRepositoryPolicy,
})
);
if (createRepoError) {
logger.error("Failed to create ECR repository", { repositoryName, region, createRepoError });
throw createRepoError;
}
if (newRepo.repositoryName !== repositoryName) {
logger.error("ECR repository name mismatch", { repositoryName, region, newRepo });
throw new Error(
`ECR repository name mismatch: ${repositoryName} !== ${newRepo.repositoryName}`
);
}
return {
repo: newRepo,
repoCreated: true,
};
}
export async function getEcrAuthToken({
registryHost,
assumeRole,
}: {
registryHost: string;
assumeRole?: AssumeRoleConfig;
}): Promise<{ username: string; password: string }> {
const { region, accountId } = parseEcrRegistryDomain(registryHost);
if (!region) {
logger.error("Invalid ECR registry host", { registryHost });
throw new Error("Invalid ECR registry host");
}
const ecr = await createEcrClient({ region, assumeRole });
const response = await ecr.send(
new GetAuthorizationTokenCommand({
registryIds: accountId ? [accountId] : undefined,
})
);
if (!response.authorizationData) {
throw new Error("Failed to get ECR authorization token");
}
const authData = response.authorizationData[0];
if (!authData.authorizationToken) {
throw new Error("No authorization token returned from ECR");
}
const authToken = Buffer.from(authData.authorizationToken, "base64").toString();
const [username, password] = authToken.split(":");
return { username, password };
}