@pipeline-builder/pipeline-manager 6.5.4 → 6.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +2 -2
  2. package/dist/agent/post-steps.d.ts +1 -1
  3. package/dist/agent/post-steps.d.ts.map +1 -1
  4. package/dist/agent/post-steps.js +27 -31
  5. package/dist/cli.d.ts.map +1 -1
  6. package/dist/cli.js +8 -9
  7. package/dist/commands/audit-stacks.d.ts +2 -1
  8. package/dist/commands/audit-stacks.d.ts.map +1 -1
  9. package/dist/commands/audit-stacks.js +12 -2
  10. package/dist/commands/deploy-job.js +4 -4
  11. package/dist/commands/provision-steps.d.ts +1 -1
  12. package/dist/commands/provision-steps.js +2 -2
  13. package/dist/commands/provision.js +2 -2
  14. package/dist/commands/redrive-events.d.ts +4 -3
  15. package/dist/commands/redrive-events.d.ts.map +1 -1
  16. package/dist/commands/redrive-events.js +51 -18
  17. package/dist/commands/runner-signing-key.js +2 -2
  18. package/dist/commands/{setup-runner.d.ts → setup-account.d.ts} +119 -71
  19. package/dist/commands/setup-account.d.ts.map +1 -0
  20. package/dist/commands/setup-account.js +1345 -0
  21. package/dist/commands/store-token.d.ts +6 -28
  22. package/dist/commands/store-token.d.ts.map +1 -1
  23. package/dist/commands/store-token.js +12 -139
  24. package/dist/config/cli.constants.d.ts +0 -8
  25. package/dist/config/cli.constants.d.ts.map +1 -1
  26. package/dist/config/cli.constants.js +1 -9
  27. package/dist/lambda/events-handler.js +1529 -0
  28. package/dist/lambda/runner-handler.d.ts +25 -1
  29. package/dist/lambda/runner-handler.d.ts.map +1 -1
  30. package/dist/lambda/runner-handler.js +403 -50
  31. package/dist/lambda/runner-inspect-connection.d.ts +32 -0
  32. package/dist/lambda/runner-inspect-connection.d.ts.map +1 -0
  33. package/dist/lambda/runner-inspect-connection.js +144 -0
  34. package/dist/lambda/runner-inspect.d.ts +6 -1
  35. package/dist/lambda/runner-inspect.d.ts.map +1 -1
  36. package/dist/lambda/runner-inspect.js +15 -5
  37. package/dist/lambda/runner-jws.d.ts.map +1 -1
  38. package/dist/lambda/runner-jws.js +59 -6
  39. package/dist/lambda/runner-sources.d.ts +12 -0
  40. package/dist/lambda/runner-sources.d.ts.map +1 -1
  41. package/dist/lambda/runner-sources.js +28 -22
  42. package/dist/lambda/token-renew-handler.d.ts +3 -2
  43. package/dist/lambda/token-renew-handler.d.ts.map +1 -1
  44. package/dist/lambda/token-renew-handler.js +17 -5
  45. package/dist/templates/account-stack.json +2049 -0
  46. package/dist/templates/forwarder-stack.json +133 -0
  47. package/dist/utils/{runner-template.d.ts → account-template.d.ts} +69 -18
  48. package/dist/utils/account-template.d.ts.map +1 -0
  49. package/dist/utils/account-template.js +316 -0
  50. package/dist/utils/inspect-buildspec.d.ts +9 -0
  51. package/dist/utils/inspect-buildspec.d.ts.map +1 -0
  52. package/dist/utils/inspect-buildspec.js +209 -0
  53. package/package.json +5 -4
  54. package/dist/commands/setup-events.d.ts +0 -15
  55. package/dist/commands/setup-events.d.ts.map +0 -1
  56. package/dist/commands/setup-events.js +0 -182
  57. package/dist/commands/setup-runner.d.ts.map +0 -1
  58. package/dist/commands/setup-runner.js +0 -1132
  59. package/dist/templates/events-stack.json +0 -192
  60. package/dist/templates/runner-stack.json +0 -948
  61. package/dist/templates/token-renew-stack.json +0 -115
  62. package/dist/utils/cron.d.ts +0 -28
  63. package/dist/utils/cron.d.ts.map +0 -1
  64. package/dist/utils/cron.js +0 -119
  65. package/dist/utils/runner-template.d.ts.map +0 -1
  66. package/dist/utils/runner-template.js +0 -229
@@ -9,7 +9,10 @@ import {
9
9
  } from "@aws-sdk/client-codepipeline";
10
10
  import { KMSClient } from "@aws-sdk/client-kms";
11
11
  import { GetResourcesCommand, ResourceGroupsTaggingAPIClient } from "@aws-sdk/client-resource-groups-tagging-api";
12
+ import { S3Client } from "@aws-sdk/client-s3";
12
13
  import { SecretsManagerClient } from "@aws-sdk/client-secrets-manager";
14
+ import { GetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs";
15
+ import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";
13
16
 
14
17
  // ../api-core/lib/types/pipeline-runners.js
15
18
  var PIPELINE_ID_TAG = "pb.pipeline-id";
@@ -30,11 +33,18 @@ var RUNNER_ACTIONS = [
30
33
  "list_sources",
31
34
  "check_source",
32
35
  // Reading a private GitHub repository for Generate from Git with the stored token, inside the account.
33
- "inspect_repository"
36
+ "inspect_repository",
37
+ // Reading any private repository for Generate from Git through a CodeConnections connection: a short
38
+ // CodeBuild job in the account clones it and leaves a bounded snapshot the platform reads back.
39
+ "inspect_connection_start",
40
+ "inspect_connection_status"
34
41
  ];
35
42
  var DEPLOY_CAPABILITY = "deploy:1";
36
43
  var SOURCES_CAPABILITY = "sources:1";
37
44
  var INSPECT_CAPABILITY = "inspect:1";
45
+ var INSPECT_CONNECTION_CAPABILITY = "inspect_connection:1";
46
+ var IDENTITY_CAPABILITY = "identity:1";
47
+ var EVENTS_CAPABILITY = "events:1";
38
48
  var DEPLOY_ACTION_CAPABILITY = {
39
49
  deploy: DEPLOY_CAPABILITY,
40
50
  deploy_status: DEPLOY_CAPABILITY,
@@ -48,8 +58,28 @@ var SOURCE_ACTION_CAPABILITY = {
48
58
  var INSPECT_ACTION_CAPABILITY = {
49
59
  inspect_repository: INSPECT_CAPABILITY
50
60
  };
51
- var ACTION_CAPABILITY = { ...DEPLOY_ACTION_CAPABILITY, ...SOURCE_ACTION_CAPABILITY, ...INSPECT_ACTION_CAPABILITY };
61
+ var INSPECT_CONNECTION_ACTION_CAPABILITY = {
62
+ inspect_connection_start: INSPECT_CONNECTION_CAPABILITY,
63
+ inspect_connection_status: INSPECT_CONNECTION_CAPABILITY
64
+ };
65
+ var ACTION_CAPABILITY = {
66
+ ...DEPLOY_ACTION_CAPABILITY,
67
+ ...SOURCE_ACTION_CAPABILITY,
68
+ ...INSPECT_ACTION_CAPABILITY,
69
+ ...INSPECT_CONNECTION_ACTION_CAPABILITY
70
+ };
52
71
  var AWS_REGION_PATTERN = /^[a-z]{2}(-[a-z]+)+-\d{1,2}$/;
72
+ var RUNNER_LABEL_MAX_LENGTH = 64;
73
+ var CONTROL_CHARS_G = /[\p{Cc}\p{Cf}\u2028\u2029]/gu;
74
+ function displayRunnerName(raw) {
75
+ if (typeof raw !== "string")
76
+ return void 0;
77
+ const v = [...raw.replace(CONTROL_CHARS_G, " ").replace(/\s+/g, " ").trim()].slice(0, RUNNER_LABEL_MAX_LENGTH).join("").trim();
78
+ return v || void 0;
79
+ }
80
+ function claimRegion(c) {
81
+ return c.sources?.region ?? c.inspect?.region ?? c.inspectConnection?.region ?? c.deploy?.region;
82
+ }
53
83
  var RUNNER_ERRORS = {
54
84
  // -- The pipeline service's answers --
55
85
  RUNNERS_UNAVAILABLE: { httpStatus: 409, retryable: false, category: "platform" },
@@ -62,6 +92,12 @@ var RUNNER_ERRORS = {
62
92
  RUNNER_LIMIT: { httpStatus: 409, retryable: false, category: "platform" },
63
93
  /** Another non-revoked runner of the org already has this label (labels are how the CLI finds a runner). */
64
94
  RUNNER_LABEL_TAKEN: { httpStatus: 409, retryable: false, category: "platform" },
95
+ /**
96
+ * The connector answered from a different AWS account than the one it was
97
+ * pinned to: nothing is delivered to it until an admin confirms the new
98
+ * account (POST …/runners/:id/confirm-account).
99
+ */
100
+ RUNNER_ACCOUNT_CHANGED: { httpStatus: 409, retryable: false, category: "platform" },
65
101
  RUN_REQUEST_RATE_LIMITED: { httpStatus: 429, retryable: false, category: "platform" },
66
102
  TOO_MANY_PENDING: { httpStatus: 429, retryable: false, category: "platform" },
67
103
  RUNNER_UPDATE_REQUIRED: { httpStatus: 409, retryable: false, category: "platform" },
@@ -85,7 +121,7 @@ var RUNNER_ERRORS = {
85
121
  /** Revoke: the typed confirmation is not the last {@link RUNNER_KEY_REVOKE_CONFIRM_CHARS} characters of the active kid. */
86
122
  RUNNER_KEY_CONFIRMATION_MISMATCH: { httpStatus: 400, retryable: false, category: "platform" },
87
123
  // -- Deploys through a runner (the pipeline service's answers) --
88
- /** The runner does not list the `deploy:1` capability (an old bundle, or a stack without --enable-deploy): update it with {@link DEPLOY_SETUP_COMMAND}. */
124
+ /** The runner does not list the `deploy:1` capability (an old bundle, or a stack without --deploy): update it with {@link DEPLOY_SETUP_COMMAND}. */
89
125
  RUNNER_DEPLOY_UNSUPPORTED: { httpStatus: 409, retryable: false, category: "platform" },
90
126
  /** Several runners can deploy this pipeline and none was named (`details.runners`: the deployable ones). */
91
127
  DEPLOY_RUNNER_REQUIRED: { httpStatus: 409, retryable: false, category: "platform" },
@@ -132,7 +168,7 @@ var RUNNER_ERRORS = {
132
168
  */
133
169
  RUNNER_ERROR: { httpStatus: 500, retryable: false, category: "runner" },
134
170
  // -- A runner's answers to the deploy actions --
135
- /** The stack was not set up with --enable-deploy (the platform clears the runner's stored capabilities). */
171
+ /** The stack was not set up with --deploy (the platform clears the runner's stored capabilities). */
136
172
  DEPLOY_NOT_ENABLED: { httpStatus: 403, retryable: false, category: "runner" },
137
173
  /** A pipeline tagged with this pipeline id already exists in the account (the platform links it instead). */
138
174
  PIPELINE_ALREADY_DEPLOYED: { httpStatus: 409, retryable: false, category: "runner" },
@@ -155,8 +191,17 @@ var RUNNER_ERRORS = {
155
191
  SOURCE_CONNECTION_WRONG_PROVIDER: { httpStatus: 409, retryable: false, category: "runner" },
156
192
  /** A token-less GitHub source, and neither the owner's nor the org's GitHub token secret exists in the region. */
157
193
  GITHUB_TOKEN_MISSING: { httpStatus: 409, retryable: false, category: "runner" },
194
+ // -- A runner's answers to the connection inspection (its start also answers the source refusals above) --
195
+ /** inspect_connection_status: no such build in the runner's own inspect project. */
196
+ INSPECT_BUILD_NOT_FOUND: { httpStatus: 404, retryable: false, category: "runner" },
197
+ /** The inspect project lives in the runner stack's own region; the connection must be there too. */
198
+ INSPECT_REGION_UNSUPPORTED: { httpStatus: 409, retryable: false, category: "runner" },
199
+ /** The inspect project is at its concurrent build limit. */
200
+ INSPECT_BUSY: { httpStatus: 409, retryable: false, category: "runner" },
158
201
  // -- Recorded by the platform --
159
202
  /** Not delivered within the request's lifetime. */
203
+ /** A reply whose echoed connector id or request id is not the request's (or an identity:1 reply without one). */
204
+ RUNNER_IDENTITY_MISMATCH: { httpStatus: null, retryable: false, category: "recorded" },
160
205
  RUN_REQUEST_EXPIRED: { httpStatus: null, retryable: false, category: "recorded" },
161
206
  /** A discovery probe that found nothing (probe rows only). */
162
207
  NO_MATCH: { httpStatus: null, retryable: false, category: "recorded" },
@@ -189,6 +234,26 @@ var INSPECT_MAX_READ_BYTES = 128 * 1024;
189
234
  var INSPECT_MAX_REPLY_BYTES = 1024 * 1024;
190
235
  var INSPECT_MAX_LISTING_ENTRIES = 1e3;
191
236
  var INSPECT_REPO_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
237
+ var INSPECT_CONNECTION_MAX_SEGMENTS = 10;
238
+ function inspectConnectionRepositoryProblem(raw) {
239
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
240
+ return "not a repository";
241
+ const r = raw;
242
+ if (Object.keys(r).some((k) => k !== "host" && k !== "path"))
243
+ return "unexpected fields";
244
+ if (typeof r.host !== "string" || !SOURCE_HOST_PATTERN.test(r.host))
245
+ return "malformed host";
246
+ if (typeof r.path !== "string")
247
+ return "malformed path";
248
+ const segments = r.path.split("/");
249
+ if (segments.length < 2 || segments.length > INSPECT_CONNECTION_MAX_SEGMENTS)
250
+ return "malformed path";
251
+ if (segments.some((seg) => seg === "." || seg === ".." || !SOURCE_OWNER_PATTERN.test(seg)))
252
+ return "malformed path";
253
+ return null;
254
+ }
255
+ var INSPECT_CONNECTION_DEADLINE_MS = 6 * 6e4;
256
+ var INSPECT_BUILD_ID_PATTERN = /^pipeline-builder-inspect[A-Za-z0-9_-]{0,200}:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
192
257
  var RUNNER_KEY_ACTIVATION_DELAY_MS = 10 * 6e4;
193
258
  var RUNNER_KEY_RETIRE_WINDOW_MS = 60 * 6e4;
194
259
  var RUNNER_TUNABLE_DEFAULTS = {
@@ -479,8 +544,9 @@ async function runDeployAction(ctx, claims) {
479
544
  }
480
545
  }
481
546
 
482
- // src/lambda/runner-inspect.ts
483
- import { GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
547
+ // src/lambda/runner-inspect-connection.ts
548
+ import { BatchGetBuildsCommand as BatchGetBuildsCommand2, StartBuildCommand as StartBuildCommand2 } from "@aws-sdk/client-codebuild";
549
+ import { DeleteObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3";
484
550
 
485
551
  // ../api-core/lib/types/pipeline-source.js
486
552
  var CONNECTION_ARN_PATTERN = /^arn:aws(?:-[a-z]+)*:(?:codeconnections|codestar-connections):[a-z0-9-]+:\d{12}:connection\/[A-Za-z0-9-]+$/;
@@ -502,6 +568,31 @@ function githubTokenStoreCommand(owner, region = "<region>") {
502
568
  return `pipeline-manager infra store-github-token --region ${region}${owner ? ` --owner ${owner.toLowerCase()}` : ""}`;
503
569
  }
504
570
  var GITHUB_TOKEN_STORE_COMMAND = githubTokenStoreCommand();
571
+ var GIT_REF_MAX_LENGTH = 200;
572
+ function gitBranchProblem(branch) {
573
+ if (!branch)
574
+ return "Enter a branch name.";
575
+ if (branch.length > GIT_REF_MAX_LENGTH)
576
+ return `A branch name is at most ${GIT_REF_MAX_LENGTH} characters.`;
577
+ if (!/^[A-Za-z0-9._/-]+$/.test(branch))
578
+ return 'A branch name uses only letters, digits, ".", "_", "-" and "/".';
579
+ if (branch.startsWith("/") || branch.endsWith("/") || branch.includes("//"))
580
+ return 'A branch name cannot start or end with "/" or contain "//".';
581
+ if (branch.startsWith("-") || branch.includes("..") || branch.endsWith(".lock") || branch.endsWith("."))
582
+ return "That is not a valid branch name.";
583
+ return null;
584
+ }
585
+ function subdirectoryProblem(subdirectory) {
586
+ if (subdirectory === "")
587
+ return null;
588
+ if (subdirectory.length > GIT_REF_MAX_LENGTH)
589
+ return `A subdirectory is at most ${GIT_REF_MAX_LENGTH} characters.`;
590
+ const segments = subdirectory.split("/");
591
+ if (segments.some((s) => s === "" || s === "." || s === ".." || !/^[A-Za-z0-9._-]+$/.test(s))) {
592
+ return 'A subdirectory is a path inside the repository, like "services/api" (letters, digits, ".", "_", "-"; no "..").';
593
+ }
594
+ return null;
595
+ }
505
596
  var GIT_PROVIDERS = {
506
597
  github: { host: "github.com", browse: "tree" },
507
598
  gitlab: { host: "gitlab.com", browse: "-/tree" },
@@ -540,6 +631,11 @@ function connectionMatchesRepository(connection, repoHost) {
540
631
  return false;
541
632
  }
542
633
  }
634
+ function secretLookupFromDescribe(out) {
635
+ if (out.DeletedDate)
636
+ return null;
637
+ return { lastChangedDate: out.LastChangedDate instanceof Date ? out.LastChangedDate.toISOString() : null };
638
+ }
543
639
  async function chooseGitHubTokenSecret(a, describe) {
544
640
  const prefix = a.prefix ?? DEFAULT_SECRETS_PATH_PREFIX;
545
641
  const owner = a.owner && !githubOwnerProblem(a.owner) ? a.owner.toLowerCase() : void 0;
@@ -622,6 +718,53 @@ function parseRepositoryReadBody(read, body) {
622
718
  return null;
623
719
  return { name, type, encoding, content };
624
720
  }
721
+ var MAX_SNAPSHOT_LISTINGS = 4;
722
+ var MAX_SNAPSHOT_FILES = 20;
723
+ var BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
724
+ function snapshotPathOk(path) {
725
+ if (path === "")
726
+ return true;
727
+ if (path.length > MAX_READ_PATH)
728
+ return false;
729
+ return path.split("/").every((seg) => seg !== "." && seg !== ".." && READ_SEGMENT_PATTERN.test(seg));
730
+ }
731
+ function parseRepositorySnapshot(raw) {
732
+ if (!isRecord(raw))
733
+ return null;
734
+ if (Object.keys(raw).some((k) => !["branch", "listings", "files", "languages"].includes(k)))
735
+ return null;
736
+ const { branch, listings, files, languages } = raw;
737
+ if (branch !== null && (typeof branch !== "string" || !READ_REF_PATTERN.test(branch)))
738
+ return null;
739
+ if (!isRecord(listings) || !isRecord(files) || !isRecord(languages))
740
+ return null;
741
+ const listingEntries = Object.entries(listings);
742
+ if (listingEntries.length > MAX_SNAPSHOT_LISTINGS)
743
+ return null;
744
+ const outListings = {};
745
+ for (const [path, entries] of listingEntries) {
746
+ if (!snapshotPathOk(path) || !Array.isArray(entries) || entries.length > INSPECT_MAX_LISTING_ENTRIES)
747
+ return null;
748
+ const kept = [];
749
+ for (const e of entries) {
750
+ if (!isRecord(e) || typeof e.name !== "string" || !READ_SEGMENT_PATTERN.test(e.name) || e.type !== "file" && e.type !== "dir")
751
+ return null;
752
+ kept.push({ name: e.name, type: e.type });
753
+ }
754
+ outListings[path] = kept;
755
+ }
756
+ const fileEntries = Object.entries(files);
757
+ if (fileEntries.length > MAX_SNAPSHOT_FILES)
758
+ return null;
759
+ for (const [path, content] of fileEntries) {
760
+ if (path === "" || !snapshotPathOk(path) || typeof content !== "string" || content.length > MAX_BASE64_CHARS || !BASE64_PATTERN.test(content))
761
+ return null;
762
+ }
763
+ const langEntries = Object.entries(languages);
764
+ if (langEntries.length > MAX_LANGUAGES || langEntries.some(([k, v]) => k.length > 100 || typeof v !== "number" || !Number.isFinite(v) || v < 0))
765
+ return null;
766
+ return { branch, listings: outListings, files: Object.fromEntries(fileEntries), languages: Object.fromEntries(langEntries) };
767
+ }
625
768
 
626
769
  // src/lambda/runner-sources.ts
627
770
  import { GetConnectionCommand, GetHostCommand, ListConnectionsCommand, ListHostsCommand } from "@aws-sdk/client-codeconnections";
@@ -634,9 +777,7 @@ var isStatus = (v) => SOURCE_CONNECTION_STATUSES.includes(v);
634
777
  function describeSecretLookup(deps, region) {
635
778
  return async (name) => {
636
779
  try {
637
- const out = await deps.secrets(region).send(new DescribeSecretCommand({ SecretId: name }));
638
- if (out.DeletedDate) return null;
639
- return { lastChangedDate: out.LastChangedDate instanceof Date ? out.LastChangedDate.toISOString() : null };
780
+ return secretLookupFromDescribe(await deps.secrets(region).send(new DescribeSecretCommand({ SecretId: name })));
640
781
  } catch (err) {
641
782
  if (isNotFound(err)) return null;
642
783
  throw err;
@@ -695,18 +836,13 @@ async function listSources(claim, accountId, deps) {
695
836
  truncated: more || matching.length > MAX_SOURCE_CONNECTIONS
696
837
  };
697
838
  }
698
- async function checkSource(claim, accountId, deps) {
699
- const source = claim.source;
700
- if (source.type === "github") {
701
- if (!claim.repository || providerForHost(claim.repository.host) !== "github") return "SOURCE_CONNECTION_WRONG_PROVIDER";
702
- return await githubTokenFor(claim, deps) ? null : "GITHUB_TOKEN_MISSING";
703
- }
704
- const parts = connectionArnParts(source.connectionArn);
705
- if (!parts || parts.accountId !== accountId) return "SOURCE_CONNECTION_WRONG_ACCOUNT";
706
- if (parts.region !== claim.region) return "SOURCE_CONNECTION_WRONG_REGION";
839
+ async function checkConnection(deps, q) {
840
+ const parts = connectionArnParts(q.connectionArn);
841
+ if (!parts || parts.accountId !== q.accountId) return "SOURCE_CONNECTION_WRONG_ACCOUNT";
842
+ if (parts.region !== q.region) return "SOURCE_CONNECTION_WRONG_REGION";
707
843
  let connection;
708
844
  try {
709
- const out = await deps.codeconnections(claim.region).send(new GetConnectionCommand({ ConnectionArn: source.connectionArn }));
845
+ const out = await deps.codeconnections(q.region).send(new GetConnectionCommand({ ConnectionArn: q.connectionArn }));
710
846
  connection = out.Connection;
711
847
  } catch (err) {
712
848
  if (isNotFound(err)) return "SOURCE_CONNECTION_NOT_FOUND";
@@ -717,7 +853,7 @@ async function checkSource(claim, accountId, deps) {
717
853
  let hostEndpoint;
718
854
  if (connection.HostArn) {
719
855
  try {
720
- const host = await deps.codeconnections(claim.region).send(new GetHostCommand({ HostArn: connection.HostArn }));
856
+ const host = await deps.codeconnections(q.region).send(new GetHostCommand({ HostArn: connection.HostArn }));
721
857
  hostEndpoint = host.ProviderEndpoint;
722
858
  } catch (err) {
723
859
  if (!isNotFound(err)) throw err;
@@ -725,10 +861,108 @@ async function checkSource(claim, accountId, deps) {
725
861
  }
726
862
  const dto = toDto(connection, hostEndpoint);
727
863
  if (!dto) return "SOURCE_CONNECTION_WRONG_PROVIDER";
728
- return !claim.repository || connectionMatchesRepository(dto, claim.repository.host) ? null : "SOURCE_CONNECTION_WRONG_PROVIDER";
864
+ return !q.repoHost || connectionMatchesRepository(dto, q.repoHost) ? dto : "SOURCE_CONNECTION_WRONG_PROVIDER";
865
+ }
866
+ async function checkSource(claim, accountId, deps) {
867
+ const source = claim.source;
868
+ if (source.type === "github") {
869
+ if (!claim.repository || providerForHost(claim.repository.host) !== "github") return "SOURCE_CONNECTION_WRONG_PROVIDER";
870
+ return await githubTokenFor(claim, deps) ? null : "GITHUB_TOKEN_MISSING";
871
+ }
872
+ const checked = await checkConnection(deps, { connectionArn: source.connectionArn, region: claim.region, accountId, repoHost: claim.repository?.host });
873
+ return typeof checked === "string" ? checked : null;
874
+ }
875
+
876
+ // src/lambda/runner-inspect-connection.ts
877
+ var SOURCE_TYPE = {
878
+ GitHub: "GITHUB",
879
+ GitHubEnterpriseServer: "GITHUB_ENTERPRISE",
880
+ GitLab: "GITLAB",
881
+ GitLabSelfManaged: "GITLAB_SELF_MANAGED",
882
+ Bitbucket: "BITBUCKET"
883
+ };
884
+ var errName3 = (err) => String(err?.name ?? "");
885
+ function resultKey(buildId) {
886
+ return `${buildId.slice(buildId.indexOf(":") + 1)}.json`;
887
+ }
888
+ async function startInspection(claim, accountId, config, deps) {
889
+ if (claim.region !== config.region) return "INSPECT_REGION_UNSUPPORTED";
890
+ const connection = await checkConnection(deps, { connectionArn: claim.connectionArn, region: claim.region, accountId, repoHost: claim.repository.host });
891
+ if (typeof connection === "string") return connection;
892
+ const location = `https://${claim.repository.host}/${claim.repository.path.split("/").map(encodeURIComponent).join("/")}.git`;
893
+ try {
894
+ const out = await deps.codebuild().send(new StartBuildCommand2({
895
+ projectName: config.projectName,
896
+ sourceTypeOverride: SOURCE_TYPE[connection.providerType],
897
+ sourceLocationOverride: location,
898
+ ...claim.branch ? { sourceVersion: claim.branch } : {},
899
+ gitCloneDepthOverride: 1,
900
+ sourceAuthOverride: { type: "CODECONNECTIONS", resource: claim.connectionArn },
901
+ environmentVariablesOverride: [
902
+ { name: "INSPECT_BRANCH", value: claim.branch, type: "PLAINTEXT" },
903
+ { name: "INSPECT_SUBDIRECTORY", value: claim.subdirectory, type: "PLAINTEXT" }
904
+ ]
905
+ }));
906
+ const buildId = out.build?.id;
907
+ if (!buildId) throw new Error("StartBuild answered no build id");
908
+ return { buildId };
909
+ } catch (err) {
910
+ if (errName3(err) === "AccountLimitExceededException") return "INSPECT_BUSY";
911
+ throw err;
912
+ }
913
+ }
914
+ var WAITING_PHASES = /* @__PURE__ */ new Set(["SUBMITTED", "QUEUED", "PROVISIONING"]);
915
+ var SOURCE_PHASES = /* @__PURE__ */ new Set(["DOWNLOAD_SOURCE"]);
916
+ function failedPhase(build) {
917
+ if (build.buildStatus !== "FAILED") return "other";
918
+ const failed = (build.phases ?? []).find((p) => p.phaseStatus === "FAILED" || p.phaseStatus === "FAULT");
919
+ if (!failed?.phaseType) return "other";
920
+ return SOURCE_PHASES.has(failed.phaseType) ? "source" : "build";
921
+ }
922
+ async function readSnapshot(buildId, config, deps) {
923
+ const key = resultKey(buildId);
924
+ let text = null;
925
+ try {
926
+ const out = await deps.s3().send(new GetObjectCommand({ Bucket: config.bucket, Key: key }));
927
+ if (out.Body && typeof out.ContentLength === "number" && out.ContentLength <= INSPECT_MAX_REPLY_BYTES) {
928
+ const bytes = await out.Body.transformToByteArray();
929
+ if (bytes.byteLength <= INSPECT_MAX_REPLY_BYTES) text = Buffer.from(bytes).toString("utf8");
930
+ }
931
+ } catch (err) {
932
+ if (errName3(err) === "NoSuchKey" || errName3(err) === "NotFound") return null;
933
+ throw err;
934
+ } finally {
935
+ await deps.s3().send(new DeleteObjectCommand({ Bucket: config.bucket, Key: key })).catch(() => void 0);
936
+ }
937
+ if (text === null) return null;
938
+ let json;
939
+ try {
940
+ json = JSON.parse(text);
941
+ } catch {
942
+ return null;
943
+ }
944
+ const snapshot = parseRepositorySnapshot(json);
945
+ return snapshot ? { state: "succeeded", snapshot } : null;
946
+ }
947
+ async function inspectionStatus(claim, config, deps) {
948
+ if (!claim.buildId.startsWith(`${config.projectName}:`)) return "INSPECT_BUILD_NOT_FOUND";
949
+ const out = await deps.codebuild().send(new BatchGetBuildsCommand2({ ids: [claim.buildId] }));
950
+ const build = (out.builds ?? []).find((b) => b.id === claim.buildId);
951
+ if (!build) return "INSPECT_BUILD_NOT_FOUND";
952
+ switch (build.buildStatus) {
953
+ case "IN_PROGRESS":
954
+ return { state: build.currentPhase && WAITING_PHASES.has(build.currentPhase) ? "queued" : "running" };
955
+ case "SUCCEEDED":
956
+ return await readSnapshot(claim.buildId, config, deps) ?? { state: "failed", failedPhase: "build" };
957
+ case "TIMED_OUT":
958
+ return { state: "timed_out" };
959
+ default:
960
+ return { state: "failed", failedPhase: failedPhase(build) };
961
+ }
729
962
  }
730
963
 
731
964
  // src/lambda/runner-inspect.ts
965
+ import { GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
732
966
  var GITHUB_API = "https://api.github.com";
733
967
  var GITHUB_TIMEOUT_MS = 6e3;
734
968
  async function readCapped(res, cap) {
@@ -756,9 +990,13 @@ var githubGet = async (url, token) => {
756
990
  "X-GitHub-Api-Version": "2022-11-28",
757
991
  "Authorization": `Bearer ${token}`
758
992
  },
759
- redirect: "error",
993
+ redirect: "manual",
760
994
  signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS)
761
995
  });
996
+ if (res.status >= 300 && res.status < 400) {
997
+ await res.body?.cancel();
998
+ return { status: res.status, text: "" };
999
+ }
762
1000
  return { status: res.status, text: await readCapped(res, INSPECT_MAX_READ_BYTES) };
763
1001
  };
764
1002
  function readUrl(repository, read) {
@@ -799,7 +1037,7 @@ async function inspectRepository(claim, deps) {
799
1037
  let total = 0;
800
1038
  const results = answers.map((a) => {
801
1039
  if (a.body === void 0) return a;
802
- total += JSON.stringify(a.body).length;
1040
+ total += Buffer.byteLength(JSON.stringify(a.body));
803
1041
  return total > INSPECT_MAX_REPLY_BYTES ? { status: 413 } : a;
804
1042
  });
805
1043
  return { results };
@@ -935,7 +1173,8 @@ async function verifyRunRequest(jws, opts) {
935
1173
  if (c.aud !== opts.runnerId) throw new SignatureError("wrong aud");
936
1174
  const isSourceAction = Object.hasOwn(SOURCE_ACTION_CAPABILITY, action);
937
1175
  const isInspect = action === "inspect_repository";
938
- if (action !== "ping" && !isSourceAction && !isInspect && !isNonEmptyString(c.pipelineId)) throw new SignatureError("missing pipelineId");
1176
+ const isInspectConnection = Object.hasOwn(INSPECT_CONNECTION_ACTION_CAPABILITY, action);
1177
+ if (action !== "ping" && !isSourceAction && !isInspect && !isInspectConnection && !isNonEmptyString(c.pipelineId)) throw new SignatureError("missing pipelineId");
939
1178
  if ((action === "stop" || action === "status") && !isNonEmptyString(c.executionId)) throw new SignatureError("missing executionId");
940
1179
  let hint;
941
1180
  if (c.hint !== void 0 && c.hint !== null) {
@@ -955,6 +1194,8 @@ async function verifyRunRequest(jws, opts) {
955
1194
  const sources = isSourceAction ? parseSourcesClaim(c.sources, action === "check_source") : void 0;
956
1195
  if (!isInspect && c.inspect !== void 0) throw new SignatureError("unexpected inspect claim");
957
1196
  const inspect = isInspect ? parseInspectClaim(c.inspect) : void 0;
1197
+ if (!isInspectConnection && c.inspectConnection !== void 0) throw new SignatureError("unexpected inspectConnection claim");
1198
+ const inspectConnection = isInspectConnection ? parseInspectConnectionClaim(c.inspectConnection, action === "inspect_connection_start") : void 0;
958
1199
  if (takesBuild) {
959
1200
  if (!isNonEmptyString(c.deployRequestId) || c.deployRequestId.length > 128) throw new SignatureError("missing deployRequestId");
960
1201
  if (typeof c.buildId !== "string" || !BUILD_ID_PATTERN.test(c.buildId)) throw new SignatureError("malformed buildId");
@@ -973,6 +1214,9 @@ async function verifyRunRequest(jws, opts) {
973
1214
  ...takesBuild ? { deployRequestId: c.deployRequestId, buildId: c.buildId } : {},
974
1215
  ...sources ? { sources } : {},
975
1216
  ...inspect ? { inspect } : {},
1217
+ ...inspectConnection ? { inspectConnection } : {},
1218
+ // Informational only (logged, echoed after cleaning): never checked, never a reason to refuse.
1219
+ ...typeof c.name === "string" ? { name: c.name } : {},
976
1220
  requestedBy: c.requestedBy
977
1221
  };
978
1222
  }
@@ -1041,7 +1285,7 @@ function parseInspectClaim(raw) {
1041
1285
  if (typeof b.region !== "string" || !AWS_REGION_PATTERN.test(b.region)) throw new SignatureError("malformed inspect region");
1042
1286
  const repo = b.repository;
1043
1287
  if (!repo || typeof repo !== "object" || Array.isArray(repo)) throw new SignatureError("missing inspect repository");
1044
- if (typeof repo.owner !== "string" || !SOURCE_OWNER_PATTERN.test(repo.owner)) throw new SignatureError("malformed inspect repository owner");
1288
+ if (typeof repo.owner !== "string" || githubOwnerProblem(repo.owner) !== null) throw new SignatureError("malformed inspect repository owner");
1045
1289
  if (typeof repo.repo !== "string" || !INSPECT_REPO_PATTERN.test(repo.repo) || repo.repo === "." || repo.repo === "..") {
1046
1290
  throw new SignatureError("malformed inspect repository repo");
1047
1291
  }
@@ -1053,6 +1297,36 @@ function parseInspectClaim(raw) {
1053
1297
  });
1054
1298
  return { orgId: b.orgId, region: b.region, repository: { owner: repo.owner, repo: repo.repo }, reads };
1055
1299
  }
1300
+ function parseInspectConnectionClaim(raw, isStart) {
1301
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SignatureError("missing inspectConnection claim");
1302
+ const b = raw;
1303
+ if (b.kind !== (isStart ? "start" : "status")) throw new SignatureError("inspectConnection kind is not the action");
1304
+ if (typeof b.region !== "string" || !AWS_REGION_PATTERN.test(b.region)) throw new SignatureError("malformed inspectConnection region");
1305
+ if (!isStart) {
1306
+ if (Object.keys(b).some((k) => !["kind", "region", "buildId"].includes(k))) throw new SignatureError("unexpected inspectConnection field");
1307
+ if (typeof b.buildId !== "string" || !INSPECT_BUILD_ID_PATTERN.test(b.buildId)) throw new SignatureError("malformed inspectConnection buildId");
1308
+ return { kind: "status", region: b.region, buildId: b.buildId };
1309
+ }
1310
+ if (Object.keys(b).some((k) => !["kind", "region", "connectionArn", "repository", "branch", "subdirectory"].includes(k))) {
1311
+ throw new SignatureError("unexpected inspectConnection field");
1312
+ }
1313
+ if (typeof b.connectionArn !== "string" || !CONNECTION_ARN_PATTERN.test(b.connectionArn)) throw new SignatureError("malformed inspectConnection connectionArn");
1314
+ const problem = inspectConnectionRepositoryProblem(b.repository);
1315
+ if (problem) throw new SignatureError(`malformed inspectConnection repository: ${problem}`);
1316
+ if (typeof b.branch !== "string" || b.branch !== "" && gitBranchProblem(b.branch) !== null) throw new SignatureError("malformed inspectConnection branch");
1317
+ if (typeof b.subdirectory !== "string" || b.subdirectory !== "" && subdirectoryProblem(b.subdirectory) !== null) {
1318
+ throw new SignatureError("malformed inspectConnection subdirectory");
1319
+ }
1320
+ const repository = b.repository;
1321
+ return {
1322
+ kind: "start",
1323
+ region: b.region,
1324
+ connectionArn: b.connectionArn,
1325
+ repository: { host: repository.host, path: repository.path },
1326
+ branch: b.branch,
1327
+ subdirectory: b.subdirectory
1328
+ };
1329
+ }
1056
1330
  var ReplayCache = class {
1057
1331
  constructor(now) {
1058
1332
  this.now = now;
@@ -1099,9 +1373,22 @@ function configFromEnv(env = process.env) {
1099
1373
  allowedRegions,
1100
1374
  allowedPrefixes,
1101
1375
  version: env.RUNNER_VERSION?.trim() || "0.0.0",
1102
- deploy: deployConfigFromEnv(env)
1376
+ deploy: deployConfigFromEnv(env),
1377
+ ...inspectConnectionFromEnv(env),
1378
+ ...reportingFromEnv(env)
1103
1379
  };
1104
1380
  }
1381
+ function reportingFromEnv(env) {
1382
+ const deadLetterQueueUrl = env.REPORTING_DLQ_URL?.trim();
1383
+ const lastEventParameter = env.REPORTING_LAST_EVENT_PARAMETER?.trim();
1384
+ return deadLetterQueueUrl && lastEventParameter ? { reporting: { deadLetterQueueUrl, lastEventParameter } } : {};
1385
+ }
1386
+ function inspectConnectionFromEnv(env) {
1387
+ const projectName = env.INSPECT_PROJECT_NAME?.trim();
1388
+ const bucket = env.INSPECT_RESULTS_BUCKET?.trim();
1389
+ const region = env.AWS_REGION?.trim();
1390
+ return projectName && bucket && region ? { inspectConnection: { projectName, bucket, region } } : {};
1391
+ }
1105
1392
  function defaultLog(level, msg, data) {
1106
1393
  const line = JSON.stringify({ level, msg, ...data });
1107
1394
  if (level === "ERROR") console.error(line);
@@ -1112,6 +1399,9 @@ function defaultDeps() {
1112
1399
  const cp = /* @__PURE__ */ new Map();
1113
1400
  let codebuild;
1114
1401
  let kms;
1402
+ let s3;
1403
+ let sqs;
1404
+ let ssm;
1115
1405
  const cc = /* @__PURE__ */ new Map();
1116
1406
  const sm = /* @__PURE__ */ new Map();
1117
1407
  return {
@@ -1127,6 +1417,7 @@ function defaultDeps() {
1127
1417
  },
1128
1418
  codebuild: () => codebuild ??= new CodeBuildClient({}),
1129
1419
  kms: () => kms ??= new KMSClient({}),
1420
+ s3: () => s3 ??= new S3Client({}),
1130
1421
  codeconnections: (region) => {
1131
1422
  if (!cc.has(region)) cc.set(region, new CodeConnectionsClient({ region }));
1132
1423
  return cc.get(region);
@@ -1135,6 +1426,8 @@ function defaultDeps() {
1135
1426
  if (!sm.has(region)) sm.set(region, new SecretsManagerClient({ region }));
1136
1427
  return sm.get(region);
1137
1428
  },
1429
+ sqs: () => sqs ??= new SQSClient({}),
1430
+ ssm: () => ssm ??= new SSMClient({}),
1138
1431
  github: githubGet,
1139
1432
  log: defaultLog
1140
1433
  };
@@ -1154,10 +1447,10 @@ function isAllowed(config, region, name) {
1154
1447
  if (!config.allowedRegions.includes(region)) return false;
1155
1448
  return config.allowedPrefixes.some((p) => p === "*" || name.startsWith(p));
1156
1449
  }
1157
- var errName3 = (err) => String(err?.name ?? "");
1450
+ var errName4 = (err) => String(err?.name ?? "");
1158
1451
  var errStatus = (err) => err?.$metadata?.httpStatusCode;
1159
1452
  function isAccessDenied(err) {
1160
- const n = errName3(err);
1453
+ const n = errName4(err);
1161
1454
  return n === "AccessDeniedException" || n === "AccessDenied" || n === "UnauthorizedOperation" || n === "AuthorizationErrorException" || errStatus(err) === 403 && !/Throttl/.test(n);
1162
1455
  }
1163
1456
  var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set(["ResourceNotFoundException", "PipelineNotFoundException", "InvalidArnException"]);
@@ -1188,7 +1481,7 @@ async function hintedTag(deps, account, hint) {
1188
1481
  try {
1189
1482
  return await readPipelineIdTag(deps.codepipeline(hint.region), resourceArn) ?? null;
1190
1483
  } catch (err) {
1191
- if (NOT_FOUND_ERRORS.has(errName3(err))) return void 0;
1484
+ if (NOT_FOUND_ERRORS.has(errName4(err))) return void 0;
1192
1485
  throw err;
1193
1486
  }
1194
1487
  }
@@ -1233,8 +1526,8 @@ function createRunner(config, deps) {
1233
1526
  if (e?.pipelineName !== void 0 && e.pipelineName !== pipelineName) return fail("RUNNER_REFUSED");
1234
1527
  return { ...e?.status ? { executionStatus: e.status } : {} };
1235
1528
  } catch (err) {
1236
- if (errName3(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
1237
- if (errName3(err) === "PipelineExecutionNotFoundException") return fail("RUNNER_REFUSED");
1529
+ if (errName4(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
1530
+ if (errName4(err) === "PipelineExecutionNotFoundException") return fail("RUNNER_REFUSED");
1238
1531
  throw err;
1239
1532
  }
1240
1533
  }
@@ -1248,7 +1541,7 @@ function createRunner(config, deps) {
1248
1541
  }));
1249
1542
  return ok("started", out.pipelineExecutionId ? { executionId: out.pipelineExecutionId } : {});
1250
1543
  } catch (err) {
1251
- if (errName3(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
1544
+ if (errName4(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
1252
1545
  throw err;
1253
1546
  }
1254
1547
  }
@@ -1265,7 +1558,7 @@ function createRunner(config, deps) {
1265
1558
  reason: `Stopped by pipeline-builder request ${claims.jti}`.slice(0, 200)
1266
1559
  }));
1267
1560
  } catch (err) {
1268
- const n = errName3(err);
1561
+ const n = errName4(err);
1269
1562
  if (n === "DuplicatedStopRequestException") return ok("stopped", { executionId });
1270
1563
  if (n === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
1271
1564
  if (n === "PipelineExecutionNotStoppableException" || n === "PipelineExecutionNotFoundException") return fail("RUNNER_REFUSED");
@@ -1305,14 +1598,53 @@ function createRunner(config, deps) {
1305
1598
  const answer2 = await inspectRepository(inspect, deps);
1306
1599
  return answer2 === "GITHUB_TOKEN_MISSING" ? fail(answer2) : ok("repository_reads", { results: answer2.results });
1307
1600
  }
1601
+ async function inspectConnectionAction(claims, account) {
1602
+ const claim = claims.inspectConnection;
1603
+ if (!config.allowedRegions.includes(claim.region)) return fail("SOURCE_REGION_NOT_ALLOWED");
1604
+ const inspect = config.inspectConnection;
1605
+ if (!inspect) return fail("INSPECT_REGION_UNSUPPORTED");
1606
+ if (claim.kind === "start") {
1607
+ if (!account) return internal();
1608
+ const started = await startInspection(claim, account.accountId, inspect, deps);
1609
+ return typeof started === "string" ? fail(started) : ok("inspection_started", { buildId: started.buildId });
1610
+ }
1611
+ const status = await inspectionStatus(claim, inspect, deps);
1612
+ return typeof status === "string" ? fail(status) : ok("inspection_status", { ...status });
1613
+ }
1614
+ async function reportingHealth() {
1615
+ const r = config.reporting;
1616
+ if (!r) return void 0;
1617
+ try {
1618
+ const q = await deps.sqs().send(new GetQueueAttributesCommand({ QueueUrl: r.deadLetterQueueUrl, AttributeNames: ["ApproximateNumberOfMessages"] }));
1619
+ const failedEvents = Number.parseInt(q.Attributes?.ApproximateNumberOfMessages ?? "0", 10);
1620
+ let lastEventAt = null;
1621
+ try {
1622
+ const p = await deps.ssm().send(new GetParameterCommand({ Name: r.lastEventParameter }));
1623
+ const v = p.Parameter?.Value;
1624
+ lastEventAt = v && !Number.isNaN(Date.parse(v)) ? new Date(v).toISOString() : null;
1625
+ } catch (err) {
1626
+ if (errName4(err) !== "ParameterNotFound") throw err;
1627
+ }
1628
+ return { failedEvents: Number.isSafeInteger(failedEvents) && failedEvents >= 0 ? failedEvents : 0, lastEventAt };
1629
+ } catch (err) {
1630
+ deps.log("WARN", "Could not read the reporting health", { error: errName4(err) || "Error" });
1631
+ return void 0;
1632
+ }
1633
+ }
1308
1634
  async function act(claims, account) {
1309
1635
  if (claims.action === "ping") {
1310
- return ok("pong", {
1311
- regions: [...config.allowedRegions],
1312
- capabilities: config.deploy.enabled ? [DEPLOY_CAPABILITY, SOURCES_CAPABILITY, INSPECT_CAPABILITY] : [SOURCES_CAPABILITY, INSPECT_CAPABILITY],
1313
- pipelinePrefixes: [...config.allowedPrefixes]
1314
- });
1636
+ const capabilities = [
1637
+ ...config.deploy.enabled ? [DEPLOY_CAPABILITY] : [],
1638
+ SOURCES_CAPABILITY,
1639
+ INSPECT_CAPABILITY,
1640
+ ...config.inspectConnection ? [INSPECT_CONNECTION_CAPABILITY] : [],
1641
+ IDENTITY_CAPABILITY,
1642
+ ...config.reporting ? [EVENTS_CAPABILITY] : []
1643
+ ];
1644
+ const reporting = await reportingHealth();
1645
+ return ok("pong", { regions: [...config.allowedRegions], capabilities, pipelinePrefixes: [...config.allowedPrefixes], ...reporting ? { reporting } : {} });
1315
1646
  }
1647
+ if (Object.hasOwn(INSPECT_CONNECTION_ACTION_CAPABILITY, claims.action)) return inspectConnectionAction(claims, account);
1316
1648
  if (Object.hasOwn(DEPLOY_ACTION_CAPABILITY, claims.action)) return deployAction(claims);
1317
1649
  if (Object.hasOwn(SOURCE_ACTION_CAPABILITY, claims.action)) return sourceAction(claims, account);
1318
1650
  if (claims.action === "inspect_repository") return inspectAction(claims);
@@ -1329,36 +1661,56 @@ function createRunner(config, deps) {
1329
1661
  return executionStatus(cp, found.name, claims);
1330
1662
  }
1331
1663
  async function handleRequest(jws, opts = {}) {
1664
+ return (await handle(jws, opts)).result;
1665
+ }
1666
+ async function handle(jws, opts = {}) {
1332
1667
  let claims;
1333
1668
  try {
1334
1669
  claims = await verifyRunRequest(jws, { jwks, runnerId: config.runnerId, now: deps.now });
1335
1670
  } catch (err) {
1336
1671
  if (err instanceof SignatureError) {
1337
1672
  deps.log("WARN", "Rejected a request that is not validly signed for this runner", { reason: err.message });
1338
- return fail("SIGNATURE_INVALID");
1673
+ return { result: fail("SIGNATURE_INVALID") };
1339
1674
  }
1340
1675
  if (err instanceof JwksUnavailableError) {
1341
1676
  deps.log("ERROR", "Could not fetch the platform signing keys", { reason: err.message });
1342
- return internal();
1677
+ return { result: internal() };
1343
1678
  }
1344
- deps.log("ERROR", "Unexpected verification failure", { error: errName3(err) || "Error" });
1345
- return internal();
1679
+ deps.log("ERROR", "Unexpected verification failure", { error: errName4(err) || "Error" });
1680
+ return { result: internal() };
1346
1681
  }
1682
+ const connectorName = displayRunnerName(claims.name);
1683
+ const region = claimRegion(claims);
1684
+ const homeRegion = process.env.AWS_REGION?.trim();
1685
+ const identity = {
1686
+ runnerId: config.runnerId,
1687
+ requestId: claims.jti,
1688
+ ...opts.account ? { accountId: opts.account.accountId } : {},
1689
+ ...homeRegion ? { homeRegion } : {},
1690
+ ...region ? { region } : {},
1691
+ ...connectorName ? { name: connectorName } : {}
1692
+ };
1347
1693
  const prior = replay.claim(claims.jti);
1348
1694
  if (prior) {
1349
1695
  deps.log("INFO", "Repeated request", { requestId: claims.jti, replayed: !!prior.result });
1350
- return prior.result ?? fail("DUPLICATE");
1696
+ return { result: prior.result ?? fail("DUPLICATE"), identity };
1351
1697
  }
1352
- const logCtx = { requestId: claims.jti, requestedBy: claims.requestedBy, action: claims.action, ...claims.pipelineId ? { pipelineId: claims.pipelineId } : {} };
1698
+ const logCtx = {
1699
+ requestId: claims.jti,
1700
+ requestedBy: claims.requestedBy,
1701
+ action: claims.action,
1702
+ ...claims.pipelineId ? { pipelineId: claims.pipelineId } : {},
1703
+ ...connectorName ? { connectorName } : {}
1704
+ };
1353
1705
  let result;
1354
1706
  try {
1355
1707
  result = await act(claims, opts.account);
1356
1708
  } catch (err) {
1357
1709
  if (isAccessDenied(err)) {
1358
- deps.log("ERROR", "The runner role was refused by AWS \u2014 redeploy the runner stack or fix its role", { ...logCtx, error: errName3(err) });
1710
+ deps.log("ERROR", "The runner role was refused by AWS \u2014 redeploy the runner stack or fix its role", { ...logCtx, error: errName4(err) });
1359
1711
  result = fail("RUNNER_PERMISSION_DENIED");
1360
1712
  } else {
1361
- deps.log("ERROR", "Request failed", { ...logCtx, error: errName3(err) || "Error" });
1713
+ deps.log("ERROR", "Request failed", { ...logCtx, error: errName4(err) || "Error" });
1362
1714
  result = internal();
1363
1715
  }
1364
1716
  }
@@ -1373,13 +1725,13 @@ function createRunner(config, deps) {
1373
1725
  // `<project>:<uuid>` — no account id. The grant and its ciphertext are never logged.
1374
1726
  ...b.buildId ? { buildId: b.buildId } : {}
1375
1727
  });
1376
- return result;
1728
+ return { result, identity };
1377
1729
  }
1378
1730
  async function handleHttp(event, account) {
1379
- const respond = (r) => ({
1731
+ const respond = (r, identity) => ({
1380
1732
  statusCode: r.status,
1381
1733
  headers: { "content-type": "application/json", "cache-control": "no-store" },
1382
- body: JSON.stringify(r.body)
1734
+ body: JSON.stringify(identity ? { ...r.body, identity } : r.body)
1383
1735
  });
1384
1736
  const method = event.requestContext?.http?.method ?? event.httpMethod;
1385
1737
  const contentType = Object.entries(event.headers ?? {}).find(([k]) => k.toLowerCase() === "content-type")?.[1] ?? "";
@@ -1388,7 +1740,8 @@ function createRunner(config, deps) {
1388
1740
  if (method !== "POST" || !/^application\/jwt\s*(;|$)/i.test(contentType) || !body || Buffer.byteLength(body) > MAX_BODY_BYTES) {
1389
1741
  return respond(fail("SIGNATURE_INVALID"));
1390
1742
  }
1391
- return respond(await handleRequest(body, { account }));
1743
+ const handled = await handle(body, { account });
1744
+ return respond(handled.result, handled.identity);
1392
1745
  }
1393
1746
  return {
1394
1747
  process: handleRequest,