fix(desktop): mint a session write's grant for the profile its body names

The Bots plugin hides and unhides a bot's sessions with
PATCH /api/sessions/<id>, naming the owning profile only in the JSON
body. Main minted the native grant from the URL alone, so a write to
another profile's session carried the window's own grant and the
gateway, which checks the body's `profile` too, answered 403
profile_scope_mismatch.

When the URL names no profile, the grant is now minted for the body's
`profile`. A URL selector still wins; the gateway refuses a body that
disagrees with it either way.

The e2e spec seeds a cron job in each profile and checks the
all-profiles cron list on both routes, and sends the Bots hide write for
the developer profile's session from a window on default. Both fail on
the previous head (ENOENT, 403 profile_scope_mismatch) and pass here
with multiplex off and on.
This commit is contained in:
unsupportedpastels
2026-10-13 02:52:24 +00:00
parent 56e92c4e74
commit fd71031264
4 changed files with 75 additions and 4 deletions

View File

@@ -55,6 +55,16 @@ seed(home / 'profiles' / 'developer' / 'state.db', [{'id': sys.argv[2], 'source'
`, JSON.stringify(ROWS), NAMED_ROW], { cwd: root, env: { ...env, PYTHONPATH: root }, encoding: 'utf8' })
expect(seed.status, seed.stderr).toBe(0)
// One cron job in each profile's own store, for the all-profiles cron list.
for (const [home, name] of [[sandbox.hermesHome, 'default-job'], [named, 'developer-job']]) {
const job = spawnSync(python, ['-c', 'import sys\nfrom cron.jobs import create_job\ncreate_job("e2e", "every 1h", name=sys.argv[1])', name], {
cwd: root, env: { ...env, HERMES_HOME: home, PYTHONPATH: root }, encoding: 'utf8'
})
expect(job.status, job.stderr).toBe(0)
}
// An existing install has a startup profile; without one the first-launch migration guesses
// from the newest state.db, which here is the named profile's.
fs.writeFileSync(path.join(sandbox.userDataDir, 'active-profile.json'), JSON.stringify({ profile: 'default' }))
@@ -120,6 +130,16 @@ seed(home / 'profiles' / 'developer' / 'state.db', [{'id': sys.argv[2], 'source'
}
}
// The all-profiles cron list, on both routes.
for (const [name, scope] of [['cron:all', {}], ['cron:all:registry', registry]] as const) {
try {
const r = await api({ path: '/api/cron/jobs?profile=all', ...scope })
out[name] = (Array.isArray(r) ? r : []).map((job: any) => `${job.profile}:${job.name}`).sort()
} catch (e) {
out[name] = 'ERR ' + String((e as Error)?.message ?? e).slice(0, 200)
}
}
try {
const r = await api({ path: '/api/profiles/sessions/pull-requests', method: 'POST', body: { ids: ['legacy-desktop-anon'] } })
out['prs:all'] = { scanned: r?.scanned ?? null }
@@ -186,6 +206,31 @@ seed(home / 'profiles' / 'developer' / 'state.db', [{'id': sys.argv[2], 'source'
await rail.getByRole('button', { name: /^Switch to / }).first().click()
views.default = await listedIn(ROWS.map(r => r.id))
await page.screenshot({ path: path.join(evidence, 'view-default.png') })
// The Bots plugin's hide write as the SDK sends it: the owner named only in the body, from
// the window, now back on default. An unopened pre-upgrade row is not editable over HTTP at all
// (only its first resume adopts it), so this runs on the developer row opened above.
probes['bots:hide'] = await page.evaluate(async () => {
const api = (window as any).hermesDesktop.api
const path = '/api/sessions/legacy-developer-desktop'
try {
const snapshot = await api({ path: `${path}/mutation-snapshot?profile=developer` })
const identity = {
expected_generation: snapshot?.runtime_generation,
expected_revision: snapshot?.runtime_revision,
request_id: crypto.randomUUID()
}
const r = await api({ path, method: 'PATCH', body: { hidden: false, profile: 'developer', ...identity } })
return { ok: r?.ok ?? null }
} catch (e) {
return 'ERR ' + String((e as Error)?.message ?? e).slice(0, 200)
}
})
console.log('BOTS_HIDE: ' + JSON.stringify(probes['bots:hide']))
} finally {
console.log('LEGACY_DESKTOP_RESULTS: ' + JSON.stringify(results))
console.log('LEGACY_DESKTOP_VIEWS: ' + JSON.stringify(views))
@@ -232,6 +277,10 @@ for p in alive:
expect.soft(probes['projects:all'], 'projects:all').toEqual(everyProfile)
expect.soft(probes['projects:all:registry'], 'projects:all:registry').toEqual(everyProfile)
expect.soft(probes['prs:all'], 'prs:all').toEqual({ scanned: ['legacy-desktop-anon'] })
const everyJob = ['default:default-job', 'developer:developer-job']
expect.soft(probes['cron:all'], 'cron:all').toEqual(everyJob)
expect.soft(probes['cron:all:registry'], 'cron:all:registry').toEqual(everyJob)
expect.soft(probes['bots:hide'], 'bots:hide').toEqual({ ok: true })
expect.soft(probes['sessions:all'], 'sessions:all').toEqual({ ids: everyRow, errors: [] })
expect.soft(probes['sidebar:default'], 'sidebar:default').toEqual({ ids: ROWS.map(r => `default:${r.id}`).sort(), errors: [] })
expect.soft(probes['sidebar:developer'], 'sidebar:developer').toEqual({ ids: [`developer:${NAMED_ROW}`], errors: [] })

View File

@@ -2,7 +2,7 @@ import path from 'node:path'
import { expect, test, vi } from 'vitest'
import { createLocalGatewayDials, ensureLocalGateway, routedGatewayEndpoint, runGatewayEnsure } from './local-gateway'
import { createLocalGatewayDials, ensureLocalGateway, nativeGrantRoute, routedGatewayEndpoint, runGatewayEnsure } from './local-gateway'
import { shortSocketTmpDir } from './local-gateway.test-helpers'
test('the ensure client inherits the caller-scrubbed parent env, not the raw Desktop env', async () => {
@@ -480,3 +480,15 @@ test.skipIf(process.platform === 'win32')('a group-writable home mints through t
await fs.rm(home, { recursive: true, force: true })
}
})
test('a session write that names its owner only in the body gets a grant for that profile', () => {
const url = 'http://127.0.0.1:1/api/sessions/s1'
expect(nativeGrantRoute(url, { hidden: true, profile: 'p2' })).toBe('p2')
// The URL's own selector wins; the gateway refuses a body that disagrees with it.
expect(nativeGrantRoute(url + '?profile=p3', { profile: 'p2' })).toBe(url + '?profile=p3')
expect(nativeGrantRoute('http://127.0.0.1:1/api/profiles/sessions/sidebar?recents_profile=p3', { profile: 'p2' })).toContain('recents_profile=p3')
for (const body of [undefined, null, {}, { profile: '' }, { profile: 7 }, [{ profile: 'p2' }]]) {
expect(nativeGrantRoute(url, body)).toBe(url)
}
})

View File

@@ -339,7 +339,17 @@ export function routedGatewayEndpoint(endpoint: GatewayEndpoint, urlOrProfile: s
return { ...endpoint, profile_id: home, control_home: endpoint.control_home || endpoint.profile_id }
}
export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string, launchHome = descriptor.gatewayEndpoint.profile_id, method = 'GET') {
/** What a native grant is minted for: the URL's own profile selector or, when it names none, a
* JSON body's `profile`. The gateway checks both against the grant, and a session write such as
* `PATCH /api/sessions/<id>` names its owner in the body alone. */
export function nativeGrantRoute(url: string, body?: unknown): string {
if (scopedProfileOf(new URL(url))?.trim()) {return url}
const profile = body && typeof body === 'object' && !Array.isArray(body) ? (body as { profile?: unknown }).profile : undefined
return typeof profile === 'string' && profile.trim() ? profile : url
}
export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: GatewayEndpoint; baseUrl: string }, url: string, launchHome = descriptor.gatewayEndpoint.profile_id, method = 'GET', body?: unknown) {
if (new URL(url).origin !== descriptor.gatewayEndpoint.api_origin || descriptor.baseUrl !== descriptor.gatewayEndpoint.api_origin) {
throw new Error('Native gateway HTTP origin mismatch')
}
@@ -347,7 +357,7 @@ export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: Ga
const purpose = method.toUpperCase() === 'POST' && new URL(url).pathname.replace(/\/$/, '') === '/api/profiles'
? 'native-profile-create' : 'native-http'
return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(routedGatewayEndpoint(descriptor.gatewayEndpoint, url, launchHome), purpose) }
return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(routedGatewayEndpoint(descriptor.gatewayEndpoint, nativeGrantRoute(url, body), launchHome), purpose) }
}
// The installed runtime's own ticket client: every Windows mint (SID-validated pipe), and a POSIX

View File

@@ -5381,7 +5381,7 @@ function fetchJson(url, token, options: any = {}) {
async (requestState: any) => {
// Mint inside each retry: a grant authorizes exactly one HTTP request.
const nativeHeaders = options.gatewayDescriptor
? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url, HERMES_HOME, options.method || 'GET')
? await nativeGatewayHttpHeaders(options.gatewayDescriptor, url, HERMES_HOME, options.method || 'GET', options.upload ? undefined : options.body)
: null
return new Promise((resolve, reject) => {