Skip to content

Commit d29dc22

Browse files
authored
fix(android): warn when a permission revoke kills the session app (#1856)
* fix(android): warn when a permission revoke kills the session app settings permission deny|reset maps to pm revoke, and Android kills the app's process whenever a runtime permission it currently holds is revoked, so a grant -> deny/reset sequence silently left the session on the launcher and the next selector failed with no hint. The revoke path now reads the prior grant state from dumpsys package first and, when it was granted, returns wasGranted: true plus a warning naming open <app> --relaunch; the settings CLI output renders response warnings, and commands.md documents the behavior next to the pm revoke mapping. Closes #1796 * fix(android): state the revoke-kill consequence conditionally Review finding: the warning asserted the app had been killed, inferred only from the prior grant state. dumpsys reports granted=true for any user profile while pm revoke acts on the current one, and the app need not have been running, so the claim could be false. State the platform rule and make the consequence conditional; the relaunch guidance is unchanged. * fix(android): model the prior grant state as granted/not_granted/unknown A failed or unparseable dumpsys read as "nothing granted", so the response asserted the app was untouched when the state was simply unknown, and the grant scan matched every granted=true line — install permissions and other users' blocks included — so another profile's grant could claim a kill that never happened. Both directions of the same defect. The read now resolves the acting user (am get-current-user) and walks the dump's nesting (Packages: > User <id>: > runtime permissions:), and reports priorGrantState: granted | not_granted | unknown. unknown carries the same relaunch guidance without claiming what the state was; only not_granted is silent. * fix(android): address the foreground user in every permission mutation The tri-state read scoped state to am get-current-user, but the mutations ran bare pm grant/revoke and clear-permission-flags. PackageManagerShellCommand defaults those to UserHandle.USER_SYSTEM, so on a device whose foreground user is nonzero the command read one user's state and edited user 0 — leaving the running app's permission untouched while reporting on a user it did not change. Proven on a Pixel 7 / API 36 emulator with the foreground user switched to 10: a bare pm revoke flipped User 0 to granted=false and left User 10 granted=true. The foreground user is now resolved once and passed as --user to pm grant/revoke, pm clear-permission-flags, and appops set, and the state read takes that same id. When it cannot be resolved the mutation keeps the platform default and the state is reported unknown rather than guessed. * test(android): pin the user-scoped permission argv in the provider scenario The scripted ADB provider answered only the unscoped pm grant/revoke form, and the Settings contract asserted the unscoped transcript entry, so the provider lane could not see which user a permission mutation addressed. * test(android): extract the settings contract out of the lifecycle monolith The user-scoped argv assertions pushed android-lifecycle.test.ts past its size ratchet, whose instruction is to extract rather than grow a file over the tripwire. assertAndroidSettingsContract moves to a sibling module and the pin drops 1597 -> 1559. * refactor(android): shrink the permission path to one concept per file Size/design pass on the #1796 change: - settings.ts was 505 lines (past the 500 extract-before-adding tripwire); the permission family moves to settings-permission.ts and the dispatcher drops to 265. - permission-grant-state.ts loses topLevelSection (a nestedBlock with an indent-0 header), its single-use line reader, and androidPriorGrantState (one map lookup at its only production call site). - the grants map narrows to 'granted' | 'not_granted': unknown was never a value, absence is what carries it, so the tests read the map directly. - the permission tests move to settings-permission.test.ts and consolidate into argv/tri-state/photos/rejection tables; the parser tests fold seven cases into two. Every red-proof re-run after the consolidation: dropping --user reds 7 argv/photos cases, and the pre-fix state model reds 13 across both files. * 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 393eb30 commit d29dc22

14 files changed

Lines changed: 911 additions & 338 deletions

‎src/__tests__/test-file-size-ratchet.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ const PINNED_TEST_FILE_LINES: Readonly<Record<string, number>> = Object.freeze({
4343
'src/platforms/android/__tests__/snapshot.test.ts': 1660,
4444
'src/platforms/apple/core/__tests__/runner-client.test.ts': 1615,
4545
'src/__tests__/client.test.ts': 1598,
46-
'test/integration/provider-scenarios/android-lifecycle.test.ts': 1597,
46+
'test/integration/provider-scenarios/android-lifecycle.test.ts': 1559,
4747
'src/utils/__tests__/daemon-client-lifecycle.test.ts': 1414,
4848
'src/platforms/apple/core/__tests__/runner-command-retry.test.ts': 1327,
4949
'src/__tests__/cli-client-commands.test.ts': 1317,

‎src/commands/capture/index.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { alertCliReader, alertDaemonWriter } from './alert.ts';
44
import { diffCliReader } from './diff.ts';
55
import { snapshotCliOutput } from './output.ts';
66
import { screenshotCliReader, screenshotDaemonWriter } from './screenshot.ts';
7-
import { settingsCliReader, settingsDaemonWriter } from './settings.ts';
7+
import { settingsCliReader, settingsCommandFacet, settingsDaemonWriter } from './settings.ts';
88
import { snapshotCliReader } from './snapshot.ts';
99
import { waitCliReader, waitDaemonWriter } from './wait.ts';
1010

@@ -187,4 +187,26 @@ describe('capture command interface', () => {
187187
positionals: ['permission', 'grant', 'camera', 'limited'],
188188
});
189189
});
190+
191+
// #1796: the Android revoke warning rides `warnings`; the human CLI line must show it.
192+
test('settings CLI output renders response warnings after the message', () => {
193+
const warning = 'android.permission.CAMERA was granted before this revoke, and Android …';
194+
const output = settingsCommandFacet.cliOutputFormatter!({
195+
input: {},
196+
result: { setting: 'permission', state: 'reset', message: 'Updated setting: permission' },
197+
});
198+
expect(output.text).toBe('Updated setting: permission');
199+
200+
const warned = settingsCommandFacet.cliOutputFormatter!({
201+
input: {},
202+
result: {
203+
setting: 'permission',
204+
state: 'reset',
205+
message: 'Updated setting: permission',
206+
warnings: [warning],
207+
},
208+
});
209+
expect(warned.text).toBe(`Updated setting: permission\nWarning: ${warning}`);
210+
expect(warned.data).toMatchObject({ warnings: [warning] });
211+
});
190212
});

‎src/commands/capture/settings.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
import type { CliReader, DaemonWriter } from '../cli-grammar/types.ts';
1818
import { defineCommandFacet } from '../family/types.ts';
1919
import { defineFieldCommandMetadata } from '../field-command-contract.ts';
20+
import { messageWithWarningsOutput } from '../output-common.ts';
2021

2122
const SETTINGS_COMMAND_NAME = 'settings';
2223
const settingsCommandDescription =
@@ -59,13 +60,15 @@ export const settingsCommandFacet = defineCommandFacet({
5960
text: {
6061
summary: 'Change OS settings and app permissions',
6162
cliDetail:
62-
'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.',
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.',
6364
},
6465
metadata: settingsCommandMetadata,
6566
definition: settingsCommandDefinition,
6667
cliSchema: settingsCliSchema,
6768
cliReader: settingsCliReader,
6869
daemonWriter: settingsDaemonWriter,
70+
// Android permission revokes append a relaunch warning (#1796); render it for humans too.
71+
cliOutputFormatter: messageWithWarningsOutput,
6972
});
7073

7174
// fallow-ignore-next-line complexity

‎src/commands/output-common.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,23 @@ export function messageCliOutput(result: Record<string, unknown>): CliOutput {
1818
return { data: result, text: readCommandMessage(result) };
1919
}
2020

21+
/**
22+
* `messageCliOutput` plus one `Warning:` line per entry of the response's `warnings`
23+
* array — the composable warnings channel (`open`, `debug`, snapshot capture use it too),
24+
* so a warning the daemon appended reaches the human CLI reader, not only `--json`.
25+
*/
26+
export const messageWithWarningsOutput = resultOutput(
27+
(result: Record<string, unknown>): CliOutput => {
28+
const output = messageCliOutput(result);
29+
const warnings = Array.isArray(result.warnings)
30+
? result.warnings.filter((warning): warning is string => typeof warning === 'string')
31+
: [];
32+
if (warnings.length === 0) return output;
33+
const lines = [output.text, ...warnings.map((warning) => `Warning: ${warning}`)];
34+
return { data: output.data, text: lines.filter(Boolean).join('\n') };
35+
},
36+
);
37+
2138
/**
2239
* ADR 0014: a reusable ref in a PARTIAL result renders in ready-to-copy
2340
* `@eN~s<refsGeneration>` form so a human CLI caller can paste it into the next
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import { parseAndroidRuntimePermissionGrants } from '../permission-grant-state.ts';
4+
5+
// Captured from `adb shell dumpsys package com.callstack.agentdevicelab` on a Pixel 7 / API 36
6+
// emulator, trimmed to the sections that decide the answer. The indentation is load-bearing:
7+
// `install permissions:` and each `User <id>:` sit at the same depth, and the runtime grants
8+
// hang under the user block — which is the only reason the two can be told apart.
9+
const DUMPSYS = [
10+
'Packages:',
11+
' Package [com.example.app] (5f3a1c2):',
12+
' install permissions:',
13+
' android.permission.MODIFY_AUDIO_SETTINGS: granted=true',
14+
' android.permission.RECORD_AUDIO: granted=true',
15+
' User 0: ceDataInode=1032405 installed=true hidden=false stopped=false',
16+
' gids=[3003]',
17+
' runtime permissions:',
18+
' android.permission.RECORD_AUDIO: granted=false, flags=[ USER_SENSITIVE_WHEN_GRANTED]',
19+
' android.permission.CAMERA: granted=true, flags=[ USER_SET]',
20+
' User 10: ceDataInode=99 installed=true hidden=false stopped=false',
21+
' runtime permissions:',
22+
' android.permission.RECORD_AUDIO: granted=true, flags=[ USER_SET]',
23+
'',
24+
'Queries:',
25+
' queryable via interaction:',
26+
' User 0:',
27+
'',
28+
'Dexopt state:',
29+
' [com.example.app]',
30+
' path: /data/app/~~abc==/com.example.app-def==',
31+
].join('\n');
32+
33+
// `undefined` is the answer for anything the dump does not place inside the requested user's
34+
// runtime block: an install-permission grant (`pm revoke` cannot touch it), another profile's
35+
// grant, or a permission that user never declared. The caller reports that as `unknown`.
36+
test.each([
37+
[0, 'android.permission.RECORD_AUDIO', 'not_granted', 'acting user overrides the install grant'],
38+
[0, 'android.permission.CAMERA', 'granted', 'acting user'],
39+
[10, 'android.permission.RECORD_AUDIO', 'granted', 'other profile, only when asked for'],
40+
[10, 'android.permission.CAMERA', undefined, 'absent for that user'],
41+
[0, 'android.permission.MODIFY_AUDIO_SETTINGS', undefined, 'install-only'],
42+
[0, 'android.permission.INTERNET', undefined, 'never mentioned'],
43+
] as const)('user %s reads %s as %s (%s)', (userId, permission, expected, _why) => {
44+
assert.equal(parseAndroidRuntimePermissionGrants(DUMPSYS, userId)?.get(permission), expected);
45+
});
46+
47+
// A missing block is not an empty one. Every input here means "the device did not tell us",
48+
// which must stay distinguishable from "the app holds nothing".
49+
test.each([
50+
['no runtime block for that user', DUMPSYS, 11],
51+
['empty output', '', 0],
52+
['no Packages section', 'Activity Resolver Table:\n User 0:\n runtime permissions:', 0],
53+
['a package section without the user', 'Packages:\n Package [com.example.app] (abc):', 0],
54+
] as const)('%s reads as unknown', (_label, output, userId) => {
55+
assert.equal(parseAndroidRuntimePermissionGrants(output, userId), undefined);
56+
});
57+
58+
test('an empty runtime block answers not_granted for everything it could have listed', () => {
59+
// Distinct from a missing block: the device reported the list and it was empty, so the app
60+
// holds nothing — a claim the parser is allowed to make.
61+
const grants = parseAndroidRuntimePermissionGrants(
62+
[
63+
'Packages:',
64+
' Package [com.example.app] (5f3a1c2):',
65+
' User 0: installed=true',
66+
' runtime permissions:',
67+
' User 10: installed=true',
68+
].join('\n'),
69+
0,
70+
);
71+
assert.notEqual(grants, undefined);
72+
assert.equal(grants?.size, 0);
73+
});
74+
75+
test('sections after Packages: cannot reopen the scan', () => {
76+
// `Queries:` repeats `User 0:` with no grants, and `Shared users:` repeats runtime grant lines
77+
// for the shared uid. Merging either would flip RECORD_AUDIO to granted for a user whose own
78+
// block says otherwise — the same wrong-answer class as reading the install section.
79+
const grants = parseAndroidRuntimePermissionGrants(
80+
[
81+
DUMPSYS,
82+
'Shared users:',
83+
' SharedUser [android.uid.shared] (a1b2):',
84+
' User 0: ceDataInode=0 installed=true',
85+
' runtime permissions:',
86+
' android.permission.RECORD_AUDIO: granted=true, flags=[ USER_SET]',
87+
].join('\n'),
88+
0,
89+
);
90+
91+
assert.equal(grants?.get('android.permission.RECORD_AUDIO'), 'not_granted');
92+
assert.equal(grants?.get('android.permission.CAMERA'), 'granted');
93+
});

0 commit comments

Comments
 (0)