diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 97f89d64f66..00000000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -android/snapshot-helper/debug.keystore binary diff --git a/.github/actions/setup-android-helper-signing/action.yml b/.github/actions/setup-android-helper-signing/action.yml new file mode 100644 index 00000000000..d8e42e2a7c6 --- /dev/null +++ b/.github/actions/setup-android-helper-signing/action.yml @@ -0,0 +1,24 @@ +name: Setup Android helper signing +description: Exports the release keystore path that scripts/build-android-helper.sh signs with. The signing step passes the password itself. +inputs: + keystore-base64: + description: Base64 of the release keystore. + required: false + keystore-password: + description: Password of the release keystore and its key. + required: false +runs: + using: composite + steps: + - shell: bash + env: + KEYSTORE_BASE64: ${{ inputs.keystore-base64 }} + KEYSTORE_PASSWORD: ${{ inputs.keystore-password }} + run: | + set -euo pipefail + if [ -z "$KEYSTORE_BASE64" ] || [ -z "$KEYSTORE_PASSWORD" ]; then + echo "::error::Release builds need the ANDROID_HELPER_KEYSTORE_BASE64 and ANDROID_HELPER_KEYSTORE_PASSWORD secrets." + exit 1 + fi + printf '%s' "$KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/android-helper.keystore" + echo "AGENT_DEVICE_ANDROID_KEYSTORE=$RUNNER_TEMP/android-helper.keystore" >> "$GITHUB_ENV" diff --git a/.github/actions/setup-android-replay-host/action.yml b/.github/actions/setup-android-replay-host/action.yml index 3db790a624f..22c22574094 100644 --- a/.github/actions/setup-android-replay-host/action.yml +++ b/.github/actions/setup-android-replay-host/action.yml @@ -36,7 +36,7 @@ runs: run: | VERSION="$(node -p 'require("./package.json").version')" echo "version=$VERSION" >> "$GITHUB_OUTPUT" - echo "value=${{ hashFiles('android/snapshot-helper/AndroidManifest.xml', 'android/snapshot-helper/debug.keystore', 'android/snapshot-helper/src/**', 'android/ime-helper/AndroidManifest.xml', 'android/ime-helper/res/**', 'android/ime-helper/src/**', 'scripts/build-android-helper.sh', 'scripts/package-android-helper.sh', '.github/actions/setup-android-replay-host/action.yml', '.github/actions/setup-android-sdk/action.yml') }}" >> "$GITHUB_OUTPUT" + echo "value=${{ hashFiles('android/snapshot-helper/AndroidManifest.xml', 'android/snapshot-helper/src/**', 'android/ime-helper/AndroidManifest.xml', 'android/ime-helper/res/**', 'android/ime-helper/src/**', 'scripts/build-android-helper.sh', 'scripts/package-android-helper.sh', '.github/actions/setup-android-replay-host/action.yml', '.github/actions/setup-android-sdk/action.yml') }}" >> "$GITHUB_OUTPUT" shell: bash # The helper build refuses to guess its build-tools version on CI, and that version decides diff --git a/.github/workflows/release-android-snapshot-helper.yml b/.github/workflows/release-android-snapshot-helper.yml index b87afd6f2f7..c6d1437579c 100644 --- a/.github/workflows/release-android-snapshot-helper.yml +++ b/.github/workflows/release-android-snapshot-helper.yml @@ -14,10 +14,6 @@ on: description: GitHub Release tag to upload assets to, for example v0.13.3. required: true type: string - checkout_ref: - description: Optional branch, tag, or commit SHA to build. Defaults to the selected workflow ref. - required: false - type: string permissions: contents: write @@ -27,11 +23,16 @@ jobs: name: Publish Android Snapshot Helper runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 30 + # The helper keystore secrets live only in the protected `release` environment. Its deployment + # rule gates github.ref, so the job builds exactly that ref. + environment: release + env: + AGENT_DEVICE_ANDROID_HELPER_RELEASE: '1' steps: - name: Checkout uses: useblacksmith/checkout@2b9fe87d796feea153b455ec2f3125b471a7b0e7 # v1.8.2 with: - ref: ${{ inputs.checkout_ref || github.ref }} + ref: ${{ github.ref }} - name: Checkout release validator uses: useblacksmith/checkout@2b9fe87d796feea153b455ec2f3125b471a7b0e7 # v1.8.2 @@ -64,6 +65,12 @@ jobs: - name: Setup Android SDK uses: ./.github/actions/setup-android-sdk + - name: Setup Android helper signing + uses: ./.github/actions/setup-android-helper-signing + with: + keystore-base64: ${{ secrets.ANDROID_HELPER_KEYSTORE_BASE64 }} + keystore-password: ${{ secrets.ANDROID_HELPER_KEYSTORE_PASSWORD }} + - name: Check Java toolchain run: | javac --version @@ -76,6 +83,7 @@ jobs: RELEASE_VERSION: ${{ steps.meta.outputs.version }} RELEASE_TAG: ${{ steps.meta.outputs.tag }} AGENT_DEVICE_ANDROID_HELPER: snapshot + AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_HELPER_KEYSTORE_PASSWORD }} run: | set -euo pipefail mkdir -p "${RELEASE_ASSET_DIR}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d894944efd3..58b0daef705 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -85,8 +85,12 @@ jobs: permissions: contents: read cache-mode: none + # The helper keystore secrets live only in the protected `release` environment, so PR dry + # runs never receive them and sign with a throwaway key. + environment: ${{ needs.plan.outputs.mode != 'dry-run' && 'release' || '' }} env: VERSION: ${{ needs.plan.outputs.version }} + AGENT_DEVICE_ANDROID_HELPER_RELEASE: ${{ needs.plan.outputs.mode != 'dry-run' && '1' || '' }} steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -100,7 +104,9 @@ jobs: persist-credentials: false ref: ${{ github.workflow_sha }} path: .release-tools - sparse-checkout: scripts/release-version.mjs + sparse-checkout: | + scripts/release-version.mjs + .github/actions/setup-android-helper-signing/action.yml sparse-checkout-cone-mode: false # No dependency cache: published bytes come from a clean install. @@ -113,10 +119,20 @@ jobs: - name: Setup Android SDK uses: ./.github/actions/setup-android-sdk + - name: Setup Android helper signing + if: needs.plan.outputs.mode != 'dry-run' + # From the workflow commit: the planned nightly source may predate this action. + uses: ./.release-tools/.github/actions/setup-android-helper-signing + with: + keystore-base64: ${{ secrets.ANDROID_HELPER_KEYSTORE_BASE64 }} + keystore-password: ${{ secrets.ANDROID_HELPER_KEYSTORE_PASSWORD }} + - name: Stamp release version run: node .release-tools/scripts/release-version.mjs stamp "$VERSION" - name: Build and verify every public package + env: + AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_HELPER_KEYSTORE_PASSWORD }} run: pnpm release:prepare - name: Upload packages diff --git a/android/snapshot-helper/README.md b/android/snapshot-helper/README.md index 33643d3eb4d..40cb1ebfee2 100644 --- a/android/snapshot-helper/README.md +++ b/android/snapshot-helper/README.md @@ -8,8 +8,8 @@ unavailable, it falls back to the active-window root. The helper is intentionally provider-neutral. Local `adb`, cloud ADB tunnels, and remote device providers can all install and run the same APK as long as they can execute ADB-style operations. -Released helper APKs use the committed `debug.keystore`; do not rotate it casually, because Android -requires a stable signing certificate for `adb install -r` upgrades. +Release helper APKs are signed from the `ANDROID_HELPER_KEYSTORE_BASE64` and +`ANDROID_HELPER_KEYSTORE_PASSWORD` secrets. Other builds use a throwaway key under `.tmp`. ## Accessibility services diff --git a/android/snapshot-helper/debug.keystore b/android/snapshot-helper/debug.keystore deleted file mode 100644 index e61a744020d..00000000000 Binary files a/android/snapshot-helper/debug.keystore and /dev/null differ diff --git a/packages/platform-android/src/__tests__/ime-helper.test.ts b/packages/platform-android/src/__tests__/ime-helper.test.ts index 48b7dfd9298..1f224feff67 100644 --- a/packages/platform-android/src/__tests__/ime-helper.test.ts +++ b/packages/platform-android/src/__tests__/ime-helper.test.ts @@ -119,6 +119,54 @@ test('ensureAndroidImeHelper installs with semantic provider install options', a assert.deepEqual(installCalls, [{ apkPath, replace: true }]); }); +test('ensureAndroidImeHelper uninstalls then reinstalls a helper signed with another key', async () => { + const tmpDir = await mkdtempForTest('ime-helper-incompatible-'); + const apkPath = path.join(tmpDir, 'helper.apk'); + await fs.writeFile(apkPath, 'helper-apk'); + const calls: string[] = []; + const adb: AndroidAdbExecutor = async (args) => { + if (args.join(' ').includes('dumpsys package')) { + return { + exitCode: 0, + stdout: `Package [${manifest.packageName}] (0):\n versionCode=${manifest.versionCode - 1}`, + stderr: '', + }; + } + if (args[0] === 'uninstall') calls.push(`uninstall ${args[1]}`); + if (isImeListCall(args)) { + return { exitCode: 0, stdout: `${manifest.serviceComponent}\n`, stderr: '' }; + } + return { exitCode: 0, stdout: '', stderr: '' }; + }; + let attempts = 0; + const adbProvider: AndroidAdbProvider = { + exec: adb, + install: async () => { + calls.push('install'); + attempts += 1; + // The transport classified the failure before redacting its output. + return attempts === 1 + ? { + exitCode: 1, + stdout: '', + stderr: '[redacted]', + failure: { reason: 'install_update_incompatible', hint: '' }, + } + : { exitCode: 0, stdout: '', stderr: '' }; + }, + }; + + const result = await ensureAndroidImeHelper({ + adb, + adbProvider, + artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } }, + deviceKey: 'android:emulator-5554', + }); + + assert.equal(result.installed, true); + assert.deepEqual(calls, ['install', `uninstall ${manifest.packageName}`, 'install']); +}); + test('ensureAndroidImeHelper replaces a newer installed version with the trusted artifact', async () => { const tmpDir = await mkdtempForTest('ime-helper-newer-'); const apkPath = path.join(tmpDir, 'helper.apk'); diff --git a/packages/platform-android/src/helper-package-install.ts b/packages/platform-android/src/helper-package-install.ts index e9ab89e0b2a..7a4b2db1a8d 100644 --- a/packages/platform-android/src/helper-package-install.ts +++ b/packages/platform-android/src/helper-package-install.ts @@ -11,7 +11,7 @@ import { type AndroidAdbProvider, } from './adb-executor.ts'; import type { AndroidAdbPackageInstallOptions } from './adb-transfer.ts'; -import { attachAndroidHelperInstallTimeoutHint } from './adb-failure.ts'; +import { attachAndroidHelperInstallTimeoutHint, classifyAndroidAdbFailure } from './adb-failure.ts'; import { requireAndroidAdbHost } from './adb-host.ts'; import { ANDROID_HELPER_INSTALL_STATE_REASONS, @@ -30,7 +30,7 @@ const ANDROID_HELPER_IDENTITY_TIMEOUT_MS = 10_000; * install-specific hint wherever a helper is pushed on. Non-timeout failures pass through * exactly as the transfer layer classified them; app installs keep their own advice. */ -export async function installAndroidHelperPackage( +async function installAndroidHelperPackage( apkPath: string, options?: AndroidAdbPackageInstallOptions, ): Promise { @@ -41,6 +41,51 @@ export async function installAndroidHelperPackage( } } +/** + * Installs a helper over the installed one. `install -r` refuses a versionCode downgrade, so a + * newer helper is removed first. A helper signed with another key cannot be updated in place, so + * it is removed and the install runs once more. + */ +export async function installAndroidHelperReplacingInstalled( + adb: AndroidAdbExecutor, + apkPath: string, + packageName: string, + options: AndroidAdbPackageInstallOptions & { uninstallFirst: boolean }, +): Promise { + const { uninstallFirst, ...installOptions } = options; + const uninstall = async () => + await adb(['uninstall', packageName], { + allowFailure: true, + timeoutMs: options.timeoutMs, + signal: options.signal, + }); + const install = async () => + await installAndroidHelperPackage(apkPath, { + ...installOptions, + replace: true, + allowFailure: true, + }); + if (uninstallFirst) await uninstall(); + const result = await install(); + const failure = + result.failure === undefined + ? classifyAndroidAdbFailure(result.stderr, result.stdout) + : result.failure; + if (result.exitCode === 0 || failure?.reason !== 'install_update_incompatible') return result; + const uninstalled = await uninstall(); + const retry = await install(); + if (retry.exitCode === 0 || !uninstalled.stderr) return retry; + return { + ...retry, + stderr: [ + retry.stderr, + `Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${uninstalled.stderr}`, + ] + .filter(Boolean) + .join('\n'), + }; +} + async function ensureAndroidHelperPackageInstalled(options: { adb: AndroidAdbExecutor; adbProvider: AndroidAdbProvider; @@ -103,15 +148,10 @@ async function ensureAndroidHelperPackageInstalled(options: { }; } - // `install -r` refuses a versionCode downgrade, so a newer helper is removed first. - if (state.reason === ANDROID_HELPER_INSTALL_STATE_REASONS.newer.reason) { - await adb(['uninstall', packageName], { allowFailure: true, timeoutMs: installTimeoutMs }); - } - const result = await installAndroidHelperPackage(apkPath, { + const result = await installAndroidHelperReplacingInstalled(adb, apkPath, packageName, { provider: adbProvider, - replace: true, - allowFailure: true, timeoutMs: installTimeoutMs, + uninstallFirst: state.reason === ANDROID_HELPER_INSTALL_STATE_REASONS.newer.reason, }); if (result.exitCode !== 0) { throw androidAdbResultError(`Failed to install ${helperLabel}`, result, { diff --git a/packages/platform-android/src/ime-activation.test.ts b/packages/platform-android/src/ime-activation.test.ts index 3e240bcd118..631c866c77a 100644 --- a/packages/platform-android/src/ime-activation.test.ts +++ b/packages/platform-android/src/ime-activation.test.ts @@ -234,3 +234,37 @@ test('activation claims ownership before settling an earlier rebind record', asy expect(state.settings.get('default_input_method')).toBe(HELPER_SERVICE); expect(getAndroidTestImeOwnership(DEVICE)?.rebindUnconfirmed).toBe(true); }); + +test('a reinstall that displaces the active helper keeps the recorded user keyboard', async () => { + const state: FakeImeDeviceState = { + settings: new Map([ + ['default_input_method', HELPER_SERVICE], + ['agent_device_ime_helper_previous_ime', 'com.samsung/.Keyboard'], + ]), + }; + bindAndroidAdbHostStub({ + // An incompatible-signature reinstall uninstalls the helper, so Android falls back. + ensureHelperInstalled: async (_config, request) => { + state.settings.set('default_input_method', 'com.android.inputmethod.latin/.LatinIME'); + return { + packageName: request.artifact.manifest.packageName, + versionCode: request.artifact.manifest.versionCode, + installed: true, + reason: 'mismatched', + }; + }, + }); + + const deviceAdb = fakeImeDeviceAdb(state); + + const result = await withDeviceAdb( + async (args) => + args[2] === 'list' + ? { exitCode: 0, stdout: `${HELPER_SERVICE}\n`, stderr: '' } + : await deviceAdb(args), + async () => await activateAndroidTestIme(DEVICE, { stateDir: STATE_DIR }), + ); + + expect(result).toMatchObject({ activated: true, previousIme: 'com.samsung/.Keyboard' }); + expect(state.settings.get('agent_device_ime_helper_previous_ime')).toBe('com.samsung/.Keyboard'); +}); diff --git a/packages/platform-android/src/ime-activation.ts b/packages/platform-android/src/ime-activation.ts index 182740a1070..1574129cc1c 100644 --- a/packages/platform-android/src/ime-activation.ts +++ b/packages/platform-android/src/ime-activation.ts @@ -82,11 +82,17 @@ async function activateAndroidTestImeAfterStartupRecovery( const adbProvider = resolveAndroidAdbProvider(device); const deviceKey = getAndroidImeHelperDeviceKey(device); + // Reinstalling the active helper lets Android pick a fallback keyboard, which must not + // replace the recorded user keyboard as the restore target. + const imeBeforeInstall = await readAndroidDefaultInputMethod(adb); // The acquisition seam, and the only step whose failure is an outcome rather than a rejection. let artifact: Awaited>; + let helperDisplacedByInstall: boolean; try { artifact = await selectAndroidImeHelperArtifact(adbProvider); - await ensureAndroidImeHelper({ adb, adbProvider, artifact, deviceKey }); + const helperWasActive = imeBeforeInstall === artifact.manifest.serviceComponent; + const decision = await ensureAndroidImeHelper({ adb, adbProvider, artifact, deviceKey }); + helperDisplacedByInstall = helperWasActive && decision.installed; } catch (error) { return androidTestImeUnavailableOutcome(error); } @@ -113,7 +119,11 @@ async function activateAndroidTestImeAfterStartupRecovery( helperPackageName: manifest.packageName, }; } - const { previousIme, priorPersistedIme } = activationRestoreTarget(record, currentIme); + const { previousIme, priorPersistedIme } = activationRestoreTarget( + record, + currentIme, + helperDisplacedByInstall, + ); if (!(await writePersistedPreviousIme(adb, previousIme))) { await restorePriorPersistedIme(adb, priorPersistedIme, device.id); emitAndroidAdbDiagnostic({ @@ -243,10 +253,12 @@ async function claimAlreadyActiveTestIme( function activationRestoreTarget( record: Exclude, currentIme: string, + helperDisplacedByInstall: boolean, ): { previousIme: string; priorPersistedIme: string | undefined } { if (record.kind === 'absent') return { previousIme: currentIme, priorPersistedIme: undefined }; return { - previousIme: record.rebindDisplaced ? record.previousIme : currentIme, + previousIme: + record.rebindDisplaced || helperDisplacedByInstall ? record.previousIme : currentIme, priorPersistedIme: record.previousIme, }; } diff --git a/packages/platform-android/src/snapshot-helper-install.ts b/packages/platform-android/src/snapshot-helper-install.ts index 37228f5d557..dea4d0261f6 100644 --- a/packages/platform-android/src/snapshot-helper-install.ts +++ b/packages/platform-android/src/snapshot-helper-install.ts @@ -1,7 +1,7 @@ import { AppError, asAppError, type ReasonTable } from '@agent-device/kernel/errors'; import { inspectInstalledAndroidHelper, - installAndroidHelperPackage, + installAndroidHelperReplacingInstalled, readAndroidHelperBaseApkPath, readInstalledAndroidHelperVersionCode, verifyAndroidHelperApkChecksum, @@ -157,8 +157,8 @@ export async function ensureAndroidSnapshotHelper(options: { let result: Awaited>; try { - result = await installAndroidSnapshotHelper(adb, options.adbProvider ?? adb, artifact.apkPath, { - packageName, + result = await installAndroidHelperReplacingInstalled(adb, artifact.apkPath, packageName, { + provider: options.adbProvider ?? adb, uninstallFirst: reason === ANDROID_HELPER_INSTALL_STATE_REASONS.newer.reason || (installedVersionCode !== undefined && installedVersionCode > versionCode), @@ -210,59 +210,3 @@ function normalizeAdbProvider( if (!provider) return { exec: adb }; return typeof provider === 'function' ? { exec: provider } : provider; } - -async function installAndroidSnapshotHelper( - adb: AndroidAdbExecutor, - adbProvider: AndroidAdbProvider | AndroidAdbExecutor, - apkPath: string, - options: { - packageName: string; - /** `install -r` refuses a versionCode downgrade, so a newer helper is removed first. */ - uninstallFirst: boolean; - timeoutMs?: number; - signal?: AbortSignal; - }, -): Promise>> { - const uninstall = async () => - await adb(['uninstall', options.packageName], { - allowFailure: true, - timeoutMs: options.timeoutMs, - signal: options.signal, - }); - if (options.uninstallFirst) await uninstall(); - const install = async () => - await installAndroidHelperPackage(apkPath, { - allowFailure: true, - provider: adbProvider, - replace: true, - timeoutMs: options.timeoutMs, - signal: options.signal, - }); - - const result = await install(); - if (result.exitCode === 0 || !isInstallUpdateIncompatible(result)) { - return result; - } - - const uninstalled = await uninstall(); - const retry = await install(); - if (retry.exitCode === 0) { - return retry; - } - - return { - ...retry, - stderr: [ - retry.stderr, - uninstalled.stderr - ? `Previous uninstall stderr after INSTALL_FAILED_UPDATE_INCOMPATIBLE: ${uninstalled.stderr}` - : '', - ] - .filter(Boolean) - .join('\n'), - }; -} - -function isInstallUpdateIncompatible(result: { stdout: string; stderr: string }): boolean { - return `${result.stdout}\n${result.stderr}`.includes('INSTALL_FAILED_UPDATE_INCOMPATIBLE'); -} diff --git a/scripts/build-android-helper.sh b/scripts/build-android-helper.sh index 2b360f2b35e..54d33997d05 100755 --- a/scripts/build-android-helper.sh +++ b/scripts/build-android-helper.sh @@ -20,7 +20,6 @@ BUILD_TOOLS_VERSION="${3:-${AGENT_DEVICE_ANDROID_BUILD_TOOLS:-}}" PROJECT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" MIN_SDK=23 TARGET_SDK=36 -KEYSTORE="$PROJECT_DIR/android/snapshot-helper/debug.keystore" # Per-helper config: HELPER_DIR/PACKAGE_NAME/APK name always differ; RUN_TEST_CLASS is # only set for the snapshot helper (it has a unit test to compile+run); RESOURCE_DIR is @@ -173,15 +172,29 @@ zip -q -j "$UNSIGNED_APK" "$DEX_DIR/classes.dex" "$BUILD_TOOLS_DIR/zipalign" -f 4 "$UNSIGNED_APK" "$ALIGNED_APK" -if [ ! -f "$KEYSTORE" ]; then - echo "Missing Android helper signing keystore: $KEYSTORE" >&2 +# Release builds sign with the keystore the caller supplies. A publishing job sets +# AGENT_DEVICE_ANDROID_HELPER_RELEASE=1, and then a missing keystore fails the build. Any other +# build gets a throwaway key that only this checkout holds, so its APK is never accepted as a +# release update. +if [ -n "${AGENT_DEVICE_ANDROID_KEYSTORE:-}" ]; then + KEYSTORE="$AGENT_DEVICE_ANDROID_KEYSTORE" + KEYSTORE_PASSWORD="${AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD:?AGENT_DEVICE_ANDROID_KEYSTORE_PASSWORD is required with AGENT_DEVICE_ANDROID_KEYSTORE}" +elif [ "${AGENT_DEVICE_ANDROID_HELPER_RELEASE:-}" = "1" ]; then + echo "AGENT_DEVICE_ANDROID_HELPER_RELEASE=1 requires AGENT_DEVICE_ANDROID_KEYSTORE: a published helper never uses a throwaway key." >&2 exit 1 +else + KEYSTORE="$PROJECT_DIR/.tmp/android-helper-dev.keystore" + KEYSTORE_PASSWORD="android" + if [ ! -f "$KEYSTORE" ]; then + mkdir -p "$(dirname "$KEYSTORE")" + keytool -genkeypair -keystore "$KEYSTORE" -storepass "$KEYSTORE_PASSWORD" -keypass "$KEYSTORE_PASSWORD" \ + -alias helper -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=agent-device dev helper" >&2 + fi fi -"$BUILD_TOOLS_DIR/apksigner" sign \ +AGENT_DEVICE_KEYSTORE_PASSWORD="$KEYSTORE_PASSWORD" "$BUILD_TOOLS_DIR/apksigner" sign \ --ks "$KEYSTORE" \ - --ks-pass pass:android \ - --key-pass pass:android \ + --ks-pass env:AGENT_DEVICE_KEYSTORE_PASSWORD \ --out "$APK_PATH" \ "$ALIGNED_APK" diff --git a/test/ci/release-workflow.test.ts b/test/ci/release-workflow.test.ts index d4e9df6b950..808368a250b 100644 --- a/test/ci/release-workflow.test.ts +++ b/test/ci/release-workflow.test.ts @@ -10,6 +10,7 @@ type Job = { 'cache-mode'?: string; 'runs-on'?: string; environment?: string; + env?: Record; permissions?: Record; steps?: Array<{ id?: string; @@ -40,19 +41,31 @@ test('only the npm publisher and the MCP Registry call can mint an id-token', () }); /** The secret names a job references, wherever in the job they appear. */ -const secretsOf = (job: Job) => - [...JSON.stringify(job).matchAll(/secrets\.([A-Za-z0-9_]+)/g)].map(([, name]) => name); +const secretsOf = (job: Job) => [ + ...new Set( + [...JSON.stringify(job).matchAll(/secrets\.([A-Za-z0-9_]+)/g)].map(([, name]) => name), + ), +]; test('the publisher authenticates through OIDC alone', () => { expect(source).not.toMatch(/NPM_TOKEN|NODE_AUTH_TOKEN/); - // No secret reaches the jobs that build or publish the packages. The one secret in the file - // is the site's deploy hook, which only the redeploy job after a stable release reads. + // No secret reaches the publisher. The build reads only the Android helper keystore, and only + // in the protected `release` environment that PR dry runs never enter. The site's deploy hook + // is read only by the redeploy job after a stable release. expect(secretsOf(workflow.jobs.publish ?? {})).toEqual([]); - expect(secretsOf(workflow.jobs.build ?? {})).toEqual([]); + expect(workflow.jobs.build?.environment).toBe( + "${{ needs.plan.outputs.mode != 'dry-run' && 'release' || '' }}", + ); + expect(workflow.jobs.build?.env?.AGENT_DEVICE_ANDROID_HELPER_RELEASE).toBe( + "${{ needs.plan.outputs.mode != 'dry-run' && '1' || '' }}", + ); const withSecrets = Object.entries(workflow.jobs) .map(([name, job]) => [name, secretsOf(job)] as const) .filter(([, names]) => names.length > 0); - expect(withSecrets).toEqual([['redeploy-site', ['VERCEL_SITE_DEPLOY_HOOK']]]); + expect(withSecrets).toEqual([ + ['build', ['ANDROID_HELPER_KEYSTORE_BASE64', 'ANDROID_HELPER_KEYSTORE_PASSWORD']], + ['redeploy-site', ['VERCEL_SITE_DEPLOY_HOOK']], + ]); const setupNode = workflow.jobs.publish?.steps?.find((step) => step.uses?.startsWith('actions/setup-node@'), ); @@ -88,6 +101,9 @@ test('the version stamping entrypoint is pinned to the workflow commit', () => { (step) => step.with?.path === '.release-tools', ); expect(entrypoint?.with?.ref).toBe('${{ github.workflow_sha }}'); + expect( + workflow.jobs.build?.steps?.find((step) => step.name === 'Setup Android helper signing')?.uses, + ).toBe('./.release-tools/.github/actions/setup-android-helper-signing'); }); test('both nightly schedules keep separate concurrency groups for cron and manual selection', () => { diff --git a/test/repo-guards/release-assets.test.ts b/test/repo-guards/release-assets.test.ts index c75768bc275..5f60c7fcc0f 100644 --- a/test/repo-guards/release-assets.test.ts +++ b/test/repo-guards/release-assets.test.ts @@ -105,6 +105,7 @@ function androidBuildFixture(helper: 'snapshot' | 'ime') { f.tool('javac', ':'); f.tool('java', ':'); f.tool('zip', ':'); + f.tool('keytool', ':'); f.tool( 'd8', `while [ "$#" -gt 0 ]; do @@ -140,9 +141,6 @@ printf signed > "$output"`, for (const name of ['aapt2', 'd8', 'zipalign', 'apksigner']) { fs.symlinkSync(path.join(f.env.PATH, name), path.join(buildTools, name)); } - const snapshot = path.join(f.root, 'android', 'snapshot-helper'); - fs.mkdirSync(snapshot, { recursive: true }); - fs.writeFileSync(path.join(snapshot, 'debug.keystore'), ''); for (const sourceSet of ['main', 'test']) { fs.mkdirSync(path.join(f.root, 'android', `${helper}-helper`, 'src', sourceSet, 'java'), { recursive: true, @@ -197,6 +195,7 @@ for (const workflow of workflows) { const repositories: Record> = { caller: { '${{ inputs.checkout_ref || github.ref }}': historical, + '${{ github.ref }}': historical, '${{ github.workflow_sha }}': historical, '${{ job.workflow_sha }}': historical, }, @@ -345,3 +344,16 @@ for (const helper of ['snapshot', 'ime'] as const) { }); } } + +test('a publishing helper build without a release keystore fails instead of using a throwaway key', () => { + const f = androidBuildFixture('snapshot'); + const result = run( + f.root, + { ...f.env, AGENT_DEVICE_ANDROID_HELPER_RELEASE: '1' }, + path.join(f.scripts, 'build-android-helper.sh'), + ['1.2.3', path.join(f.root, 'output')], + ); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /requires AGENT_DEVICE_ANDROID_KEYSTORE/); + assert.equal(fs.existsSync(path.join(f.root, '.tmp', 'android-helper-dev.keystore')), false); +});