Fix auth so it actually enforces, not just decorates

Two gaps found while wiring auth into the data routes:

1. mcp_server/auth.py: HTTPBearer() defaults to auto_error=True, which
   rejects any request with no Authorization header before
   get_current_user's own "auth not configured -> allow as guest"
   check ever runs. That meant turning on Depends(get_current_user)
   anywhere 401'd every request even with auth fully disabled.
   Switched to auto_error=False and handle the missing-credentials
   case explicitly inside get_current_user instead.

2. Frontend never actually sent the stored token on data requests.
   auth.tsx only attached it to its own /api/auth/me check; api.ts's
   fetch() calls (chat, stats, documents, upload, delete) and every
   axios call elsewhere in the app (projects, kanban, hooks) had no
   Authorization header at all. Added an authHeaders() helper in
   api.ts, and a single axios request interceptor in auth.tsx that
   attaches the token app-wide since every component imports the same
   default axios instance.

Known gap not addressed here: mcp_server/claude_code_mcp.py (the
code-forge stdio MCP server) calls the REST API with no token at all.
Harmless while auth is disabled (current state), but it will start
getting 401'd the moment CLAUDE_OS_EMAIL/PASSWORD are actually set -
needs a service-token bypass if that's ever turned on.
This commit is contained in:
Rosie Val 2026-08-22 15:46:45 -04:00
parent d999d6af4a
commit 9298de1a49
3 changed files with 38 additions and 5 deletions

View file

@ -1,5 +1,10 @@
const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:8051';
function authHeaders(): Record<string, string> {
const token = localStorage.getItem('auth_token');
return token ? { Authorization: `Bearer ${token}` } : {};
}
export interface ChatResponse {
response: string;
sources?: Array<{
@ -30,7 +35,7 @@ export async function chat(
): Promise<ChatResponse> {
const res = await fetch(`${API_BASE}/api/kb/${kbName}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json', ...authHeaders() },
body: JSON.stringify({
query,
use_hybrid: options?.useHybrid ?? false,
@ -47,7 +52,7 @@ export async function chat(
}
export async function getKBStats(kbName: string): Promise<KBStats> {
const res = await fetch(`${API_BASE}/api/kb/${kbName}/stats`);
const res = await fetch(`${API_BASE}/api/kb/${kbName}/stats`, { headers: authHeaders() });
if (!res.ok) {
throw new Error(`Failed to get KB stats: ${res.statusText}`);
}
@ -55,7 +60,7 @@ export async function getKBStats(kbName: string): Promise<KBStats> {
}
export async function listDocuments(kbName: string): Promise<Document[]> {
const res = await fetch(`${API_BASE}/api/kb/${kbName}/documents`);
const res = await fetch(`${API_BASE}/api/kb/${kbName}/documents`, { headers: authHeaders() });
if (!res.ok) {
throw new Error(`Failed to list documents: ${res.statusText}`);
}
@ -69,6 +74,7 @@ export async function uploadDocument(kbName: string, file: File): Promise<void>
const res = await fetch(`${API_BASE}/api/kb/${kbName}/upload`, {
method: 'POST',
headers: authHeaders(),
body: formData,
});
@ -80,6 +86,7 @@ export async function uploadDocument(kbName: string, file: File): Promise<void>
export async function deleteDocument(kbName: string, filename: string): Promise<void> {
const res = await fetch(`${API_BASE}/api/kb/${kbName}/documents/${encodeURIComponent(filename)}`, {
method: 'DELETE',
headers: authHeaders(),
});
if (!res.ok) {

View file

@ -1,7 +1,21 @@
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import axios from 'axios';
const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:8051';
// Every component that talks to the API via axios imports the same default
// instance, so registering the interceptor once here attaches the stored
// token everywhere - without it, auth only ever covers the two fetch() calls
// in this file, and every axios-based request (projects, kanban, hooks,
// most of the app) goes out unauthenticated.
axios.interceptors.request.use((config) => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
interface AuthContextType {
isAuthenticated: boolean;
isAuthEnabled: boolean;

View file

@ -21,7 +21,12 @@ ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days
# Security
security = HTTPBearer()
# auto_error=False: let get_current_user itself decide whether a missing
# token is OK (auth not configured -> guest) or a 401 (auth configured).
# The HTTPBearer default (auto_error=True) rejects any request with no
# Authorization header before get_current_user's body ever runs, which
# breaks the "auth disabled by default" behavior entirely.
security = HTTPBearer(auto_error=False)
def verify_password(plain_password: str, hashed_password: str) -> bool:
@ -101,7 +106,7 @@ def decode_access_token(token: str) -> Optional[dict]:
return None
def get_current_user(credentials: HTTPAuthorizationCredentials = Security(security)) -> dict:
def get_current_user(credentials: Optional[HTTPAuthorizationCredentials] = Security(security)) -> dict:
"""
Dependency to get the current authenticated user.
Use in FastAPI routes: current_user = Depends(get_current_user)
@ -112,6 +117,13 @@ def get_current_user(credentials: HTTPAuthorizationCredentials = Security(securi
if not creds:
return {"email": "guest", "auth_disabled": True}
if credentials is None:
raise HTTPException(
status_code=401,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
token = credentials.credentials
payload = decode_access_token(token)