From f351a5a9bf3d354adcabcf058a00634624fd4c62 Mon Sep 17 00:00:00 2001 From: parbez Date: Thu, 26 Nov 2026 12:22:02 +0530 Subject: [PATCH 1/2] perf(android): batch pm calls for settings permission all --- .../__tests__/settings-permission-all.test.ts | 549 ++++++++++++++++++ .../src/__tests__/settings-permission.test.ts | 279 +++++---- .../test-utils/fake-android-pm-shell.ts | 76 +++ .../src/settings-permission-batch.ts | 209 +++++++ .../src/settings-permission.ts | 179 +++++- 5 files changed, 1140 insertions(+), 152 deletions(-) create mode 100644 packages/platform-android/src/__tests__/settings-permission-all.test.ts create mode 100644 packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts create mode 100644 packages/platform-android/src/settings-permission-batch.ts diff --git a/packages/platform-android/src/__tests__/settings-permission-all.test.ts b/packages/platform-android/src/__tests__/settings-permission-all.test.ts new file mode 100644 index 0000000000..e9b41d48b5 --- /dev/null +++ b/packages/platform-android/src/__tests__/settings-permission-all.test.ts @@ -0,0 +1,549 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { AppError } from '@agent-device/kernel/errors'; +import { bindAndroidAdbHostStub } from '../adb-host.fixtures.ts'; +import { + androidRevokedPermissionWarning, + parseAndroidPermissionRequest, + setAndroidPermission, +} from '../settings-permission.ts'; +import { + androidPmBatchTimeoutMs, + buildAndroidPmBatchScript, + chunkAndroidPmBatch, + parseAndroidPmBatchOutput, +} from '../settings-permission-batch.ts'; +import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts'; +import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts'; +import { withFakeAdb } from './test-utils/fake-adb.ts'; +import { + isAndroidPmBatchShellArgs, + runFakeAndroidPmBatchInSh, + type FakePmReply, +} from './test-utils/fake-android-pm-shell.ts'; + +const DUMPSYS = 'shell dumpsys package com.example.app'; + +function makeDumpsys( + requested: readonly string[], + runtime: ReadonlyArray = [], + userId = 0, +): string { + return [ + 'Packages:', + ' Package [com.example.app] (abc):', + ' requested permissions:', + ...requested.map((id) => ` ${id}`), + ` User ${userId}: ceDataInode=0 installed=true`, + ' runtime permissions:', + ...runtime.map(([id, granted]) => ` ${id}: granted=${granted}`), + 'Queries:', + ].join('\n'); +} + +function makeBatchFake( + dumpsys: string, + pmReplies: Readonly> = {}, + extra?: (args: string[], options?: { timeoutMs?: number }) => unknown, +) { + const pmCalls: string[][] = []; + const batchOptions: Array<{ timeoutMs?: number }> = []; + const script = (args: string[], options?: { timeoutMs?: number }) => { + if (extra) { + const override = extra(args, options); + if (override !== undefined) return override as never; + } + if (isAndroidPmBatchShellArgs(args)) { + batchOptions.push({ timeoutMs: options?.timeoutMs }); + return runFakeAndroidPmBatchInSh(args[1]!, pmReplies, pmCalls); + } + const flat = args.join(' '); + if (flat === DUMPSYS) return dumpsys; + if (flat === 'shell getprop ro.build.version.sdk') return '36'; + return undefined; + }; + return { + script, + pmCalls, + batchOptions, + flatPmCalls: () => pmCalls.map((argv) => ['shell', 'pm', ...argv].join(' ')), + }; +} + +test('grant all batches contiguous pm units into one adb shell call and preserves order and warnings', async () => { + const requested = [ + 'android.permission.INTERNET', + 'android.permission.CAMERA', + 'android.permission.WAKE_LOCK', + 'android.permission.RECORD_AUDIO', + 'android.permission.WRITE_SETTINGS', + ]; + const fake = makeBatchFake(makeDumpsys(requested), { + 'shell pm grant --user 10 com.example.app android.permission.INTERNET': { + stderr: + "Exception occurred while executing 'grant':\njava.lang.SecurityException: INTERNET is NOT A CHANGEABLE PERMISSION type\n\tat com.android.server.pm.Service.grant(Service.java:1)\n", + exitCode: 1, + }, + 'shell pm grant --user 10 com.example.app android.permission.WAKE_LOCK': { + stderr: 'Permission android.permission.WAKE_LOCK is not a runtime permission', + exitCode: 1, + }, + 'shell pm grant --user 10 com.example.app android.permission.WRITE_SETTINGS': { + stderr: 'SecurityException: Permission is MANAGED BY ROLE', + exitCode: 1, + }, + }); + + await withFakeAdb(fake.script, async ({ calls, device }) => { + const result = await setAndroidPermission( + device, + 'com.example.app', + parseAndroidPermissionRequest('grant', { permissionTarget: 'all' }), + 10, + ); + assert.deepEqual(result, { + permission: 'all', + permissions: ['android.permission.CAMERA', 'android.permission.RECORD_AUDIO'], + warnings: [ + "Skipped android.permission.INTERNET for com.example.app: Exception occurred while executing 'grant': java.lang.SecurityException: INTERNET is NOT A CHANGEABLE PERMISSION type", + 'Skipped android.permission.WAKE_LOCK for com.example.app: Permission android.permission.WAKE_LOCK is not a runtime permission', + 'Skipped android.permission.WRITE_SETTINGS for com.example.app: SecurityException: Permission is MANAGED BY ROLE', + ], + }); + // One dumpsys + one batched pm shell call (not 5 separate pm calls). + assert.equal(calls.length, 2); + assert.equal(fake.batchOptions[0]?.timeoutMs, androidPmBatchTimeoutMs(5, false)); + assert.deepEqual(fake.flatPmCalls(), [ + 'shell pm grant --user 10 com.example.app android.permission.INTERNET', + 'shell pm grant --user 10 com.example.app android.permission.CAMERA', + 'shell pm grant --user 10 com.example.app android.permission.WAKE_LOCK', + 'shell pm grant --user 10 com.example.app android.permission.RECORD_AUDIO', + 'shell pm grant --user 10 com.example.app android.permission.WRITE_SETTINGS', + ]); + }); +}); + +test('reset all clears user-set and user-fixed flags inside the batch only for applied permissions', async () => { + const requested = [ + 'android.permission.INTERNET', + 'android.permission.CAMERA', + 'android.permission.RECORD_AUDIO', + ]; + const fake = makeBatchFake( + makeDumpsys(requested, [ + ['android.permission.CAMERA', true], + ['android.permission.RECORD_AUDIO', false], + ]), + { + 'shell pm revoke --user 0 com.example.app android.permission.INTERNET': { + stderr: 'SecurityException: INTERNET is not a changeable permission type', + exitCode: 1, + }, + }, + ); + + await withFakeAdb(fake.script, async ({ calls, device }) => { + const result = await setAndroidPermission( + device, + 'com.example.app', + parseAndroidPermissionRequest('reset', { permissionTarget: 'all' }), + 0, + ); + assert.deepEqual(result, { + permission: 'all', + permissions: ['android.permission.CAMERA', 'android.permission.RECORD_AUDIO'], + warnings: [ + 'Skipped android.permission.INTERNET for com.example.app: SecurityException: INTERNET is not a changeable permission type', + androidRevokedPermissionWarning('com.example.app', 'android.permission.CAMERA', 'granted')!, + ], + }); + // One dumpsys + one batched shell call (revokes + flag clears all inside that one call). + assert.equal(calls.length, 2); + assert.equal(fake.batchOptions[0]?.timeoutMs, androidPmBatchTimeoutMs(3, true)); + assert.deepEqual(fake.flatPmCalls(), [ + 'shell pm revoke --user 0 com.example.app android.permission.INTERNET', + 'shell pm revoke --user 0 com.example.app android.permission.CAMERA', + 'shell pm clear-permission-flags --user 0 com.example.app android.permission.CAMERA user-set', + 'shell pm clear-permission-flags --user 0 com.example.app android.permission.CAMERA user-fixed', + 'shell pm revoke --user 0 com.example.app android.permission.RECORD_AUDIO', + 'shell pm clear-permission-flags --user 0 com.example.app android.permission.RECORD_AUDIO user-set', + 'shell pm clear-permission-flags --user 0 com.example.app android.permission.RECORD_AUDIO user-fixed', + ]); + }); +}); + +test('deny all and reset all interleave photos and notifications in exact declared order', async () => { + const requested = [ + 'android.permission.INTERNET', + 'android.permission.CAMERA', + 'android.permission.POST_NOTIFICATIONS', + 'android.permission.RECORD_AUDIO', + 'android.permission.READ_MEDIA_IMAGES', + 'android.permission.READ_EXTERNAL_STORAGE', + 'android.permission.ACCESS_FINE_LOCATION', + 'android.permission.ACCESS_COARSE_LOCATION', + ]; + const runtime = [ + ['android.permission.CAMERA', true], + ['android.permission.POST_NOTIFICATIONS', true], + ['android.permission.RECORD_AUDIO', false], + ['android.permission.READ_MEDIA_IMAGES', true], + ['android.permission.ACCESS_FINE_LOCATION', false], + ['android.permission.ACCESS_COARSE_LOCATION', true], + ] as const; + + const fake = makeBatchFake(makeDumpsys(requested, runtime), { + 'shell pm revoke --user 0 com.example.app android.permission.INTERNET': { + stderr: 'SecurityException: INTERNET is not a changeable permission type', + exitCode: 1, + }, + }); + + await withFakeAdb(fake.script, async ({ calls, device }) => { + const result = await setAndroidPermission( + device, + 'com.example.app', + parseAndroidPermissionRequest('deny', { permissionTarget: 'all' }), + 0, + ); + assert.deepEqual(result, { + permission: 'all', + permissions: [ + 'android.permission.CAMERA', + 'android.permission.POST_NOTIFICATIONS', + 'android.permission.RECORD_AUDIO', + 'android.permission.READ_MEDIA_IMAGES', + 'android.permission.ACCESS_FINE_LOCATION', + 'android.permission.ACCESS_COARSE_LOCATION', + ], + warnings: [ + 'Skipped android.permission.INTERNET for com.example.app: SecurityException: INTERNET is not a changeable permission type', + androidRevokedPermissionWarning('com.example.app', 'android.permission.CAMERA', 'granted')!, + androidRevokedPermissionWarning( + 'com.example.app', + 'android.permission.POST_NOTIFICATIONS', + 'granted', + )!, + androidRevokedPermissionWarning( + 'com.example.app', + 'android.permission.READ_MEDIA_IMAGES', + 'granted', + )!, + androidRevokedPermissionWarning( + 'com.example.app', + 'android.permission.ACCESS_COARSE_LOCATION', + 'granted', + )!, + ], + }); + const flatCalls = calls.map((args) => args.join(' ')); + // Verify notifications appops and photos probe both ran in exact sequence between pm batches. + const appopsIdx = flatCalls.indexOf( + 'shell appops set --user 0 com.example.app POST_NOTIFICATION deny', + ); + const sdkIdx = flatCalls.indexOf('shell getprop ro.build.version.sdk'); + const photosIdx = flatCalls.indexOf( + 'shell pm revoke --user 0 com.example.app android.permission.READ_MEDIA_IMAGES', + ); + assert.ok(appopsIdx > 0 && sdkIdx > appopsIdx && photosIdx > sdkIdx, flatCalls.join(' | ')); + }); +}); + +test('hard failure mid-batch preserves exact stdout/stderr/exitCode and stops before subsequent permissions and units', async () => { + const requested = [ + 'android.permission.INTERNET', + 'android.permission.CAMERA', + 'android.permission.RECORD_AUDIO', + 'android.permission.POST_NOTIFICATIONS', + ]; + const fake = makeBatchFake(makeDumpsys(requested), { + 'shell pm grant --user 0 com.example.app android.permission.INTERNET': { + stderr: 'SecurityException: INTERNET is not a changeable permission type', + exitCode: 1, + }, + 'shell pm grant --user 0 com.example.app android.permission.CAMERA': { + stdout: 'partial-out\n', + stderr: 'Failure: permission service crashed\n', + exitCode: 42, + }, + }); + + await withFakeAdb(fake.script, async ({ calls, device }) => { + await assert.rejects( + () => + setAndroidPermission( + device, + 'com.example.app', + parseAndroidPermissionRequest('grant', { permissionTarget: 'all' }), + 0, + ), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal( + error.message, + 'Failed to grant Android permission android.permission.CAMERA for com.example.app', + ); + assert.equal(error.details?.exitCode, 42); + assert.equal(error.details?.stdout, 'partial-out\n'); + assert.equal(error.details?.stderr, 'Failure: permission service crashed\n'); + assert.equal(error.details?.appPackage, 'com.example.app'); + assert.equal(error.details?.permission, 'android.permission.CAMERA'); + return true; + }, + ); + assert.deepEqual(fake.flatPmCalls(), [ + 'shell pm grant --user 0 com.example.app android.permission.INTERNET', + 'shell pm grant --user 0 com.example.app android.permission.CAMERA', + ]); + assert.ok( + calls.every((args) => !args.includes('appops')), + 'notifications unit must not run after earlier pm batch hard failure', + ); + }); +}); + +test('host adb refusal or mid-batch transport truncation surfaces classified error for the uncompleted permission', async () => { + const requested = ['android.permission.CAMERA', 'android.permission.RECORD_AUDIO']; + + // Host adb refuses before device shell runs (no markers at all). + await withFakeAdb( + (args) => { + if (args.join(' ') === DUMPSYS) return makeDumpsys(requested); + if (isAndroidPmBatchShellArgs(args)) { + return { stdout: '', stderr: 'adb: device offline', exitCode: 1 }; + } + return undefined; + }, + async ({ device }) => { + await assert.rejects( + () => + setAndroidPermission( + device, + 'com.example.app', + parseAndroidPermissionRequest('grant', { permissionTarget: 'all' }), + 0, + ), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.match(error.message, /CAMERA/); + assert.equal(error.details?.adbFailure, 'device_offline'); + assert.equal(error.details?.adbHostRefusal, true); + return true; + }, + ); + }, + ); + + // Mid-batch truncation: record 0 completed, record 1 truncated by transport drop. + await withFakeAdb( + (args) => { + if (args.join(' ') === DUMPSYS) return makeDumpsys(requested); + if (isAndroidPmBatchShellArgs(args)) { + const match = /'(__AD_PM_BATCH_[0-9a-f]+__):OUT:'/.exec(args[1]!); + assert.ok(match?.[1]); + const marker = match[1]; + return { + stdout: `${marker}:OUT:0\n${marker}:ERR:0:0\n${marker}:END:0\n${marker}:OUT:1\npartial`, + stderr: "adb: protocol fault (couldn't read status)", + exitCode: 1, + }; + } + return undefined; + }, + async ({ device }) => { + await assert.rejects( + () => + setAndroidPermission( + device, + 'com.example.app', + parseAndroidPermissionRequest('grant', { permissionTarget: 'all' }), + 0, + ), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.match(error.message, /RECORD_AUDIO/); + assert.equal(error.details?.permission, 'android.permission.RECORD_AUDIO'); + assert.equal(error.details?.stdout, 'partial'); + assert.equal(error.details?.adbFailure, 'connection_dropped'); + return true; + }, + ); + }, + ); +}); + +test('host adb passes no batch timeout while scoped remote providers receive a capped batch timeout', async () => { + assert.equal(androidPmBatchTimeoutMs(1, false), 30_500); + assert.equal(androidPmBatchTimeoutMs(55, false), 57_500); + assert.equal(androidPmBatchTimeoutMs(55, true), 90_000); + assert.equal(androidPmBatchTimeoutMs(200, true), 90_000); + + const requested = ['android.permission.CAMERA', 'android.permission.RECORD_AUDIO']; + const observedTimeouts: Array = []; + const pmCalls: string[][] = []; + + bindAndroidAdbHostStub({ + execAdb: async (invocation, options) => { + const args = [...invocation.command]; + if (args.join(' ') === DUMPSYS) { + return { stdout: makeDumpsys(requested), stderr: '', exitCode: 0 }; + } + if (isAndroidPmBatchShellArgs(args)) { + observedTimeouts.push(options?.timeoutMs); + const reply = runFakeAndroidPmBatchInSh(args[1]!, {}, pmCalls); + assert.ok(typeof reply === 'object' && !(reply instanceof Error)); + return { + stdout: reply.stdout ?? '', + stderr: reply.stderr ?? '', + exitCode: reply.exitCode ?? 0, + }; + } + return { stdout: '', stderr: `unexpected host adb args: ${args.join(' ')}`, exitCode: 1 }; + }, + }); + try { + const result = await setAndroidPermission( + ANDROID_EMULATOR, + 'com.example.app', + parseAndroidPermissionRequest('grant', { permissionTarget: 'all' }), + 0, + ); + assert.deepEqual(result, { + permission: 'all', + permissions: requested, + }); + assert.deepEqual(observedTimeouts, [undefined]); + } finally { + bindAndroidAdbTestHost(); + } +}); + +test('batch script safely quotes adversarial permission ids and preserves exact stdout and stderr bytes', () => { + const marker = '__AD_PM_BATCH_0123456789abcdef__'; + const trickyPermissions = [ + "com.example.app.PERM'WITH'QUOTES", + 'com.example.app.PERM $(echo INJECTED); touch /nonexistent', + 'com.example.app.PERM `uname` $HOME "double" \\slash', + ]; + const skipPhrases = ['not a changeable permission', 'unknown permission']; + const script = buildAndroidPmBatchScript({ + pmAction: 'grant', + clearFlags: false, + userArgs: ['--user', '0'], + appPackage: 'com.example.app', + permissions: trickyPermissions, + skipPhrases, + marker, + }); + + const recorded: string[][] = []; + const reply = runFakeAndroidPmBatchInSh( + script, + { + [`shell pm grant --user 0 com.example.app ${trickyPermissions[0]}`]: { + stdout: 'line-no-newline', + stderr: '', + exitCode: 0, + }, + [`shell pm grant --user 0 com.example.app ${trickyPermissions[1]}`]: { + stdout: 'out %s \\n\n', + stderr: 'Unknown permission %s \\\\ with trailing newlines\n\n', + exitCode: 1, + }, + [`shell pm grant --user 0 com.example.app ${trickyPermissions[2]}`]: { + stdout: '', + stderr: '', + exitCode: 0, + }, + }, + recorded, + ); + assert.ok(typeof reply === 'object' && !(reply instanceof Error)); + assert.equal(reply.exitCode, 0); + + // Every permission reached `pm` verbatim as argv[4] with zero shell expansion or splitting. + assert.deepEqual( + recorded.map((argv) => argv[4]), + trickyPermissions, + ); + + const parsed = parseAndroidPmBatchOutput(reply.stdout ?? '', marker, trickyPermissions.length); + assert.equal(parsed.partialStdout, ''); + assert.deepEqual(parsed.records, [ + { index: 0, exitCode: 0, stdout: 'line-no-newline', stderr: '' }, + { + index: 1, + exitCode: 1, + stdout: 'out %s \\n\n', + stderr: 'Unknown permission %s \\\\ with trailing newlines\n\n', + }, + { index: 2, exitCode: 0, stdout: '', stderr: '' }, + ]); +}); + +test('chunkAndroidPmBatch splits large lists under maxScriptBytes and keeps oversized single ids intact', () => { + const marker = '__AD_PM_BATCH_0123456789abcdef__'; + const permissions = Array.from({ length: 80 }, (_, i) => `com.example.app.permission.PERM_${i}`); + const skipPhrases = ['not a changeable permission', 'unknown permission']; + const chunks = chunkAndroidPmBatch( + { + pmAction: 'revoke', + clearFlags: true, + userArgs: ['--user', '0'], + appPackage: 'com.example.app', + permissions, + skipPhrases, + marker, + }, + 1_500, + ); + assert.ok(chunks.length > 1, `expected multiple chunks, got ${chunks.length}`); + assert.deepEqual(chunks.flat(), permissions); + for (const chunk of chunks) { + const script = buildAndroidPmBatchScript({ + pmAction: 'revoke', + clearFlags: true, + userArgs: ['--user', '0'], + appPackage: 'com.example.app', + permissions: chunk, + skipPhrases, + marker, + }); + assert.ok( + Buffer.byteLength(script, 'utf8') <= 1_500, + `chunk exceeded budget: ${Buffer.byteLength(script, 'utf8')} bytes`, + ); + } + + // An oversized single permission still forms a 1-item chunk without looping forever. + const huge = `com.example.app.${'A'.repeat(2_000)}`; + const oversized = chunkAndroidPmBatch( + { + pmAction: 'grant', + clearFlags: false, + userArgs: ['--user', '0'], + appPackage: 'com.example.app', + permissions: [huge, 'android.permission.CAMERA'], + skipPhrases, + marker, + }, + 1_500, + ); + assert.deepEqual(oversized, [[huge], ['android.permission.CAMERA']]); +}); + +test('parseAndroidPmBatchOutput accepts CRLF line endings from legacy pty adb shells', () => { + const marker = '__AD_PM_BATCH_0123456789abcdef__'; + const stdout = + `${marker}:OUT:0\r\nok\r\n${marker}:ERR:0:0\r\n${marker}:END:0\r\n` + + `${marker}:OUT:1\r\n${marker}:ERR:1:1\r\nnot a changeable permission\r\n${marker}:END:1\r\n`; + const parsed = parseAndroidPmBatchOutput(stdout, marker, 2); + assert.equal(parsed.partialStdout, ''); + assert.deepEqual(parsed.records, [ + { index: 0, exitCode: 0, stdout: 'ok\r\n', stderr: '' }, + { index: 1, exitCode: 1, stdout: '', stderr: 'not a changeable permission\r\n' }, + ]); +}); diff --git a/packages/platform-android/src/__tests__/settings-permission.test.ts b/packages/platform-android/src/__tests__/settings-permission.test.ts index 516efcec80..c83766db81 100644 --- a/packages/platform-android/src/__tests__/settings-permission.test.ts +++ b/packages/platform-android/src/__tests__/settings-permission.test.ts @@ -10,6 +10,11 @@ import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts'; import { AppError } from '@agent-device/kernel/errors'; import { assertRejectsAppError } from './test-utils/app-error.ts'; import { withFakeAdb } from './test-utils/fake-adb.ts'; +import { + isAndroidPmBatchShellArgs, + runFakeAndroidPmBatchInSh, + type FakePmReply, +} from './test-utils/fake-android-pm-shell.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { SettingOptions } from '@agent-device/contracts/settings'; @@ -553,48 +558,61 @@ function dumpsysWithRequested(): string { ].join('\n'); } +function fakeAllAdb( + baseScript: (flat: string) => FakeAdbReply, + pmReplies: Readonly> = {}, +) { + const pmCalls: string[][] = []; + const script = (args: string[]) => { + if (isAndroidPmBatchShellArgs(args)) { + return runFakeAndroidPmBatchInSh(args[1]!, pmReplies, pmCalls); + } + return baseScript(args.join(' ')); + }; + const flatPmCalls = () => pmCalls.map((argv) => ['shell', 'pm', ...argv].join(' ')); + return { script, pmCalls, flatPmCalls }; +} + // `all` intersects the declared set before issuing anything: INTERNET is declared // but not changeable, so it is skipped with a reason while RECORD_AUDIO lands. test('setAndroidPermission grant all applies the declared changeable ids', async () => { - await withFakeAdb( - fakeAdb((flat) => { + const fake = fakeAllAdb( + (flat) => { if (flat === CURRENT_USER) return '0'; if (flat === DUMPSYS) return dumpsysWithRequested(); - if (flat === 'shell pm grant --user 0 com.example.app android.permission.INTERNET') { - return { - stderr: - "Exception occurred while executing 'grant':\njava.lang.SecurityException: INTERNET is not a changeable permission type", - exitCode: 1, - }; - } - if (flat === 'shell pm grant --user 0 com.example.app com.example.app.CUSTOM_PERMISSION') { - return { - stderr: - 'SecurityException: Package com.example.app has not requested permission com.example.app.CUSTOM_PERMISSION', - exitCode: 1, - }; - } return undefined; - }), - async ({ calls, device }) => { - const result = await setPermission(device, 'grant', 'com.example.app', { - permissionTarget: 'all', - }); - const flat = calls.map((args) => args.join(' ')); - assert.ok( - flat.includes('shell pm grant --user 0 com.example.app android.permission.RECORD_AUDIO'), - flat.join('; '), - ); - assert.deepEqual(result, { - permission: 'all', - permissions: ['android.permission.RECORD_AUDIO'], - warnings: [ - "Skipped android.permission.INTERNET for com.example.app: Exception occurred while executing 'grant': java.lang.SecurityException: INTERNET is not a changeable permission type", - 'Skipped com.example.app.CUSTOM_PERMISSION for com.example.app: SecurityException: Package com.example.app has not requested permission com.example.app.CUSTOM_PERMISSION', - ], - }); + }, + { + 'shell pm grant --user 0 com.example.app android.permission.INTERNET': { + stderr: + "Exception occurred while executing 'grant':\njava.lang.SecurityException: INTERNET is not a changeable permission type", + exitCode: 1, + }, + 'shell pm grant --user 0 com.example.app com.example.app.CUSTOM_PERMISSION': { + stderr: + 'SecurityException: Package com.example.app has not requested permission com.example.app.CUSTOM_PERMISSION', + exitCode: 1, + }, }, ); + await withFakeAdb(fake.script, async ({ device }) => { + const result = await setPermission(device, 'grant', 'com.example.app', { + permissionTarget: 'all', + }); + const flat = fake.flatPmCalls(); + assert.ok( + flat.includes('shell pm grant --user 0 com.example.app android.permission.RECORD_AUDIO'), + flat.join('; '), + ); + assert.deepEqual(result, { + permission: 'all', + permissions: ['android.permission.RECORD_AUDIO'], + warnings: [ + "Skipped android.permission.INTERNET for com.example.app: Exception occurred while executing 'grant': java.lang.SecurityException: INTERNET is not a changeable permission type", + 'Skipped com.example.app.CUSTOM_PERMISSION for com.example.app: SecurityException: Package com.example.app has not requested permission com.example.app.CUSTOM_PERMISSION', + ], + }); + }); }); // A role-managed id (WRITE_SETTINGS on API 36: "managed by role") is @@ -612,32 +630,32 @@ test('setAndroidPermission all skips a role-managed id', async () => { ' android.permission.RECORD_AUDIO: granted=false', 'Queries:', ].join('\n'); - await withFakeAdb( - fakeAdb((flat) => { + const fake = fakeAllAdb( + (flat) => { if (flat === CURRENT_USER) return '0'; if (flat === DUMPSYS) return requested; - if (flat === 'shell pm grant --user 0 com.example.app android.permission.WRITE_SETTINGS') { - return { - stderr: - "Exception occurred while executing 'grant':\njava.lang.SecurityException: Permission android.permission.WRITE_SETTINGS is managed by role", - exitCode: 1, - }; - } return undefined; - }), - async ({ device }) => { - const result = await setPermission(device, 'grant', 'com.example.app', { - permissionTarget: 'all', - }); - assert.deepEqual(result, { - permission: 'all', - permissions: ['android.permission.RECORD_AUDIO'], - warnings: [ - "Skipped android.permission.WRITE_SETTINGS for com.example.app: Exception occurred while executing 'grant': java.lang.SecurityException: Permission android.permission.WRITE_SETTINGS is managed by role", - ], - }); + }, + { + 'shell pm grant --user 0 com.example.app android.permission.WRITE_SETTINGS': { + stderr: + "Exception occurred while executing 'grant':\njava.lang.SecurityException: Permission android.permission.WRITE_SETTINGS is managed by role", + exitCode: 1, + }, }, ); + await withFakeAdb(fake.script, async ({ device }) => { + const result = await setPermission(device, 'grant', 'com.example.app', { + permissionTarget: 'all', + }); + assert.deepEqual(result, { + permission: 'all', + permissions: ['android.permission.RECORD_AUDIO'], + warnings: [ + "Skipped android.permission.WRITE_SETTINGS for com.example.app: Exception occurred while executing 'grant': java.lang.SecurityException: Permission android.permission.WRITE_SETTINGS is managed by role", + ], + }); + }); }); // Every skip reason the pm boundary classifies keeps rendering the same operator-facing @@ -660,32 +678,35 @@ test.each([ ' android.permission.RECORD_AUDIO: granted=false', 'Queries:', ].join('\n'); - await withFakeAdb( - fakeAdb((flat) => { + const fake = fakeAllAdb( + (flat) => { if (flat === CURRENT_USER) return '0'; if (flat === DUMPSYS) return requested; - if (flat === 'shell pm grant --user 0 com.example.app android.permission.CUSTOM') { - return { stderr: stderrText, exitCode: 1 }; - } return undefined; - }), - async ({ device }) => { - const result = (await setPermission(device, 'grant', 'com.example.app', { - permissionTarget: 'all', - })) as Record; - assert.deepEqual(result.permissions, ['android.permission.RECORD_AUDIO']); - assert.deepEqual(result.warnings, [ - `Skipped android.permission.CUSTOM for com.example.app: ${stderrText}`, - ]); + }, + { + 'shell pm grant --user 0 com.example.app android.permission.CUSTOM': { + stderr: stderrText, + exitCode: 1, + }, }, ); + await withFakeAdb(fake.script, async ({ device }) => { + const result = (await setPermission(device, 'grant', 'com.example.app', { + permissionTarget: 'all', + })) as Record; + assert.deepEqual(result.permissions, ['android.permission.RECORD_AUDIO']); + assert.deepEqual(result.warnings, [ + `Skipped android.permission.CUSTOM for com.example.app: ${stderrText}`, + ]); + }); }); // The abort side, named per the sequence it stops: an operational failure on the second // declared id leaves the first id applied (its pm call already landed) and never attempts the // third — proving the abort halts the fan-out rather than skipping past it. A mutation that // treats an unrecognized stderr as skippable (rather than aborting) makes the third id's pm -// call appear in `calls`, failing the assertion below. +// call appear in `pmCalls`, failing the assertion below. test('setAndroidPermission grant all stops after an operational failure, keeping the earlier applied id', async () => { const requested = [ 'Packages:', @@ -701,58 +722,59 @@ test('setAndroidPermission grant all stops after an operational failure, keeping ' android.permission.READ_CONTACTS: granted=false', 'Queries:', ].join('\n'); - await withFakeAdb( - fakeAdb((flat) => { + const fake = fakeAllAdb( + (flat) => { if (flat === CURRENT_USER) return '0'; if (flat === DUMPSYS) return requested; - if (flat === 'shell pm grant --user 0 com.example.app android.permission.CAMERA') { - return { stderr: 'device offline', exitCode: 1 }; - } return undefined; - }), - async ({ calls, device }) => { - await assertRejectsAppError( - () => - setPermission(device, 'grant', 'com.example.app', { - permissionTarget: 'all', - }), - { code: 'COMMAND_FAILED', message: /Failed to grant Android permission.*CAMERA/ }, - ); - const flat = calls.map((args) => args.join(' ')); - assert.ok( - flat.includes('shell pm grant --user 0 com.example.app android.permission.RECORD_AUDIO'), - flat.join('; '), - ); - assert.ok( - flat.includes('shell pm grant --user 0 com.example.app android.permission.CAMERA'), - flat.join('; '), - ); - assert.ok(!flat.some((call) => call.includes('READ_CONTACTS')), flat.join('; ')); + }, + { + 'shell pm grant --user 0 com.example.app android.permission.CAMERA': { + stderr: 'device offline', + exitCode: 1, + }, }, ); + await withFakeAdb(fake.script, async ({ device }) => { + await assertRejectsAppError( + () => + setPermission(device, 'grant', 'com.example.app', { + permissionTarget: 'all', + }), + { code: 'COMMAND_FAILED', message: /Failed to grant Android permission.*CAMERA/ }, + ); + const flat = fake.flatPmCalls(); + assert.ok( + flat.includes('shell pm grant --user 0 com.example.app android.permission.RECORD_AUDIO'), + flat.join('; '), + ); + assert.ok( + flat.includes('shell pm grant --user 0 com.example.app android.permission.CAMERA'), + flat.join('; '), + ); + assert.ok(!flat.some((call) => call.includes('READ_CONTACTS')), flat.join('; ')); + }); }); // Revoke under `all` warns per held permission, like the single path. test('setAndroidPermission revoke all warns for the held runtime id', async () => { - await withFakeAdb( - fakeAdb((flat) => { - if (flat === CURRENT_USER) return '0'; - if (flat === DUMPSYS) return dumpsysWithRequested(); - return undefined; - }), - async ({ device }) => { - const result = (await setPermission(device, 'deny', 'com.example.app', { - permissionTarget: 'all', - })) as Record; - assert.deepEqual(result.permission, 'all'); - assert.ok( - (result.permissions as string[]).includes('android.permission.RECORD_AUDIO'), - JSON.stringify(result), - ); - const warnings = (result.warnings as string[]).join('\n'); - assert.match(warnings, /RECORD_AUDIO was granted before this revoke/); - }, - ); + const fake = fakeAllAdb((flat) => { + if (flat === CURRENT_USER) return '0'; + if (flat === DUMPSYS) return dumpsysWithRequested(); + return undefined; + }); + await withFakeAdb(fake.script, async ({ device }) => { + const result = (await setPermission(device, 'deny', 'com.example.app', { + permissionTarget: 'all', + })) as Record; + assert.deepEqual(result.permission, 'all'); + assert.ok( + (result.permissions as string[]).includes('android.permission.RECORD_AUDIO'), + JSON.stringify(result), + ); + const warnings = (result.warnings as string[]).join('\n'); + assert.match(warnings, /RECORD_AUDIO was granted before this revoke/); + }); }); // Validation happens before mutation: an unreadable dump issues no pm call. @@ -861,25 +883,28 @@ test('setAndroidPermission grant camera on a package that declares nothing fails // An operational pm failure mid-`all` aborts instead of being skipped: an // offline device must not let launchApp continue with half-applied permissions. test('setAndroidPermission grant all propagates an operational pm failure', async () => { - await withFakeAdb( - fakeAdb((flat) => { + const fake = fakeAllAdb( + (flat) => { if (flat === CURRENT_USER) return '0'; if (flat === DUMPSYS) return dumpsysWithRequested(); - if (flat === 'shell pm grant --user 0 com.example.app android.permission.RECORD_AUDIO') { - return { stderr: 'device offline', exitCode: 1 }; - } return undefined; - }), - async ({ device }) => { - await assertRejectsAppError( - () => - setPermission(device, 'grant', 'com.example.app', { - permissionTarget: 'all', - }), - { code: 'COMMAND_FAILED', message: /Failed to grant Android permission.*RECORD_AUDIO/ }, - ); + }, + { + 'shell pm grant --user 0 com.example.app android.permission.RECORD_AUDIO': { + stderr: 'device offline', + exitCode: 1, + }, }, ); + await withFakeAdb(fake.script, async ({ device }) => { + await assertRejectsAppError( + () => + setPermission(device, 'grant', 'com.example.app', { + permissionTarget: 'all', + }), + { code: 'COMMAND_FAILED', message: /Failed to grant Android permission.*RECORD_AUDIO/ }, + ); + }); }); // A photos probe that fails operationally (not as non-changeable) aborts `all` diff --git a/packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts b/packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts new file mode 100644 index 0000000000..41898199d4 --- /dev/null +++ b/packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts @@ -0,0 +1,76 @@ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { shellQuote } from '@agent-device/kernel/device-shell'; +import type { FakeAdbResponse } from './fake-adb.ts'; +import { mkdtempForTestSync } from './tmp-dir.ts'; + +export type FakePmReply = Readonly<{ + stdout?: string; + stderr?: string; + exitCode?: number; +}>; + +/** + * Executes a batched Android `pm` shell script in real `/bin/sh` with a shell-function `pm()` + * shim that records every executed `pm` argv losslessly and returns per-command replies. + */ +export function runFakeAndroidPmBatchInSh( + script: string, + pmReplies: Readonly>, + recordedPmCalls: string[][], +): FakeAdbResponse { + const dir = mkdtempForTestSync('agent-device-fake-pm-'); + const logPath = path.join(dir, 'pm-calls.bin'); + try { + const cases = Object.entries(pmReplies) + .map(([flatPmArgs, reply]) => { + const actions: string[] = []; + if (reply.stdout) actions.push(`printf '%s' ${shellQuote(reply.stdout)}`); + if (reply.stderr) actions.push(`printf '%s' ${shellQuote(reply.stderr)} >&2`); + actions.push(`return ${reply.exitCode ?? 0}`); + return `${shellQuote(flatPmArgs)}) ${actions.join('; ')} ;;`; + }) + .join(' '); + + const pmShim = [ + `__FAKE_PM_LOG=${shellQuote(logPath)}`, + 'pm() {', + String.raw` for __a in "$@"; do printf '%s\0' "$__a" >> "$__FAKE_PM_LOG"; done`, + String.raw` printf '__PM_CALL_END__\0' >> "$__FAKE_PM_LOG"`, + ` case "shell pm $*" in ${cases} *) return 0 ;; esac`, + '}', + ].join('\n'); + + const result = spawnSync('/bin/sh', ['-c', `${pmShim}\n${script}`], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + if (result.error) throw result.error; + + if (fs.existsSync(logPath)) { + const tokens = fs.readFileSync(logPath).toString('utf8').split('\0'); + let current: string[] = []; + for (const token of tokens) { + if (token === '__PM_CALL_END__') { + recordedPmCalls.push(current); + current = []; + } else if (token.length > 0 || current.length > 0) { + current.push(token); + } + } + } + + return { + stdout: result.stdout ?? '', + stderr: result.stderr ?? '', + exitCode: result.status ?? 1, + }; + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +export function isAndroidPmBatchShellArgs(args: readonly string[]): boolean { + return args[0] === 'shell' && args.length === 2 && args[1]!.includes('__AD_PM_BATCH_'); +} diff --git a/packages/platform-android/src/settings-permission-batch.ts b/packages/platform-android/src/settings-permission-batch.ts new file mode 100644 index 0000000000..d387079805 --- /dev/null +++ b/packages/platform-android/src/settings-permission-batch.ts @@ -0,0 +1,209 @@ +import { randomBytes } from 'node:crypto'; +import { shellQuote } from '@agent-device/kernel/device-shell'; + +/** + * Safe per-invocation command-line budget for `adb shell`: stays well under legacy 4 KiB + * `adbd` shell buffers while fitting ~50 typical permission ids into one round trip. + */ +const ANDROID_PM_BATCH_MAX_SCRIPT_BYTES = 3_072; + +/** + * Batch timeout for scoped remote adb providers (e.g. Limrun's 30 s per-call default): + * keeps the full 30 s base budget plus 500 ms per on-device `pm` call, capped at 90 s so a + * hung device never waits tens of minutes while normal batches keep ample headroom. + */ +const ANDROID_PM_BATCH_REMOTE_BASE_TIMEOUT_MS = 30_000; +const ANDROID_PM_BATCH_REMOTE_PER_CALL_MS = 500; +const ANDROID_PM_BATCH_REMOTE_MAX_TIMEOUT_MS = 90_000; + +export function createAndroidPmBatchMarker(): string { + return `__AD_PM_BATCH_${randomBytes(8).toString('hex')}__`; +} + +export function androidPmBatchTimeoutMs(permissionCount: number, clearFlags: boolean): number { + const calls = Math.max(1, permissionCount) * (clearFlags ? 3 : 1); + return Math.min( + ANDROID_PM_BATCH_REMOTE_MAX_TIMEOUT_MS, + ANDROID_PM_BATCH_REMOTE_BASE_TIMEOUT_MS + calls * ANDROID_PM_BATCH_REMOTE_PER_CALL_MS, + ); +} + +export type AndroidPmBatchScriptParams = Readonly<{ + pmAction: 'grant' | 'revoke'; + clearFlags: boolean; + userArgs: readonly string[]; + appPackage: string; + permissions: readonly string[]; + skipPhrases: readonly string[]; + marker: string; +}>; + +/** + * Builds a POSIX `case` glob matching `phrase` case-insensitively without spawning `tr`. + * Derived from the caller's skip-phrase table so the shell's stop-on-hard-failure guard and + * `classifyAndroidPmSkip` share one source of truth. + */ +function buildShellCaseInsensitivePattern(phrase: string): string { + let body = ''; + for (const ch of phrase) { + body += /^[a-z]$/.test(ch) ? `[${ch}${ch.toUpperCase()}]` : shellQuote(ch); + } + return `*${body}*`; +} + +/** + * Splits `permissions` into chunks whose generated shell script fits within `maxScriptBytes`. + * Always emits at least one permission per chunk so an oversized id still makes progress. + */ +export function chunkAndroidPmBatch( + params: AndroidPmBatchScriptParams, + maxScriptBytes = ANDROID_PM_BATCH_MAX_SCRIPT_BYTES, +): readonly (readonly string[])[] { + const { permissions } = params; + if (permissions.length === 0) return []; + const baseBytes = Buffer.byteLength( + buildAndroidPmBatchScript({ ...params, permissions: [] }), + 'utf8', + ); + const chunks: string[][] = []; + let current: string[] = []; + let currentBytes = baseBytes; + + for (const permission of permissions) { + const quotedBytes = Buffer.byteLength(shellQuote(permission), 'utf8'); + const addedBytes = current.length === 0 ? quotedBytes : 1 + quotedBytes; + if (current.length > 0 && currentBytes + addedBytes > maxScriptBytes) { + chunks.push(current); + current = [permission]; + currentBytes = baseBytes + quotedBytes; + } else { + current.push(permission); + currentBytes += addedBytes; + } + } + if (current.length > 0) chunks.push(current); + return chunks; +} + +/** + * Builds a single POSIX `sh` script that executes `pm grant|revoke` (and `clear-permission-flags` + * on reset) across `permissions`, emitting per-command exit code, stdout, and stderr framed by + * `marker`. Stops immediately (`break`) on the first non-skippable failure so later permissions + * are never touched. + */ +export function buildAndroidPmBatchScript(params: AndroidPmBatchScriptParams): string { + const { pmAction, clearFlags, userArgs, appPackage, permissions, skipPhrases, marker } = params; + const quotedUserArgs = userArgs.map(shellQuote).join(' '); + const quotedPackage = shellQuote(appPackage); + const quotedPermissions = permissions.map(shellQuote).join(' '); + const quotedMarkerOut = shellQuote(`${marker}:OUT:`); + const quotedMarkerErr = shellQuote(`${marker}:ERR:`); + const quotedMarkerEnd = shellQuote(`${marker}:END:`); + const shellSkipCasePattern = skipPhrases.map(buildShellCaseInsensitivePattern).join('|'); + + // Android's `/system/bin/pm` is a two-line shell wrapper (`cmd package "$@"`) since API 26. + // Calling `/system/bin/cmd package` directly when verified avoids one extra `/system/bin/sh` + // fork per permission while keeping stdout, stderr, and exit status identical. + const pmSetup = [ + '_pm() { pm "$@"; }', + `if [ -x /system/bin/cmd ] && [ -r /system/bin/pm ]; then { IFS= read -r _l1; IFS= read -r _l2; } < /system/bin/pm 2>/dev/null; [ "$_l2" = 'cmd package "$@"' ] && _pm() { /system/bin/cmd package "$@"; }; fi`, + // `mksh` (Android's `/system/bin/sh`) has builtin `print` while `printf` is external toybox. + `case "$(type print 2>/dev/null)" in *builtin*) _pr() { print -rn -- "$1"; } ;; *) _pr() { printf '%s' "$1"; } ;; esac`, + ].join('; '); + + const clearFlagsStep = clearFlags + ? `if [ "$rc" -eq 0 ]; then _pm clear-permission-flags ${quotedUserArgs} ${quotedPackage} "$p" user-set >/dev/null 2>&1; _pm clear-permission-flags ${quotedUserArgs} ${quotedPackage} "$p" user-fixed >/dev/null 2>&1; fi` + : undefined; + + const loopBody = [ + `echo ${quotedMarkerOut}"$i" >&3`, + // Route pm's stdout directly to fd 3 (outer stdout) while capturing pm's stderr into $e. + // Appending `.` via builtin `echo .` preserves trailing newlines across `$(...)`. + `e=$(_pm ${pmAction} ${quotedUserArgs} ${quotedPackage} "$p" 2>&1 1>&3 3>&-; s=$?; echo .; exit $s)`, + 'rc=$?', + 'e=${e%.}', + ...(clearFlagsStep ? [clearFlagsStep] : []), + `echo ${quotedMarkerErr}"$i:$rc" >&3`, + '[ -n "$e" ] && _pr "$e" >&3', + `echo ${quotedMarkerEnd}"$i" >&3`, + `if [ "$rc" -ne 0 ]; then case "$e" in ${shellSkipCasePattern}) ;; *) break ;; esac; fi`, + 'i=$((i + 1))', + ].join('; '); + + return `exec 3>&1; ${pmSetup}; i=0; for p in ${quotedPermissions}; do ${loopBody}; done`; +} + +export type AndroidPmBatchRecord = Readonly<{ + index: number; + exitCode: number; + stdout: string; + stderr: string; +}>; + +export type AndroidPmBatchParseResult = Readonly<{ + records: readonly AndroidPmBatchRecord[]; + partialStdout: string; +}>; + +function skipLineEnding(text: string, pos: number): number | undefined { + if (text[pos] === '\r' && text[pos + 1] === '\n') return pos + 2; + if (text[pos] === '\n') return pos + 1; + return undefined; +} + +/** + * Parses marker-framed per-permission records emitted by {@link buildAndroidPmBatchScript}. + * Stops cleanly at the first incomplete record so callers can surface partial/transport failures. + */ +export function parseAndroidPmBatchOutput( + stdout: string, + marker: string, + expectedCount: number, +): AndroidPmBatchParseResult { + const records: AndroidPmBatchRecord[] = []; + let cursor = 0; + + for (let index = 0; index < expectedCount; index += 1) { + const outTag = `${marker}:OUT:${index}`; + const outPos = stdout.indexOf(outTag, cursor); + if (outPos === -1) { + return { records, partialStdout: stdout.slice(cursor) }; + } + const contentStart = skipLineEnding(stdout, outPos + outTag.length); + if (contentStart === undefined) { + return { records, partialStdout: stdout.slice(cursor) }; + } + + const errPrefix = `${marker}:ERR:${index}:`; + const errPos = stdout.indexOf(errPrefix, contentStart); + if (errPos === -1) { + return { records, partialStdout: stdout.slice(contentStart) }; + } + const cmdStdout = stdout.slice(contentStart, errPos); + + const rcStart = errPos + errPrefix.length; + const rcLineEnd = stdout.indexOf('\n', rcStart); + if (rcLineEnd === -1) { + return { records, partialStdout: cmdStdout }; + } + const rcText = stdout.slice(rcStart, rcLineEnd).replace(/\r$/, ''); + if (!/^\d+$/.test(rcText)) { + return { records, partialStdout: cmdStdout }; + } + const exitCode = Number.parseInt(rcText, 10); + + const errStart = rcLineEnd + 1; + const endTag = `${marker}:END:${index}`; + const endPos = stdout.indexOf(endTag, errStart); + if (endPos === -1) { + return { records, partialStdout: cmdStdout }; + } + const cmdStderr = stdout.slice(errStart, endPos); + + records.push({ index, exitCode, stdout: cmdStdout, stderr: cmdStderr }); + const afterEnd = endPos + endTag.length; + cursor = skipLineEnding(stdout, afterEnd) ?? afterEnd; + } + + return { records, partialStdout: '' }; +} diff --git a/packages/platform-android/src/settings-permission.ts b/packages/platform-android/src/settings-permission.ts index bd54566248..2da7deb87f 100644 --- a/packages/platform-android/src/settings-permission.ts +++ b/packages/platform-android/src/settings-permission.ts @@ -1,5 +1,6 @@ import { AppError } from '@agent-device/kernel/errors'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { shellFragment } from '@agent-device/kernel/device-shell'; import { parsePermissionAction, parsePermissionTarget, @@ -10,6 +11,7 @@ import { type PermissionAction, } from '@agent-device/contracts/settings-catalog'; import { runAndroidShell } from './adb.ts'; +import { resolveScopedAndroidAdbBackgroundTransport } from './adb-executor.ts'; import { androidAdbResultError } from './adb-failure.ts'; import { readAndroidSdkInt } from './device-sdk-int.ts'; import { @@ -218,11 +220,17 @@ async function setAllAndroidPermissions( const applied: string[] = []; const warnings: string[] = requested.length === 0 ? [`${appPackage} declares no permissions, so none was changed.`] : []; - for (const unit of allPermissionUnits(requested)) { - await applyAllPermissionUnit( - { device, appPackage, action, userArgs, grants, applied, warnings }, - unit, - ); + const ctx: AllUnitContext = { + device, + appPackage, + action, + userArgs, + grants, + applied, + warnings, + }; + for (const step of groupAllPermissionSteps(allPermissionUnits(requested))) { + await applyAllPermissionStep(ctx, step); } return { permission: 'all', @@ -241,11 +249,43 @@ type AllUnitContext = { warnings: string[]; }; -/** One declared-permission unit: strict appops for notifications, best-effort pm otherwise. */ -async function applyAllPermissionUnit(ctx: AllUnitContext, unit: AllPermissionUnit): Promise { - if (unit.kind === 'notification') return await applyAllNotificationsUnit(ctx); - if (unit.kind === 'photos') return await applyAllPhotosUnit(ctx); - return await applyAllPmUnit(ctx, unit.value); +type AllPermissionStep = + | { kind: 'photos' } + | { kind: 'notification' } + | { kind: 'pm-batch'; values: readonly string[] }; + +/** + * Merges consecutive `pm` units into one batch step while keeping notification and photos units + * in their exact declared positions, so order, warnings, and stop-on-failure boundaries stay identical. + */ +function groupAllPermissionSteps(units: readonly AllPermissionUnit[]): AllPermissionStep[] { + const steps: AllPermissionStep[] = []; + let pendingPm: string[] = []; + const flushPm = () => { + if (pendingPm.length === 0) return; + steps.push({ kind: 'pm-batch', values: pendingPm }); + pendingPm = []; + }; + for (const unit of units) { + if (unit.kind === 'pm') { + pendingPm.push(unit.value); + } else { + flushPm(); + steps.push(unit); + } + } + flushPm(); + return steps; +} + +/** One declared-permission step: strict appops for notifications, photos probe, or batched pm. */ +async function applyAllPermissionStep(ctx: AllUnitContext, step: AllPermissionStep): Promise { + if (step.kind === 'notification') return await applyAllNotificationsUnit(ctx); + if (step.kind === 'photos') return await applyAllPhotosUnit(ctx); + if (step.values.length === 1 && ctx.action !== 'reset') { + return await applyAllPmUnit(ctx, step.values[0]!); + } + return await applyAllPmBatch(ctx, step.values); } // Notifications self-clears its reset flags inside `setAndroidNotificationPermission`, so it @@ -296,6 +336,82 @@ async function applyAllPmUnit(ctx: AllUnitContext, permission: string): Promise< await finishAllUnit(ctx, permission); } +async function applyAllPmBatch(ctx: AllUnitContext, permissions: readonly string[]): Promise { + const { appPackage, action, userArgs } = ctx; + const pmAction: 'grant' | 'revoke' = action === 'grant' ? 'grant' : 'revoke'; + const clearFlags = action === 'reset'; + const batch = await import('./settings-permission-batch.ts'); + const chunks = batch.chunkAndroidPmBatch({ + pmAction, + clearFlags, + userArgs, + appPackage, + permissions, + skipPhrases: ANDROID_PM_SKIP_PHRASE_LIST, + marker: batch.createAndroidPmBatchMarker(), + }); + + for (const chunk of chunks) { + await applyAllPmBatchChunk(ctx, batch, pmAction, clearFlags, chunk); + } +} + +async function applyAllPmBatchChunk( + ctx: AllUnitContext, + batch: typeof import('./settings-permission-batch.ts'), + pmAction: 'grant' | 'revoke', + clearFlags: boolean, + chunk: readonly string[], +): Promise { + const { device, appPackage, userArgs, warnings } = ctx; + const marker = batch.createAndroidPmBatchMarker(); + const script = batch.buildAndroidPmBatchScript({ + pmAction, + clearFlags, + userArgs, + appPackage, + permissions: chunk, + skipPhrases: ANDROID_PM_SKIP_PHRASE_LIST, + marker, + }); + // Host adb has no per-call timeout; only scoped remote providers need a capped batch timeout above their 30 s single-call default. + const timeoutMs = + resolveScopedAndroidAdbBackgroundTransport(device).mode === 'transport-composed' + ? batch.androidPmBatchTimeoutMs(chunk.length, clearFlags) + : undefined; + const batchResult = await runAndroidShell(device, [shellFragment(script)], { + allowFailure: true, + ...(timeoutMs !== undefined ? { timeoutMs } : {}), + }); + const { records, partialStdout } = batch.parseAndroidPmBatchOutput( + batchResult.stdout, + marker, + chunk.length, + ); + for (const record of records) { + const permission = chunk[record.index]!; + const outcome = classifyPmResult(pmAction, appPackage, permission, record); + if (outcome.kind === 'skipped') { + warnings.push(`Skipped ${permission} for ${appPackage}: ${outcome.detail}`); + } else { + // For `reset`, `clear-permission-flags` already ran inside the batch right after exit 0. + recordAppliedPermission(ctx, permission); + } + } + if (records.length < chunk.length) { + const failedPermission = chunk[records.length]!; + throw androidAdbResultError( + `Failed to ${pmAction} Android permission ${failedPermission} for ${appPackage}`, + { + exitCode: batchResult.exitCode !== 0 ? batchResult.exitCode : 1, + stdout: partialStdout, + stderr: batchResult.stderr, + }, + { appPackage, permission: failedPermission }, + ); + } +} + /** The shared `applied`/relaunch-warning accounting every unit records once it lands. */ function recordAppliedPermission(ctx: AllUnitContext, permission: string): void { const { appPackage, action, grants, applied, warnings } = ctx; @@ -364,21 +480,25 @@ type AndroidPmSkipReason = | 'unknown-permission' | 'role-managed'; -const ANDROID_PM_SKIP_PATTERNS: ReadonlyArray = [ - [/not a changeable permission/, 'not-changeable'], - [/has not requested permission/, 'not-requested'], - [/is not a runtime permission/, 'not-runtime-permission'], - [/unknown permission/, 'unknown-permission'], - [/managed by role/, 'role-managed'], +const ANDROID_PM_SKIP_PHRASES: ReadonlyArray = [ + ['not a changeable permission', 'not-changeable'], + ['has not requested permission', 'not-requested'], + ['is not a runtime permission', 'not-runtime-permission'], + ['unknown permission', 'unknown-permission'], + ['managed by role', 'role-managed'], ]; +const ANDROID_PM_SKIP_PHRASE_LIST: readonly string[] = ANDROID_PM_SKIP_PHRASES.map( + ([phrase]) => phrase, +); + /** * The one place `pm` stderr is read to decide whether a refusal is skippable. Every other * function in this file consumes the typed reason this returns instead of re-matching stderr. */ function classifyAndroidPmSkip(stderr: string): AndroidPmSkipReason | undefined { const text = stderr.toLowerCase(); - return ANDROID_PM_SKIP_PATTERNS.find(([pattern]) => pattern.test(text))?.[1]; + return ANDROID_PM_SKIP_PHRASES.find(([phrase]) => text.includes(phrase))?.[1]; } type AndroidPmUnitOutcome = @@ -392,6 +512,22 @@ type AndroidPmSkipAttempt = { detail: string; }; +function classifyPmResult( + pmAction: 'grant' | 'revoke', + appPackage: string, + permission: string, + result: Readonly<{ exitCode: number; stdout: string; stderr: string }>, +): AndroidPmUnitOutcome { + if (result.exitCode === 0) return { kind: 'applied' }; + const reason = classifyAndroidPmSkip(result.stderr); + if (reason) return { kind: 'skipped', reason, detail: firstStderrLine(result.stderr) }; + throw androidAdbResultError( + `Failed to ${pmAction} Android permission ${permission} for ${appPackage}`, + result, + { appPackage, permission }, + ); +} + async function tryPmUnit( device: DeviceInfo, pmAction: 'grant' | 'revoke', @@ -404,14 +540,7 @@ async function tryPmUnit( ['pm', pmAction, ...userArgs, appPackage, permission], { allowFailure: true }, ); - if (result.exitCode === 0) return { kind: 'applied' }; - const reason = classifyAndroidPmSkip(result.stderr); - if (reason) return { kind: 'skipped', reason, detail: firstStderrLine(result.stderr) }; - throw androidAdbResultError( - `Failed to ${pmAction} Android permission ${permission} for ${appPackage}`, - result, - { appPackage, permission }, - ); + return classifyPmResult(pmAction, appPackage, permission, result); } async function tryPhotosUnit( From 5273126d49ebe564dd7339cd8cd91acba97b8ebf Mon Sep 17 00:00:00 2001 From: parbez Date: Thu, 26 Nov 2026 15:55:18 +0530 Subject: [PATCH 2/2] fix(android): keep partial pm stderr when a permission batch is cut off Share one fake for batched and single pm calls in the permission tests, and name two tests after what they check. --- .../__tests__/settings-permission-all.test.ts | 71 ++++++++++++------- .../src/__tests__/settings-permission.test.ts | 57 +++++++++++---- .../test-utils/fake-android-pm-shell.ts | 31 ++++++++ .../src/settings-permission-batch.ts | 16 +++-- .../src/settings-permission.ts | 4 +- 5 files changed, 131 insertions(+), 48 deletions(-) diff --git a/packages/platform-android/src/__tests__/settings-permission-all.test.ts b/packages/platform-android/src/__tests__/settings-permission-all.test.ts index e9b41d48b5..f46af85934 100644 --- a/packages/platform-android/src/__tests__/settings-permission-all.test.ts +++ b/packages/platform-android/src/__tests__/settings-permission-all.test.ts @@ -17,6 +17,7 @@ import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts' import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts'; import { withFakeAdb } from './test-utils/fake-adb.ts'; import { + createFakeAndroidPmAdb, isAndroidPmBatchShellArgs, runFakeAndroidPmBatchInSh, type FakePmReply, @@ -41,33 +42,13 @@ function makeDumpsys( ].join('\n'); } -function makeBatchFake( - dumpsys: string, - pmReplies: Readonly> = {}, - extra?: (args: string[], options?: { timeoutMs?: number }) => unknown, -) { - const pmCalls: string[][] = []; - const batchOptions: Array<{ timeoutMs?: number }> = []; - const script = (args: string[], options?: { timeoutMs?: number }) => { - if (extra) { - const override = extra(args, options); - if (override !== undefined) return override as never; - } - if (isAndroidPmBatchShellArgs(args)) { - batchOptions.push({ timeoutMs: options?.timeoutMs }); - return runFakeAndroidPmBatchInSh(args[1]!, pmReplies, pmCalls); - } +function makeBatchFake(dumpsys: string, pmReplies: Readonly> = {}) { + return createFakeAndroidPmAdb((args) => { const flat = args.join(' '); if (flat === DUMPSYS) return dumpsys; if (flat === 'shell getprop ro.build.version.sdk') return '36'; return undefined; - }; - return { - script, - pmCalls, - batchOptions, - flatPmCalls: () => pmCalls.map((argv) => ['shell', 'pm', ...argv].join(' ')), - }; + }, pmReplies); } test('grant all batches contiguous pm units into one adb shell call and preserves order and warnings', async () => { @@ -172,7 +153,7 @@ test('reset all clears user-set and user-fixed flags inside the batch only for a }); }); -test('deny all and reset all interleave photos and notifications in exact declared order', async () => { +test('deny all interleaves photos and notifications in exact declared order', async () => { const requested = [ 'android.permission.INTERNET', 'android.permission.CAMERA', @@ -373,9 +354,49 @@ test('host adb refusal or mid-batch transport truncation surfaces classified err ); }, ); + + // Truncated after the exit code: the `pm` stderr that already arrived stays in the error. + await withFakeAdb( + (args) => { + if (args.join(' ') === DUMPSYS) return makeDumpsys(requested); + if (isAndroidPmBatchShellArgs(args)) { + const match = /'(__AD_PM_BATCH_[0-9a-f]+__):OUT:'/.exec(args[1]!); + assert.ok(match?.[1]); + const marker = match[1]; + return { + stdout: `${marker}:OUT:0\nout\n${marker}:ERR:0:1\nFailure: permission service crashed\n`, + stderr: "adb: protocol fault (couldn't read status)", + exitCode: 1, + }; + } + return undefined; + }, + async ({ device }) => { + await assert.rejects( + () => + setAndroidPermission( + device, + 'com.example.app', + parseAndroidPermissionRequest('grant', { permissionTarget: 'all' }), + 0, + ), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.permission, 'android.permission.CAMERA'); + assert.equal(error.details?.stdout, 'out\n'); + assert.equal( + error.details?.stderr, + "Failure: permission service crashed\nadb: protocol fault (couldn't read status)", + ); + assert.equal(error.details?.adbFailure, 'connection_dropped'); + return true; + }, + ); + }, + ); }); -test('host adb passes no batch timeout while scoped remote providers receive a capped batch timeout', async () => { +test('batch timeout caps at 90 s and host adb passes none', async () => { assert.equal(androidPmBatchTimeoutMs(1, false), 30_500); assert.equal(androidPmBatchTimeoutMs(55, false), 57_500); assert.equal(androidPmBatchTimeoutMs(55, true), 90_000); diff --git a/packages/platform-android/src/__tests__/settings-permission.test.ts b/packages/platform-android/src/__tests__/settings-permission.test.ts index c83766db81..8fc26c7ef7 100644 --- a/packages/platform-android/src/__tests__/settings-permission.test.ts +++ b/packages/platform-android/src/__tests__/settings-permission.test.ts @@ -10,11 +10,7 @@ import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts'; import { AppError } from '@agent-device/kernel/errors'; import { assertRejectsAppError } from './test-utils/app-error.ts'; import { withFakeAdb } from './test-utils/fake-adb.ts'; -import { - isAndroidPmBatchShellArgs, - runFakeAndroidPmBatchInSh, - type FakePmReply, -} from './test-utils/fake-android-pm-shell.ts'; +import { createFakeAndroidPmAdb, type FakePmReply } from './test-utils/fake-android-pm-shell.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { SettingOptions } from '@agent-device/contracts/settings'; @@ -562,15 +558,7 @@ function fakeAllAdb( baseScript: (flat: string) => FakeAdbReply, pmReplies: Readonly> = {}, ) { - const pmCalls: string[][] = []; - const script = (args: string[]) => { - if (isAndroidPmBatchShellArgs(args)) { - return runFakeAndroidPmBatchInSh(args[1]!, pmReplies, pmCalls); - } - return baseScript(args.join(' ')); - }; - const flatPmCalls = () => pmCalls.map((argv) => ['shell', 'pm', ...argv].join(' ')); - return { script, pmCalls, flatPmCalls }; + return createFakeAndroidPmAdb((args) => baseScript(args.join(' ')), pmReplies); } // `all` intersects the declared set before issuing anything: INTERNET is declared @@ -615,6 +603,47 @@ test('setAndroidPermission grant all applies the declared changeable ids', async }); }); +// A lone declared id skips the batch and runs one plain `shell pm` call; its refusal is +// classified the same way and skipped with the reason. +test('setAndroidPermission grant all skips a lone unchangeable id on the single-call path', async () => { + const requested = [ + 'Packages:', + ' Package [com.example.app] (abc):', + ' requested permissions:', + ' android.permission.INTERNET', + 'Queries:', + ].join('\n'); + const fake = fakeAllAdb( + (flat) => { + if (flat === CURRENT_USER) return '0'; + if (flat === DUMPSYS) return requested; + return undefined; + }, + { + 'shell pm grant --user 0 com.example.app android.permission.INTERNET': { + stderr: 'SecurityException: INTERNET is not a changeable permission type', + exitCode: 1, + }, + }, + ); + await withFakeAdb(fake.script, async ({ device }) => { + const result = await setPermission(device, 'grant', 'com.example.app', { + permissionTarget: 'all', + }); + assert.deepEqual(fake.batchOptions, []); + assert.deepEqual(fake.flatPmCalls(), [ + 'shell pm grant --user 0 com.example.app android.permission.INTERNET', + ]); + assert.deepEqual(result, { + permission: 'all', + permissions: [], + warnings: [ + 'Skipped android.permission.INTERNET for com.example.app: SecurityException: INTERNET is not a changeable permission type', + ], + }); + }); +}); + // A role-managed id (WRITE_SETTINGS on API 36: "managed by role") is // declared-but-not-changeable like INTERNET, so `all` skips it with a reason // instead of aborting — found live on com.google.android.contacts. diff --git a/packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts b/packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts index 41898199d4..cdfe40470a 100644 --- a/packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts +++ b/packages/platform-android/src/__tests__/test-utils/fake-android-pm-shell.ts @@ -74,3 +74,34 @@ export function runFakeAndroidPmBatchInSh( export function isAndroidPmBatchShellArgs(args: readonly string[]): boolean { return args[0] === 'shell' && args.length === 2 && args[1]!.includes('__AD_PM_BATCH_'); } + +/** + * A fake adb script for `settings permission ... all`: batched `pm` scripts run through + * {@link runFakeAndroidPmBatchInSh}, single `shell pm ...` calls answer from the same + * `pmReplies`, and both land in `pmCalls`. Everything else goes to `fallback`. + */ +export function createFakeAndroidPmAdb( + fallback: (args: string[]) => FakeAdbResponse | undefined, + pmReplies: Readonly> = {}, +) { + const pmCalls: string[][] = []; + const batchOptions: Array<{ timeoutMs?: number }> = []; + const script = (args: string[], options?: { timeoutMs?: number }) => { + if (isAndroidPmBatchShellArgs(args)) { + batchOptions.push({ timeoutMs: options?.timeoutMs }); + return runFakeAndroidPmBatchInSh(args[1]!, pmReplies, pmCalls); + } + if (args[0] === 'shell' && args[1] === 'pm') { + pmCalls.push(args.slice(2)); + const reply = pmReplies[args.join(' ')]; + if (reply) return { stdout: '', stderr: '', exitCode: 0, ...reply }; + } + return fallback(args); + }; + return { + script, + pmCalls, + batchOptions, + flatPmCalls: () => pmCalls.map((argv) => ['shell', 'pm', ...argv].join(' ')), + }; +} diff --git a/packages/platform-android/src/settings-permission-batch.ts b/packages/platform-android/src/settings-permission-batch.ts index d387079805..92d7c241b3 100644 --- a/packages/platform-android/src/settings-permission-batch.ts +++ b/packages/platform-android/src/settings-permission-batch.ts @@ -143,6 +143,8 @@ export type AndroidPmBatchRecord = Readonly<{ export type AndroidPmBatchParseResult = Readonly<{ records: readonly AndroidPmBatchRecord[]; partialStdout: string; + /** `pm` stderr of the incomplete record, when its stream started before the output stopped. */ + partialStderr: string; }>; function skipLineEnding(text: string, pos: number): number | undefined { @@ -167,28 +169,28 @@ export function parseAndroidPmBatchOutput( const outTag = `${marker}:OUT:${index}`; const outPos = stdout.indexOf(outTag, cursor); if (outPos === -1) { - return { records, partialStdout: stdout.slice(cursor) }; + return { records, partialStdout: stdout.slice(cursor), partialStderr: '' }; } const contentStart = skipLineEnding(stdout, outPos + outTag.length); if (contentStart === undefined) { - return { records, partialStdout: stdout.slice(cursor) }; + return { records, partialStdout: stdout.slice(cursor), partialStderr: '' }; } const errPrefix = `${marker}:ERR:${index}:`; const errPos = stdout.indexOf(errPrefix, contentStart); if (errPos === -1) { - return { records, partialStdout: stdout.slice(contentStart) }; + return { records, partialStdout: stdout.slice(contentStart), partialStderr: '' }; } const cmdStdout = stdout.slice(contentStart, errPos); const rcStart = errPos + errPrefix.length; const rcLineEnd = stdout.indexOf('\n', rcStart); if (rcLineEnd === -1) { - return { records, partialStdout: cmdStdout }; + return { records, partialStdout: cmdStdout, partialStderr: '' }; } const rcText = stdout.slice(rcStart, rcLineEnd).replace(/\r$/, ''); if (!/^\d+$/.test(rcText)) { - return { records, partialStdout: cmdStdout }; + return { records, partialStdout: cmdStdout, partialStderr: '' }; } const exitCode = Number.parseInt(rcText, 10); @@ -196,7 +198,7 @@ export function parseAndroidPmBatchOutput( const endTag = `${marker}:END:${index}`; const endPos = stdout.indexOf(endTag, errStart); if (endPos === -1) { - return { records, partialStdout: cmdStdout }; + return { records, partialStdout: cmdStdout, partialStderr: stdout.slice(errStart) }; } const cmdStderr = stdout.slice(errStart, endPos); @@ -205,5 +207,5 @@ export function parseAndroidPmBatchOutput( cursor = skipLineEnding(stdout, afterEnd) ?? afterEnd; } - return { records, partialStdout: '' }; + return { records, partialStdout: '', partialStderr: '' }; } diff --git a/packages/platform-android/src/settings-permission.ts b/packages/platform-android/src/settings-permission.ts index 2da7deb87f..c4574f5dab 100644 --- a/packages/platform-android/src/settings-permission.ts +++ b/packages/platform-android/src/settings-permission.ts @@ -383,7 +383,7 @@ async function applyAllPmBatchChunk( allowFailure: true, ...(timeoutMs !== undefined ? { timeoutMs } : {}), }); - const { records, partialStdout } = batch.parseAndroidPmBatchOutput( + const { records, partialStdout, partialStderr } = batch.parseAndroidPmBatchOutput( batchResult.stdout, marker, chunk.length, @@ -405,7 +405,7 @@ async function applyAllPmBatchChunk( { exitCode: batchResult.exitCode !== 0 ? batchResult.exitCode : 1, stdout: partialStdout, - stderr: batchResult.stderr, + stderr: partialStderr + batchResult.stderr, }, { appPackage, permission: failedPermission }, );