Skip to content

Commit 0f5d1cc

Browse files
committed
fix(android): refuse permission mutations that cannot name their user
The fallback issued bare pm/appops commands when am get-current-user did not answer, which is the #1796 defect itself: those default to UserHandle.USER_SYSTEM, so a session running as user 10 had user 0 edited while the response reported only priorGrantState: unknown. It was also a fallback added without approval, and the docs' claim that every mutation names its user was false on that path. Resolving the acting user is now a prerequisite: setAndroidSetting permission fails with COMMAND_FAILED and a recovery hint, issuing no pm, appops or clear-permission-flags call at all. The test that locked the fallback in is replaced by one asserting the empty mutation call list for grant, deny and reset.
1 parent fd39b44 commit 0f5d1cc

5 files changed

Lines changed: 59 additions & 35 deletions

File tree

‎src/commands/capture/settings.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export const settingsCommandFacet = defineCommandFacet({
6060
text: {
6161
summary: 'Change OS settings and app permissions',
6262
cliDetail:
63-
'macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location|animations remain unsupported on macOS. Mobile permission actions use the active session app. On Android, deny|reset of a permission the app currently holds kills a running app; the response reports priorGrantState (granted|not_granted|unknown) and warns for granted and unknown, with open <app> --relaunch to restore it.',
63+
'macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location|animations remain unsupported on macOS. Mobile permission actions use the active session app. On Android, deny|reset of a permission the app currently holds kills a running app; the response reports priorGrantState (granted|not_granted|unknown) and warns for granted and unknown, with open <app> --relaunch to restore it. Permission changes require a resolvable foreground user and fail without mutating if adb cannot report one.',
6464
},
6565
metadata: settingsCommandMetadata,
6666
definition: settingsCommandDefinition,

‎src/platforms/android/__tests__/settings-permission.test.ts‎

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,6 @@ test.each([
187187
fakeAdb((flat) => (flat === DUMPSYS ? 'Packages:' : '0')),
188188
'unknown',
189189
],
190-
[
191-
'the acting user cannot be resolved',
192-
fakeAdb((flat) =>
193-
flat === CURRENT_USER ? { stderr: 'cmd: not found', exitCode: 1 } : dumpsys([{ id: 0 }]),
194-
),
195-
'unknown',
196-
],
197190
] as const)(
198191
'setAndroidSetting permission deny reports %s',
199192
async (_label, script, priorGrantState) => {
@@ -230,23 +223,34 @@ test('the revoke warning states the platform rule and keeps the consequence cond
230223
);
231224
});
232225

233-
// No resolvable user means no way to address one: the mutation keeps the platform default.
234-
test('setAndroidSetting permission deny omits --user when the foreground user is unknown', async () => {
235-
await withFakeAdb(
236-
fakeAdb((flat) =>
237-
flat === CURRENT_USER ? { stderr: 'cmd: not found', exitCode: 1 } : undefined,
238-
),
239-
async ({ calls, device }) => {
240-
await setAndroidSetting(device, 'permission', 'deny', 'com.example.app', {
241-
permissionTarget: 'microphone',
242-
});
243-
assert.deepEqual(calls, [
244-
['shell', 'am', 'get-current-user'],
245-
['shell', 'pm', 'revoke', 'com.example.app', MICROPHONE],
246-
]);
247-
},
248-
);
249-
});
226+
// A mutation that cannot name its user is refused, not issued unscoped: `pm` would apply it to
227+
// user 0 and leave a session running as another user untouched, which is the whole defect.
228+
test.each(['grant', 'deny', 'reset'] as const)(
229+
'setAndroidSetting permission %s refuses to mutate when the acting user cannot be resolved',
230+
async (action) => {
231+
await withFakeAdb(
232+
fakeAdb((flat) =>
233+
flat === CURRENT_USER ? { stderr: 'cmd: not found', exitCode: 1 } : undefined,
234+
),
235+
async ({ calls, device }) => {
236+
await assertRejectsAppError(
237+
() =>
238+
setAndroidSetting(device, 'permission', action, 'com.example.app', {
239+
permissionTarget: 'microphone',
240+
}),
241+
{
242+
code: 'COMMAND_FAILED',
243+
message: /Could not determine which Android user/,
244+
hint: /am get-current-user/,
245+
},
246+
);
247+
// The load-bearing assertion: the resolution attempt is the ONLY adb call. No pm, no
248+
// appops, no clear-permission-flags — nothing that could edit user 0's state.
249+
assert.deepEqual(calls, [['shell', 'am', 'get-current-user']]);
250+
},
251+
);
252+
},
253+
);
250254

251255
// `photos` is the one target whose permission is discovered by probing the device, so its
252256
// SDK-dependent candidate order and the flags that follow the resolved permission are pinned.

‎src/platforms/android/permission-grant-state.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ export type AndroidPriorGrantState = 'granted' | 'not_granted' | 'unknown';
2020
export type AndroidRuntimePermissionGrants = ReadonlyMap<string, 'granted' | 'not_granted'>;
2121

2222
/**
23-
* `userId`'s runtime permissions, or `undefined` when the state could not be read — no acting
24-
* user, adb failed, or the dump carried no runtime-permission block for that user.
23+
* `userId`'s runtime permissions, or `undefined` when the state could not be read — adb failed,
24+
* or the dump carried no runtime-permission block for that user.
2525
*
2626
* The caller passes the user its mutation will target, so the two halves cannot disagree.
2727
* `dumpsys package` prints an `install permissions:` section and one block per user, all
@@ -31,9 +31,8 @@ export type AndroidRuntimePermissionGrants = ReadonlyMap<string, 'granted' | 'no
3131
export async function readAndroidRuntimePermissionGrants(
3232
device: DeviceInfo,
3333
appPackage: string,
34-
userId: number | undefined,
34+
userId: number,
3535
): Promise<AndroidRuntimePermissionGrants | undefined> {
36-
if (userId === undefined) return undefined;
3736
const result = await runAndroidAdb(device, ['shell', 'dumpsys', 'package', appPackage], {
3837
allowFailure: true,
3938
});

‎src/platforms/android/settings-permission.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,33 @@ type AndroidPermissionTarget = ReturnType<typeof parseAndroidPermissionTarget>;
3737

3838
/**
3939
* `--user <id>` for every permission mutation, resolved once so the state read and the mutation
40-
* cannot address different users. Empty only when the foreground user could not be resolved, in
41-
* which case the platform default (`UserHandle.USER_SYSTEM`) applies and the prior state is
42-
* reported as unknown rather than guessed.
40+
* cannot address different users. Never empty: a permission mutation that cannot name its user
41+
* is refused rather than issued (see `requireAndroidPermissionUser`).
4342
*/
4443
type AndroidUserArgs = readonly string[];
4544

45+
/**
46+
* The user a permission mutation will act on, or a refusal.
47+
*
48+
* `pm` and `appops` default to `UserHandle.USER_SYSTEM`, so an unscoped mutation on a device
49+
* whose foreground user is nonzero edits user 0 and leaves the running app untouched — the
50+
* defect #1796 is about. Issuing the bare command as a fallback would reintroduce it on exactly
51+
* the path where we already know we are guessing, so the command refuses instead: no permission
52+
* state is changed when we cannot name whose state it is.
53+
*/
54+
async function requireAndroidPermissionUser(device: DeviceInfo): Promise<number> {
55+
const userId = await readAndroidCurrentUserId(device);
56+
if (userId !== undefined) return userId;
57+
throw new AppError(
58+
'COMMAND_FAILED',
59+
'Could not determine which Android user the session runs as, so no permission was changed.',
60+
{
61+
deviceId: device.id,
62+
hint: `Check adb -s ${device.id} shell am get-current-user — if the device is still booting, retry once it reports a user. agent-device refuses to change permissions it cannot scope, because pm would silently apply them to user 0.`,
63+
},
64+
);
65+
}
66+
4667
export async function setAndroidPermission(
4768
device: DeviceInfo,
4869
appPackage: string,
@@ -51,8 +72,8 @@ export async function setAndroidPermission(
5172
): Promise<Record<string, unknown> | void> {
5273
const action = parsePermissionAction(state);
5374
const target = parseAndroidPermissionTarget(options?.permissionTarget, options?.permissionMode);
54-
const userId = await readAndroidCurrentUserId(device);
55-
const userArgs: AndroidUserArgs = userId === undefined ? [] : ['--user', String(userId)];
75+
const userId = await requireAndroidPermissionUser(device);
76+
const userArgs: AndroidUserArgs = ['--user', String(userId)];
5677
if (action === 'grant') {
5778
await grantAndroidPermission(device, appPackage, target, userArgs);
5879
return;

‎website/docs/docs/commands.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -673,7 +673,7 @@ agent-device settings permission reset screen-recording --platform macos
673673
- macOS permission targets: `accessibility`, `screen-recording`, `input-monitoring`.
674674
- On macOS, `settings permission grant ...` checks/request access and opens System Settings guidance when needed; it does not silently grant TCC permissions.
675675
- On macOS, `settings permission deny ...` is intentionally unsupported.
676-
- Android uses `pm grant|revoke` for runtime permissions (`reset` maps to revoke) and `appops` for notifications. Every permission mutation names the foreground user explicitly (`--user <id>`, resolved with `am get-current-user`): `pm` defaults these operations to user 0, so on a device whose foreground user is nonzero an unscoped revoke would edit user 0 and leave the running app's permission untouched.
676+
- Android uses `pm grant|revoke` for runtime permissions (`reset` maps to revoke) and `appops` for notifications. Every permission mutation names the foreground user explicitly (`--user <id>`, resolved with `am get-current-user`): `pm` defaults these operations to user 0, so on a device whose foreground user is nonzero an unscoped revoke would edit user 0 and leave the running app's permission untouched. Resolving that user is a prerequisite — if `am get-current-user` does not answer, `settings permission` fails with `COMMAND_FAILED` and changes nothing rather than applying the mutation to user 0.
677677
- Android kills a running app whenever a runtime permission it currently holds is revoked, so `settings permission deny|reset` after a grant leaves the session app no longer running. The response reports the prior state of the revoked permission for the acting user as `priorGrantState: granted | not_granted | unknown`, and carries a warning naming `open <app> --relaunch` for both `granted` and `unknown` — `unknown` means the device did not report a readable state, not that the app was left alone. Revoking a permission the app does not hold (`not_granted`) is harmless and warns nothing.
678678
- `full|limited` mode is supported only for iOS `photos`; other targets reject mode.
679679
- Use `match`/`nonmatch` to simulate valid/invalid Face ID, Touch ID, and Android fingerprint outcomes.

0 commit comments

Comments
 (0)