diff --git a/.github/workflows/release-os-ota-publish.yml b/.github/workflows/release-os-ota-publish.yml index 5a7805214e..fb96b76992 100644 --- a/.github/workflows/release-os-ota-publish.yml +++ b/.github/workflows/release-os-ota-publish.yml @@ -43,6 +43,10 @@ on: description: Attempt that successfully completed the protected Pixel sign job required: false type: string + channel_tag: + description: OS GitHub release channel tag (defaults to os-pilot; use a dedicated os-* tag such as os-stable for user/release-keys OTAs while os-pilot serves userdebug/test-keys pilot phones) + required: false + type: string permissions: {} @@ -183,19 +187,22 @@ jobs: env: GH_TOKEN: ${{ github.token }} ASSET_NAME: ${{ inputs.asset_name }} + CHANNEL_TAG: ${{ inputs.channel_tag }} run: | set -euo pipefail work="$OS_PUBLISH_WORK" - pnpm -s release os-manifest --ota "$work/ota.zip" --asset "$OS_ASSET_NAME" --out "$work/alpha-os-update.json" + OS_CHANNEL_TAG=${CHANNEL_TAG:-os-pilot} + [[ "$OS_CHANNEL_TAG" =~ ^os-[A-Za-z0-9][A-Za-z0-9._-]{0,124}$ ]] || { echo "Invalid channel_tag: $OS_CHANNEL_TAG" >&2; exit 1; } + pnpm -s release os-manifest --ota "$work/ota.zip" --asset "$OS_ASSET_NAME" --tag "$OS_CHANNEL_TAG" --out "$work/alpha-os-update.json" if [[ -f "$RUNNER_TEMP/pixel-bundle-receipts/pins.json" ]]; then node ../../packages/cli/src/main.ts pixel-bundle --check --json --receipts "$RUNNER_TEMP/pixel-bundle-receipts" --manifest "$work/alpha-os-update.json" fi - live=https://github.com/AlphaPhone/alpha/releases/download/os-pilot/alpha-os-update.json + live="https://github.com/AlphaPhone/alpha/releases/download/$OS_CHANNEL_TAG/alpha-os-update.json" if ! curl -fsSL --proto '=https' --proto-redir '=https' --max-redirs 3 --max-filesize 65536 "$live" -o "$work/live.json" || ! cmp -s "$work/live.json" "$work/alpha-os-update.json"; then - pnpm -s release os-publish --run "$work/os-run.json" --ota "$work/ota.zip" --manifest "$work/alpha-os-update.json" --execute + pnpm -s release os-publish --run "$work/os-run.json" --ota "$work/ota.zip" --manifest "$work/alpha-os-update.json" --tag "$OS_CHANNEL_TAG" --enrollment aosp/pilot-system-update-enrollment.json --execute fi - pnpm -s release os-status --run "$work/os-run.json" --manifest "$work/alpha-os-update.json" + pnpm -s release os-status --run "$work/os-run.json" --manifest "$work/alpha-os-update.json" --tag "$OS_CHANNEL_TAG" - uses: actions/upload-artifact@v5 if: always() with: diff --git a/apps/app/scripts/release.ts b/apps/app/scripts/release.ts index 50ddcfe6d0..3f34a93f6f 100644 --- a/apps/app/scripts/release.ts +++ b/apps/app/scripts/release.ts @@ -66,10 +66,14 @@ const USAGE = [ "pnpm release os-plan --plan FILE --plan-sha256 HEX", "pnpm release os-sign --plan FILE --plan-sha256 HEX --target-files FILE --ota-tools FILE --work NEW_DIR [--scratch TMPFS_DIR]", "pnpm release os-manifest --ota FILE --asset NAME --out NEW_FILE [--receipt FILE] [--tag TAG]", - "pnpm release os-publish --run FILE --ota FILE --manifest FILE [--execute]", - "pnpm release os-status [--run FILE] [--min-timestamp N] [--manifest FILE]", + "pnpm release os-publish --run FILE --ota FILE --manifest FILE [--tag TAG] [--enrollment FILE] [--execute]", + "pnpm release os-status [--run FILE] [--min-timestamp N] [--manifest FILE] [--tag TAG]", ].join("\n"); +const OS_CHANNEL_TAG = /^os-[A-Za-z0-9][A-Za-z0-9._-]{0,124}$/; +/** Whether `tag` names a dedicated OS OTA release channel (`os-*`), excluding launcher and versioned release tags. */ +export const osChannelTagValid = (tag: string) => OS_CHANNEL_TAG.test(tag); + /** The manifest phones read, at the release of the channel's tag. */ export const manifestUrl = (tag: string = channelTag) => `https://github.com/${channelRepository}/releases/download/${tag}/${channelManifest}`; /** Where the APK of `version` is kept on the channel. */ @@ -83,9 +87,9 @@ export const osManifestUrl = (tag: string = osChannelTag) => `https://github.com /** Where the OS archive `asset` is kept on the OS channel. */ export const osArchiveUrl = (asset: string, repository: string = osChannelRepository, tag: string = osChannelTag) => `https://github.com/${repository}/releases/download/${tag}/${asset}`; -/** Whether `url` is an OS archive of `asset` kept under Alpha's repository or its earlier names. */ -export const osKept = (url: string, asset: string) => - [osChannelRepository, ...osEarlierRepositories].some((repository) => url === osArchiveUrl(asset, repository, osChannelTag)); +/** Whether `url` is an OS archive of `asset` kept under Alpha's repository or its earlier names for `tag`. */ +export const osKept = (url: string, asset: string, tag: string = osChannelTag) => + [osChannelRepository, ...osEarlierRepositories].some((repository) => url === osArchiveUrl(asset, repository, tag)); const sha256 = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex"); const sha256File = (file: string) => sha256(readFileSync(file)); @@ -478,8 +482,12 @@ export function createGithubChannel(runGh: (...args: string[]) => Effect.Effect< /** The launcher channel on GitHub: its stable release through `gh`, and what anyone downloads from it. */ export const githubChannel: ChannelPort = createGithubChannel(); -/** The OS channel on GitHub: its `os-pilot` release through `gh`, and what anyone downloads from it. */ -export const githubOsChannel: ChannelPort = githubChannelFor(osChannelTag, osChannelRepository, osChannelRepositoryId, { allowedHosts: OS_ALLOWED_HOSTS, maxHops: maxOsRedirects }); +/** Builds an OS GitHub release channel port for `tag` over `runGh`. */ +export function createGithubOsChannel(tag: string = osChannelTag, runGh: (...args: string[]) => Effect.Effect = gh): ChannelPort { + return githubChannelFor(tag, osChannelRepository, osChannelRepositoryId, { allowedHosts: OS_ALLOWED_HOSTS, maxHops: maxOsRedirects }, runGh); +} +/** The default OS channel on GitHub: its `os-pilot` release through `gh`, and what anyone downloads from it. */ +export const githubOsChannel: ChannelPort = createGithubOsChannel(osChannelTag); const text = (served: Served) => new TextDecoder().decode(served.bytes); @@ -653,13 +661,71 @@ export interface OsManifestWire { } const OS_ASSET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.zip$/; +const OS_BUILD_VARIANT = /^[^\s:/]+\/[^\s:/]+\/[^\s:/]+:[^\s:/]+\/[^\s:/]+\/[^\s:/]+:([A-Za-z0-9._-]+)\/([A-Za-z0-9._,-]+)$/; + +/** Parsed `:/` identity from an Android build fingerprint. */ +export interface OsBuildVariant { + readonly buildType: string; + readonly buildTags: string; + readonly flavor: string; +} + +/** Extracts the trailing `:/` suffix (such as `user/release-keys` or `userdebug/test-keys`) from a build fingerprint. */ +export function osBuildVariant(fingerprint: string): OsBuildVariant | undefined { + if (fingerprint.trim() !== fingerprint || /\s/.test(fingerprint)) return undefined; + const match = OS_BUILD_VARIANT.exec(fingerprint); + if (match === null) return undefined; + const [, buildType = "", buildTags = ""] = match; + return { buildType, buildTags, flavor: `${buildType}/${buildTags}` }; +} + +/** + * Returns true only when both OS fingerprints parse valid `:/` suffixes and share + * the exact same build type and signing key tags (refusing `userdebug/test-keys` <-> `user/release-keys` cross-key OTAs). + */ +export function isCompatibleOsBuildTransition(liveFingerprint: string, candidateFingerprint: string): boolean { + const live = osBuildVariant(liveFingerprint); + const candidate = osBuildVariant(candidateFingerprint); + return live !== undefined && candidate !== undefined && live.buildType === candidate.buildType && live.buildTags === candidate.buildTags; +} + +/** Subset of `pilot-system-update-enrollment.json` checked before publishing onto an enrolled OS channel tag. */ +export interface OsPilotEnrollmentRecord { + readonly manifestUrl?: string; + readonly legacyBuildFingerprint?: string; + readonly rotatePlatformOrAVBKeys?: boolean; +} + +/** + * Refuses publishing a cross-key candidate (for example `user/release-keys`) onto a channel pinned by a + * non-rotating pilot enrollment descriptor (for example `os-pilot` carrying `userdebug/test-keys` phones), + * even if the live channel manifest is temporarily absent. + */ +export function assertOsChannelEnrollmentCompatible( + tag: string, + candidateFingerprint: string, + enrollment: OsPilotEnrollmentRecord, +): void { + if (enrollment.rotatePlatformOrAVBKeys !== false) return; + if (enrollment.manifestUrl !== osManifestUrl(tag)) return; + const legacy = typeof enrollment.legacyBuildFingerprint === "string" ? enrollment.legacyBuildFingerprint : ""; + if (!isCompatibleOsBuildTransition(legacy, candidateFingerprint)) { + const legacyFlavor = osBuildVariant(legacy)?.flavor ?? "unknown"; + const candidateFlavor = osBuildVariant(candidateFingerprint)?.flavor ?? "unknown"; + throw new ReleaseRefused({ + message: `OS channel ${tag} is pinned by pilot enrollment to ${legacyFlavor} (${legacy}) with rotatePlatformOrAVBKeys=false and refuses cross-key ${candidateFlavor} (${candidateFingerprint}); publish ${candidateFlavor} OTAs to a dedicated os-* channel tag instead`, + }); + } +} const osRunOf = (file: string) => ledger(Os, file); -type OsPointer = { readonly kind: "Absent" } | { readonly kind: "Named"; readonly timestamp: number; readonly sha256: string }; +type OsPointer = + | { readonly kind: "Absent" } + | { readonly kind: "Named"; readonly timestamp: number; readonly sha256: string; readonly buildFingerprint?: string }; -const readOsPointer = (port: ChannelPort): Effect.Effect => Effect.gen(function* () { - const read = yield* Effect.catch(port.read(osManifestUrl(), MANIFEST_BYTES), (failure) => +const readOsPointer = (port: ChannelPort, tag: string = osChannelTag): Effect.Effect => Effect.gen(function* () { + const read = yield* Effect.catch(port.read(osManifestUrl(tag), MANIFEST_BYTES), (failure) => failure.httpStatus === 404 ? Effect.succeed(undefined) : Effect.fail(failure)); if (read === undefined) { if ((yield* port.listed).includes(osChannelManifest)) { @@ -675,7 +741,12 @@ const readOsPointer = (port: ChannelPort): Effect.Effect; readonly port: ChannelPort; readonly ota: string; @@ -766,10 +837,21 @@ export const publishOsRelease = ({ run, port, ota, manifestFile, assetName, mani readonly assetName: string; readonly manifest: OsManifestWire; readonly modelManifest: OsManifest; + readonly tag?: string; }) => Effect.gen(function* () { + if (!osChannelTagValid(tag)) { + return yield* new ReleaseRefused({ message: `OS channel tag must match os-*, not ${JSON.stringify(tag)}` }); + } yield* attempt(() => requireGithubOtaSize(ota)); const expectedSha256 = yield* attempt(() => sha256File(manifestFile)); - const before = yield* readOsPointer(port); + const before = yield* readOsPointer(port, tag); + if (before.kind === "Named" && (before.buildFingerprint === undefined || !isCompatibleOsBuildTransition(before.buildFingerprint, manifest.buildFingerprint))) { + const liveFlavor = before.buildFingerprint === undefined ? "missing" : (osBuildVariant(before.buildFingerprint)?.flavor ?? "unknown"); + const candidateFlavor = osBuildVariant(manifest.buildFingerprint)?.flavor ?? "unknown"; + return yield* new ReleaseRefused({ + message: `refusing cross-key OS publication to ${tag}: live manifest serves ${liveFlavor} (${before.buildFingerprint ?? "missing buildFingerprint"}), candidate is ${candidateFlavor} (${manifest.buildFingerprint}); publish ${candidateFlavor} OTAs to a dedicated os-* channel tag instead`, + }); + } const observe = { type: "observeOsPointer" as const, observedTimestamp: before.kind === "Named" ? before.timestamp : 0 }; if (run.can(observe)) yield* attempt(() => run.take(observe)); @@ -794,7 +876,7 @@ export const publishOsRelease = ({ run, port, ota, manifestFile, assetName, mani if (!pendingReadBack) { const present = (yield* port.listed).includes(assetName); - const current = yield* readOsPointer(port); + const current = yield* readOsPointer(port, tag); const unchanged = current.kind === "Absent" ? before.kind === "Absent" : before.kind === "Named" && current.timestamp === before.timestamp && current.sha256 === before.sha256; const move = { type: "moveOsPointer" as const, present, unchanged }; @@ -803,7 +885,7 @@ export const publishOsRelease = ({ run, port, ota, manifestFile, assetName, mani yield* attempt(() => run.take(move)); } - const after = yield* readOsPointer(port); + const after = yield* readOsPointer(port, tag); const exactPointer = after.kind === "Named" && after.timestamp === manifest.buildTimestamp && after.sha256 === expectedSha256; if (after.kind === "Named" && after.timestamp === manifest.buildTimestamp && !exactPointer) { return yield* new ReleaseRefused({ message: "the live OS manifest has the candidate timestamp but different bytes" }); @@ -817,20 +899,24 @@ export const publishOsRelease = ({ run, port, ota, manifestFile, assetName, mani }); /** Verifies the live OS channel manifest, anonymous archive download, whole-file CMS signer, metadata, redirect cap, and timestamp floor. */ -export const checkOsChannelStatus = ({ port, minTimestamp = 0, expectedCert = Os.pinned.certificate, expectedManifestSha256 }: { +export const checkOsChannelStatus = ({ port, tag = osChannelTag, minTimestamp = 0, expectedCert = Os.pinned.certificate, expectedManifestSha256 }: { readonly port: ChannelPort; + readonly tag?: string; readonly minTimestamp?: number; readonly expectedCert?: string; readonly expectedManifestSha256?: string; }) => Effect.gen(function* () { - const manifestRead = yield* port.read(osManifestUrl(), MANIFEST_BYTES); + if (!osChannelTagValid(tag)) { + return yield* new ReleaseRefused({ message: `OS channel tag must match os-*, not ${JSON.stringify(tag)}` }); + } + const manifestRead = yield* port.read(osManifestUrl(tag), MANIFEST_BYTES); if (expectedManifestSha256 !== undefined && manifestRead.sha256 !== expectedManifestSha256) { return yield* new ReleaseRefused({ message: "the live OS manifest differs from the expected bytes" }); } const manifestRedirects = manifestRead.redirects ?? 0; const manifest = yield* attempt(() => JSON.parse(text(manifestRead)) as Partial); const assetName = typeof manifest.url === "string" ? manifest.url.split("/").at(-1) ?? "" : ""; - const keptAsset = OS_ASSET_NAME.test(assetName) && osKept(manifest.url ?? "", assetName); + const keptAsset = OS_ASSET_NAME.test(assetName) && osKept(manifest.url ?? "", assetName, tag); const scratch = yield* attempt(() => mkdtempSync(join(tmpdir(), "alpha-os-status-"))); try { const archiveFile = join(scratch, "ota.zip"); @@ -1158,6 +1244,7 @@ const commands = { const [ota = "", asset = "", out = ""] = yield* attempt(() => found.need("ota", "asset", "out")); if (!OS_ASSET_NAME.test(asset)) return yield* new UsageError({ message: `--asset must be a safe .zip filename, not ${JSON.stringify(asset)}` }); const tag = found.values.tag ?? osChannelTag; + if (!osChannelTagValid(tag)) return yield* new UsageError({ message: `--tag must name an os-* release channel, not ${JSON.stringify(tag)}` }); const inspected = yield* attempt(() => inspectOsOtaArchive(ota)); if (!inspected.enrolled || !inspected.abType || inspected.preDevice !== Os.pinned.device) { return yield* new ReleaseRefused({ message: `OS archive ${ota} is not an enrolled A/B update for ${Os.pinned.device}` }); @@ -1190,12 +1277,19 @@ const commands = { return manifest; }), "os-publish": (argv: readonly string[], port: ChannelPort) => Effect.gen(function* () { - const found = yield* attempt(() => flags(argv, ["run", "ota", "manifest"], ["execute"])); + const found = yield* attempt(() => flags(argv, ["run", "ota", "manifest", "tag", "enrollment"], ["execute"])); const [file = "", ota = "", manifestFile = ""] = yield* attempt(() => found.need("run", "ota", "manifest")); + const tag = found.values.tag ?? osChannelTag; + if (!osChannelTagValid(tag)) return yield* new UsageError({ message: `--tag must name an os-* release channel, not ${JSON.stringify(tag)}` }); const manifest = yield* attempt(() => JSON.parse(readFileSync(manifestFile, "utf8")) as OsManifestWire); const assetName = manifest.url.split("/").at(-1) ?? ""; - if (!OS_ASSET_NAME.test(assetName) || !osKept(manifest.url, assetName)) { - return yield* new ReleaseRefused({ message: `OS manifest URL ${manifest.url} does not name a kept ${osChannelTag} asset` }); + if (!OS_ASSET_NAME.test(assetName) || !osKept(manifest.url, assetName, tag)) { + return yield* new ReleaseRefused({ message: `OS manifest URL ${manifest.url} does not name a kept ${tag} asset` }); + } + const enrollmentFile = found.values.enrollment; + if (enrollmentFile !== undefined) { + const enrollment = yield* attempt(() => JSON.parse(readFileSync(enrollmentFile, "utf8")) as OsPilotEnrollmentRecord); + yield* attempt(() => assertOsChannelEnrollmentCompatible(tag, manifest.buildFingerprint, enrollment)); } const inspected = yield* attempt(() => inspectOsOtaArchive(ota)); if (!inspected.enrolled || !inspected.abType || inspected.preDevice !== Os.pinned.device @@ -1207,14 +1301,16 @@ const commands = { if (!osManifestValid(modelManifest)) { return yield* new ReleaseRefused({ message: `OS manifest refused by spec: ${JSON.stringify(modelManifest)}` }); } - const plan = { upload: assetName, verify: manifest.url, then: osManifestUrl() }; + const plan = { upload: assetName, verify: manifest.url, then: osManifestUrl(tag) }; if (!found.on.has("execute")) return { plan, executed: false }; - const osPort = port === githubChannel ? githubOsChannel : port; + const osPort = port === githubChannel ? (tag === osChannelTag ? githubOsChannel : createGithubOsChannel(tag)) : port; const run = yield* attempt(() => osRunOf(file)); - return { plan, executed: true, state: yield* publishOsRelease({ run, port: osPort, ota, manifestFile, assetName, manifest, modelManifest }) }; + return { plan, executed: true, state: yield* publishOsRelease({ run, port: osPort, ota, manifestFile, assetName, manifest, modelManifest, tag }) }; }), "os-status": (argv: readonly string[], port: ChannelPort) => Effect.gen(function* () { - const found = yield* attempt(() => flags(argv, ["run", "min-timestamp", "manifest"])); + const found = yield* attempt(() => flags(argv, ["run", "min-timestamp", "manifest", "tag"])); + const tag = found.values.tag ?? osChannelTag; + if (!osChannelTagValid(tag)) return yield* new UsageError({ message: `--tag must name an os-* release channel, not ${JSON.stringify(tag)}` }); let minTimestamp = 0; if (found.values.run !== undefined) { const runState = yield* attempt(() => osRunOf(found.values.run ?? "").state); @@ -1223,10 +1319,10 @@ const commands = { if (found.values["min-timestamp"] !== undefined) { minTimestamp = Math.max(minTimestamp, yield* attempt(() => whole(found.values["min-timestamp"] ?? "", "min-timestamp"))); } - const osPort = port === githubChannel ? githubOsChannel : port; + const osPort = port === githubChannel ? (tag === osChannelTag ? githubOsChannel : createGithubOsChannel(tag)) : port; const manifestFile = found.values.manifest; const expectedManifest = manifestFile === undefined ? {} : { expectedManifestSha256: yield* attempt(() => sha256File(manifestFile)) }; - return yield* checkOsChannelStatus({ port: osPort, minTimestamp, ...expectedManifest }); + return yield* checkOsChannelStatus({ port: osPort, tag, minTimestamp, ...expectedManifest }); }), } as const; diff --git a/apps/app/test/os-ota-guard.test.ts b/apps/app/test/os-ota-guard.test.ts new file mode 100644 index 0000000000..544cb23809 --- /dev/null +++ b/apps/app/test/os-ota-guard.test.ts @@ -0,0 +1,443 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { Effect, Exit } from "effect"; +import { afterEach, describe, expect, it } from "vitest"; +import * as Os from "../gen/release__os.ts"; +import { + type ChannelPort, + type OsManifestWire, + type OsPilotEnrollmentRecord, + ReleaseRefused, + assertOsChannelEnrollmentCompatible, + checkOsChannelStatus, + isCompatibleOsBuildTransition, + ledger, + osArchiveUrl, + osBuildVariant, + osChannelTagValid, + osKept, + osManifestFacts, + osManifestUrl, + publishOsRelease, + release, +} from "../scripts/release.ts"; + +const APP_DIR = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const REPO_ROOT = resolve(APP_DIR, "../.."); +const PILOT_ENROLLMENT_PATH = join(APP_DIR, "aosp/pilot-system-update-enrollment.json"); +const PUBLISH_WORKFLOW_PATH = join(REPO_ROOT, ".github/workflows/release-os-ota-publish.yml"); + +const TEST_KEYS_FP_LIVE = + "Alpha/alpha_stallion_phone/stallion:17/CP2A.260605.016/alpha_wireless_delivery_20261113_15:userdebug/test-keys"; +const TEST_KEYS_FP_NEXT = + "Alpha/alpha_stallion_phone/stallion:17/CP2A.260605.016/alpha_wireless_delivery_20261205_1:userdebug/test-keys"; +const RELEASE_KEYS_FP = + "Alpha/alpha_stallion_phone/stallion:17/CP2A.260605.016/alpha.47400748471.1:user/release-keys"; + +const sha256Hex = (data: Uint8Array) => createHash("sha256").update(data).digest("hex"); +const encodeJson = (value: unknown) => new TextEncoder().encode(`${JSON.stringify(value, null, 2)}\n`); + +function failureMessage(exit: Exit.Exit): string { + if (Exit.isSuccess(exit)) return ""; + return JSON.stringify(exit.cause); +} + +function makeFakeOsChannel(tag: string, seed: Record = {}) { + const files = new Map(Object.entries(seed)); + const uploaded: string[] = []; + const prefix = osManifestUrl(tag).slice(0, osManifestUrl(tag).lastIndexOf("/") + 1); + const port: ChannelPort = { + listed: Effect.sync(() => [...files.keys()]), + assetDigest: (name) => Effect.sync(() => { + const content = files.get(name); + return content === undefined ? undefined : sha256Hex(content); + }), + upload: (sourcePath, name, clobber) => Effect.suspend(() => { + if (!clobber && files.has(name)) { + return Effect.fail(new ReleaseRefused({ message: `asset ${name} already exists` })); + } + files.set(name, new Uint8Array(readFileSync(sourcePath))); + uploaded.push(name); + return Effect.void; + }), + read: (url, bound) => Effect.suspend(() => { + if (!url.startsWith(prefix)) { + return Effect.fail(new ReleaseRefused({ message: `unexpected channel URL ${url}`, httpStatus: 404 })); + } + const asset = url.slice(prefix.length); + const data = files.get(asset); + if (data === undefined) { + return Effect.fail(new ReleaseRefused({ message: `missing ${asset}`, httpStatus: 404 })); + } + if (data.length > bound) { + return Effect.fail(new ReleaseRefused({ message: `asset ${asset} exceeds bound` })); + } + return Effect.succeed({ bytes: data, size: data.length, sha256: sha256Hex(data), redirects: 1 }); + }), + recordFile: join(APP_DIR, "aosp/signing/release-signer.json"), + }; + return { files, uploaded, port }; +} + +function buildSignedOtaFixture(workDir: string, stem: string, buildFingerprint: string, timestamp: number, keyFile: string, certFile: string) { + const tree = join(workDir, `${stem}-tree`); + mkdirSync(join(tree, "META-INF/com/android"), { recursive: true }); + writeFileSync( + join(tree, "META-INF/com/android/metadata"), + `ota-type=AB\npre-device=stallion\npost-build=${buildFingerprint}\npost-timestamp=${timestamp}\n`, + ); + writeFileSync(join(tree, "payload.bin"), `ota-bytes-${stem}-${timestamp}`); + const rawZip = join(workDir, `${stem}-raw.zip`); + execFileSync("zip", ["-qrX", rawZip, "."], { cwd: tree }); + const rawBytes = readFileSync(rawZip); + const zipBody = rawBytes.subarray(0, rawBytes.length - 2); + const bodyFile = join(workDir, `${stem}-body.bin`); + const cmsFile = join(workDir, `${stem}-cms.der`); + writeFileSync(bodyFile, zipBody); + execFileSync( + "openssl", + ["cms", "-sign", "-binary", "-in", bodyFile, "-signer", certFile, "-inkey", keyFile, "-outform", "DER", "-out", cmsFile, "-noattr"], + { stdio: "ignore" }, + ); + const cmsDer = readFileSync(cmsFile); + const trailerLen = cmsDer.length + 6; + const commentLenBuf = Buffer.alloc(2); + commentLenBuf.writeUInt16LE(trailerLen, 0); + const footerBuf = Buffer.alloc(6); + footerBuf.writeUInt16LE(trailerLen, 0); + footerBuf.writeUInt16LE(0xffff, 2); + footerBuf.writeUInt16LE(trailerLen, 4); + const signedPath = join(workDir, `${stem}.zip`); + writeFileSync(signedPath, Buffer.concat([zipBody, commentLenBuf, cmsDer, footerBuf])); + return signedPath; +} + +const tempDirs: string[] = []; +const makeWorkDir = () => { + const dir = mkdtempSync(join(tmpdir(), "alpha-os-ota-guard-")); + tempDirs.push(dir); + return dir; +}; + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("OS OTA cross-key channel guards (#2391)", () => { + it("parses build variants and refuses cross-key or cross-type transitions", () => { + expect(osBuildVariant(TEST_KEYS_FP_LIVE)).toEqual({ + buildType: "userdebug", + buildTags: "test-keys", + flavor: "userdebug/test-keys", + }); + expect(osBuildVariant(RELEASE_KEYS_FP)).toEqual({ + buildType: "user", + buildTags: "release-keys", + flavor: "user/release-keys", + }); + expect(osBuildVariant("Alpha/alpha_stallion_phone/stallion:17/no-suffix")).toBeUndefined(); + expect(osBuildVariant(` ${RELEASE_KEYS_FP}`)).toBeUndefined(); + + expect(isCompatibleOsBuildTransition(TEST_KEYS_FP_LIVE, TEST_KEYS_FP_NEXT)).toBe(true); + expect(isCompatibleOsBuildTransition(RELEASE_KEYS_FP, RELEASE_KEYS_FP.replace(".1:", ".2:"))).toBe(true); + expect(isCompatibleOsBuildTransition(TEST_KEYS_FP_LIVE, RELEASE_KEYS_FP)).toBe(false); + expect(isCompatibleOsBuildTransition(RELEASE_KEYS_FP, TEST_KEYS_FP_LIVE)).toBe(false); + expect( + isCompatibleOsBuildTransition( + "Alpha/alpha_stallion_phone/stallion:17/CP2A/1:user/test-keys", + RELEASE_KEYS_FP, + ), + ).toBe(false); + expect( + isCompatibleOsBuildTransition( + "Alpha/alpha_stallion_phone/stallion:17/CP2A/1:userdebug/release-keys", + RELEASE_KEYS_FP, + ), + ).toBe(false); + }); + + it("validates os-* channel tags and binds osKept strictly to the target tag", () => { + expect(osChannelTagValid("os-pilot")).toBe(true); + expect(osChannelTagValid("os-stable")).toBe(true); + expect(osChannelTagValid("os-prod.1")).toBe(true); + expect(osChannelTagValid("app-stable-alphacompute")).toBe(false); + expect(osChannelTagValid("alpha-v1378")).toBe(false); + expect(osChannelTagValid("os-")).toBe(false); + expect(osChannelTagValid("../os-pilot")).toBe(false); + + const stableUrl = osArchiveUrl("alpha-os-1.zip", undefined, "os-stable"); + expect(osKept(stableUrl, "alpha-os-1.zip", "os-stable")).toBe(true); + expect(osKept(stableUrl, "alpha-os-1.zip", "os-pilot")).toBe(false); + }); + + it("enforces pilot-system-update-enrollment.json against release-keys on os-pilot while allowing os-stable", () => { + const pilotEnrollment = JSON.parse(readFileSync(PILOT_ENROLLMENT_PATH, "utf8")) as OsPilotEnrollmentRecord; + + expect(() => assertOsChannelEnrollmentCompatible("os-pilot", RELEASE_KEYS_FP, pilotEnrollment)).toThrow( + /userdebug\/test-keys.*user\/release-keys/, + ); + expect(() => assertOsChannelEnrollmentCompatible("os-pilot", TEST_KEYS_FP_NEXT, pilotEnrollment)).not.toThrow(); + expect(() => assertOsChannelEnrollmentCompatible("os-stable", RELEASE_KEYS_FP, pilotEnrollment)).not.toThrow(); + expect(() => + assertOsChannelEnrollmentCompatible("os-pilot", RELEASE_KEYS_FP, { + ...pilotEnrollment, + rotatePlatformOrAVBKeys: true, + }), + ).not.toThrow(); + }); + + it("blocks cross-key publishOsRelease in both directions and allows same-key or dedicated-tag publication", async () => { + const work = makeWorkDir(); + const keyFile = join(work, "test-ota.key"); + const certFile = join(work, "test-ota.pem"); + execFileSync( + "openssl", + ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", keyFile, "-out", certFile, "-subj", "/CN=Alpha Guard Test", "-days", "1"], + { stdio: "ignore" }, + ); + const certSha = sha256Hex(execFileSync("openssl", ["x509", "-in", certFile, "-outform", "DER"])); + + const livePilotManifest: OsManifestWire = { + schema: 1, + product: "alpha_stallion_phone", + device: "stallion", + url: osArchiveUrl("alpha-os-20261113-15.zip", undefined, "os-pilot"), + sha256: "1".repeat(64), + sizeBytes: 1234, + buildFingerprint: TEST_KEYS_FP_LIVE, + buildTimestamp: 1794600000, + }; + + const releaseZip = buildSignedOtaFixture(work, "release-keys", RELEASE_KEYS_FP, 1796200001, keyFile, certFile); + const releaseBytes = readFileSync(releaseZip); + const releaseForPilot: OsManifestWire = { + schema: 1, + product: "alpha_stallion_phone", + device: "stallion", + url: osArchiveUrl("alpha-os-release-1.zip", undefined, "os-pilot"), + sha256: sha256Hex(releaseBytes), + sizeBytes: releaseBytes.length, + buildFingerprint: RELEASE_KEYS_FP, + buildTimestamp: 1796200001, + }; + const releaseForPilotFile = join(work, "release-for-pilot.json"); + writeFileSync(releaseForPilotFile, encodeJson(releaseForPilot)); + + const livePilotBytes = encodeJson(livePilotManifest); + const pilotChannel = makeFakeOsChannel("os-pilot", { "alpha-os-update.json": livePilotBytes }); + const blockedPilotRun = ledger(Os, join(work, "blocked-pilot.json")); + const blockedPilot = await Effect.runPromiseExit( + publishOsRelease({ + run: blockedPilotRun, + port: pilotChannel.port, + ota: releaseZip, + manifestFile: releaseForPilotFile, + assetName: "alpha-os-release-1.zip", + manifest: releaseForPilot, + modelManifest: osManifestFacts(releaseForPilot, 0, true), + tag: "os-pilot", + }), + ); + expect(Exit.isFailure(blockedPilot)).toBe(true); + expect(failureMessage(blockedPilot)).toContain("refusing cross-key OS publication to os-pilot"); + expect(pilotChannel.uploaded).toEqual([]); + expect(sha256Hex(pilotChannel.files.get("alpha-os-update.json") ?? new Uint8Array())).toBe(sha256Hex(livePilotBytes)); + expect(blockedPilotRun.history).toEqual([]); + + const missingFpBytes = encodeJson({ ...livePilotManifest, buildFingerprint: undefined }); + const missingFpChannel = makeFakeOsChannel("os-pilot", { "alpha-os-update.json": missingFpBytes }); + const missingFpExit = await Effect.runPromiseExit( + publishOsRelease({ + run: ledger(Os, join(work, "missing-fp.json")), + port: missingFpChannel.port, + ota: releaseZip, + manifestFile: releaseForPilotFile, + assetName: "alpha-os-release-1.zip", + manifest: releaseForPilot, + modelManifest: osManifestFacts(releaseForPilot, 0, true), + tag: "os-pilot", + }), + ); + expect(Exit.isFailure(missingFpExit)).toBe(true); + expect(missingFpChannel.uploaded).toEqual([]); + + const testKeysZip = buildSignedOtaFixture(work, "test-keys-next", TEST_KEYS_FP_NEXT, 1796200002, keyFile, certFile); + const testKeysBytes = readFileSync(testKeysZip); + const testKeysManifest: OsManifestWire = { + schema: 1, + product: "alpha_stallion_phone", + device: "stallion", + url: osArchiveUrl("alpha-os-pilot-next.zip", undefined, "os-pilot"), + sha256: sha256Hex(testKeysBytes), + sizeBytes: testKeysBytes.length, + buildFingerprint: TEST_KEYS_FP_NEXT, + buildTimestamp: 1796200002, + }; + const testKeysManifestFile = join(work, "test-keys-next.json"); + writeFileSync(testKeysManifestFile, encodeJson(testKeysManifest)); + const pilotAllowed = await Effect.runPromiseExit( + publishOsRelease({ + run: ledger(Os, join(work, "pilot-same-key.json")), + port: pilotChannel.port, + ota: testKeysZip, + manifestFile: testKeysManifestFile, + assetName: "alpha-os-pilot-next.zip", + manifest: testKeysManifest, + modelManifest: osManifestFacts(testKeysManifest, 0, true), + tag: "os-pilot", + }), + ); + expect(Exit.isSuccess(pilotAllowed)).toBe(true); + expect(pilotChannel.uploaded).toEqual(["alpha-os-pilot-next.zip", "alpha-os-update.json"]); + + const stableManifest: OsManifestWire = { + ...releaseForPilot, + url: osArchiveUrl("alpha-os-release-1.zip", undefined, "os-stable"), + }; + const stableManifestFile = join(work, "release-for-stable.json"); + writeFileSync(stableManifestFile, encodeJson(stableManifest)); + const stableChannel = makeFakeOsChannel("os-stable"); + const stablePublished = await Effect.runPromiseExit( + publishOsRelease({ + run: ledger(Os, join(work, "stable-publish.json")), + port: stableChannel.port, + ota: releaseZip, + manifestFile: stableManifestFile, + assetName: "alpha-os-release-1.zip", + manifest: stableManifest, + modelManifest: osManifestFacts(stableManifest, 0, true), + tag: "os-stable", + }), + ); + expect(Exit.isSuccess(stablePublished)).toBe(true); + + const stableStatus = await Effect.runPromiseExit( + checkOsChannelStatus({ + port: stableChannel.port, + tag: "os-stable", + minTimestamp: 1796200001, + expectedCert: certSha, + expectedManifestSha256: sha256Hex(readFileSync(stableManifestFile)), + }), + ); + expect(Exit.isSuccess(stableStatus)).toBe(true); + + const reverseManifest: OsManifestWire = { + ...testKeysManifest, + url: osArchiveUrl("alpha-os-pilot-next.zip", undefined, "os-stable"), + buildTimestamp: 1796200099, + }; + const reverseManifestFile = join(work, "reverse-for-stable.json"); + writeFileSync(reverseManifestFile, encodeJson(reverseManifest)); + const reverseBlocked = await Effect.runPromiseExit( + publishOsRelease({ + run: ledger(Os, join(work, "reverse-blocked.json")), + port: stableChannel.port, + ota: testKeysZip, + manifestFile: reverseManifestFile, + assetName: "alpha-os-pilot-next.zip", + manifest: reverseManifest, + modelManifest: osManifestFacts(reverseManifest, 0, true), + tag: "os-stable", + }), + ); + expect(Exit.isFailure(reverseBlocked)).toBe(true); + expect(failureMessage(reverseBlocked)).toContain("refusing cross-key OS publication to os-stable"); + expect(stableChannel.uploaded).toEqual(["alpha-os-release-1.zip", "alpha-os-update.json"]); + }); + + it("refuses cross-key pilot publish and invalid tags at the release CLI boundary", async () => { + const work = makeWorkDir(); + const dummyOta = join(work, "dummy.zip"); + writeFileSync(dummyOta, "not-inspected-before-guard"); + const releaseManifest: OsManifestWire = { + schema: 1, + product: "alpha_stallion_phone", + device: "stallion", + url: osArchiveUrl("alpha-os-release-1.zip", undefined, "os-pilot"), + sha256: "2".repeat(64), + sizeBytes: 24, + buildFingerprint: RELEASE_KEYS_FP, + buildTimestamp: 1796200001, + }; + const manifestFile = join(work, "manifest.json"); + writeFileSync(manifestFile, encodeJson(releaseManifest)); + const emptyPilot = makeFakeOsChannel("os-pilot"); + + const cliExit = await Effect.runPromiseExit( + release( + [ + "os-publish", + "--run", + join(work, "cli-run.json"), + "--ota", + dummyOta, + "--manifest", + manifestFile, + "--tag", + "os-pilot", + "--enrollment", + PILOT_ENROLLMENT_PATH, + "--execute", + ], + emptyPilot.port, + ), + ); + expect(Exit.isFailure(cliExit)).toBe(true); + expect(failureMessage(cliExit)).toContain("rotatePlatformOrAVBKeys=false"); + expect(emptyPilot.uploaded).toEqual([]); + + const badTagExit = await Effect.runPromiseExit( + release( + [ + "os-publish", + "--run", + join(work, "bad-tag.json"), + "--ota", + dummyOta, + "--manifest", + manifestFile, + "--tag", + "app-stable-alphacompute", + ], + emptyPilot.port, + ), + ); + expect(Exit.isFailure(badTagExit)).toBe(true); + expect(failureMessage(badTagExit)).toContain("os-*"); + + const wrongTagUrlExit = await Effect.runPromiseExit( + release( + [ + "os-publish", + "--run", + join(work, "wrong-tag.json"), + "--ota", + dummyOta, + "--manifest", + manifestFile, + "--tag", + "os-stable", + ], + emptyPilot.port, + ), + ); + expect(Exit.isFailure(wrongTagUrlExit)).toBe(true); + expect(failureMessage(wrongTagUrlExit)).toContain("kept os-stable asset"); + }); + + it("wires channel_tag and pilot enrollment guard into release-os-ota-publish.yml", () => { + const workflow = readFileSync(PUBLISH_WORKFLOW_PATH, "utf8"); + expect(workflow).toContain("channel_tag:"); + expect(workflow).toContain('^os-[A-Za-z0-9][A-Za-z0-9._-]{0,124}$'); + expect(workflow).toContain('--tag "$OS_CHANNEL_TAG"'); + expect(workflow).toContain("--enrollment aosp/pilot-system-update-enrollment.json"); + }); +}); diff --git a/packages/cli/src/commands/pixel-bundle.ts b/packages/cli/src/commands/pixel-bundle.ts index 663853efa5..7758674167 100644 --- a/packages/cli/src/commands/pixel-bundle.ts +++ b/packages/cli/src/commands/pixel-bundle.ts @@ -157,8 +157,10 @@ export function pixelBundleInputs(input: { run: string; attempt: string; signAtt if (manifest.schema !== 1 || manifest.device !== "stallion" || manifest.product !== "alpha_stallion_phone" || !fingerprint.endsWith("/" + buildNumber + ":user/release-keys") || manifest.buildFingerprint !== fingerprint || manifest.sizeBytes !== ota.bytes || ota.bytes >= githubLimit) throw new Error("Signed OTA differs from the published manifest"); - const url = string(manifest.url, /^https:\/\/github\.com\/AlphaPhone\/alpha\/releases\/download\/os-pilot\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.zip$/, "canonical OTA URL"); - return { id, attempt, buildAttempt, signAttempt: expectedSignAttempt, source, version, buildNumber, fingerprint, apk, image, avb, ota: { ...ota, url } }; + const url = string(manifest.url, /^https:\/\/github\.com\/AlphaPhone\/alpha\/releases\/download\/(os-[A-Za-z0-9][A-Za-z0-9._-]{0,124})\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.zip$/, "canonical OTA URL"); + const otaTag = /^https:\/\/github\.com\/AlphaPhone\/alpha\/releases\/download\/(os-[A-Za-z0-9][A-Za-z0-9._-]{0,124})\//.exec(url)?.[1]; + if (!otaTag) throw new Error("Invalid canonical OTA URL"); + return { id, attempt, buildAttempt, signAttempt: expectedSignAttempt, source, version, buildNumber, fingerprint, apk, image, avb, ota: { ...ota, tag: otaTag, url } }; } async function transfer(from: AsyncIterable, size: number, dest?: string): Promise { @@ -295,7 +297,7 @@ async function finalize(dir: string, receipts: string, root: string, manifest: J } } if (checkOnly) return { version, source, osCI, tag: release.tag, signedOta: ota.sha256 }; - await anonymous("os-pilot", { name: path.posix.basename(ota.url), bytes: ota.bytes, sha256: ota.sha256 }); + await anonymous(ota.tag, { name: path.posix.basename(ota.url), bytes: ota.bytes, sha256: ota.sha256 }); const space = await statfs(dir, { bigint: true }); const needed = BigInt(apk.bytes + image.bytes + avb.bytes + Math.min(image.bytes, partBytes)); if (space.bavail * space.bsize < needed) throw new Error("Insufficient space for the signed downloads"); diff --git a/packages/cli/test/pixel-bundle-channel.test.ts b/packages/cli/test/pixel-bundle-channel.test.ts new file mode 100644 index 0000000000..fce636669e --- /dev/null +++ b/packages/cli/test/pixel-bundle-channel.test.ts @@ -0,0 +1,120 @@ +import { createHash } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { pixelBundleInputs } from "../src/commands/pixel-bundle.ts"; +import { pixelObjectPrefix, pixelOtaAttemptKey } from "../src/commands/pixel-release.ts"; + +const shaOf = (text: string) => createHash("sha256").update(text).digest("hex"); + +function bundleFixture(manifestUrl: string) { + const run = "901"; + const attempt = "1"; + const signAttempt = "1"; + const source = "a".repeat(40); + const sdk = "b".repeat(40); + const inventory = "c".repeat(64); + const avbSha = shaOf("enrolled-avb-key"); + const apkSha = shaOf("launcher-apk"); + const imageSha = shaOf("fastboot-image"); + const otaSha = shaOf("release-keys-ota"); + const buildNumber = `alpha.${run}.${attempt}`; + const fingerprint = `Alpha/alpha_stallion_phone/stallion:17/CP2A.260605.016/${buildNumber}:user/release-keys`; + const prefix = `${pixelObjectPrefix("release", run, attempt, signAttempt)}/sign/`; + const otaKey = pixelOtaAttemptKey(run, attempt, signAttempt); + return { + run, + attempt, + signAttempt, + source, + sdk, + inventory, + avbSha, + delivery: { + bucket: "alpha-aosp-lab-20261024-private-apks", + object: "delivered/55-1/alpha-phone-1400.apk", + generation: "11", + bytes: 2048, + sha256: apkSha, + number: 1400, + public: false, + }, + build: { + schema: "alpha-pixel-build/v1", + commit: source, + sdkCommit: sdk, + run, + attempt, + buildNumber, + sourceLockSha256: inventory, + launcherSha256: apkSha, + }, + sign: { + schema: "alpha-pixel-signing/v1", + commit: source, + sdkCommit: sdk, + run, + attempt, + buildNumber, + fingerprint, + launcherSha256: apkSha, + image: { + bucket: "alpha-aosp-lab-20261024-private-apks", + object: `${prefix}fastboot-image.zip`, + generation: "12", + bytes: 4096, + sha256: imageSha, + }, + avb: { + bucket: "alpha-aosp-lab-20261024-private-apks", + object: `${prefix}avb_pkmd.bin`, + generation: "13", + bytes: 1024, + sha256: avbSha, + }, + ota: { + bucket: "alpha-aosp-lab-20261024-private-apks", + object: `signed/os-ota/${otaSha}/${otaKey}/ota.zip`, + generation: "14", + bytes: 8192, + sha256: otaSha, + }, + }, + manifest: { + schema: 1, + product: "alpha_stallion_phone", + device: "stallion", + url: manifestUrl, + sha256: otaSha, + sizeBytes: 8192, + buildFingerprint: fingerprint, + buildTimestamp: 1796100001, + }, + }; +} + +describe("pixel-bundle OS channel tag validation", () => { + it("accepts dedicated os-* production tags as well as os-pilot", () => { + const stable = pixelBundleInputs( + bundleFixture("https://github.com/AlphaPhone/alpha/releases/download/os-stable/alpha-os-901-1.zip"), + ); + expect(stable.ota.tag).toBe("os-stable"); + expect(stable.ota.url).toBe("https://github.com/AlphaPhone/alpha/releases/download/os-stable/alpha-os-901-1.zip"); + + const pilot = pixelBundleInputs( + bundleFixture("https://github.com/AlphaPhone/alpha/releases/download/os-pilot/alpha-os-901-1.zip"), + ); + expect(pilot.ota.tag).toBe("os-pilot"); + }); + + it("rejects non-OS channel tags and malformed download URLs", () => { + const badUrls = [ + "https://github.com/AlphaPhone/alpha/releases/download/app-stable-alphacompute/alpha-os-901-1.zip", + "https://github.com/AlphaPhone/alpha/releases/download/alpha-v1400/alpha-os-901-1.zip", + "https://github.com/AlphaPhone/alpha/releases/download/os-/alpha-os-901-1.zip", + "https://github.com/AlphaPhone/alpha/releases/download/os-stable/nested/alpha-os-901-1.zip", + "https://example.com/AlphaPhone/alpha/releases/download/os-stable/alpha-os-901-1.zip", + ]; + for (const url of badUrls) { + expect(() => pixelBundleInputs(bundleFixture(url)), url).toThrow(/canonical OTA URL/); + } + }); +});