Skip to content

A full-featured download manager.

fix(snap): preserve credential-authorized channel spelling (#2417)

Dr_rOot53c9ec53fc0b
diff --git a/.github/workflows/snap-promote.yml b/.github/workflows/snap-promote.yml
index f1eef76c..8d97bed2 100644
--- a/.github/workflows/snap-promote.yml
+++ b/.github/workflows/snap-promote.yml
@@ -219,6 +219,7 @@ jobs:
run: sudo snap install snapcraft --classic --channel=9.x/stable
- name: Validate scoped Store credential
+ id: credentials
timeout-minutes: 5
env:
SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
@@ -232,7 +233,8 @@ jobs:
fi
python3 scripts/verify_snap_credential_scope.py \
--snapcraft /snap/bin/snapcraft \
- --channel "$TARGET_CHANNEL"
+ --channel "$TARGET_CHANNEL" \
+ --github-output "$GITHUB_OUTPUT"
snapcraft status motrix
- name: Reverify approved source revisions
@@ -259,10 +261,12 @@ jobs:
SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
EXPECTED_VERSION: ${{ inputs.expected_version }}
TARGET_CHANNEL: ${{ needs.preflight.outputs.target_channel }}
+ SNAPCRAFT_CHANNEL: ${{ steps.credentials.outputs.snapcraft_channel }}
run: >-
node scripts/release-snap-build-set.mjs
--snap motrix
--channel "$TARGET_CHANNEL"
+ --snapcraft-channel "$SNAPCRAFT_CHANNEL"
--version "$EXPECTED_VERSION"
--amd64-revision
"${{ needs.preflight.outputs.amd64_revision }}"
diff --git a/scripts/release-snap-build-set.mjs b/scripts/release-snap-build-set.mjs
index 062d3b0f..1cccac19 100644
--- a/scripts/release-snap-build-set.mjs
+++ b/scripts/release-snap-build-set.mjs
@@ -11,6 +11,8 @@ import {
const execFileAsync = promisify(execFile)
const ARCHITECTURES = ['amd64', 'arm64']
const SNAP_NAME_PATTERN = /^[a-z0-9](?:-?[a-z0-9])*$/
+const CHANNEL_PATTERN =
+ /^(?<track>[A-Za-z0-9][A-Za-z0-9._-]*)\/(?<risk>stable|candidate|beta|edge)$/
const DEFAULT_SNAPCRAFT_COMMAND_TIMEOUT_MS = 120_000
function normalizeRevision(value, architecture) {
@@ -52,9 +54,25 @@ function snapshotsMatch(left, right) {
)
}
-function snapcraftChannel(channel) {
- const [track, risk, extra] = channel.split('/')
- return track === 'latest' && risk && extra === undefined ? risk : channel
+function resolveSnapcraftChannel(channel, requestedChannel) {
+ const match = typeof channel === 'string' && CHANNEL_PATTERN.exec(channel)
+ if (!match?.groups || match[0] !== channel) {
+ throw new Error(
+ `Invalid channel "${channel}"; expected <track>/<stable|candidate|beta|edge>`
+ )
+ }
+ const { track, risk } = match.groups
+ const defaultChannel = track === 'latest' ? risk : channel
+ if (requestedChannel === undefined) return defaultChannel
+ if (
+ requestedChannel !== channel &&
+ !(track === 'latest' && requestedChannel === risk)
+ ) {
+ throw new Error(
+ 'Snapcraft channel must be an equivalent spelling of channel'
+ )
+ }
+ return requestedChannel
}
function wait(milliseconds) {
@@ -144,6 +162,7 @@ async function defaultRunSnapcraft(snapcraftPath, args, timeoutMs) {
export async function releaseSnapBuildSet({
snapName,
channel,
+ snapcraftChannel,
version,
revisions,
snapcraftPath = '/snap/bin/snapcraft',
@@ -179,10 +198,10 @@ export async function releaseSnapBuildSet({
)
}
const approved = normalizeRevisions(revisions)
- // Snap Store API responses use the canonical latest/<risk> spelling, while
- // channel-restricted macaroons issued for the default track authorize the
- // short risk name used by Snapcraft's mutation commands.
- const mutationChannel = snapcraftChannel(channel)
+ // Public verification uses canonical track/risk. Restricted credentials can
+ // authorize either equivalent spelling of the default track, so preserve the
+ // selected request spelling throughout release, rollback, and containment.
+ const mutationChannel = resolveSnapcraftChannel(channel, snapcraftChannel)
const snapshotOptions = {
snapName,
channel,
@@ -268,6 +287,7 @@ function parseArguments(argv) {
const allowed = new Set([
'--snap',
'--channel',
+ '--snapcraft-channel',
'--version',
'--amd64-revision',
'--arm64-revision',
@@ -304,6 +324,7 @@ async function main() {
const result = await releaseSnapBuildSet({
snapName: args.get('--snap'),
channel: args.get('--channel'),
+ snapcraftChannel: args.get('--snapcraft-channel'),
version: args.get('--version'),
revisions: {
amd64: args.get('--amd64-revision'),
diff --git a/scripts/verify_snap_credential_scope.py b/scripts/verify_snap_credential_scope.py
index c2a03cbe..6f0a6d8a 100644
--- a/scripts/verify_snap_credential_scope.py
+++ b/scripts/verify_snap_credential_scope.py
@@ -65,15 +65,16 @@ def scope_items(value: str) -> list[str] | None:
return items
-def verify_scope(output: str, channel: str) -> None:
+def verify_scope(output: str, channel: str) -> str:
match = re.fullmatch(
r"([A-Za-z0-9][A-Za-z0-9._-]*)/(stable|candidate|beta|edge)", channel
)
if not match:
raise ScopeError("Expected a track/risk target channel", "target_invalid")
track, risk = match.groups()
- # Match the exact channel argument sent by release-snap-build-set.mjs.
- release_channel = risk if track == "latest" else channel
+ # Snapcraft accepts both forms for the latest track, while Store credential
+ # patterns match the actual request spelling. Keep the prior short default.
+ release_channels = [risk, channel] if track == "latest" else [channel]
fields = parse_whoami(output)
permissions = scope_items(fields["permissions"])
channels = scope_items(fields["channels"])
@@ -88,13 +89,15 @@ def verify_scope(output: str, channel: str) -> None:
)
# Store channel restrictions use Python fnmatch against the release request.
# https://dashboard.snapcraft.io/docs/reference/v1/snap.html
- if channels is not None and not any(
- fnmatch.fnmatchcase(release_channel, pattern) for pattern in channels
- ):
- raise ScopeError(
- f"Snap credential does not permit release to {channel}",
- "destination_denied",
- )
+ for release_channel in release_channels:
+ if channels is None or any(
+ fnmatch.fnmatchcase(release_channel, pattern) for pattern in channels
+ ):
+ return release_channel
+ raise ScopeError(
+ f"Snap credential does not permit release to {channel}",
+ "destination_denied",
+ )
def emit_diagnostics(reason: str, result, channel: str) -> None:
@@ -134,6 +137,7 @@ def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--snapcraft", default="/snap/bin/snapcraft")
parser.add_argument("--channel", required=True)
+ parser.add_argument("--github-output")
options = parser.parse_args()
try:
result = subprocess.run(
@@ -159,11 +163,20 @@ def main() -> None:
"Snapcraft whoami emitted diagnostics; credential scope was not verified"
)
try:
- verify_scope(result.stdout, options.channel)
+ release_channel = verify_scope(result.stdout, options.channel)
except ScopeError:
emit_diagnostics("scope_rejected", result, options.channel)
raise
- print(f"Verified Snap credential permits release to {options.channel}")
+ if options.github_output:
+ try:
+ with open(options.github_output, "a", encoding="utf-8") as output:
+ output.write(f"snapcraft_channel={release_channel}\n")
+ except OSError:
+ raise ScopeError("Could not write the verified Snap request channel") from None
+ print(
+ f"Verified Snap credential permits release to {options.channel} "
+ f"using {release_channel}"
+ )
if __name__ == "__main__":
diff --git a/tests/scripts/snap-build-set-release.test.ts b/tests/scripts/snap-build-set-release.test.ts
index bcc4e89e..a29156c5 100644
--- a/tests/scripts/snap-build-set-release.test.ts
+++ b/tests/scripts/snap-build-set-release.test.ts
@@ -1,17 +1,23 @@
+import { execFileSync } from 'node:child_process'
+import path from 'node:path'
import { describe, expect, it, vi } from 'vitest'
// @ts-expect-error — build tooling is intentionally plain ESM.
import { releaseSnapBuildSet } from '../../scripts/release-snap-build-set.mjs'
-function payload(entries: Array<['amd64' | 'arm64', string, string]>) {
+function payload(
+ entries: Array<['amd64' | 'arm64', string, string]>,
+ channel = 'latest/candidate'
+) {
+ const [track, risk] = channel.split('/')
return {
name: 'motrix',
snap: { name: 'motrix' },
'channel-map': entries.map(([architecture, revision, version]) => ({
channel: {
architecture,
- name: 'candidate',
- risk: 'candidate',
- track: 'latest',
+ name: risk,
+ risk,
+ track,
},
revision,
version,
@@ -28,6 +34,61 @@ function response(document: ReturnType<typeof payload>) {
}
describe('release-snap-build-set', () => {
+ it('passes the CLI override through all mutation commands while verifying the canonical channel', () => {
+ const document = payload([
+ ['amd64', '20', '2.0.0'],
+ ['arm64', '21', '2.0.0'],
+ ])
+ const preload = `
+ import childProcess from 'node:child_process'
+ import { syncBuiltinESMExports } from 'node:module'
+ globalThis.fetch = async () => ({
+ ok: true,
+ status: 200,
+ json: async () => (${JSON.stringify(document)}),
+ })
+ childProcess.execFile = (file, args, options, callback) => {
+ console.log(JSON.stringify(args))
+ callback(null, '', '')
+ }
+ syncBuiltinESMExports()
+ `
+ const output = execFileSync(
+ process.execPath,
+ [
+ '--import',
+ `data:text/javascript,${encodeURIComponent(preload)}`,
+ path.resolve('scripts/release-snap-build-set.mjs'),
+ '--snap',
+ 'motrix',
+ '--channel',
+ 'latest/candidate',
+ '--snapcraft-channel',
+ 'latest/candidate',
+ '--version',
+ '2.0.0',
+ '--amd64-revision',
+ '20',
+ '--arm64-revision',
+ '21',
+ '--snapcraft',
+ process.execPath,
+ '--attempts',
+ '1',
+ '--delay-ms',
+ '0',
+ ],
+ { encoding: 'utf8', timeout: 10_000 }
+ )
+
+ expect(output.trim().split('\n')).toEqual([
+ JSON.stringify(['close', 'motrix', 'latest/candidate']),
+ JSON.stringify(['release', 'motrix', '20', 'latest/candidate']),
+ JSON.stringify(['release', 'motrix', '21', 'latest/candidate']),
+ 'Released motrix 2.0.0 to latest/candidate: {"amd64":"20","arm64":"21"}',
+ ])
+ })
+
it('rejects invalid release metadata before reading or mutating the Store', async () => {
const fetchImpl = vi.fn()
const runSnapcraft = vi.fn()
@@ -48,6 +109,102 @@ describe('release-snap-build-set', () => {
expect(runSnapcraft).not.toHaveBeenCalled()
})
+ it.each([
+ '',
+ null,
+ 1,
+ 'stable',
+ 'latest/stable',
+ '2/candidate',
+ 'latest/candidate/branch',
+ 'candidate/branch',
+ 'candidate,stable',
+ 'latest/candidate,latest/stable',
+ ' candidate',
+ 'candidate ',
+ 'candidate\n',
+ 'latest/candidate\n',
+ 'candidate stable',
+ 'candidate;echo injected',
+ '$(echo candidate)',
+ '--help',
+ ])(
+ 'rejects inequivalent request spelling %j before reading the Store',
+ async (snapcraftChannel) => {
+ const fetchImpl = vi.fn()
+ const runSnapcraft = vi.fn()
+
+ await expect(
+ releaseSnapBuildSet({
+ snapName: 'motrix',
+ channel: 'latest/candidate',
+ snapcraftChannel,
+ version: '2.0.0',
+ revisions: { amd64: '20', arm64: '21' },
+ attempts: 1,
+ delayMs: 0,
+ fetchImpl,
+ runSnapcraft,
+ })
+ ).rejects.toThrow(/Snapcraft channel must be an equivalent spelling/)
+ expect(fetchImpl).not.toHaveBeenCalled()
+ expect(runSnapcraft).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['candidate', 'latest/candidate', '3/candidate'])(
+ 'rejects %s for a non-default track before reading the Store',
+ async (snapcraftChannel) => {
+ const fetchImpl = vi.fn()
+ const runSnapcraft = vi.fn()
+
+ await expect(
+ releaseSnapBuildSet({
+ snapName: 'motrix',
+ channel: '2/candidate',
+ snapcraftChannel,
+ version: '2.0.0',
+ revisions: { amd64: '20', arm64: '21' },
+ attempts: 1,
+ delayMs: 0,
+ fetchImpl,
+ runSnapcraft,
+ })
+ ).rejects.toThrow(/Snapcraft channel must be an equivalent spelling/)
+ expect(fetchImpl).not.toHaveBeenCalled()
+ expect(runSnapcraft).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([
+ 'candidate',
+ 'latest/candidate/branch',
+ 'latest/candidate,latest/stable',
+ 'latest/candidate\n',
+ ])(
+ 'rejects noncanonical public channel %j before reading the Store',
+ async (channel) => {
+ const fetchImpl = vi.fn()
+ const runSnapcraft = vi.fn()
+
+ await expect(
+ releaseSnapBuildSet({
+ snapName: 'motrix',
+ channel,
+ snapcraftChannel: channel,
+ version: '2.0.0',
+ revisions: { amd64: '20', arm64: '21' },
+ attempts: 1,
+ delayMs: 0,
+ fetchImpl,
+ runSnapcraft,
+ })
+ ).rejects.toThrow(/Invalid channel/)
+ expect(fetchImpl).not.toHaveBeenCalled()
+ expect(runSnapcraft).not.toHaveBeenCalled()
+ }
+ )
+
it('does not mutate the Store when the initial snapshot cannot be read', async () => {
const fetchImpl = vi.fn().mockRejectedValue(new Error('Store unavailable'))
const runSnapcraft = vi.fn()
@@ -67,97 +224,121 @@ describe('release-snap-build-set', () => {
expect(runSnapcraft).not.toHaveBeenCalled()
})
- it('closes the target before releasing the approved exact revisions', async () => {
- const fetchImpl = vi
- .fn()
- .mockResolvedValueOnce(
- response(
- payload([
- ['amd64', '10', '1.8.19'],
- ['arm64', '11', '1.8.19'],
- ])
+ it.each([
+ ['latest/candidate', undefined, 'candidate'],
+ ['latest/edge', undefined, 'edge'],
+ ['latest/candidate', 'candidate', 'candidate'],
+ ['latest/candidate', 'latest/candidate', 'latest/candidate'],
+ ['latest/stable', 'stable', 'stable'],
+ ['latest/stable', 'latest/stable', 'latest/stable'],
+ ['2/stable', undefined, '2/stable'],
+ ['2/stable', '2/stable', '2/stable'],
+ ])(
+ 'releases %s with override %s using request spelling %s',
+ async (channel, snapcraftChannel, mutationChannel) => {
+ const fetchImpl = vi
+ .fn()
+ .mockResolvedValueOnce(
+ response(
+ payload(
+ [
+ ['amd64', '10', '1.8.19'],
+ ['arm64', '11', '1.8.19'],
+ ],
+ channel
+ )
+ )
)
- )
- .mockResolvedValueOnce(
- response(
- payload([
- ['amd64', '20', '2.0.0'],
- ['arm64', '21', '2.0.0'],
- ])
+ .mockResolvedValueOnce(
+ response(
+ payload(
+ [
+ ['amd64', '20', '2.0.0'],
+ ['arm64', '21', '2.0.0'],
+ ],
+ channel
+ )
+ )
)
- )
- const runSnapcraft = vi.fn().mockResolvedValue(undefined)
+ const runSnapcraft = vi.fn().mockResolvedValue(undefined)
- await expect(
- releaseSnapBuildSet({
- snapName: 'motrix',
- channel: 'latest/candidate',
+ await expect(
+ releaseSnapBuildSet({
+ snapName: 'motrix',
+ channel,
+ snapcraftChannel,
+ version: '2.0.0',
+ revisions: { amd64: '20', arm64: '21' },
+ attempts: 1,
+ delayMs: 0,
+ fetchImpl,
+ runSnapcraft,
+ })
+ ).resolves.toEqual({
+ channel,
+ previous: { amd64: '10', arm64: '11' },
+ released: { amd64: '20', arm64: '21' },
version: '2.0.0',
- revisions: { amd64: '20', arm64: '21' },
- attempts: 1,
- delayMs: 0,
- fetchImpl,
- runSnapcraft,
})
- ).resolves.toEqual({
- channel: 'latest/candidate',
- previous: { amd64: '10', arm64: '11' },
- released: { amd64: '20', arm64: '21' },
- version: '2.0.0',
- })
- expect(runSnapcraft.mock.calls).toEqual([
- [['close', 'motrix', 'candidate']],
- [['release', 'motrix', '20', 'candidate']],
- [['release', 'motrix', '21', 'candidate']],
- ])
- })
+ expect(runSnapcraft.mock.calls).toEqual([
+ [['close', 'motrix', mutationChannel]],
+ [['release', 'motrix', '20', mutationChannel]],
+ [['release', 'motrix', '21', mutationChannel]],
+ ])
+ expect(fetchImpl).toHaveBeenCalledTimes(2)
+ }
+ )
- it('closes partial state and restores the previous target on failure', async () => {
- const fetchImpl = vi
- .fn()
- .mockResolvedValueOnce(
- response(
- payload([
- ['amd64', '10', '1.8.19'],
- ['arm64', '11', '1.8.19'],
- ])
+ it.each(['candidate', 'latest/candidate'])(
+ 'uses %s to close partial state and restore the previous target on failure',
+ async (snapcraftChannel) => {
+ const fetchImpl = vi
+ .fn()
+ .mockResolvedValueOnce(
+ response(
+ payload([
+ ['amd64', '10', '1.8.19'],
+ ['arm64', '11', '1.8.19'],
+ ])
+ )
)
- )
- .mockResolvedValueOnce(
- response(
- payload([
- ['amd64', '10', '1.8.19'],
- ['arm64', '11', '1.8.19'],
- ])
+ .mockResolvedValueOnce(
+ response(
+ payload([
+ ['amd64', '10', '1.8.19'],
+ ['arm64', '11', '1.8.19'],
+ ])
+ )
)
- )
- const runSnapcraft = vi.fn(async (args: string[]) => {
- if (args[0] === 'release' && args[2] === '21') {
- throw new Error('Store rejected arm64 release')
- }
- })
-
- await expect(
- releaseSnapBuildSet({
- snapName: 'motrix',
- channel: 'latest/candidate',
- version: '2.0.0',
- revisions: { amd64: '20', arm64: '21' },
- attempts: 1,
- delayMs: 0,
- fetchImpl,
- runSnapcraft,
+ const runSnapcraft = vi.fn(async (args: string[]) => {
+ if (args[0] === 'release' && args[2] === '21') {
+ throw new Error('Store rejected arm64 release')
+ }
})
- ).rejects.toThrow(/previous revisions were restored/)
- expect(runSnapcraft.mock.calls).toEqual([
- [['close', 'motrix', 'candidate']],
- [['release', 'motrix', '20', 'candidate']],
- [['release', 'motrix', '21', 'candidate']],
- [['close', 'motrix', 'candidate']],
- [['release', 'motrix', '10', 'candidate']],
- [['release', 'motrix', '11', 'candidate']],
- ])
- })
+
+ await expect(
+ releaseSnapBuildSet({
+ snapName: 'motrix',
+ channel: 'latest/candidate',
+ snapcraftChannel,
+ version: '2.0.0',
+ revisions: { amd64: '20', arm64: '21' },
+ attempts: 1,
+ delayMs: 0,
+ fetchImpl,
+ runSnapcraft,
+ })
+ ).rejects.toThrow(/previous revisions were restored/)
+ expect(runSnapcraft.mock.calls).toEqual([
+ [['close', 'motrix', snapcraftChannel]],
+ [['release', 'motrix', '20', snapcraftChannel]],
+ [['release', 'motrix', '21', snapcraftChannel]],
+ [['close', 'motrix', snapcraftChannel]],
+ [['release', 'motrix', '10', snapcraftChannel]],
+ [['release', 'motrix', '11', snapcraftChannel]],
+ ])
+ }
+ )
it('restores after the initial close commits but its response is lost', async () => {
const fetchImpl = vi
@@ -396,6 +577,49 @@ describe('release-snap-build-set', () => {
])
})
+ it.each(['candidate', 'latest/candidate'])(
+ 'keeps request spelling %s when partial rollback requires containment',
+ async (snapcraftChannel) => {
+ const fetchImpl = vi.fn().mockResolvedValueOnce(
+ response(
+ payload([
+ ['amd64', '10', '1.8.19'],
+ ['arm64', '11', '1.8.19'],
+ ])
+ )
+ )
+ const runSnapcraft = vi.fn(async (args: string[]) => {
+ if (args[0] === 'release' && ['21', '11'].includes(args[2])) {
+ throw new Error('Store rejected arm64 release')
+ }
+ })
+
+ await expect(
+ releaseSnapBuildSet({
+ snapName: 'motrix',
+ channel: 'latest/candidate',
+ snapcraftChannel,
+ version: '2.0.0',
+ revisions: { amd64: '20', arm64: '21' },
+ attempts: 1,
+ delayMs: 0,
+ fetchImpl,
+ runSnapcraft,
+ })
+ ).rejects.toThrow(/rollback failed and the target channel was closed/)
+ expect(runSnapcraft.mock.calls).toEqual([
+ [['close', 'motrix', snapcraftChannel]],
+ [['release', 'motrix', '20', snapcraftChannel]],
+ [['release', 'motrix', '21', snapcraftChannel]],
+ [['close', 'motrix', snapcraftChannel]],
+ [['release', 'motrix', '10', snapcraftChannel]],
+ [['release', 'motrix', '11', snapcraftChannel]],
+ [['close', 'motrix', snapcraftChannel]],
+ ])
+ expect(fetchImpl).toHaveBeenCalledTimes(1)
+ }
+ )
+
it('reports when the final containment close also fails', async () => {
const fetchImpl = vi.fn().mockResolvedValueOnce(
response(
diff --git a/tests/scripts/workflow-snap.test.ts b/tests/scripts/workflow-snap.test.ts
index e94b637d..0f66cf7e 100644
--- a/tests/scripts/workflow-snap.test.ts
+++ b/tests/scripts/workflow-snap.test.ts
@@ -516,6 +516,7 @@ describe('Snap promotion workflow contract', () => {
) as LooseRecord
expect(steps.indexOf(credentials)).toBeLessThan(steps.indexOf(release))
expect(credentials['continue-on-error']).toBeUndefined()
+ expect(credentials.id).toBe('credentials')
expect(release.if).toBeUndefined()
expect(stringField(credentials, 'run')).toContain(
'python3 scripts/verify_snap_credential_scope.py'
@@ -523,6 +524,12 @@ describe('Snap promotion workflow contract', () => {
expect(stringField(credentials, 'run')).toContain(
'--channel "$TARGET_CHANNEL"'
)
+ expect(stringField(credentials, 'run')).toContain(
+ '--github-output "$GITHUB_OUTPUT"'
+ )
+ expect(stringField(release, 'run')).toContain(
+ '--snapcraft-channel "$SNAPCRAFT_CHANNEL"'
+ )
expect(asRecord(credentials.env, 'credential environment')).toMatchObject({
SNAPCRAFT_STORE_CREDENTIALS: `\${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}`,
TARGET_CHANNEL: `\${{ needs.preflight.outputs.target_channel }}`,
@@ -530,6 +537,7 @@ describe('Snap promotion workflow contract', () => {
expect(asRecord(release.env, 'release environment')).toMatchObject({
SNAPCRAFT_STORE_CREDENTIALS: `\${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}`,
TARGET_CHANNEL: `\${{ needs.preflight.outputs.target_channel }}`,
+ SNAPCRAFT_CHANNEL: `\${{ steps.credentials.outputs.snapcraft_channel }}`,
})
})
@@ -707,6 +715,7 @@ describe.skipIf(process.platform === 'win32')(
const result = runPromotionCredentialGate(options)
expect(result.status).toBe(1)
expect(result.releaseCalls).toEqual([])
+ expect(result.githubOutput).toBe('')
expect(result.snapcraftCalls).toEqual(['whoami --verbosity brief'])
const diagnosticLines = result.stderr
.split('\n')
@@ -756,6 +765,22 @@ describe.skipIf(process.platform === 'win32')(
it.each([
{ target: 'candidate', channels: 'candidate' },
{ target: 'stable', channels: 'stable' },
+ {
+ target: 'candidate',
+ channels: 'latest/candidate',
+ selectedChannel: 'latest/candidate',
+ },
+ {
+ target: 'stable',
+ channels: 'latest/stable',
+ selectedChannel: 'latest/stable',
+ },
+ {
+ target: 'candidate',
+ channels: 'latest/*',
+ selectedChannel: 'latest/candidate',
+ },
+ { target: 'candidate', channels: 'latest/candidate, candidate' },
{ target: 'candidate', channels: 'edge, candidate, stable' },
{ target: 'stable', channels: 'no restrictions' },
{ target: 'candidate', channels: 'candi?ate' },
@@ -784,14 +809,21 @@ describe.skipIf(process.platform === 'win32')(
expect(result.releaseCalls[0]).toContain(
`--channel latest/${options.target}`
)
+ const selectedChannel = options.selectedChannel ?? options.target
+ expect(result.githubOutput).toBe(`snapcraft_channel=${selectedChannel}\n`)
+ expect(result.releaseCalls[0]).toContain(
+ `--snapcraft-channel ${selectedChannel} `
+ )
})
it.each([
{ channels: 'candidate', target: 'stable' },
{ channels: '2.0/candidate' },
- { channels: 'latest/candidate' },
+ { channels: 'latest/stable' },
+ { channels: 'latest/candidate', target: 'stable' },
+ { channels: 'latest/candidate/branch' },
{ channels: 'candidate/branch' },
- { channels: '[!c]*' },
+ { channels: '[!cl]*' },
{ permissions: 'package_access, package_push' },
{ permissions: 'package_release_extra' },
{ permissions: '' },
@@ -827,6 +859,7 @@ describe.skipIf(process.platform === 'win32')(
const result = runPromotionCredentialGate(options)
expect(result.status).not.toBe(0)
expect(result.releaseCalls).toEqual([])
+ expect(result.githubOutput).toBe('')
expect(result.snapcraftCalls).toEqual(['whoami --verbosity brief'])
expect(result.stdout + result.stderr).not.toContain(
@@ -875,9 +908,11 @@ function runPromotionCredentialGate({
const whoamiFile = path.join(root, 'whoami.txt')
const snapcraftLog = path.join(root, 'snapcraft.log')
const releaseLog = path.join(root, 'release.log')
+ const githubOutput = path.join(root, 'github-output')
writeFileSync(whoamiFile, output)
writeFileSync(snapcraftLog, '')
writeFileSync(releaseLog, '')
+ writeFileSync(githubOutput, '')
writeFileSync(
path.join(root, 'snapcraft'),
[
@@ -909,10 +944,16 @@ function runPromotionCredentialGate({
const release = steps.find(
(step) => step.name === 'Release approved build set'
) as LooseRecord
- // A failed credential step prevents subsequent Actions steps. Execute both
- // real commands under the credential step's errexit to prove that boundary.
+ // A failed credential step prevents subsequent Actions steps. Transfer its
+ // actual output to the release step as data, without evaluating shell text.
+ const transferOutput = [
+ 'while IFS="=" read -r key value; do',
+ ' [[ "$key" == snapcraft_channel ]] || exit 97',
+ ' export SNAPCRAFT_CHANNEL="$value"',
+ 'done < "$GITHUB_OUTPUT"',
+ ].join('\n')
const command =
- `${stringField(credentials, 'run')}\n${stringField(release, 'run')}`
+ `${stringField(credentials, 'run')}\n${transferOutput}\n${stringField(release, 'run')}`
.replaceAll('/snap/bin/snapcraft', 'snapcraft')
.replaceAll(`\${{ needs.preflight.outputs.amd64_revision }}`, '111')
.replaceAll(`\${{ needs.preflight.outputs.arm64_revision }}`, '112')
@@ -927,6 +968,7 @@ function runPromotionCredentialGate({
PROMOTION_TARGET: target,
TARGET_CHANNEL: `latest/${target}`,
EXPECTED_VERSION: '2.0.0',
+ GITHUB_OUTPUT: githubOutput,
MOTRIX_TEST_WHOAMI_FILE: whoamiFile,
MOTRIX_TEST_DIAGNOSTIC: diagnostic,
MOTRIX_TEST_EXIT_CODE: String(exitCode),
@@ -936,6 +978,7 @@ function runPromotionCredentialGate({
})
return {
...result,
+ githubOutput: readFileSync(githubOutput, 'utf8'),
snapcraftCalls: readFileSync(snapcraftLog, 'utf8')
.split('\n')
.filter(Boolean),