Skip to content

The agent that grows with you

fix(profiles): method-aware profile routes; fail closed on an unknown launch home

Tekniumb4a7225bfbc5
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.ts
index f924f0ec107..ddb0ab32b13 100644
--- a/apps/desktop/electron/connection-config.test.ts
+++ b/apps/desktop/electron/connection-config.test.ts
@@ -665,6 +665,14 @@ test('a /api/profiles/<name>/… path already names its profile: no ambient scop
}
assert.equal(pathWithProfileScope('/api/profiles/p2/soul', 'default'), '/api/profiles/p2/soul')
+ // Method-aware: PATCH/DELETE of a profile NAMED active/import/sessions names that profile.
+ for (const [path, method] of [['/api/profiles/active', 'PATCH'], ['/api/profiles/import', 'DELETE'],
+ ['/api/profiles/sessions', 'DELETE']]) {
+ assert.equal(pathForRegistryBackendRequest(path, 'beta', { mode: 'local' }, method), path)
+ }
+
+ assert.equal(pathForRegistryBackendRequest('/api/profiles/active', 'beta', { mode: 'local' }, 'GET'),
+ '/api/profiles/active?profile=beta')
})
test('registry model reads and writes retain each profile on a shared local backend', () => {
diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.ts
index e1f89b36257..7b691bb18a1 100644
--- a/apps/desktop/electron/connection-config.ts
+++ b/apps/desktop/electron/connection-config.ts
@@ -36,6 +36,7 @@
// force a needless full re-login every ~15 min — hence cookiesHaveLiveSession.
import { readStatusCode } from './api-transport'
import { sharesHostBackend } from './host-backend-singleton'
+import { profileCollectionRoute, profileRouteSuffix } from './profile-routes'
const AT_COOKIE_VARIANTS = ['__Host-hermes_session_at', '__Secure-hermes_session_at', 'hermes_session_at']
const RT_COOKIE_VARIANTS = ['__Host-hermes_session_rt', '__Secure-hermes_session_rt', 'hermes_session_rt']
@@ -1007,22 +1008,7 @@ function translateSelfProfileQuery(path, profile, backendProfile) {
* gateway host serving every profile, scoped per request). An explicit
* `?profile=` already on the path wins; an empty profile is a no-op.
*/
-// `/api/profiles/<suffix>` routes that are collections, not a profile named in the path. Matched on
-// the whole suffix (the gateway's native_http._check_profile_scope and local-gateway.ts's
-// PROFILE_COLLECTION_ROUTES use the same set), so a profile NAMED `sessions` keeps its own path.
-const PROFILE_COLLECTION_SUFFIXES = new Set([
- 'active', 'import', 'projects/tree', 'sessions', 'sessions/pull-requests', 'sessions/sidebar'
-])
-
-/** True for `/api/profiles/<name>[/…]`: the path itself names the target profile (#140791). */
-function pathNamesProfile(pathname: string): boolean {
- const suffix = pathname.replace(/\/+$/, '').startsWith('/api/profiles/')
- ? pathname.replace(/\/+$/, '').slice('/api/profiles/'.length) : ''
-
- return Boolean(suffix) && !PROFILE_COLLECTION_SUFFIXES.has(suffix)
-}
-
-function pathWithProfileScope(path, profile) {
+function pathWithProfileScope(path, profile, method?: string) {
const scopedProfile = connectionScopeKey(profile)
if (!scopedProfile) {
@@ -1045,7 +1031,8 @@ function pathWithProfileScope(path, profile) {
// A path that already names its profile never also carries the ambient one: the two disagree
// whenever the sidebar is on another profile or "All profiles", and the gateway refuses the pair.
- if (parsed.searchParams.has('profile') || pathNamesProfile(parsed.pathname)) {
+ if (parsed.searchParams.has('profile')
+ || (profileRouteSuffix(parsed.pathname) && !profileCollectionRoute(parsed.pathname, method))) {
return path
}
@@ -1068,9 +1055,9 @@ export interface RegistryBackendRequestScope {
* isolated SSH backends already own one profile but may translate a Desktop
* alias in an existing self-profile filter.
*/
-function pathForRegistryBackendRequest(path, profile, backend: RegistryBackendRequestScope) {
+function pathForRegistryBackendRequest(path, profile, backend: RegistryBackendRequestScope, method?: string) {
return backend.sharedRemote || backend.sharedPrimary || backend.mode === 'local'
- ? pathWithProfileScope(path, profile)
+ ? pathWithProfileScope(path, profile, method)
: translateSelfProfileQuery(path, profile, backend.remoteProfile)
}
diff --git a/apps/desktop/electron/local-gateway-python.ts b/apps/desktop/electron/local-gateway-python.ts
index c8eaf7bec2e..876a5380390 100644
--- a/apps/desktop/electron/local-gateway-python.ts
+++ b/apps/desktop/electron/local-gateway-python.ts
@@ -2,6 +2,7 @@ import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'
import { statSync } from 'node:fs'
import path from 'node:path'
+import type { GatewayTicketPurpose } from './local-gateway'
import { hiddenWindowsChildOptions } from './windows-child-options'
interface TicketEndpoint {
@@ -77,7 +78,7 @@ class TicketBridge {
this.child.on('close', () => this.dispose())
}
- request(endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create' | 'native-profile-registry'): Promise<string> {
+ request(endpoint: TicketEndpoint, purpose: GatewayTicketPurpose): Promise<string> {
clearTimeout(this.idleTimer)
return new Promise((resolve, reject) => {
@@ -238,7 +239,7 @@ export function createGatewayTicketResolver(resolveBackend: () => Promise<Resolv
let cached: Promise<{ command: string; env?: NodeJS.ProcessEnv }> | undefined
let cachedGeneration = -1
- return async (endpoint: TicketEndpoint, purpose: 'interactive' | 'native-http' | 'native-profile-create' | 'native-profile-registry'): Promise<string> => {
+ return async (endpoint: TicketEndpoint, purpose: GatewayTicketPurpose): Promise<string> => {
const generation = bridgeGeneration
if (!cached || cachedGeneration !== generation) {
@@ -264,7 +265,7 @@ export function mintGatewayTicketWithPython(
backend: { command: string; env?: NodeJS.ProcessEnv },
cwd: string,
endpoint: TicketEndpoint,
- purpose: 'interactive' | 'native-http' | 'native-profile-create' | 'native-profile-registry'
+ purpose: GatewayTicketPurpose
): Promise<string> {
const env = { ...process.env, ...backend.env, HERMES_HOME: endpoint.profile_id,
PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1' }
diff --git a/apps/desktop/electron/local-gateway.test.ts b/apps/desktop/electron/local-gateway.test.ts
index 3550e0255bf..ad3451d5d74 100644
--- a/apps/desktop/electron/local-gateway.test.ts
+++ b/apps/desktop/electron/local-gateway.test.ts
@@ -72,7 +72,7 @@ test.skipIf(process.platform === 'win32').each([0o700, 0o750, 0o701])('native HT
const server = net.createServer(socket => socket.once('data', chunk => {
const request = JSON.parse(chunk.toString())
requests.push(request)
- socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: home, instance_id: 'owner', runtime_protocol: 1, ticket: `grant-${requests.length}` } }) + '\n')
+ socket.end(JSON.stringify({ protocol: 1, id: 1, ok: true, result: { profile_id: request.params?.profile_id ?? home, instance_id: 'owner', runtime_protocol: 1, ticket: `grant-${requests.length}` } }) + '\n')
}))
await new Promise<void>(resolve => server.listen(path.join(home, 'gateway.sock'), resolve))
@@ -102,12 +102,23 @@ test.skipIf(process.platform === 'win32').each([0o700, 0o750, 0o701])('native HT
['/api/profiles/default', 'PATCH', 'native-profile-registry'],
['/api/profiles/default', 'delete', 'native-profile-registry'],
['/api/profiles/default/soul', 'PUT', 'native-http'],
- ['/api/profiles/active', 'PATCH', 'native-http'],
- ['/api/profiles/import', 'DELETE', 'native-http']
+ // The collection routes of these names stay on the endpoint's own profile.
+ ['/api/profiles/active', 'GET', 'native-http'],
+ ['/api/profiles/active', 'POST', 'native-http'],
+ ['/api/profiles/sessions?profile=default', 'GET', 'native-http']
]) {
await nativeGatewayHttpHeaders(descriptor, endpoint.api_origin + route, home, method)
expect(requests.at(-1).params).toEqual({ profile_id: home, instance_id: 'owner', purpose })
}
+
+ // A profile NAMED active/import/sessions (valid names): its PATCH/DELETE is that profile's own
+ // rename/delete (the collection routes are GET/POST only), on the registry grant for its home.
+ for (const [name, method] of [['active', 'PATCH'], ['import', 'DELETE'], ['sessions', 'DELETE']]) {
+ await fs.mkdir(path.join(home, 'profiles', name), { recursive: true, mode: 0o700 })
+ await nativeGatewayHttpHeaders(descriptor, `${endpoint.api_origin}/api/profiles/${name}`, home, method)
+ expect(requests.at(-1).params).toEqual({ profile_id: await fs.realpath(path.join(home, 'profiles', name)),
+ instance_id: 'owner', purpose: 'native-profile-registry' })
+ }
} finally {
await new Promise<void>(resolve => server.close(() => resolve()))
await fs.rm(home, { recursive: true, force: true })
@@ -578,6 +589,9 @@ test('a session write that names its owner only in the body gets a grant for tha
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')
+ // The profile NAMED `active` is the ticket's profile for its own rename; the collection GET is not.
+ expect(nativeGrantRoute('http://127.0.0.1:1/api/profiles/active', { profile: 'p2' }, 'PATCH')).toBe('http://127.0.0.1:1/api/profiles/active')
+ expect(nativeGrantRoute('http://127.0.0.1:1/api/profiles/active', { profile: 'p2' }, 'GET')).toBe('p2')
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' }]]) {
diff --git a/apps/desktop/electron/local-gateway.ts b/apps/desktop/electron/local-gateway.ts
index 671261b3aad..a7c28d5d31c 100644
--- a/apps/desktop/electron/local-gateway.ts
+++ b/apps/desktop/electron/local-gateway.ts
@@ -1,6 +1,7 @@
import { spawn } from 'node:child_process'
import crypto from 'node:crypto'
+import { profileCollectionRoute, profileRouteSuffix } from './profile-routes'
import { hiddenWindowsChildOptions, windowsShellCommand } from './windows-child-options'
// `hermes gateway ensure` answers with a protocol verdict (ready, or `starting: deadline`) within
@@ -398,27 +399,19 @@ function shellQuote(file: string): string {
return `'${file.replace(/'/g, `'\\''`)}'`
}
-// Exact `/api/profiles/<suffix>` collection paths, mirroring the gateway's native-http scope check
-// (hermes_cli/dashboard_auth/native_http.py::_check_profile_scope). Matched on the whole suffix, so a
-// profile NAMED `projects` or `sessions` still gets its own ticket on `/api/profiles/projects/soul`.
-const PROFILE_COLLECTION_ROUTES = new Set([
- 'active', 'import', 'projects/tree', 'sessions', 'sessions/pull-requests', 'sessions/sidebar'
-])
-
/** The batched sidebar names its owner in `recents_profile`. A named profile route carries its
- * owner in the first path segment; all other profile-scoped routes use `profile`. */
-function scopedProfileOf(url: URL): null | string {
- const pathname = url.pathname.replace(/\/+$/, '')
+ * owner in the first path segment (method-aware: `PATCH /api/profiles/active` renames the profile
+ * named `active`); all other profile-scoped routes use `profile`. */
+function scopedProfileOf(url: URL, method?: string): null | string {
+ const collection = profileCollectionRoute(url.pathname, method)
- if (pathname === '/api/profiles/sessions/sidebar') {
+ if (collection === 'sessions/sidebar') {
return url.searchParams.get('recents_profile')
}
- const prefix = '/api/profiles/'
- const suffix = pathname.startsWith(prefix) ? pathname.slice(prefix.length) : ''
- const segment = suffix.split('/', 1)[0]
+ const segment = profileRouteSuffix(url.pathname).split('/', 1)[0]
- if (segment && !PROFILE_COLLECTION_ROUTES.has(suffix)) {
+ if (segment && !collection) {
try {
return decodeURIComponent(segment)
} catch {
@@ -432,8 +425,8 @@ function scopedProfileOf(url: URL): null | string {
/** The endpoint a `?profile=<name>` request is scoped to on a shared host descriptor: the same
* daemon, ticket minted for the sibling profile's home (`profiles/<name>` under the launch root).
* The gateway refuses a ticket whose profile it does not serve, so a bad name fails closed. */
-export function routedGatewayEndpoint(endpoint: GatewayEndpoint, urlOrProfile: string, _launchHome: string): GatewayEndpoint {
- const profile = (/^[a-z]+:\/\//.test(urlOrProfile) ? scopedProfileOf(new URL(urlOrProfile)) : urlOrProfile)?.trim()
+export function routedGatewayEndpoint(endpoint: GatewayEndpoint, urlOrProfile: string, _launchHome: string, method?: string): GatewayEndpoint {
+ const profile = (/^[a-z]+:\/\//.test(urlOrProfile) ? scopedProfileOf(new URL(urlOrProfile), method) : urlOrProfile)?.trim()
if (!profile || profile === 'current') {return endpoint}
const own = path.basename(endpoint.profile_id)
@@ -453,8 +446,8 @@ export function routedGatewayEndpoint(endpoint: GatewayEndpoint, urlOrProfile: s
/** `routedGatewayEndpoint` bound to the home the gateway reserved for the routed profile. It serves
* `profiles/<name>` at that directory's resolved home, so a symlinked or junction-linked named
* profile mints for its target; the gateway still refuses a home it does not serve. */
-export async function routedTicketEndpoint(endpoint: GatewayEndpoint, urlOrProfile: string, launchHome: string): Promise<GatewayEndpoint> {
- const routed = routedGatewayEndpoint(endpoint, urlOrProfile, launchHome)
+export async function routedTicketEndpoint(endpoint: GatewayEndpoint, urlOrProfile: string, launchHome: string, method?: string): Promise<GatewayEndpoint> {
+ const routed = routedGatewayEndpoint(endpoint, urlOrProfile, launchHome, method)
// The endpoint's own home and the root it was routed from are advertised: they keep their checks.
if (routed.profile_id === endpoint.profile_id || routed.profile_id === routed.control_home) {return routed}
@@ -478,9 +471,10 @@ export function nativeGrantPurpose(url: string, method = 'GET'): GatewayTicketPu
const pathname = new URL(url).pathname.replace(/\/+$/, '')
if (verb === 'POST' && pathname === '/api/profiles') {return 'native-profile-create'}
- const suffix = pathname.startsWith('/api/profiles/') ? pathname.slice('/api/profiles/'.length) : ''
+ const suffix = profileRouteSuffix(pathname)
- if ((verb === 'PATCH' || verb === 'DELETE') && suffix && !suffix.includes('/') && !PROFILE_COLLECTION_ROUTES.has(suffix)) {
+ // Method-aware: PATCH/DELETE of `/api/profiles/active|import|sessions` is the profile of that name.
+ if ((verb === 'PATCH' || verb === 'DELETE') && suffix && !suffix.includes('/') && !profileCollectionRoute(pathname, verb)) {
return 'native-profile-registry'
}
@@ -490,8 +484,8 @@ export function nativeGrantPurpose(url: string, method = 'GET'): GatewayTicketPu
/** 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}
+export function nativeGrantRoute(url: string, body?: unknown, method?: string): string {
+ if (scopedProfileOf(new URL(url), method)?.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
@@ -504,7 +498,7 @@ export async function nativeGatewayHttpHeaders(descriptor: { gatewayEndpoint: Ga
const purpose = nativeGrantPurpose(url, method)
- return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(await routedTicketEndpoint(descriptor.gatewayEndpoint, nativeGrantRoute(url, body), launchHome), purpose) }
+ return { 'X-Hermes-Gateway-Ticket': await mintLocalGatewayTicket(await routedTicketEndpoint(descriptor.gatewayEndpoint, nativeGrantRoute(url, body, method), launchHome, method), purpose) }
}
// The installed runtime's own ticket client: every Windows mint (SID-validated pipe), and a POSIX
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 24244a37d7c..59af19ce5f4 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -16344,7 +16344,7 @@ async function dispatchRegistryApiRequest(
ensureRegistryBackend(registryConnectionId, routeProfile)
)
- const requestPath = pathForRegistryBackendRequest(request.path, requestProfile, connection)
+ const requestPath = pathForRegistryBackendRequest(request.path, requestProfile, connection, request?.method || 'GET')
const response = await fetchJsonForBackend(connection, requestPath, {
method: request?.method,
diff --git a/apps/desktop/electron/profile-routes.ts b/apps/desktop/electron/profile-routes.ts
new file mode 100644
index 00000000000..48cd1508cc6
--- /dev/null
+++ b/apps/desktop/electron/profile-routes.ts
@@ -0,0 +1,31 @@
+/** `/api/profiles/<suffix>` collection routes, by method (hermes_cli/web_routers/profiles.py). Any
+ * other method on these paths is the per-profile `/api/profiles/{name}` route of a profile NAMED
+ * `active`, `import`, `sessions`, …, which are valid profile names. Mirror of the gateway's
+ * hermes_cli/dashboard_auth/native_http.py `PROFILE_COLLECTION_ROUTES`: grant selection, ticket
+ * routing and ambient profile scoping all read this one table. */
+const PROFILE_COLLECTION_ROUTES: Readonly<Record<string, readonly string[]>> = {
+ active: ['GET', 'POST'],
+ import: ['POST'],
+ 'projects/tree': ['GET'],
+ sessions: ['GET'],
+ 'sessions/pull-requests': ['POST'],
+ 'sessions/sidebar': ['GET']
+}
+
+/** The `/api/profiles/` suffix of *pathname* (trailing slashes dropped), or '' for any other path. */
+export function profileRouteSuffix(pathname: string): string {
+ const trimmed = pathname.replace(/\/+$/, '')
+
+ return trimmed.startsWith('/api/profiles/') ? trimmed.slice('/api/profiles/'.length) : ''
+}
+
+/** The collection `method pathname` serves, or null when the path names a profile (or is not a
+ * `/api/profiles/` path at all). With no *method* (a caller that only has the path), every listed
+ * suffix reads as its collection, as before. */
+export function profileCollectionRoute(pathname: string, method?: string): null | string {
+ const suffix = profileRouteSuffix(pathname)
+
+ if (!suffix || !Object.hasOwn(PROFILE_COLLECTION_ROUTES, suffix)) {return null}
+
+ return method === undefined || PROFILE_COLLECTION_ROUTES[suffix].includes(method.toUpperCase()) ? suffix : null
+}
diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.py
index 6315f50bdac..57e15edafad 100644
--- a/hermes_cli/dashboard_auth/native_http.py
+++ b/hermes_cli/dashboard_auth/native_http.py
@@ -82,10 +82,11 @@ async def _check_profile_scope(request, profile_id):
raise PermissionError('profile_scope_mismatch')
elif path.startswith('/api/profiles/'):
suffix = path.removeprefix('/api/profiles/')
+ collection = profile_collection_route(path, request.method)
aggregate_selector = {
'sessions': 'profile', 'sessions/sidebar': 'recents_profile',
'projects/tree': 'profile', 'sessions/pull-requests': 'profile',
- }.get(suffix)
+ }.get(collection)
if aggregate_selector:
values = request.query_params.getlist(aggregate_selector)
if not values:
@@ -93,9 +94,9 @@ async def _check_profile_scope(request, profile_id):
for value in values:
# These routes interpret absent/all differently from /api/config.
_own_profile(value, profile_id, current=False)
- elif suffix == 'active' and request.method == 'GET':
+ elif collection == 'active' and request.method == 'GET':
return # Discovery of sticky defaults does not switch this daemon.
- elif suffix in {'active', 'import'}:
+ elif collection in {'active', 'import'}:
raise PermissionError('profile_scope_mismatch')
else:
_own_profile(suffix.split('/', 1)[0], profile_id, current=False)
@@ -105,12 +106,31 @@ async def _check_profile_scope(request, profile_id):
raise PermissionError('profile_scope_mismatch')
+# ``/api/profiles/<suffix>`` collection routes, by method (hermes_cli/web_routers/profiles.py). Every
+# other method on these paths is the per-profile ``/api/profiles/{name}`` route of a profile NAMED
+# ``active``/``import``/``sessions``/…: valid profile names (PROFILE_ID_RE, not reserved).
+# Desktop mirror: apps/desktop/electron/profile-routes.ts.
+PROFILE_COLLECTION_ROUTES = {
+ 'active': frozenset({'GET', 'POST'}), 'import': frozenset({'POST'}),
+ 'projects/tree': frozenset({'GET'}), 'sessions': frozenset({'GET'}),
+ 'sessions/pull-requests': frozenset({'POST'}), 'sessions/sidebar': frozenset({'GET'}),
+}
+
+
+def profile_collection_route(path, method):
+ """The collection suffix ``method path`` serves, or None when the path names a profile."""
+ suffix = path.rstrip('/').removeprefix('/api/profiles/')
+ if suffix == path.rstrip('/'):
+ return None
+ return suffix if method.upper() in PROFILE_COLLECTION_ROUTES.get(suffix, ()) else None
+
+
def _registry_target(request):
"""The profile a ``PATCH``/``DELETE /api/profiles/<name>`` names, or None for any other route."""
if request.method not in {'PATCH', 'DELETE'}:
return None
suffix = request.url.path.rstrip('/').removeprefix('/api/profiles/')
- if suffix == request.url.path.rstrip('/') or not suffix or '/' in suffix or suffix in {'active', 'import'}:
+ if suffix == request.url.path.rstrip('/') or not suffix or '/' in suffix:
return None
return suffix
@@ -126,9 +146,14 @@ def _check_registry_scope(request, profile_id, launch_home):
for value in request.query_params.getlist('profile'):
_own_profile(value, profile_id, current=False)
_own_profile(target, profile_id, current=False)
- from hermes_constants import get_default_hermes_root
- if Path(profile_id) == launch_home and not (
- request.method == 'PATCH' and launch_home == get_default_hermes_root().resolve()):
+ if launch_home is None:
+ # Fail closed: with no known launch home the guard below cannot tell it apart.
+ raise PermissionError('profile_scope_mismatch')
+ from hermes_constants import get_default_hermes_root, hermes_home_key
+ # Compared by hermes_home_key, as SessionAuthorities keys homes (symlinks, case, separators).
+ launch = hermes_home_key(launch_home)
+ if hermes_home_key(profile_id) == launch and not (
+ request.method == 'PATCH' and launch == hermes_home_key(get_default_hermes_root())):
raise PermissionError('profile_scope_mismatch')
@@ -157,7 +182,7 @@ def _launch_home(runner):
from gateway.session_authorities import all_authorities
registry = getattr(runner, 'session_authorities', None)
launch = registry.launch if registry is not None else (all_authorities(runner) or [None])[0]
- return Path(launch.profile_id) if launch is not None else None
+ return launch.profile_id if launch is not None else None
def _native_store(conn, tickets):
diff --git a/tests/hermes_cli/test_native_profile_route_names.py b/tests/hermes_cli/test_native_profile_route_names.py
new file mode 100644
index 00000000000..f7850aca326
--- /dev/null
+++ b/tests/hermes_cli/test_native_profile_route_names.py
@@ -0,0 +1,82 @@
+"""Profiles NAMED like a collection route (``active``, ``import``, ``sessions``) are ordinary profiles.
+
+``/api/profiles/active`` is the sticky-default collection for GET/POST only, ``/import`` for POST,
+``/sessions`` for GET; PATCH/DELETE of those paths reach ``/api/profiles/{name}`` for the profile of
+that name. The registry grant and the native-http scope check used to be method-blind, so those
+profiles could never be renamed or deleted from Desktop, and an ordinary native-http grant could
+PATCH/DELETE the profile named ``sessions`` through the aggregate branch (review of #140970).
+"""
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from starlette.datastructures import Headers, QueryParams
+
+from hermes_cli.dashboard_auth import native_http
+
+
+def _request(method, path, query=''):
+ async def json():
+ raise ValueError
+ return SimpleNamespace(method=method, url=SimpleNamespace(path=path), query_params=QueryParams(query),
+ headers=Headers({}), json=json)
+
+
+def root(tmp_path, monkeypatch):
+ root = tmp_path / 'root'
+ for name in ('active', 'import', 'sessions', 'beta'):
+ (root / 'profiles' / name).mkdir(parents=True)
+ monkeypatch.setenv('HERMES_HOME', str(root))
+ from hermes_cli import web_server_profiles
+ # The profile registry's own name -> dir mapping (validation + existence), rooted here.
+ monkeypatch.setattr(web_server_profiles, '_resolve_profile_dir',
+ lambda name: root / 'profiles' / name if name != 'default' else root)
+ return root.resolve()
+
+
[email protected]('name', ['active', 'import', 'sessions'])
[email protected]('method', ['PATCH', 'DELETE'])
+def test_registry_grant_renames_and_deletes_a_profile_named_like_a_collection(root, name, method):
+ request = _request(method, f'/api/profiles/{name}')
+ assert native_http._registry_target(request) == name
+ native_http._check_registry_scope(request, str(root / 'profiles' / name), str(root))
+ with pytest.raises(PermissionError): # still bound to the grant's own profile
+ native_http._check_registry_scope(request, str(root / 'profiles' / 'beta'), str(root))
+
+
[email protected]('method,path', [('GET', '/api/profiles/active'), ('POST', '/api/profiles/active'),
+ ('POST', '/api/profiles/import'), ('GET', '/api/profiles/sessions')])
+def test_collection_routes_are_never_registry_targets(method, path):
+ assert native_http.profile_collection_route(path, method) is not None
+ assert native_http._registry_target(_request(method, path)) is None or method in {'GET', 'POST'}
+
+
+def test_native_http_grant_cannot_rename_or_delete_the_profile_named_sessions(root):
+ # @dokterdok: the aggregate-selector branch checked only ?profile=, with no method check.
+ for method in ('PATCH', 'DELETE'):
+ request = _request(method, '/api/profiles/sessions', 'profile=sessions')
+ with pytest.raises(PermissionError):
+ asyncio.run(native_http._check_profile_scope(request, str(root / 'profiles' / 'sessions')))
+ # Its collection read keeps working for the profile it names.
+ asyncio.run(native_http._check_profile_scope(_request('GET', '/api/profiles/sessions', 'profile=sessions'),
+ str(root / 'profiles' / 'sessions')))
+
+
+def test_registry_scope_fails_closed_when_the_launch_home_is_unknown(root):
+ # @kshitijk4poor: _launch_home() returning None skipped the launch-home guard.
+ with pytest.raises(PermissionError):
+ native_http._check_registry_scope(_request('DELETE', '/api/profiles/beta'),
+ str(root / 'profiles' / 'beta'), None)
+
+
+def test_launch_home_guard_compares_home_keys_not_raw_paths(root, tmp_path):
+ # A launch home reached through a symlink is still the launch home (hermes_home_key, as
+ # SessionAuthorities keys it), so deleting it stays refused.
+ link = tmp_path / 'link'
+ link.symlink_to(root / 'profiles' / 'beta')
+ with pytest.raises(PermissionError):
+ native_http._check_registry_scope(_request('DELETE', '/api/profiles/beta'),
+ str(root / 'profiles' / 'beta'), str(link))
+ assert Path(link).resolve() == root / 'profiles' / 'beta'