@pipeline-builder/pipeline-manager 6.5.2 → 6.5.4

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.
@@ -1,5 +1,6 @@
1
1
  // src/lambda/runner-handler.ts
2
2
  import { CodeBuildClient } from "@aws-sdk/client-codebuild";
3
+ import { CodeConnectionsClient } from "@aws-sdk/client-codeconnections";
3
4
  import {
4
5
  CodePipelineClient,
5
6
  GetPipelineExecutionCommand,
@@ -8,20 +9,46 @@ import {
8
9
  } from "@aws-sdk/client-codepipeline";
9
10
  import { KMSClient } from "@aws-sdk/client-kms";
10
11
  import { GetResourcesCommand, ResourceGroupsTaggingAPIClient } from "@aws-sdk/client-resource-groups-tagging-api";
12
+ import { SecretsManagerClient } from "@aws-sdk/client-secrets-manager";
11
13
 
12
14
  // ../api-core/lib/types/pipeline-runners.js
13
15
  var PIPELINE_ID_TAG = "pb.pipeline-id";
14
16
  function runnerJwksPath(runnerId) {
15
17
  return `/api/pipelines/runner/runners/${encodeURIComponent(runnerId)}/jwks.json`;
16
18
  }
17
- var RUNNER_ACTIONS = ["start", "stop", "probe", "ping", "status", "deploy", "deploy_status", "deploy_cancel", "undeploy"];
19
+ var RUNNER_ACTIONS = [
20
+ "start",
21
+ "stop",
22
+ "probe",
23
+ "ping",
24
+ "status",
25
+ "deploy",
26
+ "deploy_status",
27
+ "deploy_cancel",
28
+ "undeploy",
29
+ // The account's source connections (the create review's picker) and the pre-deploy source check.
30
+ "list_sources",
31
+ "check_source",
32
+ // Reading a private GitHub repository for Generate from Git with the stored token, inside the account.
33
+ "inspect_repository"
34
+ ];
18
35
  var DEPLOY_CAPABILITY = "deploy:1";
36
+ var SOURCES_CAPABILITY = "sources:1";
37
+ var INSPECT_CAPABILITY = "inspect:1";
19
38
  var DEPLOY_ACTION_CAPABILITY = {
20
39
  deploy: DEPLOY_CAPABILITY,
21
40
  deploy_status: DEPLOY_CAPABILITY,
22
41
  deploy_cancel: DEPLOY_CAPABILITY,
23
42
  undeploy: DEPLOY_CAPABILITY
24
43
  };
44
+ var SOURCE_ACTION_CAPABILITY = {
45
+ list_sources: SOURCES_CAPABILITY,
46
+ check_source: SOURCES_CAPABILITY
47
+ };
48
+ var INSPECT_ACTION_CAPABILITY = {
49
+ inspect_repository: INSPECT_CAPABILITY
50
+ };
51
+ var ACTION_CAPABILITY = { ...DEPLOY_ACTION_CAPABILITY, ...SOURCE_ACTION_CAPABILITY, ...INSPECT_ACTION_CAPABILITY };
25
52
  var AWS_REGION_PATTERN = /^[a-z]{2}(-[a-z]+)+-\d{1,2}$/;
26
53
  var RUNNER_ERRORS = {
27
54
  // -- The pipeline service's answers --
@@ -113,6 +140,21 @@ var RUNNER_ERRORS = {
113
140
  DEPLOY_BUSY: { httpStatus: 409, retryable: true, category: "runner" },
114
141
  /** deploy_status / deploy_cancel: no such build in the runner's own deploy project. */
115
142
  DEPLOY_BUILD_NOT_FOUND: { httpStatus: 404, retryable: false, category: "runner" },
143
+ // -- A runner's answers to the source actions (check_source's refusals; list_sources uses only the first) --
144
+ /** The region asked about is not one of the runner's allowed regions. */
145
+ SOURCE_REGION_NOT_ALLOWED: { httpStatus: 403, retryable: false, category: "runner" },
146
+ /** No such CodeConnections connection in the account. */
147
+ SOURCE_CONNECTION_NOT_FOUND: { httpStatus: 404, retryable: false, category: "runner" },
148
+ /** The connection exists but is not AVAILABLE (its handshake is pending, or it is in error). */
149
+ SOURCE_CONNECTION_NOT_AVAILABLE: { httpStatus: 409, retryable: false, category: "runner" },
150
+ /** The connection ARN names another AWS account than the runner's. */
151
+ SOURCE_CONNECTION_WRONG_ACCOUNT: { httpStatus: 409, retryable: false, category: "runner" },
152
+ /** The connection ARN names another region than the deploy's. */
153
+ SOURCE_CONNECTION_WRONG_REGION: { httpStatus: 409, retryable: false, category: "runner" },
154
+ /** The connection is for another Git provider or server than the repository's host. */
155
+ SOURCE_CONNECTION_WRONG_PROVIDER: { httpStatus: 409, retryable: false, category: "runner" },
156
+ /** A token-less GitHub source, and neither the owner's nor the org's GitHub token secret exists in the region. */
157
+ GITHUB_TOKEN_MISSING: { httpStatus: 409, retryable: false, category: "runner" },
116
158
  // -- Recorded by the platform --
117
159
  /** Not delivered within the request's lifetime. */
118
160
  RUN_REQUEST_EXPIRED: { httpStatus: null, retryable: false, category: "recorded" },
@@ -139,6 +181,14 @@ var RUN_REQUEST_ISS = "pipeline-builder";
139
181
  var RUN_REQUEST_TTL_MS = 6e5;
140
182
  var RUN_REQUEST_MAX_LIFETIME_SECONDS = RUN_REQUEST_TTL_MS / 1e3;
141
183
  var RUN_REQUEST_CLOCK_SKEW_SECONDS = 120;
184
+ var SOURCE_ORG_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
185
+ var SOURCE_HOST_PATTERN = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
186
+ var SOURCE_OWNER_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
187
+ var INSPECT_MAX_READS = 10;
188
+ var INSPECT_MAX_READ_BYTES = 128 * 1024;
189
+ var INSPECT_MAX_REPLY_BYTES = 1024 * 1024;
190
+ var INSPECT_MAX_LISTING_ENTRIES = 1e3;
191
+ var INSPECT_REPO_PATTERN = /^[A-Za-z0-9._-]{1,100}$/;
142
192
  var RUNNER_KEY_ACTIVATION_DELAY_MS = 10 * 6e4;
143
193
  var RUNNER_KEY_RETIRE_WINDOW_MS = 60 * 6e4;
144
194
  var RUNNER_TUNABLE_DEFAULTS = {
@@ -151,7 +201,9 @@ var RUNNER_TUNABLE_DEFAULTS = {
151
201
  DEPLOY_REQUESTS_PER_HOUR: "20",
152
202
  MAX_ACTIVE_DEPLOYS_PER_RUNNER: "2",
153
203
  RUNNER_DEPLOY_DEADLINE_MINUTES: "120",
154
- RUNNER_DEPLOY_STATUS_POLL_SECONDS: "30"
204
+ RUNNER_DEPLOY_STATUS_POLL_SECONDS: "30",
205
+ SOURCE_OPTIONS_REQUESTS_PER_MINUTE: "30",
206
+ SOURCE_OPTIONS_CACHE_SECONDS: "60"
155
207
  };
156
208
  var DEPLOY_STAGES = [
157
209
  "queued",
@@ -427,6 +479,332 @@ async function runDeployAction(ctx, claims) {
427
479
  }
428
480
  }
429
481
 
482
+ // src/lambda/runner-inspect.ts
483
+ import { GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
484
+
485
+ // ../api-core/lib/types/pipeline-source.js
486
+ var CONNECTION_ARN_PATTERN = /^arn:aws(?:-[a-z]+)*:(?:codeconnections|codestar-connections):[a-z0-9-]+:\d{12}:connection\/[A-Za-z0-9-]+$/;
487
+ var GITHUB_OWNER_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/;
488
+ function githubOwnerProblem(owner) {
489
+ return GITHUB_OWNER_PATTERN.test(owner) ? null : "A GitHub owner is 1-39 letters, digits or single hyphens, not starting or ending with a hyphen.";
490
+ }
491
+ var DEFAULT_SECRETS_PATH_PREFIX = "pipeline-builder";
492
+ function githubTokenSecretName(orgId, owner, prefix = DEFAULT_SECRETS_PATH_PREFIX) {
493
+ const base = `${prefix}/${orgId}/github-token`;
494
+ if (owner === void 0)
495
+ return base;
496
+ const problem = githubOwnerProblem(owner);
497
+ if (problem)
498
+ throw new Error(`Invalid GitHub owner "${owner}": ${problem}`);
499
+ return `${base}/${owner.toLowerCase()}`;
500
+ }
501
+ function githubTokenStoreCommand(owner, region = "<region>") {
502
+ return `pipeline-manager infra store-github-token --region ${region}${owner ? ` --owner ${owner.toLowerCase()}` : ""}`;
503
+ }
504
+ var GITHUB_TOKEN_STORE_COMMAND = githubTokenStoreCommand();
505
+ var GIT_PROVIDERS = {
506
+ github: { host: "github.com", browse: "tree" },
507
+ gitlab: { host: "gitlab.com", browse: "-/tree" },
508
+ bitbucket: { host: "bitbucket.org", browse: "src" },
509
+ unknown: { host: null, browse: "tree" }
510
+ };
511
+ function providerForHost(host) {
512
+ const hit = Object.keys(GIT_PROVIDERS).find((id) => GIT_PROVIDERS[id].host === host);
513
+ return hit ?? "unknown";
514
+ }
515
+ var SOURCE_CONNECTION_PROVIDER_TYPES = ["GitHub", "GitHubEnterpriseServer", "GitLab", "GitLabSelfManaged", "Bitbucket"];
516
+ var SOURCE_CONNECTION_STATUSES = ["PENDING", "AVAILABLE", "ERROR"];
517
+ var PUBLIC_PROVIDER_TYPE = {
518
+ github: "GitHub",
519
+ gitlab: "GitLab",
520
+ bitbucket: "Bitbucket"
521
+ };
522
+ var SELF_MANAGED_PROVIDER_TYPES = ["GitHubEnterpriseServer", "GitLabSelfManaged"];
523
+ function connectionArnParts(arn) {
524
+ const value = arn.trim();
525
+ if (!CONNECTION_ARN_PATTERN.test(value))
526
+ return null;
527
+ const [, partition, , region, accountId] = value.split(":");
528
+ return { partition, region, accountId };
529
+ }
530
+ function connectionMatchesRepository(connection, repoHost) {
531
+ const host = repoHost.trim().toLowerCase();
532
+ const provider = providerForHost(host);
533
+ if (provider !== "unknown")
534
+ return connection.providerType === PUBLIC_PROVIDER_TYPE[provider];
535
+ if (!SELF_MANAGED_PROVIDER_TYPES.includes(connection.providerType) || !connection.hostEndpoint)
536
+ return false;
537
+ try {
538
+ return new URL(connection.hostEndpoint).hostname.toLowerCase() === host;
539
+ } catch {
540
+ return false;
541
+ }
542
+ }
543
+ async function chooseGitHubTokenSecret(a, describe) {
544
+ const prefix = a.prefix ?? DEFAULT_SECRETS_PATH_PREFIX;
545
+ const owner = a.owner && !githubOwnerProblem(a.owner) ? a.owner.toLowerCase() : void 0;
546
+ if (owner) {
547
+ const ownerSecret = githubTokenSecretName(a.orgId, owner, prefix);
548
+ const found = await describe(ownerSecret);
549
+ if (found)
550
+ return { secret: ownerSecret, owner, scope: "owner", found };
551
+ }
552
+ const orgDefault = githubTokenSecretName(a.orgId, void 0, prefix);
553
+ return { secret: orgDefault, ...owner ? { owner } : {}, scope: "org", found: await describe(orgDefault) };
554
+ }
555
+ var MAX_SOURCE_CONNECTIONS = 100;
556
+ var isRecord = (v) => !!v && typeof v === "object" && !Array.isArray(v);
557
+ var MAX_READ_PATH = 500;
558
+ var READ_SEGMENT_PATTERN = /^[^\u0000-\u001f\u007f?#\\]{1,255}$/;
559
+ var READ_REF_PATTERN = /^[^\s\u0000-\u001f\u007f?#]{1,255}$/;
560
+ function repositoryReadProblem(raw) {
561
+ if (!isRecord(raw))
562
+ return "not a read";
563
+ if (raw.kind === "repo" || raw.kind === "languages")
564
+ return Object.keys(raw).length === 1 ? null : "unexpected fields";
565
+ if (raw.kind !== "contents")
566
+ return "unknown read";
567
+ const { path, ref } = raw;
568
+ if (typeof ref !== "string" || !READ_REF_PATTERN.test(ref) || ref.includes(".."))
569
+ return "malformed ref";
570
+ if (typeof path !== "string" || path.length > MAX_READ_PATH)
571
+ return "malformed path";
572
+ if (path === "")
573
+ return null;
574
+ const segments = path.split("/");
575
+ if (segments.some((seg) => seg === "." || seg === ".." || !READ_SEGMENT_PATTERN.test(seg)))
576
+ return "malformed path";
577
+ return null;
578
+ }
579
+ var MAX_TEXT = 2e3;
580
+ var MAX_TOPICS = 50;
581
+ var MAX_LANGUAGES = 100;
582
+ var MAX_BASE64_CHARS = 2e5;
583
+ var optionalString = (v, max) => v === void 0 || v === null || typeof v === "string" && v.length <= max;
584
+ function parseRepositoryReadBody(read, body) {
585
+ if (read.kind === "repo") {
586
+ if (!isRecord(body))
587
+ return null;
588
+ const { default_branch: branch, description, topics, private: isPrivate, visibility } = body;
589
+ if (!optionalString(branch, 255) || !optionalString(description, MAX_TEXT))
590
+ return null;
591
+ if (isPrivate !== void 0 && typeof isPrivate !== "boolean")
592
+ return null;
593
+ if (visibility !== void 0 && visibility !== "public" && visibility !== "private" && visibility !== "internal")
594
+ return null;
595
+ if (topics !== void 0 && (!Array.isArray(topics) || topics.length > MAX_TOPICS || topics.some((t) => typeof t !== "string" || t.length > 100)))
596
+ return null;
597
+ return {
598
+ ...typeof branch === "string" ? { default_branch: branch } : {},
599
+ ...typeof description === "string" ? { description } : {},
600
+ ...Array.isArray(topics) ? { topics } : {},
601
+ ...typeof isPrivate === "boolean" ? { private: isPrivate } : {},
602
+ ...typeof visibility === "string" ? { visibility } : {}
603
+ };
604
+ }
605
+ if (read.kind === "languages") {
606
+ if (!isRecord(body))
607
+ return null;
608
+ const entries = Object.entries(body);
609
+ if (entries.length > MAX_LANGUAGES || entries.some(([k, v]) => k.length > 100 || typeof v !== "number" || !Number.isFinite(v)))
610
+ return null;
611
+ return Object.fromEntries(entries);
612
+ }
613
+ if (Array.isArray(body)) {
614
+ if (body.length > INSPECT_MAX_LISTING_ENTRIES)
615
+ return null;
616
+ return body.filter((e) => isRecord(e) && typeof e.name === "string" && e.name.length <= 255 && (e.type === "file" || e.type === "dir")).map((e) => ({ name: e.name, type: e.type }));
617
+ }
618
+ if (!isRecord(body))
619
+ return null;
620
+ const { name, type, encoding, content } = body;
621
+ if (typeof name !== "string" || name.length > 255 || type !== "file" || encoding !== "base64" || typeof content !== "string" || content.length > MAX_BASE64_CHARS)
622
+ return null;
623
+ return { name, type, encoding, content };
624
+ }
625
+
626
+ // src/lambda/runner-sources.ts
627
+ import { GetConnectionCommand, GetHostCommand, ListConnectionsCommand, ListHostsCommand } from "@aws-sdk/client-codeconnections";
628
+ import { DescribeSecretCommand } from "@aws-sdk/client-secrets-manager";
629
+ var MAX_PAGES = 10;
630
+ var errName2 = (err) => String(err?.name ?? "");
631
+ var isNotFound = (err) => errName2(err) === "ResourceNotFoundException";
632
+ var isProviderType = (v) => SOURCE_CONNECTION_PROVIDER_TYPES.includes(v);
633
+ var isStatus = (v) => SOURCE_CONNECTION_STATUSES.includes(v);
634
+ function describeSecretLookup(deps, region) {
635
+ return async (name) => {
636
+ 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 };
640
+ } catch (err) {
641
+ if (isNotFound(err)) return null;
642
+ throw err;
643
+ }
644
+ };
645
+ }
646
+ async function githubTokenFor(claim, deps) {
647
+ const repository = claim.repository;
648
+ if (!repository || providerForHost(repository.host) !== "github") return null;
649
+ const choice = await chooseGitHubTokenSecret(
650
+ { orgId: claim.orgId, owner: repository.owner, prefix: DEFAULT_SECRETS_PATH_PREFIX },
651
+ describeSecretLookup(deps, claim.region)
652
+ );
653
+ return choice.found ? { secretName: choice.secret, scope: choice.scope, lastChangedDate: choice.found.lastChangedDate } : null;
654
+ }
655
+ async function hostEndpoints(deps, region) {
656
+ const endpoints = /* @__PURE__ */ new Map();
657
+ let token;
658
+ let pages = 0;
659
+ do {
660
+ const out = await deps.codeconnections(region).send(new ListHostsCommand({ MaxResults: 100, ...token ? { NextToken: token } : {} }));
661
+ for (const h of out.Hosts ?? []) if (h.HostArn && h.ProviderEndpoint) endpoints.set(h.HostArn, h.ProviderEndpoint);
662
+ token = out.NextToken || void 0;
663
+ } while (token && ++pages < MAX_PAGES);
664
+ return endpoints;
665
+ }
666
+ function toDto(c, hostEndpoint) {
667
+ if (!c.ConnectionArn || !c.ConnectionName || !isProviderType(c.ProviderType) || !isStatus(c.ConnectionStatus)) return null;
668
+ return {
669
+ arn: c.ConnectionArn,
670
+ name: c.ConnectionName,
671
+ providerType: c.ProviderType,
672
+ status: c.ConnectionStatus,
673
+ ...hostEndpoint ? { hostEndpoint } : {}
674
+ };
675
+ }
676
+ async function listSources(claim, accountId, deps) {
677
+ const repoHost = claim.repository.host;
678
+ const raw = [];
679
+ let token;
680
+ let pages = 0;
681
+ let more = false;
682
+ do {
683
+ const out = await deps.codeconnections(claim.region).send(new ListConnectionsCommand({ MaxResults: 100, ...token ? { NextToken: token } : {} }));
684
+ raw.push(...out.Connections ?? []);
685
+ token = out.NextToken || void 0;
686
+ more = !!token && ++pages >= MAX_PAGES;
687
+ } while (token && !more);
688
+ const hosts = raw.some((c) => c.HostArn) && providerForHost(repoHost) === "unknown" ? await hostEndpoints(deps, claim.region) : /* @__PURE__ */ new Map();
689
+ const matching = raw.map((c) => toDto(c, c.HostArn ? hosts.get(c.HostArn) : void 0)).filter((c) => !!c && connectionMatchesRepository(c, repoHost)).sort((a, b) => a.name.localeCompare(b.name) || a.arn.localeCompare(b.arn));
690
+ return {
691
+ accountId,
692
+ region: claim.region,
693
+ connections: matching.slice(0, MAX_SOURCE_CONNECTIONS),
694
+ githubToken: await githubTokenFor(claim, deps),
695
+ truncated: more || matching.length > MAX_SOURCE_CONNECTIONS
696
+ };
697
+ }
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";
707
+ let connection;
708
+ try {
709
+ const out = await deps.codeconnections(claim.region).send(new GetConnectionCommand({ ConnectionArn: source.connectionArn }));
710
+ connection = out.Connection;
711
+ } catch (err) {
712
+ if (isNotFound(err)) return "SOURCE_CONNECTION_NOT_FOUND";
713
+ throw err;
714
+ }
715
+ if (!connection) return "SOURCE_CONNECTION_NOT_FOUND";
716
+ if (connection.ConnectionStatus !== "AVAILABLE") return "SOURCE_CONNECTION_NOT_AVAILABLE";
717
+ let hostEndpoint;
718
+ if (connection.HostArn) {
719
+ try {
720
+ const host = await deps.codeconnections(claim.region).send(new GetHostCommand({ HostArn: connection.HostArn }));
721
+ hostEndpoint = host.ProviderEndpoint;
722
+ } catch (err) {
723
+ if (!isNotFound(err)) throw err;
724
+ }
725
+ }
726
+ const dto = toDto(connection, hostEndpoint);
727
+ if (!dto) return "SOURCE_CONNECTION_WRONG_PROVIDER";
728
+ return !claim.repository || connectionMatchesRepository(dto, claim.repository.host) ? null : "SOURCE_CONNECTION_WRONG_PROVIDER";
729
+ }
730
+
731
+ // src/lambda/runner-inspect.ts
732
+ var GITHUB_API = "https://api.github.com";
733
+ var GITHUB_TIMEOUT_MS = 6e3;
734
+ async function readCapped(res, cap) {
735
+ if (!res.body) return "";
736
+ const reader = res.body.getReader();
737
+ const chunks = [];
738
+ let size = 0;
739
+ for (; ; ) {
740
+ const { done, value } = await reader.read();
741
+ if (done) break;
742
+ size += value.byteLength;
743
+ if (size > cap) {
744
+ await reader.cancel();
745
+ return null;
746
+ }
747
+ chunks.push(value);
748
+ }
749
+ return Buffer.concat(chunks).toString("utf8");
750
+ }
751
+ var githubGet = async (url, token) => {
752
+ const res = await fetch(url, {
753
+ headers: {
754
+ "Accept": "application/vnd.github+json",
755
+ "User-Agent": "pipeline-builder-runner",
756
+ "X-GitHub-Api-Version": "2022-11-28",
757
+ "Authorization": `Bearer ${token}`
758
+ },
759
+ redirect: "error",
760
+ signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS)
761
+ });
762
+ return { status: res.status, text: await readCapped(res, INSPECT_MAX_READ_BYTES) };
763
+ };
764
+ function readUrl(repository, read) {
765
+ const base = `${GITHUB_API}/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}`;
766
+ if (read.kind === "repo") return base;
767
+ if (read.kind === "languages") return `${base}/languages`;
768
+ const path = read.path ? read.path.split("/").map(encodeURIComponent).join("/") : "";
769
+ return `${base}/contents/${path}?ref=${encodeURIComponent(read.ref)}`;
770
+ }
771
+ async function answer(deps, claim, read, token) {
772
+ let got;
773
+ try {
774
+ got = await deps.github(readUrl(claim.repository, read), token);
775
+ } catch {
776
+ return { status: 504 };
777
+ }
778
+ if (got.status < 200 || got.status >= 300) return { status: got.status };
779
+ if (got.text === null) return { status: 413 };
780
+ let json;
781
+ try {
782
+ json = JSON.parse(got.text);
783
+ } catch {
784
+ return { status: 502 };
785
+ }
786
+ const body = parseRepositoryReadBody(read, json);
787
+ return body === null ? { status: 502 } : { status: got.status, body };
788
+ }
789
+ async function inspectRepository(claim, deps) {
790
+ const choice = await chooseGitHubTokenSecret(
791
+ { orgId: claim.orgId, owner: claim.repository.owner, prefix: DEFAULT_SECRETS_PATH_PREFIX },
792
+ describeSecretLookup(deps, claim.region)
793
+ );
794
+ if (!choice.found) return "GITHUB_TOKEN_MISSING";
795
+ const out = await deps.secrets(claim.region).send(new GetSecretValueCommand({ SecretId: choice.secret }));
796
+ const token = typeof out.SecretString === "string" ? out.SecretString.trim() : "";
797
+ if (!token) return "GITHUB_TOKEN_MISSING";
798
+ const answers = await Promise.all(claim.reads.map((read) => answer(deps, claim, read, token)));
799
+ let total = 0;
800
+ const results = answers.map((a) => {
801
+ if (a.body === void 0) return a;
802
+ total += JSON.stringify(a.body).length;
803
+ return total > INSPECT_MAX_REPLY_BYTES ? { status: 413 } : a;
804
+ });
805
+ return { results };
806
+ }
807
+
430
808
  // src/lambda/runner-jws.ts
431
809
  import { createPublicKey, verify as cryptoVerify } from "node:crypto";
432
810
  var JWKS_TTL_MS = 10 * 60 * 1e3;
@@ -555,7 +933,9 @@ async function verifyRunRequest(jws, opts) {
555
933
  const action = c.action;
556
934
  if (!opts.runnerId) throw new SignatureError("runner has no RUNNER_ID");
557
935
  if (c.aud !== opts.runnerId) throw new SignatureError("wrong aud");
558
- if (action !== "ping" && !isNonEmptyString(c.pipelineId)) throw new SignatureError("missing pipelineId");
936
+ const isSourceAction = Object.hasOwn(SOURCE_ACTION_CAPABILITY, action);
937
+ const isInspect = action === "inspect_repository";
938
+ if (action !== "ping" && !isSourceAction && !isInspect && !isNonEmptyString(c.pipelineId)) throw new SignatureError("missing pipelineId");
559
939
  if ((action === "stop" || action === "status") && !isNonEmptyString(c.executionId)) throw new SignatureError("missing executionId");
560
940
  let hint;
561
941
  if (c.hint !== void 0 && c.hint !== null) {
@@ -571,6 +951,10 @@ async function verifyRunRequest(jws, opts) {
571
951
  if (!takesBuild && c.deployRequestId !== void 0) throw new SignatureError("unexpected deployRequestId");
572
952
  if (!takesBuild && c.buildId !== void 0) throw new SignatureError("unexpected buildId");
573
953
  const deploy = takesBlock ? parseDeployClaim(c.deploy, action) : void 0;
954
+ if (!isSourceAction && c.sources !== void 0) throw new SignatureError("unexpected sources claim");
955
+ const sources = isSourceAction ? parseSourcesClaim(c.sources, action === "check_source") : void 0;
956
+ if (!isInspect && c.inspect !== void 0) throw new SignatureError("unexpected inspect claim");
957
+ const inspect = isInspect ? parseInspectClaim(c.inspect) : void 0;
574
958
  if (takesBuild) {
575
959
  if (!isNonEmptyString(c.deployRequestId) || c.deployRequestId.length > 128) throw new SignatureError("missing deployRequestId");
576
960
  if (typeof c.buildId !== "string" || !BUILD_ID_PATTERN.test(c.buildId)) throw new SignatureError("malformed buildId");
@@ -587,6 +971,8 @@ async function verifyRunRequest(jws, opts) {
587
971
  ...isNonEmptyString(c.executionId) ? { executionId: c.executionId } : {},
588
972
  ...deploy ? { deploy } : {},
589
973
  ...takesBuild ? { deployRequestId: c.deployRequestId, buildId: c.buildId } : {},
974
+ ...sources ? { sources } : {},
975
+ ...inspect ? { inspect } : {},
590
976
  requestedBy: c.requestedBy
591
977
  };
592
978
  }
@@ -619,6 +1005,54 @@ function parseDeployClaim(raw, action) {
619
1005
  toolchainRelease: d.toolchainRelease
620
1006
  };
621
1007
  }
1008
+ function parseSourcesClaim(raw, isCheck) {
1009
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SignatureError("missing sources claim");
1010
+ const b = raw;
1011
+ if (typeof b.orgId !== "string" || !SOURCE_ORG_ID_PATTERN.test(b.orgId)) throw new SignatureError("malformed sources orgId");
1012
+ if (typeof b.region !== "string" || !AWS_REGION_PATTERN.test(b.region)) throw new SignatureError("malformed sources region");
1013
+ const repo = b.repository;
1014
+ let repository;
1015
+ if (repo !== void 0) {
1016
+ if (!repo || typeof repo !== "object" || Array.isArray(repo)) throw new SignatureError("missing sources repository");
1017
+ if (typeof repo.host !== "string" || !SOURCE_HOST_PATTERN.test(repo.host)) throw new SignatureError("malformed sources repository host");
1018
+ if (typeof repo.owner !== "string" || !SOURCE_OWNER_PATTERN.test(repo.owner)) throw new SignatureError("malformed sources repository owner");
1019
+ repository = { host: repo.host, owner: repo.owner };
1020
+ }
1021
+ const claim = { orgId: b.orgId, region: b.region, ...repository ? { repository } : {} };
1022
+ if (!isCheck) {
1023
+ if (b.source !== void 0) throw new SignatureError("unexpected source on list_sources");
1024
+ if (!repository) throw new SignatureError("missing sources repository");
1025
+ return claim;
1026
+ }
1027
+ const src = b.source;
1028
+ if (!src || typeof src !== "object" || Array.isArray(src)) throw new SignatureError("missing source to check");
1029
+ if (src.type === "github") {
1030
+ if (!repository) throw new SignatureError("missing sources repository");
1031
+ return { ...claim, source: { type: "github" } };
1032
+ }
1033
+ if (src.type !== "codestar") throw new SignatureError("unknown source type to check");
1034
+ if (typeof src.connectionArn !== "string" || !CONNECTION_ARN_PATTERN.test(src.connectionArn)) throw new SignatureError("malformed source connectionArn");
1035
+ return { ...claim, source: { type: "codestar", connectionArn: src.connectionArn } };
1036
+ }
1037
+ function parseInspectClaim(raw) {
1038
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SignatureError("missing inspect claim");
1039
+ const b = raw;
1040
+ if (typeof b.orgId !== "string" || !SOURCE_ORG_ID_PATTERN.test(b.orgId)) throw new SignatureError("malformed inspect orgId");
1041
+ if (typeof b.region !== "string" || !AWS_REGION_PATTERN.test(b.region)) throw new SignatureError("malformed inspect region");
1042
+ const repo = b.repository;
1043
+ 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");
1045
+ if (typeof repo.repo !== "string" || !INSPECT_REPO_PATTERN.test(repo.repo) || repo.repo === "." || repo.repo === "..") {
1046
+ throw new SignatureError("malformed inspect repository repo");
1047
+ }
1048
+ if (!Array.isArray(b.reads) || b.reads.length === 0 || b.reads.length > INSPECT_MAX_READS) throw new SignatureError("malformed inspect reads");
1049
+ const reads = b.reads.map((r) => {
1050
+ const problem = repositoryReadProblem(r);
1051
+ if (problem) throw new SignatureError(`malformed inspect read: ${problem}`);
1052
+ return { ...r };
1053
+ });
1054
+ return { orgId: b.orgId, region: b.region, repository: { owner: repo.owner, repo: repo.repo }, reads };
1055
+ }
622
1056
  var ReplayCache = class {
623
1057
  constructor(now) {
624
1058
  this.now = now;
@@ -678,6 +1112,8 @@ function defaultDeps() {
678
1112
  const cp = /* @__PURE__ */ new Map();
679
1113
  let codebuild;
680
1114
  let kms;
1115
+ const cc = /* @__PURE__ */ new Map();
1116
+ const sm = /* @__PURE__ */ new Map();
681
1117
  return {
682
1118
  fetch: (url, init) => fetch(url, init),
683
1119
  now: () => Date.now(),
@@ -691,6 +1127,15 @@ function defaultDeps() {
691
1127
  },
692
1128
  codebuild: () => codebuild ??= new CodeBuildClient({}),
693
1129
  kms: () => kms ??= new KMSClient({}),
1130
+ codeconnections: (region) => {
1131
+ if (!cc.has(region)) cc.set(region, new CodeConnectionsClient({ region }));
1132
+ return cc.get(region);
1133
+ },
1134
+ secrets: (region) => {
1135
+ if (!sm.has(region)) sm.set(region, new SecretsManagerClient({ region }));
1136
+ return sm.get(region);
1137
+ },
1138
+ github: githubGet,
694
1139
  log: defaultLog
695
1140
  };
696
1141
  }
@@ -709,10 +1154,10 @@ function isAllowed(config, region, name) {
709
1154
  if (!config.allowedRegions.includes(region)) return false;
710
1155
  return config.allowedPrefixes.some((p) => p === "*" || name.startsWith(p));
711
1156
  }
712
- var errName2 = (err) => String(err?.name ?? "");
1157
+ var errName3 = (err) => String(err?.name ?? "");
713
1158
  var errStatus = (err) => err?.$metadata?.httpStatusCode;
714
1159
  function isAccessDenied(err) {
715
- const n = errName2(err);
1160
+ const n = errName3(err);
716
1161
  return n === "AccessDeniedException" || n === "AccessDenied" || n === "UnauthorizedOperation" || n === "AuthorizationErrorException" || errStatus(err) === 403 && !/Throttl/.test(n);
717
1162
  }
718
1163
  var NOT_FOUND_ERRORS = /* @__PURE__ */ new Set(["ResourceNotFoundException", "PipelineNotFoundException", "InvalidArnException"]);
@@ -743,7 +1188,7 @@ async function hintedTag(deps, account, hint) {
743
1188
  try {
744
1189
  return await readPipelineIdTag(deps.codepipeline(hint.region), resourceArn) ?? null;
745
1190
  } catch (err) {
746
- if (NOT_FOUND_ERRORS.has(errName2(err))) return void 0;
1191
+ if (NOT_FOUND_ERRORS.has(errName3(err))) return void 0;
747
1192
  throw err;
748
1193
  }
749
1194
  }
@@ -788,8 +1233,8 @@ function createRunner(config, deps) {
788
1233
  if (e?.pipelineName !== void 0 && e.pipelineName !== pipelineName) return fail("RUNNER_REFUSED");
789
1234
  return { ...e?.status ? { executionStatus: e.status } : {} };
790
1235
  } catch (err) {
791
- if (errName2(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
792
- if (errName2(err) === "PipelineExecutionNotFoundException") return fail("RUNNER_REFUSED");
1236
+ if (errName3(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
1237
+ if (errName3(err) === "PipelineExecutionNotFoundException") return fail("RUNNER_REFUSED");
793
1238
  throw err;
794
1239
  }
795
1240
  }
@@ -803,7 +1248,7 @@ function createRunner(config, deps) {
803
1248
  }));
804
1249
  return ok("started", out.pipelineExecutionId ? { executionId: out.pipelineExecutionId } : {});
805
1250
  } catch (err) {
806
- if (errName2(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
1251
+ if (errName3(err) === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
807
1252
  throw err;
808
1253
  }
809
1254
  }
@@ -820,7 +1265,7 @@ function createRunner(config, deps) {
820
1265
  reason: `Stopped by pipeline-builder request ${claims.jti}`.slice(0, 200)
821
1266
  }));
822
1267
  } catch (err) {
823
- const n = errName2(err);
1268
+ const n = errName3(err);
824
1269
  if (n === "DuplicatedStopRequestException") return ok("stopped", { executionId });
825
1270
  if (n === "PipelineNotFoundException") return fail("PIPELINE_NOT_FOUND");
826
1271
  if (n === "PipelineExecutionNotStoppableException" || n === "PipelineExecutionNotFoundException") return fail("RUNNER_REFUSED");
@@ -834,7 +1279,7 @@ function createRunner(config, deps) {
834
1279
  return ok("status", { executionId: claims.executionId, executionStatus: execution.executionStatus ?? "Unknown" });
835
1280
  }
836
1281
  async function deployAction(claims) {
837
- const answer = await runDeployAction({
1282
+ const answer2 = await runDeployAction({
838
1283
  runnerId: config.runnerId,
839
1284
  config: config.deploy,
840
1285
  codebuild: deps.codebuild(),
@@ -842,19 +1287,35 @@ function createRunner(config, deps) {
842
1287
  isAllowed: (region, name) => isAllowed(config, region, name),
843
1288
  alreadyDeployed: async (pipelineId) => (await arnsByTag(config, deps, pipelineId)).length > 0
844
1289
  }, claims);
845
- if ("refuse" in answer) return fail(answer.refuse);
846
- const { outcome, ...details } = answer;
1290
+ if ("refuse" in answer2) return fail(answer2.refuse);
1291
+ const { outcome, ...details } = answer2;
847
1292
  return ok(outcome, details);
848
1293
  }
1294
+ async function sourceAction(claims, account) {
1295
+ const sources = claims.sources;
1296
+ if (!config.allowedRegions.includes(sources.region)) return fail("SOURCE_REGION_NOT_ALLOWED");
1297
+ if (!account) return internal();
1298
+ if (claims.action === "list_sources") return ok("sources", { ...await listSources(sources, account.accountId, deps) });
1299
+ const refusal = await checkSource(sources, account.accountId, deps);
1300
+ return refusal ? fail(refusal) : ok("source_ok");
1301
+ }
1302
+ async function inspectAction(claims) {
1303
+ const inspect = claims.inspect;
1304
+ if (!config.allowedRegions.includes(inspect.region)) return fail("SOURCE_REGION_NOT_ALLOWED");
1305
+ const answer2 = await inspectRepository(inspect, deps);
1306
+ return answer2 === "GITHUB_TOKEN_MISSING" ? fail(answer2) : ok("repository_reads", { results: answer2.results });
1307
+ }
849
1308
  async function act(claims, account) {
850
1309
  if (claims.action === "ping") {
851
1310
  return ok("pong", {
852
1311
  regions: [...config.allowedRegions],
853
- capabilities: config.deploy.enabled ? [DEPLOY_CAPABILITY] : [],
1312
+ capabilities: config.deploy.enabled ? [DEPLOY_CAPABILITY, SOURCES_CAPABILITY, INSPECT_CAPABILITY] : [SOURCES_CAPABILITY, INSPECT_CAPABILITY],
854
1313
  pipelinePrefixes: [...config.allowedPrefixes]
855
1314
  });
856
1315
  }
857
1316
  if (Object.hasOwn(DEPLOY_ACTION_CAPABILITY, claims.action)) return deployAction(claims);
1317
+ if (Object.hasOwn(SOURCE_ACTION_CAPABILITY, claims.action)) return sourceAction(claims, account);
1318
+ if (claims.action === "inspect_repository") return inspectAction(claims);
858
1319
  const found = await findPipeline(config, deps, account, claims.pipelineId, claims.hint);
859
1320
  if (claims.action === "probe") {
860
1321
  if (found.kind === "ambiguous") return fail("AMBIGUOUS_PIPELINE");
@@ -880,7 +1341,7 @@ function createRunner(config, deps) {
880
1341
  deps.log("ERROR", "Could not fetch the platform signing keys", { reason: err.message });
881
1342
  return internal();
882
1343
  }
883
- deps.log("ERROR", "Unexpected verification failure", { error: errName2(err) || "Error" });
1344
+ deps.log("ERROR", "Unexpected verification failure", { error: errName3(err) || "Error" });
884
1345
  return internal();
885
1346
  }
886
1347
  const prior = replay.claim(claims.jti);
@@ -894,10 +1355,10 @@ function createRunner(config, deps) {
894
1355
  result = await act(claims, opts.account);
895
1356
  } catch (err) {
896
1357
  if (isAccessDenied(err)) {
897
- deps.log("ERROR", "The runner role was refused by AWS \u2014 redeploy the runner stack or fix its role", { ...logCtx, error: errName2(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) });
898
1359
  result = fail("RUNNER_PERMISSION_DENIED");
899
1360
  } else {
900
- deps.log("ERROR", "Request failed", { ...logCtx, error: errName2(err) || "Error" });
1361
+ deps.log("ERROR", "Request failed", { ...logCtx, error: errName3(err) || "Error" });
901
1362
  result = internal();
902
1363
  }
903
1364
  }