Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitattributes

This file was deleted.

24 changes: 24 additions & 0 deletions .github/actions/setup-android-helper-signing/action.yml
Original file line number Diff line number Diff line change
@@ -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"
2 changes: 1 addition & 1 deletion .github/actions/setup-android-replay-host/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 13 additions & 5 deletions .github/workflows/release-android-snapshot-helper.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Comment thread
thymikee marked this conversation as resolved.
Resolved
with:
ref: ${{ inputs.checkout_ref || github.ref }}
ref: ${{ github.ref }}

- name: Checkout release validator
uses: useblacksmith/checkout@2b9fe87d796feea153b455ec2f3125b471a7b0e7 # v1.8.2
Expand Down Expand Up @@ -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
Expand All @@ -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}"
Expand Down
18 changes: 17 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions android/snapshot-helper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Binary file removed android/snapshot-helper/debug.keystore
Binary file not shown.
48 changes: 48 additions & 0 deletions packages/platform-android/src/__tests__/ime-helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
58 changes: 49 additions & 9 deletions packages/platform-android/src/helper-package-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<AndroidAdbExecutorResult> {
Expand All @@ -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<AndroidAdbExecutorResult> {
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;
Expand Down Expand Up @@ -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, {
Expand Down
34 changes: 34 additions & 0 deletions packages/platform-android/src/ime-activation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
18 changes: 15 additions & 3 deletions packages/platform-android/src/ime-activation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType<typeof selectAndroidImeHelperArtifact>>;
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);
}
Expand All @@ -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({
Expand Down Expand Up @@ -243,10 +253,12 @@ async function claimAlreadyActiveTestIme(
function activationRestoreTarget(
record: Exclude<AndroidTestImeDeviceRecord, { kind: 'unreadable' }>,
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,
};
}
Loading
Loading