@xemahq/repo-build-tooling 0.16.0 → 0.18.0

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.
@@ -0,0 +1,175 @@
1
+ // The trust half of `xema-promote-image`: what must be PROVEN about a develop
2
+ // digest before its bytes may be published under a release tag, and how a release digest main
3
+ // already promoted is reused.
4
+ //
5
+ // A develop digest is promotable only on a CONJUNCTION, each leg proven from the
6
+ // develop lane's SIGNED provenance and never from a tag:
7
+ // (a) signer: a SLSA v1 provenance attestation on the digest verifies under the
8
+ // develop workflow identity `<server>/<repo>/.github/workflows/<file>@refs/heads/develop`
9
+ // and the GitHub OIDC issuer (a unit branch or PR lane does not match);
10
+ // (b) ancestry: its `vcs.revision` is an ancestor of the caller's main ref;
11
+ // (c) content: the caller's tag command at that revision AND at the promoted
12
+ // commit both print the content tag being promoted.
13
+ // Every refusal names its leg and is an error, never a miss.
14
+
15
+ import { createHash } from 'node:crypto';
16
+ import { describeFailure, runTool } from './promote-image-registry.mjs';
17
+
18
+ export const GITHUB_SERVER = 'https://github.com';
19
+ export const GITHUB_OIDC_ISSUER = 'https://token.actions.githubusercontent.com';
20
+ export const SLSA_PROVENANCE_V1 = 'https://slsa.dev/provenance/v1';
21
+ const COSIGN_SLSA_V1_TYPE = 'slsaprovenance1';
22
+ const COMMIT = /^[0-9a-f]{40}$/;
23
+ export const IMAGE_PROMOTION_PREDICATE_TYPE = 'https://xema.dev/attestations/image-promotion/v1';
24
+
25
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
+
27
+ /** The anchored certificate-identity pattern for `files` of `repository` on `branch`. */
28
+ export function workflowIdentityPattern(repository, files, branch) {
29
+ const alternatives = files.map(escapeRegExp).join('|');
30
+ return `^${escapeRegExp(`${GITHUB_SERVER}/${repository}/.github/workflows/`)}(?:${alternatives})${escapeRegExp(`@refs/heads/${branch}`)}$`;
31
+ }
32
+
33
+ function readStatements(stdout, subject, label) {
34
+ const byDigest = new Map();
35
+ for (const line of stdout.split('\n').map((text) => text.trim()).filter(Boolean)) {
36
+ let payload;
37
+ let statement;
38
+ try {
39
+ payload = Buffer.from(JSON.parse(line).payload, 'base64');
40
+ statement = JSON.parse(payload.toString('utf8'));
41
+ } catch (error) {
42
+ throw new Error(`${label}: cosign returned an unreadable attestation for ${subject}`, { cause: error });
43
+ }
44
+ byDigest.set(`sha256:${createHash('sha256').update(payload).digest('hex')}`, statement);
45
+ }
46
+ return byDigest;
47
+ }
48
+
49
+ /**
50
+ * Runs `cosign verify-attestation` of `type` on `subject` under `pattern` and requires exactly one distinct verified
51
+ * statement whose subject is the digest. Returns `{ statement, payloadDigest }`.
52
+ */
53
+ function verifiedStatement({ subject, digest, type, predicateType, what, noun, pattern, label }, run) {
54
+ const verified = run('cosign', [
55
+ 'verify-attestation',
56
+ '--type', type,
57
+ '--certificate-identity-regexp', pattern,
58
+ '--certificate-oidc-issuer', GITHUB_OIDC_ISSUER,
59
+ subject,
60
+ ]);
61
+ if (verified.error) throw new Error(`${label}: could not run cosign to verify ${subject}: ${verified.error.message}`);
62
+ if (verified.status !== 0) {
63
+ const detail = describeFailure(verified);
64
+ throw new Error(`${label}: ${subject} has no ${what} signed by ${pattern}: ${detail}`);
65
+ }
66
+ const statements = readStatements(verified.stdout, subject, label);
67
+ if (statements.size !== 1) {
68
+ throw new Error(`${label}: ${subject} carries ${statements.size} distinct verified ${noun} statements; exactly one is promotable`);
69
+ }
70
+ const [[payloadDigest, statement]] = statements;
71
+ const hex = digest.slice('sha256:'.length);
72
+ if (statement.predicateType !== predicateType || !statement.subject?.some((entry) => entry?.digest?.sha256 === hex)) {
73
+ throw new Error(`${label}: the verified statement is not ${what} about ${subject}`);
74
+ }
75
+ return { statement, payloadDigest };
76
+ }
77
+
78
+ /** The predicate types of every attestation on `subject`, listed without verifying any signature. A registry error is an error. */
79
+ function attestationTypes(subject, label, run) {
80
+ const listed = run('cosign', ['download', 'attestation', subject]);
81
+ if (listed.error) throw new Error(`${label}: could not run cosign to list the attestations of ${subject}: ${listed.error.message}`);
82
+ if (listed.status !== 0) throw new Error(`${label}: listing the attestations of ${subject} failed: ${describeFailure(listed)}`);
83
+ return listed.stdout.split('\n').map((text) => text.trim()).filter(Boolean).map((line) => {
84
+ try {
85
+ return JSON.parse(Buffer.from(JSON.parse(line).payload, 'base64').toString('utf8')).predicateType;
86
+ } catch (error) {
87
+ throw new Error(`${label}: cosign listed an unreadable attestation for ${subject}`, { cause: error });
88
+ }
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Reuse of a release digest main already promoted. Verifies its image-promotion/v1 attestation under one of main's
94
+ * release workflows (anchored identity, GitHub OIDC issuer) and returns `{ source, developProvenance }` copied from it.
95
+ * Returns `undefined` when the digest carries no promotion attestation (a legacy image); a registry error, a signature or identity
96
+ * failure, or a source outside `<registry>/<owner>/dev/`, is an error.
97
+ */
98
+ export function reuseEarlierPromotion({ releaseRef, tag, digest, repository, releaseWorkflows }, run = runTool) {
99
+ const subject = `${releaseRef}@${digest}`;
100
+ const label = 'reuse';
101
+ // (a) presence, without identity verification: only the predicate types are read
102
+ if (!attestationTypes(subject, label, run).includes(IMAGE_PROMOTION_PREDICATE_TYPE)) return undefined;
103
+ // (b) a promotion attestation is present: any verification failure is an error
104
+ const found = verifiedStatement({
105
+ subject, digest, type: IMAGE_PROMOTION_PREDICATE_TYPE, predicateType: IMAGE_PROMOTION_PREDICATE_TYPE,
106
+ what: 'image-promotion/v1 attestation', noun: 'promotion', pattern: workflowIdentityPattern(repository, releaseWorkflows, 'main'),
107
+ label,
108
+ }, run);
109
+ const { source, developProvenance, release } = found.statement.predicate ?? {};
110
+ for (const [field, expected, stated] of [['digest', digest, release?.digest], ['repository', releaseRef, release?.repository], ['tag', tag, release?.tag]]) {
111
+ if (stated !== expected) throw new Error(`${label}: the promotion attestation of ${subject} states release ${field} ${stated}, not ${expected}`);
112
+ }
113
+ const owner = repository.split('/')[0].toLowerCase();
114
+ const devSource = new RegExp(`^ghcr\\.io/${escapeRegExp(owner)}/dev/[a-z0-9][a-z0-9._/-]*@${escapeRegExp(digest)}$`);
115
+ if (typeof source?.reference !== 'string' || !devSource.test(source.reference)) {
116
+ throw new Error(`${label}: the promotion attestation of ${subject} names source '${source?.reference}', not a ghcr.io/${owner}/dev/<name>@${digest} reference`);
117
+ }
118
+ if (typeof source.revision !== 'string' || !COMMIT.test(source.revision)) {
119
+ throw new Error(`${label}: the promotion attestation of ${subject} names no 40-hex source revision`);
120
+ }
121
+ const { predicateType, payloadDigest, signerIdentityPattern } = developProvenance ?? {};
122
+ if (![predicateType, payloadDigest, signerIdentityPattern].every((value) => typeof value === 'string' && value !== '')) {
123
+ throw new Error(`${label}: the promotion attestation of ${subject} carries no developProvenance`);
124
+ }
125
+ return {
126
+ source: { reference: source.reference, revision: source.revision },
127
+ developProvenance: { predicateType, payloadDigest, signerIdentityPattern },
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Whether `<devRef>@<digest>` carries any SLSA v1 provenance attestation, listed without verifying a signature. A digest
133
+ * with none (an image reused on develop from before provenance) is not promotable but not an error; a registry error is.
134
+ */
135
+ export function hasDevelopProvenance({ devRef, digest }, run = runTool) {
136
+ return attestationTypes(`${devRef}@${digest}`, 'copy', run).includes(SLSA_PROVENANCE_V1);
137
+ }
138
+
139
+ /** Proves legs (a), (b) and (c) for `<devRef>@<digest>`; returns `{ revision, provenanceDigest, signerPattern }`. */
140
+ export function verifyDevelopProvenance(
141
+ { devRef, digest, repository, developWorkflow, mainRef, commit, tag, tagCommand },
142
+ run = runTool,
143
+ ) {
144
+ const subject = `${devRef}@${digest}`;
145
+ const signerPattern = workflowIdentityPattern(repository, [developWorkflow], 'develop');
146
+
147
+ // (a) signer
148
+ const { statement, payloadDigest: provenanceDigest } = verifiedStatement(
149
+ { subject, digest, type: COSIGN_SLSA_V1_TYPE, predicateType: SLSA_PROVENANCE_V1, what: 'SLSA v1 provenance', noun: 'provenance', pattern: signerPattern, label: 'leg (a) signer' },
150
+ run,
151
+ );
152
+ const revision = statement.predicate?.runDetails?.metadata?.buildkit_metadata?.vcs?.revision;
153
+ if (typeof revision !== 'string' || !COMMIT.test(revision)) {
154
+ throw new Error(`leg (a) signer: the provenance of ${subject} names no 40-hex vcs.revision`);
155
+ }
156
+
157
+ // (b) ancestry
158
+ const ancestry = run('git', ['merge-base', '--is-ancestor', revision, mainRef]);
159
+ if (ancestry.error || (ancestry.status !== 0 && ancestry.status !== 1)) {
160
+ throw new Error(`leg (b) ancestry: git could not order ${revision} against ${mainRef}: ${describeFailure(ancestry)}`);
161
+ }
162
+ if (ancestry.status === 1) throw new Error(`leg (b) ancestry: ${revision}, the revision ${subject} was built from, is not an ancestor of ${mainRef}`);
163
+
164
+ // (c) content
165
+ for (const [label, at] of [['the provenance revision', revision], ['the promoted commit', commit]]) {
166
+ const [command, ...args] = tagCommand;
167
+ const hashed = run(command, [...args, '--commit', at]);
168
+ if (hashed.error || hashed.status !== 0) {
169
+ throw new Error(`leg (c) content: the tag command failed at ${label} ${at}: ${describeFailure(hashed)}`);
170
+ }
171
+ const computed = hashed.stdout.trim();
172
+ if (computed !== tag) throw new Error(`leg (c) content: the content tag at ${label} ${at} is ${computed}, not ${tag}`);
173
+ }
174
+ return { revision, provenanceDigest, signerPattern };
175
+ }
@@ -0,0 +1,63 @@
1
+ // The registry half of `xema-promote-image`: probe one `<repository>:<tag>` for
2
+ // its manifest digest, and copy a digest to a new tag, through
3
+ // `docker buildx imagetools` (the job's `docker login` supplies the credential).
4
+ //
5
+ // A probe has exactly three outcomes. A digest; a DEFINITE "not found" (the
6
+ // registry said the manifest does not exist); or an error. Anything that is not
7
+ // provably "not found" is an error, never a miss: a miss makes the caller build,
8
+ // so a credential or registry failure misread as one would hide the failure
9
+ // behind a rebuild.
10
+
11
+ import { spawnSync } from 'node:child_process';
12
+
13
+ export const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/;
14
+
15
+ // Checked FIRST: an auth refusal is never a miss, even when its text also says
16
+ // "not found" (some registries answer a private repository that way).
17
+ const AUTH_REFUSAL = /\b(unauthorized|denied|forbidden|401|403)\b/i;
18
+ // The definite "does not exist" answers: containerd's resolver reports a 404 on
19
+ // the manifest as `<ref>: not found`; the OCI distribution code is MANIFEST_UNKNOWN.
20
+ const NOT_FOUND = /(: not found$|manifest unknown|\b404\b)/im;
21
+
22
+ /**
23
+ * Runs one external tool (`docker`, `cosign`, `git`, the caller's tag command).
24
+ * @returns {{status: number|null, stdout: string, stderr: string, error?: Error}}
25
+ */
26
+ export function runTool(command, args) {
27
+ return spawnSync(command, args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
28
+ }
29
+
30
+ export function describeFailure(result) {
31
+ if (result.error) return result.error.message;
32
+ return (result.stderr || result.stdout || `exit ${result.status}`).trim();
33
+ }
34
+
35
+ /** Returns the manifest digest of `reference`, or `undefined` on a definite "not found". */
36
+ export function probeDigest(reference, run = runTool) {
37
+ const result = run('docker', ['buildx', 'imagetools', 'inspect', reference, '--format', '{{json .Manifest}}']);
38
+ if (result.error) throw new Error(`could not run docker to probe ${reference}: ${result.error.message}`);
39
+ if (result.status !== 0) {
40
+ const detail = describeFailure(result);
41
+ if (AUTH_REFUSAL.test(detail)) throw new Error(`the registry refused the credential while probing ${reference}: ${detail}`);
42
+ if (NOT_FOUND.test(detail)) return undefined;
43
+ throw new Error(`probing ${reference} failed (not a "not found"): ${detail}`);
44
+ }
45
+ let digest;
46
+ try {
47
+ digest = JSON.parse(result.stdout).digest;
48
+ } catch (error) {
49
+ throw new Error(`probing ${reference} returned unparseable output: ${result.stdout.trim()}`, { cause: error });
50
+ }
51
+ if (typeof digest !== 'string' || !DIGEST_PATTERN.test(digest)) {
52
+ throw new Error(`probing ${reference} returned no sha256 digest: ${result.stdout.trim()}`);
53
+ }
54
+ return digest;
55
+ }
56
+
57
+ /** Points `target` (`<repository>:<tag>`) at `source` (`<repository>@<digest>`), keeping its manifest bytes. */
58
+ export function copyByDigest(source, target, run = runTool) {
59
+ const result = run('docker', ['buildx', 'imagetools', 'create', '--tag', target, source]);
60
+ if (result.error || result.status !== 0) {
61
+ throw new Error(`copying ${source} to ${target} failed: ${describeFailure(result)}`);
62
+ }
63
+ }
@@ -0,0 +1,223 @@
1
+ #!/usr/bin/env node
2
+ // `xema-promote-image`: publish to the RELEASE repository the exact bytes the
3
+ // DEVELOP repository already holds for one content-addressed tag, instead of
4
+ // rebuilding them, and only when the develop bytes are PROVEN promotable.
5
+ //
6
+ // 1. `<release-ref>:<tag>` exists: its image-promotion/v1 attestation must verify under one of main's
7
+ // `--release-workflow` identities (exactly one statement about the digest), and its source must be a
8
+ // `ghcr.io/<owner>/dev/<name>` reference -> reused (evidence=prior-promotion)
9
+ // - no image-promotion/v1 attestation (a legacy image) -> miss (reason=reuse-no-promotion): the caller builds
10
+ // - a signature / identity failure, or a source outside dev/ -> error, never a miss
11
+ // 2. else `<dev-ref>:<tag>` exists: prove it (legs a, b, c in
12
+ // promote-image-provenance.mjs), copy it by digest (`imagetools create`
13
+ // from `<dev-ref>@<digest>`, so an index stays whole), re-probe, and refuse
14
+ // unless the release digest equals the source -> copied (evidence=develop-provenance)
15
+ // - no SLSA provenance on the dev digest at all (reused on develop from before the swap) -> miss (reason=copy-no-develop-provenance)
16
+ // - provenance present but any leg fails -> error, never a miss
17
+ // 3. else -> miss: the caller builds.
18
+ //
19
+ // On every non-miss result it writes the promotion predicate
20
+ // (`https://xema.dev/attestations/image-promotion/v1`) to `--promotion-predicate-out`, for the caller to
21
+ // `cosign attest` under main's own identity. A copy states the facts it just proved; a reuse states this run's
22
+ // release and commit and carries `source` and `developProvenance` from main's earlier promotion. It signs
23
+ // nothing itself; the develop identity is evidence for the promotion, never a signature the release side trusts.
24
+ //
25
+ // `--tag` is the caller's content key, and everything after `--` is the command
26
+ // that computes it (e.g. `node tooling/release/compute-image-tag.mjs --service
27
+ // <svc> --path .`); this tool appends `--commit <sha>`. That command reads the
28
+ // commit from the git object store, so it runs in the caller's checkout, which
29
+ // must hold the history (`fetch-depth: 0`) and the main ref. Needs `docker`,
30
+ // `cosign` and `git` on PATH.
31
+ //
32
+ // No retries. Every refusal is an error, never a miss.
33
+ //
34
+ // Outputs: `result`, `digest`, `source`, `revision`, `evidence`,
35
+ // `provenance_digest`, `promotion_predicate` and `promotion_predicate_type` appended to `$GITHUB_OUTPUT`
36
+ // (required; empty values where a fact does not apply), and one stdout line
37
+ // `promote-image result=<r> digest=<d> src=<repository>@<d> revision=<sha> evidence=<e>`, with ` reason=<why>` appended
38
+ // to a miss that has a reason.
39
+
40
+ import { appendFileSync, existsSync } from 'node:fs';
41
+ import process from 'node:process';
42
+ import { describeErrorChain } from '@xemahq/release-policy/registry';
43
+ import { invokedDirectly } from './readiness.mjs';
44
+ import { IMAGE_PROMOTION_PREDICATE_TYPE, promotionPredicate, reusedPromotionPredicate, writePromotionPredicate } from './promote-image-predicate.mjs';
45
+ import { hasDevelopProvenance, reuseEarlierPromotion, verifyDevelopProvenance } from './promote-image-provenance.mjs';
46
+ import { copyByDigest, probeDigest, runTool } from './promote-image-registry.mjs';
47
+
48
+ export const PromoteResult = Object.freeze({ REUSED: 'reused', COPIED: 'copied', MISS: 'miss' });
49
+ export const PromoteEvidence = Object.freeze({
50
+ PRIOR_PROMOTION: 'prior-promotion',
51
+ DEVELOP_PROVENANCE: 'develop-provenance',
52
+ NONE: 'none',
53
+ });
54
+ export const PromoteMissReason = Object.freeze({ NO_PROMOTION: 'reuse-no-promotion', NO_DEVELOP_PROVENANCE: 'copy-no-develop-provenance' });
55
+
56
+ // The one cosign major shared by the develop attest step, this verb and xema-deploy's verify (xema-deploy pins
57
+ // v2.x in scripts/install-cosign.sh and refuses anything else). v2 `attest` stores `.att` tags; v3 stores
58
+ // bundles/referrers, so a mixed pair makes `cosign download attestation` see nothing and every promotion
59
+ // would silently become a build.
60
+ export const COSIGN_MAJOR = 2;
61
+
62
+ /** Runs `cosign version` once and refuses unless its GitVersion is major `COSIGN_MAJOR`. */
63
+ export function assertCosignMajor(run = runTool) {
64
+ const result = run('cosign', ['version']);
65
+ if (result.error) throw new Error(`could not run cosign to read its version: ${result.error.message}`);
66
+ if (result.status !== 0) throw new Error(`cosign version failed: ${(result.stderr || result.stdout || `exit ${result.status}`).trim()}`);
67
+ const match = /^GitVersion:\s*v?(\d+)\.\d+\.\d+/m.exec(result.stdout ?? '');
68
+ if (match === null) throw new Error('cosign version printed no parsable GitVersion; refusing to promote with an unknown cosign');
69
+ if (Number(match[1]) !== COSIGN_MAJOR) {
70
+ throw new Error(
71
+ `cosign major ${match[1]} found, but this verb needs cosign v${COSIGN_MAJOR}.x: v2 and v3 store attestations differently, ` +
72
+ 'so a mismatch with the develop attest step would make every promotion silently a build. Refusing.',
73
+ );
74
+ }
75
+ }
76
+
77
+ const USAGE =
78
+ 'usage: xema-promote-image --service <name> --dev-ref <registry/repository> --release-ref <registry/repository> ' +
79
+ '--tag <content tag> --commit <40-hex> --main-ref <git ref> --signer-repository <owner/repo> ' +
80
+ '--develop-workflow <file.yaml> --release-workflow <file.yaml>... --promotion-predicate-out <path> -- <tag command>...';
81
+
82
+ const SINGLE = Object.freeze(['service', 'dev-ref', 'release-ref', 'tag', 'commit', 'main-ref', 'signer-repository',
83
+ 'develop-workflow', 'promotion-predicate-out']);
84
+ const REPEATABLE = Object.freeze(['release-workflow']);
85
+ // A repository reference with no tag and no digest (those are passed separately).
86
+ const REPOSITORY_REF = /^[a-z0-9][a-z0-9.-]*(:[0-9]+)?(\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+$/;
87
+ // The OCI distribution tag grammar.
88
+ const TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/;
89
+ const COMMIT = /^[0-9a-f]{40}$/;
90
+ const GITHUB_REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
91
+ const WORKFLOW_FILE = /^[A-Za-z0-9_.-]+\.ya?ml$/;
92
+
93
+ function refuse(flag, value, what) {
94
+ throw new Error(`--${flag} '${value}' is not ${what}`);
95
+ }
96
+
97
+ export function parsePromoteArguments(argv) {
98
+ const separator = argv.indexOf('--');
99
+ const flags = separator === -1 ? argv : argv.slice(0, separator);
100
+ const tagCommand = separator === -1 ? [] : argv.slice(separator + 1);
101
+ const options = { 'release-workflow': [] };
102
+ for (let i = 0; i < flags.length; i += 1) {
103
+ const arg = flags[i];
104
+ const name = arg.startsWith('--') ? arg.slice(2) : undefined;
105
+ const repeatable = REPEATABLE.includes(name);
106
+ if (name === undefined || (!SINGLE.includes(name) && !repeatable)) throw new Error(`unknown argument ${arg}\n${USAGE}`);
107
+ if (!repeatable && options[name] !== undefined) throw new Error(`${arg} given twice`);
108
+ const value = flags[i + 1];
109
+ if (value === undefined || value.startsWith('--') || value === '') throw new Error(`${arg} needs a value`);
110
+ if (repeatable) options[name].push(value);
111
+ else options[name] = value;
112
+ i += 1;
113
+ }
114
+ const missing = SINGLE.filter((flag) => options[flag] === undefined);
115
+ if (options['release-workflow'].length === 0) missing.push('release-workflow');
116
+ if (missing.length > 0) throw new Error(`missing ${missing.map((flag) => `--${flag}`).join(', ')}\n${USAGE}`);
117
+ if (tagCommand.length === 0) throw new Error(`missing the tag command after --\n${USAGE}`);
118
+ for (const flag of ['dev-ref', 'release-ref']) {
119
+ if (!REPOSITORY_REF.test(options[flag])) refuse(flag, options[flag], 'a lowercase registry/repository reference without a tag or digest');
120
+ }
121
+ if (!TAG.test(options.tag)) refuse('tag', options.tag, 'a valid image tag');
122
+ if (!COMMIT.test(options.commit)) refuse('commit', options.commit, 'a 40-hex commit');
123
+ if (options['main-ref'].startsWith('-')) refuse('main-ref', options['main-ref'], 'a git ref');
124
+ if (!GITHUB_REPOSITORY.test(options['signer-repository'])) refuse('signer-repository', options['signer-repository'], 'an owner/repo');
125
+ for (const file of [options['develop-workflow'], ...options['release-workflow']]) {
126
+ if (!WORKFLOW_FILE.test(file)) throw new Error(`workflow '${file}' is not a workflow file name under .github/workflows`);
127
+ }
128
+ return {
129
+ service: options.service,
130
+ devRef: options['dev-ref'],
131
+ releaseRef: options['release-ref'],
132
+ tag: options.tag,
133
+ commit: options.commit,
134
+ mainRef: options['main-ref'],
135
+ repository: options['signer-repository'],
136
+ developWorkflow: options['develop-workflow'],
137
+ releaseWorkflows: options['release-workflow'],
138
+ predicateOut: options['promotion-predicate-out'],
139
+ tagCommand,
140
+ };
141
+ }
142
+
143
+ const MISS = Object.freeze({ result: PromoteResult.MISS, digest: '', source: '', evidence: PromoteEvidence.NONE });
144
+
145
+ /**
146
+ * Runs the steps. Returns `{ result, digest, source, evidence, predicate?, revision?, provenanceDigest?, reason? }`;
147
+ * `predicate` is set on every non-miss result, `reason` on a miss that has one.
148
+ */
149
+ export function promoteImage(options, run = runTool) {
150
+ const { service, devRef, releaseRef, tag, commit, repository, releaseWorkflows } = options;
151
+ assertCosignMajor(run);
152
+ const releaseTagged = `${releaseRef}:${tag}`;
153
+ const released = probeDigest(releaseTagged, run);
154
+ if (released !== undefined) {
155
+ const earlier = reuseEarlierPromotion({ releaseRef, tag, digest: released, repository, releaseWorkflows }, run);
156
+ if (earlier === undefined) return { ...MISS, reason: PromoteMissReason.NO_PROMOTION };
157
+ return {
158
+ result: PromoteResult.REUSED,
159
+ digest: released,
160
+ source: earlier.source.reference,
161
+ evidence: PromoteEvidence.PRIOR_PROMOTION,
162
+ revision: earlier.source.revision,
163
+ provenanceDigest: earlier.developProvenance.payloadDigest,
164
+ predicate: reusedPromotionPredicate({ releaseRef, tag, digest: released, commit, ...earlier }),
165
+ };
166
+ }
167
+ const developed = probeDigest(`${devRef}:${tag}`, run);
168
+ if (developed === undefined) return MISS;
169
+
170
+ if (!hasDevelopProvenance({ devRef, digest: developed }, run)) return { ...MISS, reason: PromoteMissReason.NO_DEVELOP_PROVENANCE };
171
+ const proof = verifyDevelopProvenance({ ...options, digest: developed }, run);
172
+ const source = `${devRef}@${developed}`;
173
+ copyByDigest(source, releaseTagged, run);
174
+ const copied = probeDigest(releaseTagged, run);
175
+ if (copied !== developed) {
176
+ throw new Error(
177
+ `${service}: ${releaseTagged} resolves to ${copied ?? 'nothing'} after copying ${source}; ` +
178
+ 'the copy did not preserve the digest, so the release tag does not name the develop bytes. Refusing.',
179
+ );
180
+ }
181
+ return {
182
+ result: PromoteResult.COPIED,
183
+ digest: developed,
184
+ source,
185
+ evidence: PromoteEvidence.DEVELOP_PROVENANCE,
186
+ revision: proof.revision,
187
+ provenanceDigest: proof.provenanceDigest,
188
+ predicate: promotionPredicate({ releaseRef, tag, digest: developed, source, commit, ...proof }),
189
+ };
190
+ }
191
+
192
+ export function main(argv, { githubOutput, run = runTool, write = (text) => process.stdout.write(text) } = {}) {
193
+ const options = parsePromoteArguments(argv);
194
+ if (!githubOutput) throw new Error('GITHUB_OUTPUT is not set; the step outputs have nowhere to go');
195
+ if (existsSync(options.predicateOut)) {
196
+ throw new Error(`--promotion-predicate-out ${options.predicateOut} already exists; refusing to leave a stale predicate to attest`);
197
+ }
198
+ const { result, digest, source, evidence, predicate, revision, provenanceDigest, reason } = promoteImage(options, run);
199
+ if (predicate !== undefined) writePromotionPredicate(options.predicateOut, predicate);
200
+ const outputs = {
201
+ result,
202
+ digest,
203
+ source,
204
+ revision: revision ?? '',
205
+ evidence,
206
+ provenance_digest: provenanceDigest ?? '',
207
+ promotion_predicate: predicate === undefined ? '' : options.predicateOut,
208
+ promotion_predicate_type: predicate === undefined ? '' : IMAGE_PROMOTION_PREDICATE_TYPE,
209
+ };
210
+ appendFileSync(githubOutput, Object.entries(outputs).map(([key, value]) => `${key}=${value}\n`).join(''));
211
+ write(`promote-image result=${result} digest=${digest} src=${source} revision=${outputs.revision} evidence=${evidence}${reason === undefined ? '' : ` reason=${reason}`}\n`);
212
+ }
213
+
214
+ if (invokedDirectly(process.argv[1], import.meta.url)) {
215
+ try {
216
+ main(process.argv.slice(2), { githubOutput: process.env.GITHUB_OUTPUT });
217
+ } catch (error) {
218
+ const [head, ...causes] = describeErrorChain(error);
219
+ console.error(`xema-promote-image: ${error?.message ?? head}`);
220
+ for (const cause of causes) console.error(` caused by ${cause}`);
221
+ process.exit(1);
222
+ }
223
+ }