@pipeline-builder/pipeline-manager 6.5.3 → 6.5.5

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.
@@ -28,10 +28,13 @@ var RUNNER_ACTIONS = [
28
28
  "undeploy",
29
29
  // The account's source connections (the create review's picker) and the pre-deploy source check.
30
30
  "list_sources",
31
- "check_source"
31
+ "check_source",
32
+ // Reading a private GitHub repository for Generate from Git with the stored token, inside the account.
33
+ "inspect_repository"
32
34
  ];
33
35
  var DEPLOY_CAPABILITY = "deploy:1";
34
36
  var SOURCES_CAPABILITY = "sources:1";
37
+ var INSPECT_CAPABILITY = "inspect:1";
35
38
  var DEPLOY_ACTION_CAPABILITY = {
36
39
  deploy: DEPLOY_CAPABILITY,
37
40
  deploy_status: DEPLOY_CAPABILITY,
@@ -42,7 +45,10 @@ var SOURCE_ACTION_CAPABILITY = {
42
45
  list_sources: SOURCES_CAPABILITY,
43
46
  check_source: SOURCES_CAPABILITY
44
47
  };
45
- var ACTION_CAPABILITY = { ...DEPLOY_ACTION_CAPABILITY, ...SOURCE_ACTION_CAPABILITY };
48
+ var INSPECT_ACTION_CAPABILITY = {
49
+ inspect_repository: INSPECT_CAPABILITY
50
+ };
51
+ var ACTION_CAPABILITY = { ...DEPLOY_ACTION_CAPABILITY, ...SOURCE_ACTION_CAPABILITY, ...INSPECT_ACTION_CAPABILITY };
46
52
  var AWS_REGION_PATTERN = /^[a-z]{2}(-[a-z]+)+-\d{1,2}$/;
47
53
  var RUNNER_ERRORS = {
48
54
  // -- The pipeline service's answers --
@@ -178,6 +184,11 @@ var RUN_REQUEST_CLOCK_SKEW_SECONDS = 120;
178
184
  var SOURCE_ORG_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
179
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])?)*$/;
180
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}$/;
181
192
  var RUNNER_KEY_ACTIVATION_DELAY_MS = 10 * 6e4;
182
193
  var RUNNER_KEY_RETIRE_WINDOW_MS = 60 * 6e4;
183
194
  var RUNNER_TUNABLE_DEFAULTS = {
@@ -468,8 +479,8 @@ async function runDeployAction(ctx, claims) {
468
479
  }
469
480
  }
470
481
 
471
- // src/lambda/runner-jws.ts
472
- import { createPublicKey, verify as cryptoVerify } from "node:crypto";
482
+ // src/lambda/runner-inspect.ts
483
+ import { GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
473
484
 
474
485
  // ../api-core/lib/types/pipeline-source.js
475
486
  var CONNECTION_ARN_PATTERN = /^arn:aws(?:-[a-z]+)*:(?:codeconnections|codestar-connections):[a-z0-9-]+:\d{12}:connection\/[A-Za-z0-9-]+$/;
@@ -529,6 +540,11 @@ function connectionMatchesRepository(connection, repoHost) {
529
540
  return false;
530
541
  }
531
542
  }
543
+ function secretLookupFromDescribe(out) {
544
+ if (out.DeletedDate)
545
+ return null;
546
+ return { lastChangedDate: out.LastChangedDate instanceof Date ? out.LastChangedDate.toISOString() : null };
547
+ }
532
548
  async function chooseGitHubTokenSecret(a, describe) {
533
549
  const prefix = a.prefix ?? DEFAULT_SECRETS_PATH_PREFIX;
534
550
  const owner = a.owner && !githubOwnerProblem(a.owner) ? a.owner.toLowerCase() : void 0;
@@ -542,8 +558,262 @@ async function chooseGitHubTokenSecret(a, describe) {
542
558
  return { secret: orgDefault, ...owner ? { owner } : {}, scope: "org", found: await describe(orgDefault) };
543
559
  }
544
560
  var MAX_SOURCE_CONNECTIONS = 100;
561
+ var isRecord = (v) => !!v && typeof v === "object" && !Array.isArray(v);
562
+ var MAX_READ_PATH = 500;
563
+ var READ_SEGMENT_PATTERN = /^[^\u0000-\u001f\u007f?#\\]{1,255}$/;
564
+ var READ_REF_PATTERN = /^[^\s\u0000-\u001f\u007f?#]{1,255}$/;
565
+ function repositoryReadProblem(raw) {
566
+ if (!isRecord(raw))
567
+ return "not a read";
568
+ if (raw.kind === "repo" || raw.kind === "languages")
569
+ return Object.keys(raw).length === 1 ? null : "unexpected fields";
570
+ if (raw.kind !== "contents")
571
+ return "unknown read";
572
+ const { path, ref } = raw;
573
+ if (typeof ref !== "string" || !READ_REF_PATTERN.test(ref) || ref.includes(".."))
574
+ return "malformed ref";
575
+ if (typeof path !== "string" || path.length > MAX_READ_PATH)
576
+ return "malformed path";
577
+ if (path === "")
578
+ return null;
579
+ const segments = path.split("/");
580
+ if (segments.some((seg) => seg === "." || seg === ".." || !READ_SEGMENT_PATTERN.test(seg)))
581
+ return "malformed path";
582
+ return null;
583
+ }
584
+ var MAX_TEXT = 2e3;
585
+ var MAX_TOPICS = 50;
586
+ var MAX_LANGUAGES = 100;
587
+ var MAX_BASE64_CHARS = 2e5;
588
+ var optionalString = (v, max) => v === void 0 || v === null || typeof v === "string" && v.length <= max;
589
+ function parseRepositoryReadBody(read, body) {
590
+ if (read.kind === "repo") {
591
+ if (!isRecord(body))
592
+ return null;
593
+ const { default_branch: branch, description, topics, private: isPrivate, visibility } = body;
594
+ if (!optionalString(branch, 255) || !optionalString(description, MAX_TEXT))
595
+ return null;
596
+ if (isPrivate !== void 0 && typeof isPrivate !== "boolean")
597
+ return null;
598
+ if (visibility !== void 0 && visibility !== "public" && visibility !== "private" && visibility !== "internal")
599
+ return null;
600
+ if (topics !== void 0 && (!Array.isArray(topics) || topics.length > MAX_TOPICS || topics.some((t) => typeof t !== "string" || t.length > 100)))
601
+ return null;
602
+ return {
603
+ ...typeof branch === "string" ? { default_branch: branch } : {},
604
+ ...typeof description === "string" ? { description } : {},
605
+ ...Array.isArray(topics) ? { topics } : {},
606
+ ...typeof isPrivate === "boolean" ? { private: isPrivate } : {},
607
+ ...typeof visibility === "string" ? { visibility } : {}
608
+ };
609
+ }
610
+ if (read.kind === "languages") {
611
+ if (!isRecord(body))
612
+ return null;
613
+ const entries = Object.entries(body);
614
+ if (entries.length > MAX_LANGUAGES || entries.some(([k, v]) => k.length > 100 || typeof v !== "number" || !Number.isFinite(v)))
615
+ return null;
616
+ return Object.fromEntries(entries);
617
+ }
618
+ if (Array.isArray(body)) {
619
+ if (body.length > INSPECT_MAX_LISTING_ENTRIES)
620
+ return null;
621
+ 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 }));
622
+ }
623
+ if (!isRecord(body))
624
+ return null;
625
+ const { name, type, encoding, content } = body;
626
+ if (typeof name !== "string" || name.length > 255 || type !== "file" || encoding !== "base64" || typeof content !== "string" || content.length > MAX_BASE64_CHARS)
627
+ return null;
628
+ return { name, type, encoding, content };
629
+ }
630
+
631
+ // src/lambda/runner-sources.ts
632
+ import { GetConnectionCommand, GetHostCommand, ListConnectionsCommand, ListHostsCommand } from "@aws-sdk/client-codeconnections";
633
+ import { DescribeSecretCommand } from "@aws-sdk/client-secrets-manager";
634
+ var MAX_PAGES = 10;
635
+ var errName2 = (err) => String(err?.name ?? "");
636
+ var isNotFound = (err) => errName2(err) === "ResourceNotFoundException";
637
+ var isProviderType = (v) => SOURCE_CONNECTION_PROVIDER_TYPES.includes(v);
638
+ var isStatus = (v) => SOURCE_CONNECTION_STATUSES.includes(v);
639
+ function describeSecretLookup(deps, region) {
640
+ return async (name) => {
641
+ try {
642
+ return secretLookupFromDescribe(await deps.secrets(region).send(new DescribeSecretCommand({ SecretId: name })));
643
+ } catch (err) {
644
+ if (isNotFound(err)) return null;
645
+ throw err;
646
+ }
647
+ };
648
+ }
649
+ async function githubTokenFor(claim, deps) {
650
+ const repository = claim.repository;
651
+ if (!repository || providerForHost(repository.host) !== "github") return null;
652
+ const choice = await chooseGitHubTokenSecret(
653
+ { orgId: claim.orgId, owner: repository.owner, prefix: DEFAULT_SECRETS_PATH_PREFIX },
654
+ describeSecretLookup(deps, claim.region)
655
+ );
656
+ return choice.found ? { secretName: choice.secret, scope: choice.scope, lastChangedDate: choice.found.lastChangedDate } : null;
657
+ }
658
+ async function hostEndpoints(deps, region) {
659
+ const endpoints = /* @__PURE__ */ new Map();
660
+ let token;
661
+ let pages = 0;
662
+ do {
663
+ const out = await deps.codeconnections(region).send(new ListHostsCommand({ MaxResults: 100, ...token ? { NextToken: token } : {} }));
664
+ for (const h of out.Hosts ?? []) if (h.HostArn && h.ProviderEndpoint) endpoints.set(h.HostArn, h.ProviderEndpoint);
665
+ token = out.NextToken || void 0;
666
+ } while (token && ++pages < MAX_PAGES);
667
+ return endpoints;
668
+ }
669
+ function toDto(c, hostEndpoint) {
670
+ if (!c.ConnectionArn || !c.ConnectionName || !isProviderType(c.ProviderType) || !isStatus(c.ConnectionStatus)) return null;
671
+ return {
672
+ arn: c.ConnectionArn,
673
+ name: c.ConnectionName,
674
+ providerType: c.ProviderType,
675
+ status: c.ConnectionStatus,
676
+ ...hostEndpoint ? { hostEndpoint } : {}
677
+ };
678
+ }
679
+ async function listSources(claim, accountId, deps) {
680
+ const repoHost = claim.repository.host;
681
+ const raw = [];
682
+ let token;
683
+ let pages = 0;
684
+ let more = false;
685
+ do {
686
+ const out = await deps.codeconnections(claim.region).send(new ListConnectionsCommand({ MaxResults: 100, ...token ? { NextToken: token } : {} }));
687
+ raw.push(...out.Connections ?? []);
688
+ token = out.NextToken || void 0;
689
+ more = !!token && ++pages >= MAX_PAGES;
690
+ } while (token && !more);
691
+ const hosts = raw.some((c) => c.HostArn) && providerForHost(repoHost) === "unknown" ? await hostEndpoints(deps, claim.region) : /* @__PURE__ */ new Map();
692
+ 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));
693
+ return {
694
+ accountId,
695
+ region: claim.region,
696
+ connections: matching.slice(0, MAX_SOURCE_CONNECTIONS),
697
+ githubToken: await githubTokenFor(claim, deps),
698
+ truncated: more || matching.length > MAX_SOURCE_CONNECTIONS
699
+ };
700
+ }
701
+ async function checkSource(claim, accountId, deps) {
702
+ const source = claim.source;
703
+ if (source.type === "github") {
704
+ if (!claim.repository || providerForHost(claim.repository.host) !== "github") return "SOURCE_CONNECTION_WRONG_PROVIDER";
705
+ return await githubTokenFor(claim, deps) ? null : "GITHUB_TOKEN_MISSING";
706
+ }
707
+ const parts = connectionArnParts(source.connectionArn);
708
+ if (!parts || parts.accountId !== accountId) return "SOURCE_CONNECTION_WRONG_ACCOUNT";
709
+ if (parts.region !== claim.region) return "SOURCE_CONNECTION_WRONG_REGION";
710
+ let connection;
711
+ try {
712
+ const out = await deps.codeconnections(claim.region).send(new GetConnectionCommand({ ConnectionArn: source.connectionArn }));
713
+ connection = out.Connection;
714
+ } catch (err) {
715
+ if (isNotFound(err)) return "SOURCE_CONNECTION_NOT_FOUND";
716
+ throw err;
717
+ }
718
+ if (!connection) return "SOURCE_CONNECTION_NOT_FOUND";
719
+ if (connection.ConnectionStatus !== "AVAILABLE") return "SOURCE_CONNECTION_NOT_AVAILABLE";
720
+ let hostEndpoint;
721
+ if (connection.HostArn) {
722
+ try {
723
+ const host = await deps.codeconnections(claim.region).send(new GetHostCommand({ HostArn: connection.HostArn }));
724
+ hostEndpoint = host.ProviderEndpoint;
725
+ } catch (err) {
726
+ if (!isNotFound(err)) throw err;
727
+ }
728
+ }
729
+ const dto = toDto(connection, hostEndpoint);
730
+ if (!dto) return "SOURCE_CONNECTION_WRONG_PROVIDER";
731
+ return !claim.repository || connectionMatchesRepository(dto, claim.repository.host) ? null : "SOURCE_CONNECTION_WRONG_PROVIDER";
732
+ }
733
+
734
+ // src/lambda/runner-inspect.ts
735
+ var GITHUB_API = "https://api.github.com";
736
+ var GITHUB_TIMEOUT_MS = 6e3;
737
+ async function readCapped(res, cap) {
738
+ if (!res.body) return "";
739
+ const reader = res.body.getReader();
740
+ const chunks = [];
741
+ let size = 0;
742
+ for (; ; ) {
743
+ const { done, value } = await reader.read();
744
+ if (done) break;
745
+ size += value.byteLength;
746
+ if (size > cap) {
747
+ await reader.cancel();
748
+ return null;
749
+ }
750
+ chunks.push(value);
751
+ }
752
+ return Buffer.concat(chunks).toString("utf8");
753
+ }
754
+ var githubGet = async (url, token) => {
755
+ const res = await fetch(url, {
756
+ headers: {
757
+ "Accept": "application/vnd.github+json",
758
+ "User-Agent": "pipeline-builder-runner",
759
+ "X-GitHub-Api-Version": "2022-11-28",
760
+ "Authorization": `Bearer ${token}`
761
+ },
762
+ redirect: "manual",
763
+ signal: AbortSignal.timeout(GITHUB_TIMEOUT_MS)
764
+ });
765
+ if (res.status >= 300 && res.status < 400) {
766
+ await res.body?.cancel();
767
+ return { status: res.status, text: "" };
768
+ }
769
+ return { status: res.status, text: await readCapped(res, INSPECT_MAX_READ_BYTES) };
770
+ };
771
+ function readUrl(repository, read) {
772
+ const base = `${GITHUB_API}/repos/${encodeURIComponent(repository.owner)}/${encodeURIComponent(repository.repo)}`;
773
+ if (read.kind === "repo") return base;
774
+ if (read.kind === "languages") return `${base}/languages`;
775
+ const path = read.path ? read.path.split("/").map(encodeURIComponent).join("/") : "";
776
+ return `${base}/contents/${path}?ref=${encodeURIComponent(read.ref)}`;
777
+ }
778
+ async function answer(deps, claim, read, token) {
779
+ let got;
780
+ try {
781
+ got = await deps.github(readUrl(claim.repository, read), token);
782
+ } catch {
783
+ return { status: 504 };
784
+ }
785
+ if (got.status < 200 || got.status >= 300) return { status: got.status };
786
+ if (got.text === null) return { status: 413 };
787
+ let json;
788
+ try {
789
+ json = JSON.parse(got.text);
790
+ } catch {
791
+ return { status: 502 };
792
+ }
793
+ const body = parseRepositoryReadBody(read, json);
794
+ return body === null ? { status: 502 } : { status: got.status, body };
795
+ }
796
+ async function inspectRepository(claim, deps) {
797
+ const choice = await chooseGitHubTokenSecret(
798
+ { orgId: claim.orgId, owner: claim.repository.owner, prefix: DEFAULT_SECRETS_PATH_PREFIX },
799
+ describeSecretLookup(deps, claim.region)
800
+ );
801
+ if (!choice.found) return "GITHUB_TOKEN_MISSING";
802
+ const out = await deps.secrets(claim.region).send(new GetSecretValueCommand({ SecretId: choice.secret }));
803
+ const token = typeof out.SecretString === "string" ? out.SecretString.trim() : "";
804
+ if (!token) return "GITHUB_TOKEN_MISSING";
805
+ const answers = await Promise.all(claim.reads.map((read) => answer(deps, claim, read, token)));
806
+ let total = 0;
807
+ const results = answers.map((a) => {
808
+ if (a.body === void 0) return a;
809
+ total += Buffer.byteLength(JSON.stringify(a.body));
810
+ return total > INSPECT_MAX_REPLY_BYTES ? { status: 413 } : a;
811
+ });
812
+ return { results };
813
+ }
545
814
 
546
815
  // src/lambda/runner-jws.ts
816
+ import { createPublicKey, verify as cryptoVerify } from "node:crypto";
547
817
  var JWKS_TTL_MS = 10 * 60 * 1e3;
548
818
  var JWKS_MIN_REFETCH_MS = 60 * 1e3;
549
819
  var REPLAY_WINDOW_MS = 15 * 60 * 1e3;
@@ -671,7 +941,8 @@ async function verifyRunRequest(jws, opts) {
671
941
  if (!opts.runnerId) throw new SignatureError("runner has no RUNNER_ID");
672
942
  if (c.aud !== opts.runnerId) throw new SignatureError("wrong aud");
673
943
  const isSourceAction = Object.hasOwn(SOURCE_ACTION_CAPABILITY, action);
674
- if (action !== "ping" && !isSourceAction && !isNonEmptyString(c.pipelineId)) throw new SignatureError("missing pipelineId");
944
+ const isInspect = action === "inspect_repository";
945
+ if (action !== "ping" && !isSourceAction && !isInspect && !isNonEmptyString(c.pipelineId)) throw new SignatureError("missing pipelineId");
675
946
  if ((action === "stop" || action === "status") && !isNonEmptyString(c.executionId)) throw new SignatureError("missing executionId");
676
947
  let hint;
677
948
  if (c.hint !== void 0 && c.hint !== null) {
@@ -689,6 +960,8 @@ async function verifyRunRequest(jws, opts) {
689
960
  const deploy = takesBlock ? parseDeployClaim(c.deploy, action) : void 0;
690
961
  if (!isSourceAction && c.sources !== void 0) throw new SignatureError("unexpected sources claim");
691
962
  const sources = isSourceAction ? parseSourcesClaim(c.sources, action === "check_source") : void 0;
963
+ if (!isInspect && c.inspect !== void 0) throw new SignatureError("unexpected inspect claim");
964
+ const inspect = isInspect ? parseInspectClaim(c.inspect) : void 0;
692
965
  if (takesBuild) {
693
966
  if (!isNonEmptyString(c.deployRequestId) || c.deployRequestId.length > 128) throw new SignatureError("missing deployRequestId");
694
967
  if (typeof c.buildId !== "string" || !BUILD_ID_PATTERN.test(c.buildId)) throw new SignatureError("malformed buildId");
@@ -706,6 +979,7 @@ async function verifyRunRequest(jws, opts) {
706
979
  ...deploy ? { deploy } : {},
707
980
  ...takesBuild ? { deployRequestId: c.deployRequestId, buildId: c.buildId } : {},
708
981
  ...sources ? { sources } : {},
982
+ ...inspect ? { inspect } : {},
709
983
  requestedBy: c.requestedBy
710
984
  };
711
985
  }
@@ -767,6 +1041,25 @@ function parseSourcesClaim(raw, isCheck) {
767
1041
  if (typeof src.connectionArn !== "string" || !CONNECTION_ARN_PATTERN.test(src.connectionArn)) throw new SignatureError("malformed source connectionArn");
768
1042
  return { ...claim, source: { type: "codestar", connectionArn: src.connectionArn } };
769
1043
  }
1044
+ function parseInspectClaim(raw) {
1045
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SignatureError("missing inspect claim");
1046
+ const b = raw;
1047
+ if (typeof b.orgId !== "string" || !SOURCE_ORG_ID_PATTERN.test(b.orgId)) throw new SignatureError("malformed inspect orgId");
1048
+ if (typeof b.region !== "string" || !AWS_REGION_PATTERN.test(b.region)) throw new SignatureError("malformed inspect region");
1049
+ const repo = b.repository;
1050
+ if (!repo || typeof repo !== "object" || Array.isArray(repo)) throw new SignatureError("missing inspect repository");
1051
+ if (typeof repo.owner !== "string" || githubOwnerProblem(repo.owner) !== null) throw new SignatureError("malformed inspect repository owner");
1052
+ if (typeof repo.repo !== "string" || !INSPECT_REPO_PATTERN.test(repo.repo) || repo.repo === "." || repo.repo === "..") {
1053
+ throw new SignatureError("malformed inspect repository repo");
1054
+ }
1055
+ if (!Array.isArray(b.reads) || b.reads.length === 0 || b.reads.length > INSPECT_MAX_READS) throw new SignatureError("malformed inspect reads");
1056
+ const reads = b.reads.map((r) => {
1057
+ const problem = repositoryReadProblem(r);
1058
+ if (problem) throw new SignatureError(`malformed inspect read: ${problem}`);
1059
+ return { ...r };
1060
+ });
1061
+ return { orgId: b.orgId, region: b.region, repository: { owner: repo.owner, repo: repo.repo }, reads };
1062
+ }
770
1063
  var ReplayCache = class {
771
1064
  constructor(now) {
772
1065
  this.now = now;
@@ -794,111 +1087,6 @@ var ReplayCache = class {
794
1087
  }
795
1088
  };
796
1089
 
797
- // src/lambda/runner-sources.ts
798
- import { GetConnectionCommand, GetHostCommand, ListConnectionsCommand, ListHostsCommand } from "@aws-sdk/client-codeconnections";
799
- import { DescribeSecretCommand } from "@aws-sdk/client-secrets-manager";
800
- var MAX_PAGES = 10;
801
- var errName2 = (err) => String(err?.name ?? "");
802
- var isNotFound = (err) => errName2(err) === "ResourceNotFoundException";
803
- var isProviderType = (v) => SOURCE_CONNECTION_PROVIDER_TYPES.includes(v);
804
- var isStatus = (v) => SOURCE_CONNECTION_STATUSES.includes(v);
805
- function describeSecret(deps, region) {
806
- return async (name) => {
807
- try {
808
- const out = await deps.secrets(region).send(new DescribeSecretCommand({ SecretId: name }));
809
- if (out.DeletedDate) return null;
810
- return { lastChangedDate: out.LastChangedDate instanceof Date ? out.LastChangedDate.toISOString() : null };
811
- } catch (err) {
812
- if (isNotFound(err)) return null;
813
- throw err;
814
- }
815
- };
816
- }
817
- async function githubTokenFor(claim, deps) {
818
- const repository = claim.repository;
819
- if (!repository || providerForHost(repository.host) !== "github") return null;
820
- const choice = await chooseGitHubTokenSecret(
821
- { orgId: claim.orgId, owner: repository.owner, prefix: DEFAULT_SECRETS_PATH_PREFIX },
822
- describeSecret(deps, claim.region)
823
- );
824
- return choice.found ? { secretName: choice.secret, scope: choice.scope, lastChangedDate: choice.found.lastChangedDate } : null;
825
- }
826
- async function hostEndpoints(deps, region) {
827
- const endpoints = /* @__PURE__ */ new Map();
828
- let token;
829
- let pages = 0;
830
- do {
831
- const out = await deps.codeconnections(region).send(new ListHostsCommand({ MaxResults: 100, ...token ? { NextToken: token } : {} }));
832
- for (const h of out.Hosts ?? []) if (h.HostArn && h.ProviderEndpoint) endpoints.set(h.HostArn, h.ProviderEndpoint);
833
- token = out.NextToken || void 0;
834
- } while (token && ++pages < MAX_PAGES);
835
- return endpoints;
836
- }
837
- function toDto(c, hostEndpoint) {
838
- if (!c.ConnectionArn || !c.ConnectionName || !isProviderType(c.ProviderType) || !isStatus(c.ConnectionStatus)) return null;
839
- return {
840
- arn: c.ConnectionArn,
841
- name: c.ConnectionName,
842
- providerType: c.ProviderType,
843
- status: c.ConnectionStatus,
844
- ...hostEndpoint ? { hostEndpoint } : {}
845
- };
846
- }
847
- async function listSources(claim, accountId, deps) {
848
- const repoHost = claim.repository.host;
849
- const raw = [];
850
- let token;
851
- let pages = 0;
852
- let more = false;
853
- do {
854
- const out = await deps.codeconnections(claim.region).send(new ListConnectionsCommand({ MaxResults: 100, ...token ? { NextToken: token } : {} }));
855
- raw.push(...out.Connections ?? []);
856
- token = out.NextToken || void 0;
857
- more = !!token && ++pages >= MAX_PAGES;
858
- } while (token && !more);
859
- const hosts = raw.some((c) => c.HostArn) && providerForHost(repoHost) === "unknown" ? await hostEndpoints(deps, claim.region) : /* @__PURE__ */ new Map();
860
- 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));
861
- return {
862
- accountId,
863
- region: claim.region,
864
- connections: matching.slice(0, MAX_SOURCE_CONNECTIONS),
865
- githubToken: await githubTokenFor(claim, deps),
866
- truncated: more || matching.length > MAX_SOURCE_CONNECTIONS
867
- };
868
- }
869
- async function checkSource(claim, accountId, deps) {
870
- const source = claim.source;
871
- if (source.type === "github") {
872
- if (!claim.repository || providerForHost(claim.repository.host) !== "github") return "SOURCE_CONNECTION_WRONG_PROVIDER";
873
- return await githubTokenFor(claim, deps) ? null : "GITHUB_TOKEN_MISSING";
874
- }
875
- const parts = connectionArnParts(source.connectionArn);
876
- if (!parts || parts.accountId !== accountId) return "SOURCE_CONNECTION_WRONG_ACCOUNT";
877
- if (parts.region !== claim.region) return "SOURCE_CONNECTION_WRONG_REGION";
878
- let connection;
879
- try {
880
- const out = await deps.codeconnections(claim.region).send(new GetConnectionCommand({ ConnectionArn: source.connectionArn }));
881
- connection = out.Connection;
882
- } catch (err) {
883
- if (isNotFound(err)) return "SOURCE_CONNECTION_NOT_FOUND";
884
- throw err;
885
- }
886
- if (!connection) return "SOURCE_CONNECTION_NOT_FOUND";
887
- if (connection.ConnectionStatus !== "AVAILABLE") return "SOURCE_CONNECTION_NOT_AVAILABLE";
888
- let hostEndpoint;
889
- if (connection.HostArn) {
890
- try {
891
- const host = await deps.codeconnections(claim.region).send(new GetHostCommand({ HostArn: connection.HostArn }));
892
- hostEndpoint = host.ProviderEndpoint;
893
- } catch (err) {
894
- if (!isNotFound(err)) throw err;
895
- }
896
- }
897
- const dto = toDto(connection, hostEndpoint);
898
- if (!dto) return "SOURCE_CONNECTION_WRONG_PROVIDER";
899
- return !claim.repository || connectionMatchesRepository(dto, claim.repository.host) ? null : "SOURCE_CONNECTION_WRONG_PROVIDER";
900
- }
901
-
902
1090
  // src/lambda/runner-handler.ts
903
1091
  var MAX_BODY_BYTES = 16 * 1024;
904
1092
  var csv = (v) => (v ?? "").split(",").map((s) => s.trim()).filter(Boolean);
@@ -954,6 +1142,7 @@ function defaultDeps() {
954
1142
  if (!sm.has(region)) sm.set(region, new SecretsManagerClient({ region }));
955
1143
  return sm.get(region);
956
1144
  },
1145
+ github: githubGet,
957
1146
  log: defaultLog
958
1147
  };
959
1148
  }
@@ -1097,7 +1286,7 @@ function createRunner(config, deps) {
1097
1286
  return ok("status", { executionId: claims.executionId, executionStatus: execution.executionStatus ?? "Unknown" });
1098
1287
  }
1099
1288
  async function deployAction(claims) {
1100
- const answer = await runDeployAction({
1289
+ const answer2 = await runDeployAction({
1101
1290
  runnerId: config.runnerId,
1102
1291
  config: config.deploy,
1103
1292
  codebuild: deps.codebuild(),
@@ -1105,8 +1294,8 @@ function createRunner(config, deps) {
1105
1294
  isAllowed: (region, name) => isAllowed(config, region, name),
1106
1295
  alreadyDeployed: async (pipelineId) => (await arnsByTag(config, deps, pipelineId)).length > 0
1107
1296
  }, claims);
1108
- if ("refuse" in answer) return fail(answer.refuse);
1109
- const { outcome, ...details } = answer;
1297
+ if ("refuse" in answer2) return fail(answer2.refuse);
1298
+ const { outcome, ...details } = answer2;
1110
1299
  return ok(outcome, details);
1111
1300
  }
1112
1301
  async function sourceAction(claims, account) {
@@ -1117,16 +1306,23 @@ function createRunner(config, deps) {
1117
1306
  const refusal = await checkSource(sources, account.accountId, deps);
1118
1307
  return refusal ? fail(refusal) : ok("source_ok");
1119
1308
  }
1309
+ async function inspectAction(claims) {
1310
+ const inspect = claims.inspect;
1311
+ if (!config.allowedRegions.includes(inspect.region)) return fail("SOURCE_REGION_NOT_ALLOWED");
1312
+ const answer2 = await inspectRepository(inspect, deps);
1313
+ return answer2 === "GITHUB_TOKEN_MISSING" ? fail(answer2) : ok("repository_reads", { results: answer2.results });
1314
+ }
1120
1315
  async function act(claims, account) {
1121
1316
  if (claims.action === "ping") {
1122
1317
  return ok("pong", {
1123
1318
  regions: [...config.allowedRegions],
1124
- capabilities: config.deploy.enabled ? [DEPLOY_CAPABILITY, SOURCES_CAPABILITY] : [SOURCES_CAPABILITY],
1319
+ capabilities: config.deploy.enabled ? [DEPLOY_CAPABILITY, SOURCES_CAPABILITY, INSPECT_CAPABILITY] : [SOURCES_CAPABILITY, INSPECT_CAPABILITY],
1125
1320
  pipelinePrefixes: [...config.allowedPrefixes]
1126
1321
  });
1127
1322
  }
1128
1323
  if (Object.hasOwn(DEPLOY_ACTION_CAPABILITY, claims.action)) return deployAction(claims);
1129
1324
  if (Object.hasOwn(SOURCE_ACTION_CAPABILITY, claims.action)) return sourceAction(claims, account);
1325
+ if (claims.action === "inspect_repository") return inspectAction(claims);
1130
1326
  const found = await findPipeline(config, deps, account, claims.pipelineId, claims.hint);
1131
1327
  if (claims.action === "probe") {
1132
1328
  if (found.kind === "ambiguous") return fail("AMBIGUOUS_PIPELINE");
@@ -0,0 +1,32 @@
1
+ import { type RunInspectClaim } from '@pipeline-builder/api-core/pipeline-runners';
2
+ import { type RepositoryReadResult } from '@pipeline-builder/api-core/pipeline-source';
3
+ import type { Sender } from './pipeline-tag.js';
4
+ /**
5
+ * One authenticated GET to the GitHub API: the status, and the body text —
6
+ * null when it was larger than {@link INSPECT_MAX_READ_BYTES} (never buffered
7
+ * past it).
8
+ */
9
+ export type GitHubGet = (url: string, token: string) => Promise<{
10
+ status: number;
11
+ text: string | null;
12
+ }>;
13
+ /** What inspect_repository uses. */
14
+ export interface InspectDeps {
15
+ secrets(region: string): Sender;
16
+ github: GitHubGet;
17
+ }
18
+ /**
19
+ * The real GitHub GET: a timeout, the body capped, and redirects NEVER
20
+ * followed — the token must not reach another URL. A redirect (GitHub answers a
21
+ * renamed repository with 301) is returned as its own status, a failed read the
22
+ * analyzer reports, rather than a network error.
23
+ */
24
+ export declare const githubGet: GitHubGet;
25
+ /**
26
+ * inspect_repository: the reads, in order, or GITHUB_TOKEN_MISSING when neither
27
+ * the owner's nor the org's token secret holds a token in the claim's region.
28
+ */
29
+ export declare function inspectRepository(claim: RunInspectClaim, deps: InspectDeps): Promise<{
30
+ results: RepositoryReadResult[];
31
+ } | 'GITHUB_TOKEN_MISSING'>;
32
+ //# sourceMappingURL=runner-inspect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-inspect.d.ts","sources":["../../src/lambda/runner-inspect.ts"],"names":[],"mappings":"AA2BA,OAAO,EAEgB,KAAK,eAAe,EAC1C,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAC0E,KAAK,oBAAoB,EACzG,MAAM,4CAA4C,CAAC;AACpD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAQhD;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,CAAC;AAEzG,oCAAoC;AACpC,MAAM,WAAW,WAAW;IAC1B,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IAChC,MAAM,EAAE,SAAS,CAAC;CACnB;AAqBD;;;;;GAKG;AACH,eAAO,MAAM,SAAS,EAAE,SAgBvB,CAAC;AA+BF;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC;IAAE,OAAO,EAAE,oBAAoB,EAAE,CAAA;CAAE,GAAG,sBAAsB,CAAC,CAoBxJ"}