Repository navigation
Expand file tree
/
Copy pathdaemon-policy.test.ts
More file actions
279 lines (232 loc) · 10.3 KB
/
Copy pathdaemon-policy.test.ts
File metadata and controls
279 lines (232 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import fs from 'node:fs';
import path from 'node:path';
import { beforeEach, expect, test, vi } from 'vitest';
import { getResolveTargetDeviceMock } from './request-router-dispatch-mocks.ts';
vi.mock('../device/device-ready.ts', () => ({ ensureDeviceReady: vi.fn(async () => {}) }));
import type { DeviceInfo } from '@agent-device/kernel/device';
import { ANDROID_EMULATOR, IOS_SIMULATOR } from '../../__tests__/test-utils/device-fixtures.ts';
import { createTestDeviceInventoryGateways } from '../../__tests__/test-utils/device-inventory-gateways.ts';
import { makeIosSession } from '../../__tests__/test-utils/session-factories.ts';
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
import { parseDaemonPolicy } from '../../daemon-policy-file.ts';
import { assertDaemonPolicyAdmitsRequest } from '../daemon-policy.ts';
import type { DaemonRequest } from '../daemon-request.ts';
import { LeaseRegistry } from '../lease-registry.ts';
import { createHostDiagnostics } from '../../platform-runtime-host-diagnostics.ts';
import {
createRequestHandler,
lifecycleDeviceRuntimeGateway,
systemRuntimeSpies,
} from './test-device-runtime-gateway.ts';
const mockResolveTargetDevice = vi.mocked(getResolveTargetDeviceMock());
const OTHER_SIMULATOR: DeviceInfo = { ...IOS_SIMULATOR, id: 'sim-2', name: 'iPhone 16' };
beforeEach(() => {
systemRuntimeSpies.appSwitcher.mockClear();
mockResolveTargetDevice.mockReset();
mockResolveTargetDevice.mockResolvedValue(IOS_SIMULATOR);
});
function policy(raw: Record<string, unknown>) {
return parseDaemonPolicy({ version: 1, ...raw }, '/etc/agent-device/policy.json');
}
function makeHandler(
daemonPolicy: ReturnType<typeof policy>,
options: { inventory?: readonly DeviceInfo[]; providerInventory?: readonly DeviceInfo[] } = {},
) {
const sessionStore = makeSessionStore('agent-device-daemon-policy-');
sessionStore.set('default', makeIosSession('default', { appBundleId: 'com.example.app' }));
const bind = vi.fn(lifecycleDeviceRuntimeGateway.bind);
const inspectFacts = vi.fn(lifecycleDeviceRuntimeGateway.inspectFacts);
const handler = createRequestHandler({
logPath: path.join(mkdtempForTestSync('daemon-policy'), 'daemon.log'),
token: 'test-token',
sessionStore,
leaseRegistry: new LeaseRegistry(),
deviceRuntimeGateway: { ...lifecycleDeviceRuntimeGateway, bind, inspectFacts },
deviceInventoryGateways: createTestDeviceInventoryGateways({
local: async () => options.inventory ?? [],
provider: options.providerInventory
? {
discover: async () => ({
kind: 'inventory',
devices: [...(options.providerInventory ?? [])],
}),
}
: undefined,
}),
trackDownloadableArtifact: () => 'artifact-id',
hostDiagnostics: createHostDiagnostics(),
daemonPolicy,
});
return { handler, bind, inspectFacts };
}
function request(command: string, extra: Partial<DaemonRequest> = {}): DaemonRequest {
return {
token: 'test-token',
session: 'default',
command,
positionals: [],
...extra,
meta: { requestId: `policy-${command}`, sessionExplicit: true, ...extra.meta },
};
}
function expectPolicyDenied(response: unknown, rule: string) {
expect(response).toMatchObject({
ok: false,
error: { code: 'UNAUTHORIZED', details: { reason: 'DAEMON_POLICY_DENIED', rule } },
});
}
test('a denied command is refused before it binds a device', async () => {
const { handler, bind } = makeHandler(policy({ commands: { deny: ['app-switcher'] } }));
const response = await handler(request('app-switcher'));
expectPolicyDenied(response, 'command');
expect(bind).not.toHaveBeenCalled();
expect(systemRuntimeSpies.appSwitcher).not.toHaveBeenCalled();
});
test('an allow list admits only the commands it names', async () => {
const { handler } = makeHandler(policy({ commands: { allow: ['app-switcher'] } }));
expect(await handler(request('app-switcher'))).toMatchObject({ ok: true });
expectPolicyDenied(await handler(request('shutdown')), 'command');
});
test('a batch naming a denied step is refused before any step runs', async () => {
const { handler } = makeHandler(policy({ commands: { deny: ['shutdown'] } }));
const response = await handler(
request('batch', {
flags: { batchSteps: [{ command: 'app-switcher' }, { command: 'shutdown' }] },
}),
);
expectPolicyDenied(response, 'command');
expect(systemRuntimeSpies.appSwitcher).not.toHaveBeenCalled();
});
test('replay actions re-enter policy admission', async () => {
const root = mkdtempForTestSync('agent-device-daemon-policy-replay-');
const replayPath = path.join(root, 'flow.ad');
fs.writeFileSync(replayPath, 'app-switcher\n');
const { handler } = makeHandler(policy({ commands: { deny: ['app-switcher'] } }));
const response = await handler(
request('replay', { positionals: [replayPath], meta: { cwd: root } }),
);
expect(response.ok).toBe(false);
expect(JSON.stringify(response)).toContain('DAEMON_POLICY_DENIED');
expect(systemRuntimeSpies.appSwitcher).not.toHaveBeenCalled();
});
test('close --shutdown is refused when the policy denies device-shutdown', async () => {
const { handler, bind } = makeHandler(policy({ capabilities: { deny: ['device-shutdown'] } }));
const response = await handler(request('close', { flags: { shutdown: true } }));
expectPolicyDenied(response, 'capability');
expect(bind).not.toHaveBeenCalled();
});
test('an explicit device outside the policy is refused', async () => {
const { handler } = makeHandler(policy({ devices: { allow: [{ udid: IOS_SIMULATOR.id }] } }));
const response = await handler(request('open', { flags: { udid: OTHER_SIMULATOR.id } }));
expectPolicyDenied(response, 'device');
});
test('a session bound to a device outside the policy cannot inspect or bind it', async () => {
const { handler, bind, inspectFacts } = makeHandler(
policy({ devices: { allow: [{ udid: 'sim-pinned' }] } }),
);
const response = await handler(request('app-switcher'));
expectPolicyDenied(response, 'device');
expect(inspectFacts).not.toHaveBeenCalled();
expect(bind).not.toHaveBeenCalled();
expect(systemRuntimeSpies.appSwitcher).not.toHaveBeenCalled();
});
test('device inventory lists only the devices the policy allows', async () => {
const { handler } = makeHandler(policy({ devices: { allow: [{ udid: IOS_SIMULATOR.id }] } }), {
inventory: [IOS_SIMULATOR, OTHER_SIMULATOR, ANDROID_EMULATOR],
});
const response = await handler(request('devices', { session: undefined }));
expect(response).toMatchObject({
ok: true,
data: { devices: [expect.objectContaining({ id: IOS_SIMULATOR.id })] },
});
});
test('a batch step that shuts down or names a foreign device is refused before any step runs', async () => {
const { handler } = makeHandler(
policy({
devices: { allow: [{ udid: IOS_SIMULATOR.id }] },
capabilities: { deny: ['device-shutdown'] },
}),
);
const shutdownStep = await handler(
request('batch', {
flags: {
batchSteps: [{ command: 'app-switcher' }, { command: 'close', flags: { shutdown: true } }],
},
}),
);
const foreignStep = await handler(
request('batch', {
flags: {
batchSteps: [
{ command: 'app-switcher' },
{ command: 'open', flags: { udid: OTHER_SIMULATOR.id } },
],
},
}),
);
expectPolicyDenied(shutdownStep, 'capability');
expectPolicyDenied(foreignStep, 'device');
expect(systemRuntimeSpies.appSwitcher).not.toHaveBeenCalled();
});
test('an empty device selector names no device and is not a policy denial', () => {
const pinned = policy({ devices: { allow: [{ udid: IOS_SIMULATOR.id }] } });
expect(() =>
assertDaemonPolicyAdmitsRequest(pinned, request('open', { flags: { udid: '', serial: ' ' } })),
).not.toThrow();
});
test('a provider answering with only out-of-scope devices does not hide allowed local ones', async () => {
const { handler } = makeHandler(policy({ devices: { allow: [{ udid: IOS_SIMULATOR.id }] } }), {
inventory: [IOS_SIMULATOR],
providerInventory: [OTHER_SIMULATOR],
});
const response = await handler(request('devices', { session: undefined }));
expect(response).toMatchObject({
ok: true,
data: { devices: [expect.objectContaining({ id: IOS_SIMULATOR.id })] },
});
});
test('an allow list denies the internal runtime command unless it names runtime', async () => {
const { handler, bind } = makeHandler(policy({ commands: { allow: ['snapshot'] } }));
const response = await handler(request('runtime', { positionals: ['clear'] }));
expectPolicyDenied(response, 'command');
expect(response).toMatchObject({ error: { details: { command: 'runtime' } } });
expect(bind).not.toHaveBeenCalled();
});
test('command rules name internal device commands the registry way', () => {
const denyRuntime = policy({ commands: { deny: ['runtime', 'install-from-source'] } });
const allowSnapshot = policy({ commands: { allow: ['snapshot'] } });
expect(() => assertDaemonPolicyAdmitsRequest(denyRuntime, request('runtime'))).toThrow(
/denies the runtime command/,
);
expect(() => assertDaemonPolicyAdmitsRequest(denyRuntime, request('install_source'))).toThrow(
/denies the install-from-source command/,
);
// Protocol plumbing (leases, session bookkeeping) is never decided by command rules.
expect(() =>
assertDaemonPolicyAdmitsRequest(allowSnapshot, request('lease_heartbeat')),
).not.toThrow();
// A name the registry does not know fails closed under an allow list.
expect(() => assertDaemonPolicyAdmitsRequest(allowSnapshot, request('not-a-command'))).toThrow(
/denies the not-a-command command/,
);
});
test('doctor counts only the devices the policy allows', async () => {
const { handler } = makeHandler(policy({ devices: { allow: [{ udid: IOS_SIMULATOR.id }] } }), {
inventory: [IOS_SIMULATOR, OTHER_SIMULATOR],
});
const response = await handler(
request('doctor', { session: undefined, flags: { platform: 'ios' } }),
);
expect(response).toMatchObject({
ok: true,
data: {
checks: expect.arrayContaining([
expect.objectContaining({
id: 'device',
evidence: expect.objectContaining({ available: 1 }),
}),
]),
},
});
});