Skip to content

The agent that grows with you

fix(auth): audit API 401s and name stale app-token mint failures

brooklyn!fbff2b8a7a1c
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.ts
index d2d7c26f300..cfd9239e4f1 100644
--- a/apps/desktop/electron/connection-config.test.ts
+++ b/apps/desktop/electron/connection-config.test.ts
@@ -14,6 +14,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
+import { httpStatusError } from './api-transport'
import { makeNousCloudBackendDownError } from './backend-health'
import {
apiRequestRegistryConnectionId,
@@ -50,6 +51,7 @@ import {
translateSelfProfileQuery,
withTransientRetries
} from './connection-config'
+import { mintGatewayWsTicket } from './oauth-rest-request'
// --- connectionScopeKey / normAuthMode ---
@@ -1303,6 +1305,40 @@ test('resolveTestWsUrl (oauth, auth rejected) requests sign-in and does not skip
)
})
+test('resolveTestWsUrl (oauth, stale app bearer) names the app token, not the server OAuth session', async () => {
+ const staleBearer = 'stale-app-bearer-do-not-log'
+
+ const cause = await mintGatewayWsTicket('https://gw.example.com', {
+ ensureNativeAccessToken: async () => staleBearer,
+ fetchJson: async (_url, _token, options) => {
+ assert.equal(options.bearer, staleBearer)
+ throw httpStatusError(401, JSON.stringify({ reason: 'invalid_or_expired_session' }))
+ },
+ fetchJsonViaOauthSession: async () => {
+ throw httpStatusError(401, JSON.stringify({ reason: 'no_cookie' }))
+ }
+ }).catch((error: unknown) => error)
+
+ await assert.rejects(
+ () =>
+ resolveTestWsUrl('https://gw.example.com', 'oauth', null, {
+ mintTicket: async () => {
+ throw cause
+ }
+ }),
+ (err: any) => {
+ assert.match(err.message, /app token is invalid/i)
+ assert.match(err.message, /saved gateway bearer/i)
+ assert.doesNotMatch(err.message, /oauth session/i)
+ assert.doesNotMatch(err.message, /re-authenticate/i)
+ assert.equal(err.message.includes(staleBearer), false)
+ assert.equal(err.needsOauthLogin, true)
+
+ return true
+ }
+ )
+})
+
test('resolveTestWsUrl (oauth, transport failure) remains a retryable connection error', async () => {
const cause = new Error('socket timed out')
diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.ts
index 0b376bdaeb6..6538377337b 100644
--- a/apps/desktop/electron/connection-config.ts
+++ b/apps/desktop/electron/connection-config.ts
@@ -107,9 +107,22 @@ function isGatewayAuthRejection(error) {
return statusCode === 401 || statusCode === 403
}
+/** True when the rejected credential is the app's saved bearer, not the server session. */
+function isStaleAppTokenRejection(error: unknown) {
+ return Boolean(error && typeof error === 'object' && (error as any).appTokenRejected === true)
+}
+
function gatewayTicketFailure(error, authMessage, transportMessage) {
const needsOauthLogin = isGatewayAuthRejection(error)
- const err = new Error(needsOauthLogin ? authMessage : transportMessage)
+
+ const message = needsOauthLogin
+ ? isStaleAppTokenRejection(error)
+ ? 'Reached the gateway over HTTP, but the app token is invalid. ' +
+ "The app's saved gateway bearer is no longer valid. Sign out in the app and sign in again to replace it."
+ : authMessage
+ : transportMessage
+
+ const err = new Error(message)
if (needsOauthLogin) {
;(err as any).needsOauthLogin = true
@@ -229,6 +242,8 @@ async function resolveTestWsUrl(baseUrl, authMode, token, deps: any = {}) {
try {
ticket = await mintTicket(baseUrl)
} catch (error) {
+ // Untagged 401s keep the server OAuth-session wording. A stale app
+ // bearer is named inside gatewayTicketFailure.
throw gatewayTicketFailure(
error,
'Reached the gateway over HTTP, but the OAuth session was rejected while minting a WebSocket ticket. ' +
diff --git a/apps/desktop/electron/oauth-rest-request.ts b/apps/desktop/electron/oauth-rest-request.ts
index 2539be94c47..fc79111cafa 100644
--- a/apps/desktop/electron/oauth-rest-request.ts
+++ b/apps/desktop/electron/oauth-rest-request.ts
@@ -1,3 +1,4 @@
+import { readStatusCode } from './api-transport'
import { isGatewayAuthRejection } from './connection-config'
import { type NativeAccessTokenOptions, NativeAuthChangedError } from './native-access-token'
import { shouldRotateNativeTokenAfterRejection } from './native-auth-decisions'
@@ -25,6 +26,13 @@ async function cookieFallback<T>(request: () => Promise<T>, nativeError: unknown
}
}
+/** A confirmed bearer 401 is an app-token failure, not a server OAuth session. */
+function markStaleAppToken(error: unknown): void {
+ if (error && typeof error === 'object') {
+ ;(error as { appTokenRejected?: boolean }).appTokenRejected = true
+ }
+}
+
/**
* Native-first OAuth selection for REST, readiness, downloads and media.
* Cookie coexistence can recover a failed refresh, but an empty cookie jar
@@ -97,6 +105,10 @@ export async function mintGatewayWsTicket(
return await mintWithBearer(rotatedAt)
}
} catch (error) {
+ if (readStatusCode(error) === 401) {
+ markStaleAppToken(error)
+ }
+
return cookieFallback(requestWithCookie, error)
}
}
diff --git a/apps/desktop/src/components/boot-failure-reauth.test.ts b/apps/desktop/src/components/boot-failure-reauth.test.ts
index 42542ea0fbf..6fe527c7341 100644
--- a/apps/desktop/src/components/boot-failure-reauth.test.ts
+++ b/apps/desktop/src/components/boot-failure-reauth.test.ts
@@ -106,6 +106,7 @@ describe('isRemoteReauthError', () => {
it('recognizes auth-shaped boot errors', () => {
expect(isRemoteReauthError('Your remote gateway session has expired.')).toBe(true)
expect(isRemoteReauthError('OAuth: please sign in')).toBe(true)
+ expect(isRemoteReauthError('Reached the gateway over HTTP, but the app token is invalid.')).toBe(true)
})
it('ignores non-auth boot errors and nullish', () => {
diff --git a/apps/desktop/src/components/boot-failure-reauth.ts b/apps/desktop/src/components/boot-failure-reauth.ts
index d84604b6f3f..265a6b87afd 100644
--- a/apps/desktop/src/components/boot-failure-reauth.ts
+++ b/apps/desktop/src/components/boot-failure-reauth.ts
@@ -56,6 +56,7 @@ export function isRemoteReauthError(error: string | null | undefined): boolean {
text.includes('remote gateway session has expired') ||
text.includes('gateway sign-in required') ||
text.includes('needs oauth login') ||
+ text.includes('app token is invalid') ||
(text.includes('oauth') && (text.includes('not signed in') || text.includes('sign in')))
)
}
diff --git a/hermes_cli/dashboard_auth/audit.py b/hermes_cli/dashboard_auth/audit.py
index 101dfa40e46..ebb126b1108 100644
--- a/hermes_cli/dashboard_auth/audit.py
+++ b/hermes_cli/dashboard_auth/audit.py
@@ -31,6 +31,7 @@ class AuditEvent(enum.Enum):
REFRESH_FAILURE = "refresh_failure"
REVOKE = "revoke"
SESSION_VERIFY_FAILURE = "session_verify_failure"
+ SESSION_REJECTED = "session_rejected"
WS_TICKET_MINTED = "ws_ticket_minted"
WS_TICKET_REJECTED = "ws_ticket_rejected"
TOKEN_AUTH_SUCCESS = "token_auth_success"
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.py
index 5561976c699..e9ff98d2e52 100644
--- a/hermes_cli/dashboard_auth/middleware.py
+++ b/hermes_cli/dashboard_auth/middleware.py
@@ -71,6 +71,9 @@ def _unauth_response(request: Request, *, reason: str) -> Response:
login_url = f"{prefix}/login?next={next_param}" if next_param else f"{prefix}/login"
if request.url.path.startswith("/api/"):
expired = reason == "invalid_or_expired_session"
+ # Same reason the client already receives. Never include the bearer.
+ audit_log(AuditEvent.SESSION_REJECTED, reason=reason, path=request.url.path,
+ ip=_client_ip(request))
return JSONResponse(
{"error": "session_expired" if expired else "unauthenticated", "detail": "Unauthorized",
"reason": reason, "login_url": login_url}, status_code=401)
diff --git a/tests/hermes_cli/test_dashboard_auth_middleware.py b/tests/hermes_cli/test_dashboard_auth_middleware.py
index 56e5d9c2bb1..f85b15fec62 100644
--- a/tests/hermes_cli/test_dashboard_auth_middleware.py
+++ b/tests/hermes_cli/test_dashboard_auth_middleware.py
@@ -14,6 +14,8 @@ without any external IDP. Exercises:
"""
from __future__ import annotations
+import json
+
import pytest
from fastapi.testclient import TestClient
@@ -257,6 +259,38 @@ def test_invalid_cookie_returns_401_on_api(gated_app):
assert r.status_code == 401
+def test_bearer_401_audits_client_facing_reason(gated_app, tmp_path):
+ """A rejected app bearer is a 401 the operator can see in the audit log.
+
+ The reason written to disk is the same reason returned to the client.
+ The bearer value itself must not appear in the log.
+ """
+ bearer = "stale-app-bearer-do-not-log"
+ response = gated_app.post(
+ "/api/auth/ws-ticket",
+ headers={"Authorization": f"Bearer {bearer}"},
+ )
+ assert response.status_code == 401
+ body = response.json()
+ assert body["reason"] == "invalid_or_expired_session"
+
+ log_path = tmp_path / "hermes_test" / "logs" / "dashboard-auth.log"
+ raw = log_path.read_text(encoding="utf-8")
+ assert bearer not in raw
+ rejected = [
+ event
+ for line in raw.splitlines()
+ if line.strip()
+ for event in [json.loads(line)]
+ if event.get("event") == "session_rejected"
+ ]
+ assert rejected, raw
+ latest = rejected[-1]
+ assert latest["reason"] == body["reason"]
+ assert latest["path"] == "/api/auth/ws-ticket"
+ assert latest.get("ip")
+
+
# ---------------------------------------------------------------------------