Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(oauth): native OAuth 2.1 authorization for MCP clients (#1870)

t0saki7d5fa6239835
diff --git a/Caddyfile b/Caddyfile
new file mode 100644
index 000000000..4d431e72e
--- /dev/null
+++ b/Caddyfile
@@ -0,0 +1,33 @@
+# OpenViking aggregated reverse proxy
+#
+# Port 1934 merges the API server (1933) and Console (8020) under one origin.
+# This block always serves plain HTTP — suitable for local dev, internal
+# networks, and as an upstream behind your own TLS-terminating proxy.
+#
+# To add public HTTPS, append a domain block below (Caddy auto-provisions
+# Let's Encrypt certs):
+#
+# {$OPENVIKING_PUBLIC_BASE_URL} {
+# @console path /console /console/*
+# handle @console {
+# reverse_proxy openviking:8020
+# }
+# handle {
+# reverse_proxy openviking:1933
+# }
+# # Optional: pin ACME email
+# # tls {$OV_ACME_EMAIL}
+# }
+#
+# Then expose ports 80/443 in docker-compose.yml and set
+# OPENVIKING_PUBLIC_BASE_URL=https://your-domain.com in .env.
+
+:1934 {
+ @console path /console /console/*
+ handle @console {
+ reverse_proxy openviking:8020
+ }
+ handle {
+ reverse_proxy openviking:1933
+ }
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index 5a90caf1a..33b6822ff 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,15 +1,31 @@
version: "3.8"
+# Set OPENVIKING_PUBLIC_BASE_URL in a `.env` file next to this compose file
+# when you need public HTTPS (OAuth, MCP clients on the internet).
+#
+# .env example for local-only (leave unset or empty):
+# # no .env needed — just `docker compose up -d`
+#
+# .env example for public HTTPS:
+# OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com
+#
+# See docs/en/guides/12-public-access.md for the full walkthrough.
+
services:
openviking:
image: ghcr.io/volcengine/openviking:latest
container_name: openviking
+ # Direct access to individual services (optional — caddy:1934 is the
+ # recommended single entry point). Comment these out once Caddy is your
+ # only ingress.
ports:
- "1933:1933"
- "8020:8020"
volumes:
- # All persistent state (ov.conf, ovcli.conf, workspace) lives here.
- ~/.openviking:/app/.openviking
+ environment:
+ OPENVIKING_PUBLIC_BASE_URL: ${OPENVIKING_PUBLIC_BASE_URL:-}
healthcheck:
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:1933/health || exit 1"]
interval: 30s
@@ -17,6 +33,34 @@ services:
retries: 3
start_period: 30s
restart: unless-stopped
- # If you need to override the default command (which runs openviking-server),
- # you can do so here. For example, to run the CLI:
- # command: ["openviking", "--help"]
+
+ # Aggregated reverse proxy — merges API (1933) + Console (8020) on port
+ # 1934 under one origin. Always enabled, plain HTTP by default.
+ #
+ # For public HTTPS: edit the Caddyfile to add a domain block, set
+ # OPENVIKING_PUBLIC_BASE_URL in .env, uncomment the 80/443 port lines
+ # below, and add the caddy volumes at the bottom.
+ caddy:
+ image: caddy:2
+ container_name: openviking-caddy
+ restart: unless-stopped
+ ports:
+ - "1934:1934"
+ # Uncomment for public HTTPS (after adding a domain block to Caddyfile):
+ # - "80:80"
+ # - "443:443"
+ volumes:
+ - ./Caddyfile:/etc/caddy/Caddyfile:ro
+ # Uncomment for public HTTPS (Caddy stores certs here):
+ # - caddy_data:/data
+ # - caddy_config:/config
+ environment:
+ OPENVIKING_PUBLIC_BASE_URL: ${OPENVIKING_PUBLIC_BASE_URL:-}
+ OV_ACME_EMAIL: ${OV_ACME_EMAIL:-}
+ depends_on:
+ - openviking
+
+# Uncomment for public HTTPS:
+# volumes:
+# caddy_data:
+# caddy_config:
diff --git a/docs/design/mcp-oauth2-1.md b/docs/design/mcp-oauth2-1.md
new file mode 100644
index 000000000..b44d3a061
--- /dev/null
+++ b/docs/design/mcp-oauth2-1.md
@@ -0,0 +1,372 @@
+# OpenViking 原生 OAuth 2.1(MCP 客户端授权)实施方案
+
+## Context
+
+**问题**:Claude.ai / Claude Desktop / ChatGPT 等只接受 OAuth 2.1 的 MCP 客户端,必须经由社区项目 [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth) 的 Cloudflare Workers 代理才能连接 OpenViking 的 `/mcp`。痛点:
+
+1. **额外部署单元** — 自建 CF Worker + 2 个 KV namespace,运维成本高
+2. **生态绑定** — `@cloudflare/workers-oauth-provider` + KV 强绑定 CF Workers,无法脱离 CF 生态
+3. **体验差与信任风险** — 用户在浏览器手动粘贴 API Key,且 Worker 部署方有解密 Key 的能力
+
+**目标**:在 OpenViking 服务端原生实现 OAuth 2.1(MCP 子集),消除中间代理;保留 API Key 认证向后兼容;提供顺手的浏览器授权 UX。
+
+**最终决策(与设计早期不同)**:
+
+- **协议层用 `mcp.server.auth` SDK**(已在依赖中)。SDK 提供完整的 RFC 6749 / 7591 / 8414 实现:DCR、authorize 解析、token endpoint、metadata、PKCE S256 校验、redirect_uri 校验、错误码格式化。
+- **Token 用 opaque + SQLite,不用 JWT**。Access / refresh / auth_code / OTP 全部是 `secrets.token_urlsafe()` 随机串,按 SHA-256 哈希存表,每次校验做一次 SQLite 查询。**OpenViking 侧零密码学代码**。
+- **不做 redirect_uri 白名单**,但 SDK 会强制 strict-equal 校验防 code injection。
+- **Phase 1 用 device-flow 风格的 OTP 流程**:authorize page **显示** 6 字符码,用户在 console(已登录环境)**输入** 该码确认授权。比早期的"console 取码、page 输入"流程少一次 tab 切换,且符合 RFC 8628 的心理模型。
+
+---
+
+## 架构
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ OpenViking 1933 │
+│ │
+│ ┌────────────────────┐ ┌──────────────────────────┐ │
+│ │ mcp.server.auth │ │ openviking.server.oauth │ │
+│ │ (SDK, 协议层) │ │ (适配 + 自定义路由) │ │
+│ ├────────────────────┤ ├──────────────────────────┤ │
+│ │ /.well-known/ │ │ /.well-known/ │ │
+│ │ oauth-auth-server│ │ oauth-protected- │ │
+│ │ /register (DCR) │ │ resource (PRM 9728) │ │
+│ │ /authorize │ │ /oauth/authorize/page │ │
+│ │ /token │ │ /oauth/authorize/page/ │ │
+│ │ /revoke │ │ status (轮询) │ │
+│ └─────────┬──────────┘ │ /api/v1/auth/oauth- │ │
+│ │ │ verify (确认入口) │ │
+│ │ │ /api/v1/auth/otp │ │
+│ │ │ (legacy push) │ │
+│ │ └──────────┬───────────────┘ │
+│ │ │ │
+│ ↓ load_access_token() ↓ DELETE/INSERT │
+│ ┌────────────────────┐ ┌──────────────────────────┐ │
+│ │ auth.py │ │ workspace/oauth.db │ │
+│ │ resolve_identity │ │ oauth_clients │ │
+│ │ 识别 ovat_ → │ │ oauth_codes (otp+code) │ │
+│ │ provider 查找 │ │ oauth_refresh_tokens │ │
+│ │ → ResolvedIdentity │ │ oauth_access_tokens │ │
+│ └────────────────────┘ │ oauth_pending_authorizations │
+│ │ (display_code, verified, ...) │
+│ └──────────────────────────┘ │
+└─────────────────────────────────────────────────────────────────┘
+ ↑ verify (Bearer)
+┌─────────────────────────────────────────────────────────────────┐
+│ OpenViking Console 8020 │
+│ Settings → "Authorize an MCP client" 表单 │
+│ - 输入 6 字符 display_code → 调 /console/api/v1/ov/auth/ │
+│ oauth-verify (proxy → 1933 /api/v1/auth/oauth-verify) │
+│ 浏览器 sessionStorage 存 API Key (key=ov_console_api_key) │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## 设计要点
+
+### 1. 认证模式
+
+不引入新的 `AuthMode.OAUTH`。OAuth 叠加在现有 `AuthMode.API_KEY` 之上:当 `oauth.enabled = true` 时,`Authorization: Bearer <token>` 优先按 OAuth 处理:
+
+- 若 token 以 `ovat_` 前缀开头 → 走 `provider.load_access_token()` 路径,**fail-closed**(前缀正确但查不到不会回退到 API Key 路径)
+- 否则 → 走现有 APIKeyManager 路径,行为与改动前完全一致
+
+`ResolvedIdentity` 新增 `from_oauth: bool` 标记位;`get_request_context` 对 OAuth 身份跳过 ROOT-tenant-headers 强校验(claims 已钉死 account/user)。
+
+### 2. Token 权限范围与撤销
+
+OAuth token = API Key 等效,能调任何当前用户身份能调的 REST 端点(不仅 `/mcp`)。
+
+- **不是权限放大**:opaque token 都钉死 `(account_id, user_id, role)`
+- **撤销粒度**:以 `(account, user)` 为单位 — 删除某 user 的 API Key 时一刀切撤销该 user 名下所有 OAuth token,见 `OAuthStore.revoke_user_tokens()`
+- Phase 2 计划引入 OAuth scope 做更细收紧
+
+### 3. Token 形态(全部 opaque)
+
+| 类型 | 形态 | 前缀 | TTL | 存储 |
+|---|---|---|---|---|
+| access_token | `secrets.token_urlsafe(40)` | `ovat_` | 1h | SQLite (SHA-256 哈希) |
+| refresh_token | `secrets.token_urlsafe(40)` | `ovrt_` | 30d | SQLite (SHA-256 哈希) |
+| authorization_code | `secrets.token_urlsafe(40)` | `ovac_` | 5min | SQLite (SHA-256 哈希) |
+| display_code (人类可读) | 6 字符(去歧义字母+数字) | — | 10min | pending_authorizations |
+| OTP(legacy push) | 同上 | — | 5min | oauth_codes |
+
+前缀是 fast-path discriminator(不参与鉴权决策)— 让 `auth.py` 在每次请求只对 `ovat_` 开头的 bearer 做 DB 查询,普通 API Key 不受影响。
+
+### 4. 公网 URL 解析(issuer / PRM resource / WWW-Authenticate / page 链接)
+
+统一 4 级回退:
+
+1. `OPENVIKING_PUBLIC_BASE_URL` 环境变量(最高优先级,部署 override)
+2. `oauth.issuer` 配置项
+3. `X-Forwarded-Proto` + `X-Forwarded-Host`(反代场景)
+4. 请求 scheme + `Host` 头(直连)
+
+非 localhost 部署强烈建议显式设置 (1) 或 (2),因为 SDK 强制 issuer 必须是 HTTPS(除 loopback)。
+
+### 5. PKCE / redirect_uri / 错误格式
+
+由 SDK 强制 S256,`plain` 拒绝;`code_verifier` 长度 43–128。SDK 在 `TokenHandler` 中验证。`/authorize` 时 `OAuthClientMetadata.validate_redirect_uri` 做 strict-equal;`/token` 时再次比对(防 code injection)。RFC 6749 错误码由 SDK 返回。
+
+### 6. WWW-Authenticate 401 头
+
+`/mcp` 鉴权失败时 `_IdentityASGIMiddleware` 注入:
+```
+WWW-Authenticate: Bearer resource_metadata="https://<host>/.well-known/oauth-protected-resource"
+```
+URL 走 §4 的 4 级回退。RFC 9728 客户端发现入口。
+
+---
+
+## 端到端流程(device-flow / pull 模式)
+
+```
+1. 用户输入 https://my.ov/mcp 到 Claude.ai
+2. Claude POST /mcp → 401 + WWW-Authenticate: Bearer resource_metadata="..."
+3. Claude GET /.well-known/oauth-protected-resource → 拿 issuer
+4. Claude GET /.well-known/oauth-authorization-server → 拿 endpoint [SDK]
+5. Claude POST /register {redirect_uris} → 拿 client_id [SDK]
+6. Claude 浏览器跳到 /authorize → SDK 校验 → 调 provider.authorize() →
+ server 生成 display_code (e.g. "AB3X7K") + pending → 302 →
+ /oauth/authorize/page?pending=... [SDK→OV]
+7. Page 显示大字 "AB3X7K" + 链接 https://my.ov/console,
+ 并启动 JS 轮询 /oauth/authorize/page/status?pending=...
+8. 用户切到 console (sessionStorage 已经在登录) → Settings →
+ "Authorize an MCP client" 输入 AB3X7K → 点 Authorize
+9. Console JS POST /console/api/v1/ov/auth/oauth-verify {code, decision}
+ ↓ proxy
+ 1933 POST /api/v1/auth/oauth-verify
+ → server 找 pending by display_code → mark verified, 写入 caller 身份
+10. Page 下次轮询命中 status=approved → response.redirect_url 含 auth_code
+11. Page JS window.location.replace(redirect_url) → Claude 收到 ?code=...&state=...
+12. Claude POST /token (PKCE) → ovat_ + ovrt_ [SDK]
+13. Claude POST /mcp (Authorization: Bearer ovat_...) → 通过 [SDK→auth.py]
+```
+
+**同源加速(可选)**:第 7 步 page JS 检测到 `sessionStorage.ov_console_api_key` 存在(即与 console 同域 + 已登录)时,显示绿色 "Quick authorize" 面板。点击该按钮等价于在 console 输入码 → 直接跳到第 10 步。**仍要点击确认**,不会自动一步跳转。要让同源生效,nginx 反代把 8020 与 1933 放到同一域名(`/console/...` → 8020,`/...` → 1933)。
+
+---
+
+## 模块清单
+
+### 新增 / 改写
+
+| 文件 | 用途 | 行数 |
+|---|---|---|
+| `openviking/server/oauth/storage.py` | SQLite 5 张表 + CRUD + GC + verify/find_pending_by_display_code | ~620 |
+| `openviking/server/oauth/provider.py` | `OAuthAuthorizationServerProvider` Protocol 适配;子类化 SDK 的 `AuthorizationCode/RefreshToken/AccessToken` 嵌入 `(account, user, role)`;`authorize()` 自动生成 display_code | ~280 |
+| `openviking/server/oauth/router.py` | PRM、authorize page (HTML+JS)、page/status 轮询、`/api/v1/auth/oauth-verify`、legacy `/api/v1/auth/otp` | ~440 |
+| `openviking/server/oauth/otp.py` | `generate_otp` / `hash_secret`(stdlib) | ~30 |
+| `openviking_cli/utils/config/oauth_config.py` | `OAuthConfig` pydantic | ~70 |
+
+### 修改
+
+| 文件 | 改动 |
+|---|---|
+| `openviking/server/auth.py` | `_try_resolve_oauth_token`:识别 `ovat_` → `provider.load_access_token` → `ResolvedIdentity(from_oauth=True)` |
+| `openviking/server/identity.py` | `ResolvedIdentity.from_oauth: bool` |
+| `openviking/server/mcp_endpoint.py` | 401 注入 `WWW-Authenticate` 头;`_scope_to_origin` 4 级回退含 env |
+| `openviking/server/app.py` | lifespan 初始化 `OAuthStore` + GC 任务;`create_app` 用 `mcp.server.auth.routes.create_auth_routes()` 挂 SDK routes + 自定义 router;issuer 优先读 `OPENVIKING_PUBLIC_BASE_URL` env |
+| `openviking_cli/utils/config/open_viking_config.py` | 接入 `OAuthConfig` |
+| `openviking/console/app.py` | 加 `POST /console/api/v1/ov/auth/otp` 和 `POST /console/api/v1/ov/auth/oauth-verify` 转发路由 |
+| `openviking/console/static/index.html` | Settings 面板加 "Authorize an MCP client" 表单(device flow 入口)和折叠的 legacy "Get OTP" 入口 |
+| `openviking/console/static/app.js` | 表单事件 handler;调 verify 端点;keydown=Enter 触发授权 |
+
+### 删除(vs 早期 JWT 方案)
+
+- `openviking/server/oauth/jwt.py`(手搓 HS256)
+- `tests/server/oauth/test_jwt.py`
+
+---
+
+## 端点全表
+
+| 端点 | 方法 | 由谁实现 | 鉴权 | 说明 |
+|---|---|---|---|---|
+| `/.well-known/oauth-authorization-server` | GET | SDK | 无 | RFC 8414 |
+| `/.well-known/oauth-protected-resource` | GET | OpenViking | 无 | RFC 9728,列出 issuer 和 bearer_methods |
+| `/register` | POST | SDK | 无 | DCR (RFC 7591),SDK 生成 client_id/secret,调 `provider.register_client()` |
+| `/authorize` | GET/POST | SDK → provider.authorize() | 无 | SDK 校验 client + redirect_uri + PKCE,调 `provider.authorize()` 生成 display_code + pending_id;返回 302 → `/oauth/authorize/page?pending=...` |
+| `/oauth/authorize/page` | GET | OpenViking | 无 | 显示 display_code + console 链接 + 同源 quick-authorize 面板(如检测到 sessionStorage 中的 API key);JS 轮询 status |
+| `/oauth/authorize/page/status` | GET | OpenViking | 无 | 返回 `{status: pending\|approved\|expired, redirect_url?}`;status=approved 时原子签发 auth_code 并删除 pending |
+| `/token` | POST | SDK | client auth | SDK 验 PKCE / redirect_uri / client,调 `provider.exchange_authorization_code()` 或 `exchange_refresh_token()` |
+| `/revoke` | POST | SDK | client auth | SDK 调 `provider.revoke_token()` |
+| `POST /api/v1/auth/oauth-verify` | POST | OpenViking | 现有 API Key(`Depends(get_request_context)`) | 接受 `{code, decision: approve\|deny}`;approve 时把 caller 身份写入 pending;deny 时删除 pending |
+| `POST /api/v1/auth/otp` | POST | OpenViking | 现有 API Key | **legacy push flow**:生成 OTP 绑定调用方身份;保留供 CLI/脚本场景使用 |
+
+---
+
+## 部署运维
+
+### 启动
+
+| 服务 | 命令 | 默认端口 |
+|---|---|---|
+| 主服务(API + MCP + OAuth) | `openviking-server [--host --port --config --workers]` | 1933 |
+| Web Console | `python -m openviking.console.bootstrap [--host --port --openviking-url --write-enabled]` | 8020 |
+
+> Console 当前没有 `openviking-console` entry point,只能 `python -m`。后续可加。
+
+### 关键配置
+
+| 项 | 何处 | 说明 |
+|---|---|---|
+| 存储路径 | `ov.conf:storage.workspace`(默认 `./data`) | `oauth.db` 落在 `<workspace>/oauth.db` |
+| OAuth 启用 | `ov.conf:oauth.enabled = true` | 默认 false,关闭时所有 OAuth 路径不挂载 |
+| Issuer URL | `OPENVIKING_PUBLIC_BASE_URL` env > `ov.conf:oauth.issuer` | 非 localhost 必须 HTTPS |
+| TTL | `ov.conf:oauth.{access,refresh,auth_code,otp}_ttl_seconds` | 默认 1h / 30d / 5min / 5min |
+| Console 上游 | `--openviking-url`(默认 `http://127.0.0.1:1933`) | 反代后改成 `http://127.0.0.1:1933` 即可 |
+
+### nginx 反代模板(推荐部署形态,**未在仓库**)
+
+```nginx
+server {
+ listen 443 ssl;
+ server_name my.ov;
+
+ # 8020 console
+ location /console {
+ proxy_pass http://127.0.0.1:8020;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+
+ # 其他都走 1933 (REST + MCP + OAuth + .well-known)
+ location / {
+ proxy_pass http://127.0.0.1:1933;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+}
+```
+
+这种部署下 console 和 OAuth page 同源,page 的"quick-authorize"面板自动可用。后续可在 `deploy/` 下落一份正式模板。
+
+---
+
+## 实施进度
+
+### ✅ M1 — 基础设施
+- `OAuthConfig` 接入 `OpenVikingConfig`(默认 disabled)
+- `OAuthStore` 5 张表 + CRUD + 原子一次性消费 + revoke_user_tokens
+- `oauth/otp.py` OTP 生成
+- `app.py` lifespan 注入 store + provider + GC
+
+### ✅ M2 — Bearer 路径与 401 头
+- `auth.py` `_try_resolve_oauth_token` 识别 `ovat_` 前缀走 OAuth 路径
+- `ResolvedIdentity.from_oauth` 标记位 + `get_request_context` 跳过 ROOT-tenant 强校验
+- `mcp_endpoint.py` 401 注入 `WWW-Authenticate` 头(含 4 级 origin 回退)
+
+### ✅ M3 — SDK 接入与完整流程
+- `OpenVikingOAuthProvider`(8 个 Protocol 方法)
+- 自定义 authorize HTML 页 + display_code 显示 + JS 轮询
+- `POST /api/v1/auth/oauth-verify`(device flow 确认入口)
+- `POST /api/v1/auth/otp`(legacy push flow,保留)
+- `GET /.well-known/oauth-protected-resource`(RFC 9728)
+- `app.py` 用 `create_auth_routes()` 挂 SDK 路由
+
+### ✅ M4 — Console 集成
+- console proxy 加 `oauth-verify` / `otp` 转发
+- Settings 加 "Authorize an MCP client" 表单(device flow)
+- legacy "Get OTP" 折叠在 details 内
+- 同源 quick-authorize 面板(page JS 检测 sessionStorage)
+
+### ✅ M5 — `OPENVIKING_PUBLIC_BASE_URL` 环境变量
+- 4 级 origin 回退在 `_public_origin` (router) 和 `_scope_to_origin` (mcp_endpoint) 共用
+- SDK issuer 启动时读
+
+### ⏳ Phase 1 剩余
+1. **Claude.ai / Claude Desktop / Cursor 端到端实测**(需要起 server,等 benchmark 跑完)
+2. **`deploy/nginx.conf.example`** + 部署文档(同源 quick-authorize 的运维侧条件)
+3. **`openviking-console` entry point script**(让 8020 启动统一为 `openviking-console`)
+
+### 🔜 Phase 2 / 3(不在本 PR 范围)
+- OAuth scope 机制(`mcp` / `fs.read` / `fs.write` / `admin`)
+- GitHub / Google 第三方登录(`identity_links` 表)
+- 邮件 OTP 投递(SMTP 集成)
+- `ov otp` Rust CLI 子命令
+
+---
+
+## 验证
+
+### 单元 / 集成测试
+```bash
+pytest tests/server/oauth/ -v # 38 通过(含完整 device flow happy path)
+pytest tests/server/test_auth.py tests/server/test_mcp_endpoint.py -v # 回归
+```
+
+### 端到端 curl(device flow)
+```bash
+# 1. 注册客户端
+curl -X POST -H "Content-Type: application/json" \
+ -d '{"redirect_uris":["http://127.0.0.1:9999/cb"],"client_name":"test","token_endpoint_auth_method":"none"}' \
+ http://127.0.0.1:1933/register
+
+# 2. PKCE
+VERIFIER=$(openssl rand -base64 64 | tr -d '=+/' | head -c 64)
+CHALLENGE=$(printf "%s" "$VERIFIER" | openssl dgst -sha256 -binary | basenc --base64url | tr -d '=')
+
+# 3. 浏览器: GET /authorize?... → 跳到 /oauth/authorize/page → 显示 6 字符码 e.g. "AB3X7K"
+
+# 4. 用户在 console 输入 AB3X7K(或直接 curl)
+curl -X POST -H "X-Api-Key: $ROOT_KEY" -H "Content-Type: application/json" \
+ -d '{"code":"AB3X7K","decision":"approve"}' \
+ http://127.0.0.1:1933/api/v1/auth/oauth-verify
+
+# 5. Page 自动 302 回 redirect_uri,从中取 auth_code
+
+# 6. 换 token
+curl -X POST -d "grant_type=authorization_code&code=ovac_...&client_id=...&code_verifier=$VERIFIER&redirect_uri=..." \
+ http://127.0.0.1:1933/token
+# → {"access_token":"ovat_...","refresh_token":"ovrt_...","expires_in":3600}
+
+# 7. 调 MCP
+curl -X POST -H "Authorization: Bearer ovat_..." \
+ http://127.0.0.1:1933/mcp -d '{"jsonrpc":"2.0","method":"tools/list","id":1}'
+```
+
+### 向后兼容
+- `oauth.enabled=false`(默认):`auth.py` 中 `oauth_provider is None`,OAuth 分流被跳过;行为与改动前一致
+- `oauth.enabled=true`:`Authorization: Bearer <api_key>`(无 `ovat_` 前缀)仍走 APIKeyManager;现有客户端无感知
+
+---
+
+## 关键文件路径速查
+
+**新增**:
+- `openviking/server/oauth/{provider,storage,router,otp,__init__}.py`
+- `openviking_cli/utils/config/oauth_config.py`
+- `tests/server/oauth/test_{storage,router,auth_integration,mcp_www_authenticate}.py`
+
+**修改**:
+- `openviking/server/auth.py`(`_try_resolve_oauth_token`)
+- `openviking/server/mcp_endpoint.py`(`WWW-Authenticate` + `_scope_to_origin`)
+- `openviking/server/identity.py`(`from_oauth` 字段)
+- `openviking/server/app.py`(lifespan + `create_auth_routes` + env-aware issuer)
+- `openviking_cli/utils/config/open_viking_config.py`(接入 `OAuthConfig`)
+- `openviking/console/app.py`(proxy `/auth/otp`, `/auth/oauth-verify`)
+- `openviking/console/static/{index.html,app.js}`(device flow 表单 + 同源 quick-authorize)
+
+**复用**(不改):
+- `openviking/server/identity.py:AuthMode/Role/ResolvedIdentity`
+- `openviking_cli/utils/config/storage_config.py:StorageConfig.workspace`
+- `mcp.server.auth.*`(官方 SDK,无新依赖)
+
+---
+
+## 风险与已识别问题
+
+| 风险 | 处理 |
+|---|---|
+| 反代后 `issuer` 派生错(HTTPS 终结于代理) | `OPENVIKING_PUBLIC_BASE_URL` env 或 `oauth.issuer` 配置;非 localhost 部署强烈建议显式设 |
+| 同源 quick-authorize 是隐式确认 | 即使检测到 sessionStorage,**仍需点击 "Authorize" 按钮**才生效,不会一步跳转 |
+| display_code 暴力枚举 | 6 字符 × 32 字母表 = ~1B 组合;TTL 10min;pending 一次性消费;建议在反代层加每 IP 速率限制 |
+| Refresh token 重放 | 实现:检测重放→`store.revoke_user_tokens(account, user)` 一并撤销该 user 名下所有 OAuth state |
+| Token 权限范围 = 整个 REST API | 已与用户确认 Phase 1 不限制;Phase 2 引入 scope 机制收紧 |
+| API Key → 撤销 OAuth token 的精度 | 当前粒度 `(account, user)`:删 user 时调 `revoke_user_tokens` cascade;满足需求 |
+| Console 与 OAuth page 同源依赖反代 | 文档提供 nginx 模板;不反代时退化为"console 复制 OTP,page 输入"流程仍可用 |
diff --git a/docs/en/guides/03-deployment.md b/docs/en/guides/03-deployment.md
index 1ca447478..01a0f3a9a 100644
--- a/docs/en/guides/03-deployment.md
+++ b/docs/en/guides/03-deployment.md
@@ -276,8 +276,11 @@ docker compose up -d
```
After startup, you can access:
-- API service: `http://localhost:1933`
-- Console UI: `http://localhost:8020`
+- Aggregated entry point: `http://localhost:1934` (Caddy merges API + Console)
+- API service (direct): `http://localhost:1933`
+- Console UI (direct): `http://localhost:8020`
+
+For public HTTPS access, see the [Public Access Guide](12-public-access.md).
To build the image yourself, pass an explicit OpenViking version:
`docker build --build-arg OPENVIKING_VERSION=0.3.12 -t openviking:latest .`
@@ -314,6 +317,8 @@ Use `/health` for Kubernetes liveness probes and `/ready` for readiness probes.
## Related Documentation
+- [Public Access & Reverse Proxy](12-public-access.md) - HTTPS, Caddy, nginx
- [Authentication](04-authentication.md) - API key setup
+- [OAuth Guide](11-oauth.md) - OAuth 2.1 for MCP clients
- [Observability & Diagnostics](05-observability.md) - Health checks, tracing, and debugging
- [API Overview](../api/01-overview.md) - Complete API reference
diff --git a/docs/en/guides/06-mcp-integration.md b/docs/en/guides/06-mcp-integration.md
index 91b0e5c5f..c3f944cfd 100644
--- a/docs/en/guides/06-mcp-integration.md
+++ b/docs/en/guides/06-mcp-integration.md
@@ -18,7 +18,7 @@ The following platforms have been successfully integrated with OpenViking MCP:
|----------|-------------------|
| **Claude Code** | `type: http` |
| **ChatGPT & Codex** | Standard MCP config |
-| **Claude.ai / Claude Desktop** | Via MCP-Key2OAuth proxy |
+| **Claude.ai / Claude Desktop** | Native OAuth 2.1 (see [11-oauth](11-oauth.md)) |
| **Manus** | Standard MCP config |
| **Trae** | Standard MCP config |
@@ -78,31 +78,27 @@ Or in `.mcp.json`:
Add `--scope user` to make the config global (shared across all projects).
-### Claude.ai / Claude Desktop (OAuth Proxy)
+### Claude.ai / Claude Desktop / ChatGPT / Cursor (OAuth)
-Claude.ai and Claude Desktop Connector require MCP servers to use OAuth 2.1 authentication — API Keys cannot be passed directly.
+These clients only accept OAuth 2.1 — API Keys cannot be passed directly.
+OpenViking ships a native OAuth 2.1 implementation (DCR + PKCE + opaque
+tokens, backed by SQLite, with a console-driven OTP authorization page) so
+no external proxy is needed.
-#### Official OAuth Support (Planned)
+**See the [OAuth 2.1 Guide](11-oauth.md)** for:
-We are evaluating built-in OAuth 2.1 authorization endpoints for `openviking-server`. The initial design includes:
+- End-to-end flow (device-flow style: page displays a 6-character code,
+ user confirms in the OpenViking console)
+- HTTP (local) and HTTPS (production) deployment, including Caddy and nginx
+ reverse-proxy templates plus a docker-compose example
+- Connecting Claude.ai / Claude Desktop / Cursor / ChatGPT step by step
+- `OPENVIKING_PUBLIC_BASE_URL` and the `oauth` config block
+- Token model (`ovat_` / `ovrt_` / `ovac_` prefixes) and revocation
-- **OTP Authorization**: Obtain a one-time passcode via CLI (`ov otp`) or REST API, then enter it on the OAuth authorization page — no external dependencies required
-- **Console Quick-Auth**: Leverage the Web Console (port 8020) same-origin session for one-click authorization
-- **Third-party Login**: Optional delegated login via GitHub / Google or other IdPs
-
-These approaches are currently in design review; implementation timeline is TBD.
-
-#### Current Workaround: MCP-Key2OAuth (Community Project)
-
-Until official OAuth support is available, the community project [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth) can proxy API Key auth as an OAuth flow:
-
-1. Follow the project README to self-host the proxy (Cloudflare Workers)
-2. Enter your OpenViking MCP server URL (e.g., `https://your-server.com/mcp`)
-3. Generate the proxied URL
-4. In Claude.ai / Claude Desktop, enter the generated URL — it will redirect to the proxy for auth
-5. After authorization, MCP tools are available
-
-> ⚠️ **Disclaimer:** MCP-Key2OAuth is a third-party community-maintained project. The OpenViking team makes no guarantees regarding its security, availability, or data handling. Please assess the risks before use. If you have concerns, consider waiting for the official OAuth implementation or deploying your own proxy.
+> The community [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth)
+> Cloudflare Worker proxy is still around and remains a valid third-party
+> option, but the native flow is recommended now: no extra deployment unit,
+> no third-party trust boundary on the API key.
## Available MCP Tools
diff --git a/docs/en/guides/11-oauth.md b/docs/en/guides/11-oauth.md
new file mode 100644
index 000000000..9ca48c09f
--- /dev/null
+++ b/docs/en/guides/11-oauth.md
@@ -0,0 +1,364 @@
+# OAuth 2.1 Guide
+
+OpenViking server ships a native OAuth 2.1 implementation. Any client that
+needs OAuth — including MCP clients (Claude.ai, Claude Desktop, ChatGPT,
+Cursor) and any future first-party browser app — can authorize against the
+server directly, without a third-party proxy. The protocol surface (DCR,
+authorize, token, metadata) is provided by the official `mcp.server.auth`
+SDK and is otherwise standards-compliant OAuth 2.1, so non-MCP OAuth clients
+work just as well.
+
+## Recommended setup
+
+> **Prerequisite**: public HTTPS. OAuth 2.1 (and the MCP SDK) **requires
+> HTTPS** for any non-localhost issuer. See the
+> [Public Access Guide](12-public-access.md) for how to set up HTTPS with
+> Caddy or nginx.
+
+1. **Set up HTTPS** — follow [Public Access Guide](12-public-access.md) to
+ get `https://ov.your-domain.com` working (Caddy + `.env` +
+ `docker compose up`).
+
+2. **Enable OAuth in `~/.openviking/ov.conf`:**
+
+ ```json
+ { "oauth": { "enabled": true } }
+ ```
+
+3. **Restart** (`docker compose restart openviking`).
+
+4. **Connect a client.** In Claude.ai → Connectors → Add, enter
+ `https://ov.your-domain.com/mcp`. The browser will open an authorize page
+ that displays a 6-character code; open
+ `https://ov.your-domain.com/console`, sign in with your API key, paste
+ the code in Settings → "Authorize an MCP client", click Authorize. The
+ browser flips back to Claude.ai and the connector is live.
+
+That's the whole production path. The rest of this guide explains why each
+piece exists, how to test locally without HTTPS, and how to verify with curl
+when something doesn't work.
+
+---
+
+## Why native OAuth
+
+Some MCP clients only accept OAuth 2.1, not API keys. Until now the only path
+was to deploy the community [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth)
+Cloudflare Worker proxy that translates OAuth into an API-Key bearer. Native
+support removes:
+
+- The extra deployment unit (CF Worker + KV namespaces)
+- The third-party trust boundary (the proxy operator can decrypt the upstream API key)
+- The copy-paste UX where users paste the API key into a browser textbox
+
+API-Key auth still works as before — OAuth layers on top.
+
+---
+
+## How it works
+
+OpenViking implements a **device-flow style** OTP exchange (closer to RFC 8628
+than the original push flow). When an MCP client opens the browser to
+authorize:
+
+```
+1. MCP client POST /mcp → 401 + WWW-Authenticate header
+2. MCP client GET /.well-known/oauth-protected-resource (RFC 9728)
+3. MCP client GET /.well-known/oauth-authorization-server (RFC 8414)
+4. MCP client POST /register (Dynamic Client Registration, RFC 7591)
+5. MCP client GET /authorize?... (browser redirect)
+6. Server → /oauth/authorize/page?pending=...
+ (page displays a 6-character code, e.g. "AB3X7K")
+7. User opens the OpenViking web console (already signed in)
+ → Settings → "Authorize an MCP client" → enters AB3X7K → Authorize
+8. Server marks the pending authorization as verified, binding the
+ console user's identity (account / user / role)
+9. Page polls /oauth/authorize/page/status, sees "approved",
+ redirects browser to the MCP client's redirect_uri with code
+10. MCP client POST /token (PKCE S256) → access_token (ovat_...) +
+ refresh_token (ovrt_...)
+11. MCP client POST /mcp (Authorization: Bearer ovat_...) → tool list
+```
+
+The 6-character code is shown on the authorize page and **typed into the
+console**, not the other way around. This means the user always confirms from
+an environment where they're already authenticated. If the console is on the
+same origin as the OAuth page (recommended deployment), the page can also
+detect the user's signed-in console session and offer a one-click "Quick
+authorize" button — but the click is still required, never automatic.
+
+A legacy "push" flow is also retained for CLI-driven scenarios: the console
+has a "Generate OTP" button, and `POST /api/v1/auth/otp` issues a one-time
+passcode bound to the caller's API key.
+
+---
+
+## Quick start (HTTP, local only)
+
+The fastest way to verify OAuth is wired correctly is on `127.0.0.1`. The MCP
+SDK accepts `http://127.0.0.1` and `http://localhost` as issuer URLs without
+HTTPS — but Claude.ai and Claude Desktop themselves require **public HTTPS**
+endpoints, so this mode is only useful for local testing with tools like
+[MCP Inspector](https://github.com/modelcontextprotocol/inspector).
+
+1. **Enable OAuth in `~/.openviking/ov.conf`:**
+
+ ```json
+ {
+ "oauth": {
+ "enabled": true
+ }
+ }
+ ```
+
+2. **Start the services:**
+
+ ```bash
+ docker compose up -d
+ ```
+
+ Or without Docker:
+
+ ```bash
+ openviking-server
+ # in another terminal
+ python -m openviking.console.bootstrap --write-enabled
+ ```
+
+3. **Sign in to the console** at <http://127.0.0.1:1934/console> (or
+ `:8020/console` if running without the aggregated proxy), paste your API
+ key into Settings, click Save. The "Authorize an MCP client" form is now
+ available.
+
+4. **Connect a local MCP client** (e.g. MCP Inspector) to
+ `http://127.0.0.1:1934/mcp` (or `:1933/mcp`). The client will hit the
+ OAuth flow above; copy the 6-character code from the authorize page into
+ the console form, click Authorize, and the client will receive a token.
+
+For Claude.ai / Claude Desktop on the public internet, see the
+[Public Access Guide](12-public-access.md).
+
+---
+
+## Production deployment (HTTPS)
+
+OAuth 2.1 **requires HTTPS** for any non-localhost issuer. The
+[Public Access Guide](12-public-access.md) covers the full setup — Caddy,
+nginx, docker compose, CDN — in detail. The short version:
+
+1. Follow [Public Access Guide § Adding HTTPS](12-public-access.md#adding-https-for-public-access)
+ to get `https://your-domain.com` serving port 1934 over TLS.
+2. Enable OAuth: `{ "oauth": { "enabled": true } }` in `ov.conf`.
+3. Restart: `docker compose restart openviking`.
+4. Set `OPENVIKING_PUBLIC_BASE_URL=https://your-domain.com` in `.env` (the
+ server uses this as the issuer in OAuth metadata and `WWW-Authenticate`).
+
+Once HTTPS + OAuth are both up, connect clients as described below.
+
+---
+
+## Connecting OAuth-only MCP clients
+
+### Claude.ai (web)
+
+1. Settings → Connectors → **Add connector**.
+2. Enter `https://my.ov/mcp` as the server URL.
+3. Claude opens an authorize page in a popup; copy the 6-character code.
+4. Open <https://my.ov/console> in another tab (the popup also has a link).
+5. Sign in if needed → Settings → "Authorize an MCP client" → paste the code → **Authorize**.
+6. The popup automatically redirects back to Claude with a fresh access token.
+
+### Claude Desktop / Claude Code
+
+The same flow works from Claude Desktop. For Claude Code, the simpler path is
+still API key:
+
+```bash
+claude mcp add --transport http openviking https://my.ov/mcp \
+ --header "Authorization: Bearer <api-key>"
+```
+
+If you want Claude Code to drive OAuth, the connector flow is identical to
+Claude.ai's once configured.
+
+### ChatGPT (Codex, Plus, Enterprise)
+
+Connector setup is via Settings → Beta features → Custom Connectors. Enter
+the MCP URL; ChatGPT discovers the OAuth endpoints from the
+`/.well-known/...` documents and walks the same authorize → token flow.
+
+### Cursor
+
+Cursor's MCP integration honors OAuth automatically when the server URL
+returns a 401 with `WWW-Authenticate: Bearer resource_metadata=...`. Add the
+URL via Cursor's MCP settings.
+
+---
+
+## Verifying with `curl`
+
+You can drive the entire flow without a real MCP client:
+
+```bash
+# 1. Register a client
+curl -X POST -H "Content-Type: application/json" \
+ -d '{"redirect_uris":["http://127.0.0.1:9999/cb"],"client_name":"test","token_endpoint_auth_method":"none"}' \
+ https://my.ov/register
+# → {"client_id":"...", ...}
+
+# 2. PKCE pair
+VERIFIER=$(openssl rand -base64 64 | tr -d '=+/' | head -c 64)
+CHALLENGE=$(printf "%s" "$VERIFIER" | openssl dgst -sha256 -binary | basenc --base64url | tr -d '=')
+
+# 3. Open the authorize URL in a browser. The page shows a 6-char code.
+echo "https://my.ov/authorize?response_type=code&client_id=$CID&redirect_uri=http://127.0.0.1:9999/cb&code_challenge=$CHALLENGE&code_challenge_method=S256&state=xyz"
+
+# 4. Approve the displayed code from the console (or via API).
+curl -X POST -H "X-Api-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"code":"AB3X7K","decision":"approve"}' \
+ https://my.ov/api/v1/auth/oauth-verify
+
+# 5. The browser auto-redirects to /cb?code=ovac_...&state=xyz. Copy the code.
+
+# 6. Exchange the auth code for tokens.
+curl -X POST \
+ -d "grant_type=authorization_code&code=ovac_...&client_id=$CID&code_verifier=$VERIFIER&redirect_uri=http://127.0.0.1:9999/cb" \
+ https://my.ov/token
+# → {"access_token":"ovat_...","refresh_token":"ovrt_...","expires_in":3600}
+
+# 7. Call MCP with the access token.
+curl -X POST -H "Authorization: Bearer ovat_..." \
+ -d '{"jsonrpc":"2.0","method":"tools/list","id":1}' \
+ https://my.ov/mcp
+```
+
+---
+
+## Configuration reference
+
+`ov.conf` excerpt:
+
+```jsonc
+{
+ "oauth": {
+ "enabled": false, // off by default
+ "issuer": null, // e.g. "https://my.ov" (optional; env var wins)
+ "access_token_ttl_seconds": 3600, // 1 hour
+ "refresh_token_ttl_seconds": 2592000, // 30 days
+ "auth_code_ttl_seconds": 300, // 5 minutes
+ "otp_ttl_seconds": 300, // 5 minutes
+ "db_filename": "oauth.db" // relative to storage.workspace
+ }
+}
+```
+
+Environment variables:
+
+| Variable | Purpose |
+|---|---|
+| `OPENVIKING_PUBLIC_BASE_URL` | Highest-priority public origin override (used as issuer, in PRM, in `WWW-Authenticate`) |
+| `OPENVIKING_CONFIG_FILE` | Path to `ov.conf` (or pass `--config`) |
+
+---
+
+## Token model
+
+| Token | Format | Prefix | Lifetime | Storage |
+|---|---|---|---|---|
+| Access token | `secrets.token_urlsafe(40)` | `ovat_` | 1 hour | SQLite (SHA-256 indexed) |
+| Refresh token | `secrets.token_urlsafe(40)` | `ovrt_` | 30 days | SQLite (SHA-256 indexed) |
+| Authorization code | `secrets.token_urlsafe(40)` | `ovac_` | 5 minutes | SQLite (SHA-256 indexed) |
+| Display code (page) | 6-char alphanumeric (no O/0/I/1) | — | 10 minutes | SQLite (`oauth_pending_authorizations`) |
+
+All tokens are opaque; OpenViking does **not** issue JWTs. There is no
+cryptographic key to manage on the server side. Token claims are looked up
+from SQLite on every request, so revoking a token is a single `UPDATE`.
+
+### Token = identity
+
+Each issued token is bound to a single `(account_id, user_id, role)` triple
+recorded at authorization time. An OAuth token grants the same permissions
+as the API key that produced it — *not* more, *not* less.
+
+### OAuth lifetime ≤ authorizing key lifetime
+
+Every issued token additionally records the SHA-256 fingerprint of the API
+key whose holder authorized it. On every OAuth bearer request the server
+recomputes the user's current key fingerprint and demands a strict match.
+The practical effects:
+
+- **Rotating** a user's API key (`regenerate_key`) immediately invalidates
+ every OAuth access and refresh token previously issued under that user.
+ No manual revocation step is needed — the next bearer request gets a 401
+ asking the client to re-authorize.
+- **Removing** a user (`remove_user`) has the same effect: the fingerprint
+ lookup returns `None` and all the user's OAuth tokens stop working.
+- **ROOT** keys and **trusted-mode** identities cannot issue OAuth state
+ (no per-user key to bind to). `/api/v1/auth/otp` and
+ `/api/v1/auth/oauth-verify` reject these callers with 400.
+
+The fingerprint is `sha256(stored_key_value)`, where the stored value is
+either the plaintext key (when API key hashing is disabled) or its
+Argon2id hash (when enabled). Both are written once at create / regenerate
+and never mutate, so the fingerprint is stable until the next rotation.
+
+---
+
+## Troubleshooting
+
+### Claude.ai shows "We couldn't connect" without ever opening a popup
+
+The first thing Claude.ai does is GET `/.well-known/oauth-protected-resource`
+on the URL you entered. If that 404s, the OAuth flow doesn't start. Check:
+
+```bash
+curl -i https://my.ov/.well-known/oauth-protected-resource
+```
+
+You should get a JSON body with `authorization_servers`. If you get 404,
+either OAuth is disabled (`oauth.enabled = false`) or the reverse proxy isn't
+forwarding `/.well-known/...` to 1933.
+
+### "Issuer URL must be HTTPS"
+
+The MCP SDK rejects `http://` issuers other than `127.0.0.1` / `localhost`.
+Either:
+
+- Set `OPENVIKING_PUBLIC_BASE_URL=https://my.ov`, or
+- Set `oauth.issuer` to an `https://` URL in `ov.conf`, or
+- For local testing only, ensure your client connects via `http://127.0.0.1:1933` directly
+
+### The authorize page shows a code, but the console says "Invalid code"
+
+Codes are 6 characters, **uppercase**, and case-sensitive on the wire. The
+console form normalizes input to uppercase. If you're typing manually, check
+for letters that look like digits (the alphabet excludes `O`, `0`, `I`, `1`
+to reduce confusion).
+
+### Token rotates but the next refresh is rejected
+
+Refresh tokens are one-shot. If you refresh and *both* the old and new
+refresh tokens get used (e.g. by a buggy client), the second one will be
+rejected and that token chain is revoked entirely (RFC 9700 §4.14). The
+client must restart the authorize flow.
+
+### `WWW-Authenticate` header missing on `/mcp` 401
+
+The header is only emitted when an `oauth_provider` is registered on
+`app.state` — i.e. when `oauth.enabled = true`. Confirm with:
+
+```bash
+curl -i https://my.ov/mcp -d '{}' -H 'Content-Type: application/json' | grep -i www-authenticate
+```
+
+---
+
+## References
+
+- [Public Access & Reverse Proxy Guide](12-public-access.md) — HTTPS, Caddy, nginx, docker compose
+- [MCP Specification — Authorization](https://modelcontextprotocol.io/specification/2025-03-26/server/authorization)
+- [RFC 8414 — OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414)
+- [RFC 9728 — OAuth 2.0 Protected Resource Metadata](https://datatracker.ietf.org/doc/html/rfc9728)
+- [RFC 7591 — Dynamic Client Registration](https://datatracker.ietf.org/doc/html/rfc7591)
+- [RFC 7636 — PKCE](https://datatracker.ietf.org/doc/html/rfc7636)
+- [OpenViking MCP Integration Guide](06-mcp-integration.md)
diff --git a/docs/en/guides/12-public-access.md b/docs/en/guides/12-public-access.md
new file mode 100644
index 000000000..d770092a5
--- /dev/null
+++ b/docs/en/guides/12-public-access.md
@@ -0,0 +1,262 @@
+# Public Access & Reverse Proxy
+
+OpenViking runs two internal services:
+
+| Port | Service | Handles |
+|------|---------|---------|
+| 1933 | API server | REST API, MCP, OAuth, `.well-known/*` |
+| 8020 | Console | Web UI at `/console/...` |
+
+The bundled **Caddy reverse proxy** merges them into a single port — **1934** — so
+clients only need one URL. This works out of the box with `docker compose up`.
+
+## Port overview
+
+```
+ ┌────────────────────────┐
+Internet / LAN ──► │ Caddy :1934 (HTTP) │
+ │ │
+ │ /console/* → :8020 │
+ │ /* → :1933 │
+ └────────────────────────┘
+```
+
+Port 1934 is plain HTTP — fine for local development, internal networks, and
+as an upstream target behind your own TLS-terminating proxy or CDN.
+
+For **public HTTPS** (required for OAuth with MCP clients like Claude.ai,
+ChatGPT, Cursor), Caddy can also serve port 443 with automatic Let's Encrypt
+certificates. See [Adding HTTPS](#adding-https-for-public-access) below.
+
+## Quick start (local / internal)
+
+```bash
+docker compose up -d
+```
+
+Both services are now reachable on one port:
+
+```bash
+curl http://localhost:1934/health # API server health
+curl http://localhost:1934/api/v1/system/status \
+ -H "X-Api-Key: YOUR_KEY" # REST API
+open http://localhost:1934/console # Web console
+```
+
+You can still access 1933 and 8020 directly — those port mappings are left in
+`docker-compose.yml` for debugging. Once you're confident everything works
+through 1934, feel free to comment them out.
+
+## Adding HTTPS for public access
+
+You need: a public domain, ports 80 + 443 reachable, DNS pointing here.
+
+### 1. Create `.env`
+
+```dotenv
+OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com
[email protected] # optional; recommended for Let's Encrypt
+```
+
+`OPENVIKING_PUBLIC_BASE_URL` is read by both the OpenViking container (it
+publishes this URL in OAuth metadata and `WWW-Authenticate` headers) and by
+Caddy (as the site address for the HTTPS block).
+
+### 2. Add a domain block to `Caddyfile`
+
+Append this below the existing `:1934` block:
+
+```caddyfile
+{$OPENVIKING_PUBLIC_BASE_URL} {
+ @console path /console /console/*
+ handle @console {
+ reverse_proxy openviking:8020
+ }
+ handle {
+ reverse_proxy openviking:1933
+ }
+ # Pin ACME registration email (optional):
+ # tls {$OV_ACME_EMAIL}
+}
+```
+
+The `:1934` block stays — it continues to serve HTTP for local/internal
+access. The new block serves HTTPS on 443 for the public domain.
+
+### 3. Uncomment HTTPS lines in `docker-compose.yml`
+
+Three places:
+
+```yaml
+# In caddy.ports — uncomment:
+- "80:80"
+- "443:443"
+
+# In caddy.volumes — uncomment:
+- caddy_data:/data
+- caddy_config:/config
+
+# At the bottom — uncomment:
+volumes:
+ caddy_data:
+ caddy_config:
+```
+
+### 4. Launch
+
+```bash
+docker compose up -d
+```
+
+The first HTTPS request triggers ACME certificate issuance. Subsequent
+requests use the cached cert. Caddy handles renewal automatically.
+
+### 5. Verify
+
+```bash
+curl https://ov.your-domain.com/health
+# {"status": "ok"}
+
+# OAuth metadata (if oauth.enabled = true):
+curl https://ov.your-domain.com/.well-known/oauth-authorization-server
+```
+
+## Using your own reverse proxy
+
+If you already have nginx, Traefik, or another proxy handling TLS, point it
+at port 1934 instead of juggling 1933 + 8020 separately. Port 1934 already
+does the path-based routing internally.
+
+### nginx (TLS termination at nginx, plain HTTP to 1934)
+
+```nginx
+server {
+ listen 443 ssl http2;
+ server_name ov.your-domain.com;
+
+ ssl_certificate /etc/letsencrypt/live/ov.your-domain.com/fullchain.pem;
+ ssl_certificate_key /etc/letsencrypt/live/ov.your-domain.com/privkey.pem;
+
+ location / {
+ proxy_pass http://127.0.0.1:1934;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+}
+
+server {
+ listen 80;
+ server_name ov.your-domain.com;
+ return 301 https://$host$request_uri;
+}
+```
+
+With this setup, remove the Caddy HTTPS block from the Caddyfile — keep only
+the `:1934` block.
+
+### Caddy (external, without docker-compose Caddy)
+
+If you run Caddy on the host rather than inside compose:
+
+```caddyfile
+ov.your-domain.com {
+ reverse_proxy 127.0.0.1:1934
+}
+```
+
+### Cloudflare / CDN
+
+Point the CDN origin at `http://your-server-ip:1934`. Set
+`OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com` so the server knows
+its public-facing origin. Ensure the CDN forwards `Host`,
+`X-Forwarded-Proto`, and `X-Forwarded-Host` headers.
+
+## Tell the server its public URL
+
+OAuth metadata, `WWW-Authenticate` headers, and resource URLs all need to
+contain the public-facing origin. Resolution order (highest priority first):
+
+1. `OPENVIKING_PUBLIC_BASE_URL` environment variable
+2. `oauth.issuer` in `ov.conf`
+3. `X-Forwarded-Proto` + `X-Forwarded-Host` request headers
+4. The request `Host` header
+
+Behind any reverse proxy, set option 1 explicitly:
+
+```bash
+export OPENVIKING_PUBLIC_BASE_URL="https://ov.your-domain.com"
+```
+
+Or in `ov.conf`:
+
+```jsonc
+{
+ "oauth": {
+ "enabled": true,
+ "issuer": "https://ov.your-domain.com"
+ }
+}
+```
+
+## HTTPS and OAuth
+
+OAuth 2.1 (and the MCP SDK) **requires HTTPS** for any non-localhost issuer.
+If the server's published origin is `http://` on a non-loopback address, MCP
+clients will refuse to connect with an "Issuer URL must be HTTPS" error.
+
+This is a protocol-level requirement, not an OpenViking limitation. For local
+testing, `http://127.0.0.1:1934` works without HTTPS. For anything else, set
+up TLS as described above.
+
+Non-OAuth API access (API key auth) works fine over HTTP if you accept the
+risk — the protocol doesn't enforce TLS for bearer tokens.
+
+## Without Docker
+
+If you run `openviking-server` and the console directly (systemd, bare
+metal, etc.), install Caddy on the host and use the same Caddyfile pattern
+with `127.0.0.1` upstreams:
+
+```caddyfile
+:1934 {
+ @console path /console /console/*
+ handle @console {
+ reverse_proxy 127.0.0.1:8020
+ }
+ handle {
+ reverse_proxy 127.0.0.1:1933
+ }
+}
+
+# Add domain block for HTTPS if needed:
+# ov.your-domain.com { ... }
+```
+
+Or with nginx:
+
+```nginx
+server {
+ listen 1934;
+
+ location /console {
+ proxy_pass http://127.0.0.1:8020;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+
+ location / {
+ proxy_pass http://127.0.0.1:1933;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+}
+```
+
+## Related
+
+- [Deployment Guide](03-deployment.md) — Docker, systemd, Kubernetes
+- [OAuth Guide](11-oauth.md) — OAuth 2.1 configuration and client setup
+- [Authentication](04-authentication.md) — API key management
diff --git a/docs/zh/guides/03-deployment.md b/docs/zh/guides/03-deployment.md
index 79c5a8cfb..da30f9ccb 100644
--- a/docs/zh/guides/03-deployment.md
+++ b/docs/zh/guides/03-deployment.md
@@ -274,8 +274,11 @@ docker compose up -d
```
启动后可以访问:
-- API 服务:`http://localhost:1933`
-- Console 界面:`http://localhost:8020`
+- 聚合入口:`http://localhost:1934`(Caddy 合并 API + Console)
+- API 服务(直连):`http://localhost:1933`
+- Console 界面(直连):`http://localhost:8020`
+
+如需公网 HTTPS 访问,请参考 [公网访问指南](12-public-access.md)。
如需自行构建镜像,请显式传入 OpenViking 版本:
`docker build --build-arg OPENVIKING_VERSION=0.3.12 -t openviking:latest .`
@@ -312,6 +315,8 @@ curl http://localhost:1933/ready
## 相关文档
+- [公网访问与反向代理](12-public-access.md) - HTTPS、Caddy、nginx
- [认证](04-authentication.md) - API Key 设置
+- [OAuth 接入指南](11-oauth.md) - 面向 MCP 客户端的 OAuth 2.1
- [可观测性与排障](05-observability.md) - 健康检查、追踪与排障
- [API 概览](../api/01-overview.md) - 完整 API 参考
diff --git a/docs/zh/guides/06-mcp-integration.md b/docs/zh/guides/06-mcp-integration.md
index fb6b90758..f3c271c6b 100644
--- a/docs/zh/guides/06-mcp-integration.md
+++ b/docs/zh/guides/06-mcp-integration.md
@@ -18,7 +18,7 @@ MCP 端点位于 `http://<server>:1933/mcp`,与 REST API 同进程、同端口
|------|----------|
| **Claude Code** | `type: http` 接入 |
| **ChatGPT & Codex** | 标准 MCP 配置 |
-| **Claude.ai / Claude Desktop** | 通过 MCP-Key2OAuth 代理接入 |
+| **Claude.ai / Claude Desktop** | 原生 OAuth 2.1(见 [11-oauth](11-oauth.md)) |
| **Manus** | 标准 MCP 配置 |
| **Trae** | 标准 MCP 配置 |
@@ -78,31 +78,19 @@ claude mcp add --transport http openviking \
加 `--scope user` 可将配置设为全局(所有项目共享)。
-### Claude.ai / Claude Desktop(OAuth 代理鉴权)
+### Claude.ai / Claude Desktop / ChatGPT / Cursor(OAuth)
-Claude.ai 和 Claude Desktop Connector 强制要求 MCP 服务器使用 OAuth 2.1 鉴权,无法直接传入 API Key。
+这些客户端只接受 OAuth 2.1,不接受 API Key。OpenViking 已经原生实现 OAuth 2.1(DCR + PKCE + opaque token,SQLite 后端,配合 console 驱动的 OTP 授权页),不再需要外部代理。
-#### 官方 OAuth 支持(规划中)
+**详见 [OAuth 2.1 接入指南](11-oauth.md)**:
-我们正在考虑在 `openviking-server` 中内置 OAuth 2.1 授权端点,初步方案包括:
+- 端到端流程(device-flow 风格:authorize 页显示 6 字符码,用户在 console 确认)
+- HTTP(本地)与 HTTPS(生产)两阶段部署,包含 Caddy / nginx 反代模板和 docker-compose 示例
+- Claude.ai / Claude Desktop / Cursor / ChatGPT 接入步骤
+- `OPENVIKING_PUBLIC_BASE_URL` 与 `oauth` 配置项
+- Token 模型(`ovat_` / `ovrt_` / `ovac_` 前缀)与撤销
-- **OTP 授权**:通过 CLI (`ov otp`) 或 REST API 获取一次性口令,在 OAuth 授权页面输入完成认证,无需外部依赖
-- **Console 快捷授权**:利用 Web Console (8020) 同源 session 实现一键授权
-- **第三方登录**:可选的 GitHub / Google 等 IdP 委托登录
-
-上述方案尚在设计评审阶段,实现时间待定。
-
-#### 当前可用方案:MCP-Key2OAuth(社区项目)
-
-在官方 OAuth 实现就绪之前,可以借助社区项目 [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth) 将 API Key 认证代理为 OAuth 流程:
-
-1. 参照项目 README 自行部署代理服务(Cloudflare Workers)
-2. 填入你的 OpenViking MCP 服务器 URL(如 `https://your-server.com/mcp`)
-3. 生成代理后的新 URL
-4. 在 Claude.ai / Claude Desktop 中填入生成的新 URL,连接时会跳转至代理站进行鉴权
-5. 授权完成后即可正常使用
-
-> ⚠️ **免责声明:** MCP-Key2OAuth 为社区维护的第三方项目,OpenViking 团队不对其安全性、可用性或数据处理方式做任何保证。使用前请自行评估风险。如有顾虑,建议等待官方 OAuth 实现或自行搭建代理。
+> 社区项目 [MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth) Cloudflare Worker 代理仍可作为第三方备选方案,但现在更推荐原生流程:无需额外部署单元,也不会引入第三方对 API Key 的信任面。
## 可用的 MCP 工具
diff --git a/docs/zh/guides/11-oauth.md b/docs/zh/guides/11-oauth.md
new file mode 100644
index 000000000..02afc28cc
--- /dev/null
+++ b/docs/zh/guides/11-oauth.md
@@ -0,0 +1,338 @@
+# OAuth 2.1 接入指南
+
+OpenViking 服务端原生实现 OAuth 2.1。任何需要 OAuth 的客户端 — 包括 MCP
+客户端(Claude.ai / Claude Desktop / ChatGPT / Cursor)以及其他浏览器应用
+— 都可以直接对服务器授权,无需任何第三方代理。协议层(DCR、authorize、
+token、metadata)由官方 `mcp.server.auth` SDK 提供,整体遵循 OAuth 2.1
+规范,非 MCP 的 OAuth 客户端也能正常工作。
+
+## 推荐配置
+
+> **前提**:公网 HTTPS。OAuth 2.1(以及 MCP SDK)对非 localhost 的 issuer
+> **强制要求 HTTPS**。请参阅[公网访问指南](12-public-access.md)了解如何配置
+> Caddy 或 nginx 的 HTTPS。
+
+1. **配置 HTTPS** — 按[公网访问指南](12-public-access.md)设置好
+ `https://ov.your-domain.com`(Caddy + `.env` + `docker compose up`)。
+
+2. **在 `~/.openviking/ov.conf` 启用 OAuth:**
+
+ ```json
+ { "oauth": { "enabled": true } }
+ ```
+
+3. **重启**(`docker compose restart openviking`)。
+
+4. **接入客户端。** Claude.ai → Connectors → Add → 输入
+ `https://ov.your-domain.com/mcp`。浏览器打开授权页,显示一个 6 字符码;
+ 再打开 `https://ov.your-domain.com/console`,用 API Key 登录,把码粘到
+ Settings → "Authorize an MCP client" → 点 Authorize。浏览器自动跳回
+ Claude.ai,连接器就位。
+
+线上路径就这四步。后续章节解释每一块为什么这样设计、本地怎么不走 HTTPS 做
+联调、出问题时怎么用 curl 排查。
+
+---
+
+## 为什么需要原生 OAuth
+
+部分 MCP 客户端只接受 OAuth 2.1,不接受 API Key。在此之前唯一的方案是部署社区的
+[MCP-Key2OAuth](https://github.com/t0saki/MCP-Key2OAuth) Cloudflare Worker
+代理,把 OAuth 翻译成 API Key bearer。原生支持解决了:
+
+- 额外部署单元(CF Worker + 2 个 KV namespace)
+- 第三方信任面(代理运营方有解密上游 API Key 的能力)
+- 用户在浏览器里手动粘贴 API Key 的体验
+
+API Key 认证仍按原方式工作,OAuth 只是叠加层。
+
+---
+
+## 工作原理
+
+OpenViking 实现的是 **device-flow 风格**的 OTP 流程(更接近 RFC 8628),
+而不是早期"console 取码 → page 输入"的 push 流程。MCP 客户端打开浏览器
+授权时:
+
+```
+1. MCP 客户端 POST /mcp → 401 + WWW-Authenticate
+2. MCP 客户端 GET /.well-known/oauth-protected-resource (RFC 9728)
+3. MCP 客户端 GET /.well-known/oauth-authorization-server (RFC 8414)
+4. MCP 客户端 POST /register 动态客户端注册 (RFC 7591)
+5. MCP 客户端 GET /authorize?... (浏览器重定向)
+6. 服务端 → /oauth/authorize/page?pending=...
+ 页面显示一个 6 字符码,例如 "AB3X7K"
+7. 用户 打开 OpenViking Web Console(已登录状态)
+ → Settings → "Authorize an MCP client" → 输入 AB3X7K → 点 Authorize
+8. 服务端 把 pending 标记为 verified,绑定 console 用户的身份
+ (account / user / role)
+9. 页面 轮询 /oauth/authorize/page/status,命中 "approved",
+ 自动跳转回 MCP 客户端的 redirect_uri 并附 auth code
+10. MCP 客户端 POST /token (PKCE S256) → access_token (ovat_...)
+ + refresh_token (ovrt_...)
+11. MCP 客户端 POST /mcp (Authorization: Bearer ovat_...) → 调工具
+```
+
+6 字符码显示在 authorize 页,**用户把它输入到 console 表单**(而不是反过来)。
+这样确认动作发生在用户已登录的环境,符合"我在已登录的地方批准那边的请求"的直觉。
+
+如果 console 与 OAuth 页面同源(推荐部署形态),page 还会检测用户已有的 console
+session,提供一键 "Quick authorize" 按钮 — **依然需要点一下**,不会自动跳。
+
+服务端还保留了"push 模式"的 OTP 端点 `POST /api/v1/auth/otp` 供 CLI 场景使用:
+console 也提供一个折叠的 "Generate OTP" 入口供脚本类客户端使用。
+
+---
+
+## 快速验证(HTTP,仅本地)
+
+最快确认 OAuth 装配正确的方式是在 `127.0.0.1` 跑一遍。MCP SDK 接受
+`http://127.0.0.1` 与 `http://localhost` 作为 issuer URL 而无需 HTTPS — 但
+Claude.ai / Claude Desktop 等线上客户端**只接受公网 HTTPS**,所以这个模式只
+适合用 [MCP Inspector](https://github.com/modelcontextprotocol/inspector)
+之类的本地工具做联调。
+
+1. **在 `~/.openviking/ov.conf` 启用 OAuth:**
+
+ ```json
+ {
+ "oauth": {
+ "enabled": true
+ }
+ }
+ ```
+
+2. **启动:**
+
+ ```bash
+ docker compose up -d
+ ```
+
+ 或不用 Docker:
+
+ ```bash
+ openviking-server
+ # 另开一个终端
+ python -m openviking.console.bootstrap --write-enabled
+ ```
+
+3. **登录 console**:访问 <http://127.0.0.1:1934/console>(不走聚合代理时用
+ `:8020/console`),把 API Key 粘到 Settings → 点 Save。"Authorize an MCP
+ client" 表单现在可用。
+
+4. **接一个本地 MCP 客户端**(例如 MCP Inspector)到
+ `http://127.0.0.1:1934/mcp`(或 `:1933/mcp`)。客户端会走上面那套流程;把
+ authorize 页显示的 6 字符码复制到 console 表单 → 点 Authorize → 客户端拿到
+ token。
+
+线上接 Claude.ai / Claude Desktop 走[公网访问指南](12-public-access.md)。
+
+---
+
+## 生产部署(HTTPS)
+
+OAuth 2.1 对非 localhost 的 issuer **强制要求 HTTPS**。
+[公网访问指南](12-public-access.md)详细介绍了 Caddy、nginx、docker compose、
+CDN 的配置方法。简要步骤:
+
+1. 按[公网访问指南 § 添加 HTTPS](12-public-access.md#添加-https公网访问)
+ 配置好 `https://your-domain.com`,使 1934 端口走 TLS。
+2. 启用 OAuth:`ov.conf` 里 `{ "oauth": { "enabled": true } }`。
+3. 重启:`docker compose restart openviking`。
+4. 在 `.env` 设置 `OPENVIKING_PUBLIC_BASE_URL=https://your-domain.com`
+ (服务端用它作为 OAuth 元数据和 `WWW-Authenticate` 的 issuer)。
+
+HTTPS + OAuth 就绪后,按下面的方式接入客户端。
+
+---
+
+## 接入仅支持 OAuth 的 MCP 客户端
+
+### Claude.ai (Web)
+
+1. Settings → Connectors → **Add connector**。
+2. 输入 `https://my.ov/mcp` 作为服务器 URL。
+3. Claude 弹出授权页面,记下 6 字符码。
+4. 另开标签访问 <https://my.ov/console>(弹出页里也有这个链接)。
+5. 登录(如未登录)→ Settings → "Authorize an MCP client" → 粘码 → **Authorize**。
+6. 弹出页自动跳回 Claude,token 已颁发。
+
+### Claude Desktop / Claude Code
+
+Claude Desktop 流程相同。Claude Code 直接用 API Key 更简单:
+
+```bash
+claude mcp add --transport http openviking https://my.ov/mcp \
+ --header "Authorization: Bearer <api-key>"
+```
+
+如果你想让 Claude Code 走 OAuth,体验和 Claude.ai 一致。
+
+### ChatGPT (Codex / Plus / Enterprise)
+
+Settings → Beta features → Custom Connectors。输入 MCP URL,ChatGPT 通过
+`/.well-known/...` 文档自动发现 OAuth 端点,走相同的 authorize → token 流程。
+
+### Cursor
+
+Cursor 看到 401 + `WWW-Authenticate: Bearer resource_metadata=...` 后会自动
+进入 OAuth 流程。在 Cursor 的 MCP 设置里加 URL 即可。
+
+---
+
+## 用 `curl` 验证完整流程
+
+不需要真实 MCP 客户端:
+
+```bash
+# 1. 注册客户端
+curl -X POST -H "Content-Type: application/json" \
+ -d '{"redirect_uris":["http://127.0.0.1:9999/cb"],"client_name":"test","token_endpoint_auth_method":"none"}' \
+ https://my.ov/register
+# → {"client_id":"...", ...}
+
+# 2. PKCE 对
+VERIFIER=$(openssl rand -base64 64 | tr -d '=+/' | head -c 64)
+CHALLENGE=$(printf "%s" "$VERIFIER" | openssl dgst -sha256 -binary | basenc --base64url | tr -d '=')
+
+# 3. 浏览器访问 authorize URL,页面会显示 6 字符码
+echo "https://my.ov/authorize?response_type=code&client_id=$CID&redirect_uri=http://127.0.0.1:9999/cb&code_challenge=$CHALLENGE&code_challenge_method=S256&state=xyz"
+
+# 4. 在 console 输入码(或直接 curl)
+curl -X POST -H "X-Api-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"code":"AB3X7K","decision":"approve"}' \
+ https://my.ov/api/v1/auth/oauth-verify
+
+# 5. 浏览器自动 302 到 /cb?code=ovac_...&state=xyz,记下 code
+
+# 6. 用 auth code 换 token
+curl -X POST \
+ -d "grant_type=authorization_code&code=ovac_...&client_id=$CID&code_verifier=$VERIFIER&redirect_uri=http://127.0.0.1:9999/cb" \
+ https://my.ov/token
+# → {"access_token":"ovat_...","refresh_token":"ovrt_...","expires_in":3600}
+
+# 7. 用 access token 调 MCP
+curl -X POST -H "Authorization: Bearer ovat_..." \
+ -d '{"jsonrpc":"2.0","method":"tools/list","id":1}' \
+ https://my.ov/mcp
+```
+
+---
+
+## 配置参考
+
+`ov.conf` 片段:
+
+```jsonc
+{
+ "oauth": {
+ "enabled": false, // 默认关闭
+ "issuer": null, // 例 "https://my.ov"(可选;env 变量优先级更高)
+ "access_token_ttl_seconds": 3600, // 1 小时
+ "refresh_token_ttl_seconds": 2592000, // 30 天
+ "auth_code_ttl_seconds": 300, // 5 分钟
+ "otp_ttl_seconds": 300, // 5 分钟
+ "db_filename": "oauth.db" // 相对 storage.workspace
+ }
+}
+```
+
+环境变量:
+
+| 变量 | 用途 |
+|---|---|
+| `OPENVIKING_PUBLIC_BASE_URL` | 最高优先级的公网 origin override(用作 issuer / PRM / `WWW-Authenticate`) |
+| `OPENVIKING_CONFIG_FILE` | `ov.conf` 路径(也可用 `--config`) |
+
+---
+
+## Token 模型
+
+| Token | 形态 | 前缀 | TTL | 存储 |
+|---|---|---|---|---|
+| Access token | `secrets.token_urlsafe(40)` | `ovat_` | 1 小时 | SQLite (SHA-256 索引) |
+| Refresh token | `secrets.token_urlsafe(40)` | `ovrt_` | 30 天 | SQLite (SHA-256 索引) |
+| Authorization code | `secrets.token_urlsafe(40)` | `ovac_` | 5 分钟 | SQLite (SHA-256 索引) |
+| Display code(页面) | 6 字符(去 O/0/I/1) | — | 10 分钟 | SQLite (`oauth_pending_authorizations`) |
+
+所有 token 都是 opaque(不签发 JWT),服务端**没有任何加密密钥需要管理**。
+每次请求按 SHA-256 哈希查 SQLite,撤销 token 是一次 `UPDATE`。
+
+### Token 与身份
+
+每个 token 在签发时绑定一个 `(account_id, user_id, role)` 三元组。OAuth
+token 拥有的权限 = 颁发它时所用 API Key 的权限,**不更多也不更少**。
+
+### OAuth 生命周期 ≤ 授权 Key 生命周期
+
+每个 token 额外记录授权方 API Key 的 SHA-256 指纹。每次 OAuth bearer
+鉴权时服务端重算该用户当前的 key 指纹并严格比对,效果:
+
+- **轮换** 用户 API Key(`regenerate_key`)立即让该用户名下所有 OAuth
+ access / refresh token 失效。无需手动撤销,下一次 bearer 请求即返回
+ 401,客户端需重新走授权流程。
+- **删除** 用户(`remove_user`)同理:指纹查找返回 `None`,所有 OAuth
+ token 立即停用。
+- **ROOT** key 和 **trusted-mode** 身份无法签发 OAuth(没有 per-user
+ key 可绑定)。`/api/v1/auth/otp` 和 `/api/v1/auth/oauth-verify` 会以
+ 400 拒绝这类调用方。
+
+指纹算法为 `sha256(stored_key_value)`:API Key 哈希未开启时即明文 key
+的 SHA-256,开启时即 Argon2id 哈希结果的 SHA-256。两种情况下 stored
+值都是创建/轮换时写入一次后不再变动,因此指纹在两次轮换之间稳定。
+
+---
+
+## 故障排查
+
+### Claude.ai 直接报 "We couldn't connect" 没弹出授权页
+
+Claude.ai 第一步是 GET `/.well-known/oauth-protected-resource`。如果这一步
+404,OAuth 流程就根本不会启动。检查:
+
+```bash
+curl -i https://my.ov/.well-known/oauth-protected-resource
+```
+
+应当返回带 `authorization_servers` 字段的 JSON。如果是 404,要么
+`oauth.enabled = false`,要么反代没把 `/.well-known/...` 路径转发到 1933。
+
+### "Issuer URL must be HTTPS"
+
+MCP SDK 拒绝非 `127.0.0.1` / `localhost` 的 `http://` issuer。三选一:
+
+- 设置 `OPENVIKING_PUBLIC_BASE_URL=https://my.ov`
+- 在 `ov.conf` 里把 `oauth.issuer` 写成 `https://...`
+- 仅本地测试时让客户端直连 `http://127.0.0.1:1933`
+
+### Authorize 页有码,但 console 报 "Invalid code"
+
+码是 6 字符**全大写**,传输时区分大小写。console 的输入框会自动转大写。如果手
+动输入,注意字母与数字的混淆字符(字母表已经排除了 `O`、`0`、`I`、`1`)。
+
+### Refresh 一次后再用旧 token 被拒
+
+Refresh token 是一次性的。如果旧 refresh 与新 refresh **同时被使用**(例如客户
+端有 bug),第二个会被拒绝,整条 token 链会被撤销(RFC 9700 §4.14)。客户端必
+须重新走 authorize 流程。
+
+### `/mcp` 401 没有 `WWW-Authenticate` 头
+
+这个头只在 `app.state` 上有 `oauth_provider` 时才发出 — 即
+`oauth.enabled = true`。检查:
+
+```bash
+curl -i https://my.ov/mcp -d '{}' -H 'Content-Type: application/json' | grep -i www-authenticate
+```
+
+---
+
+## 参考
+
+- [公网访问与反向代理指南](12-public-access.md) — HTTPS、Caddy、nginx、docker compose
+- [MCP 规范 — Authorization](https://modelcontextprotocol.io/specification/2025-03-26/server/authorization)
+- [RFC 8414 — OAuth 2.0 Authorization Server Metadata](https://datatracker.ietf.org/doc/html/rfc8414)
+- [RFC 9728 — OAuth 2.0 Protected Resource Metadata](https://datatracker.ietf.org/doc/html/rfc9728)
+- [RFC 7591 — Dynamic Client Registration](https://datatracker.ietf.org/doc/html/rfc7591)
+- [RFC 7636 — PKCE](https://datatracker.ietf.org/doc/html/rfc7636)
+- [OpenViking MCP 集成指南](06-mcp-integration.md)
diff --git a/docs/zh/guides/12-public-access.md b/docs/zh/guides/12-public-access.md
new file mode 100644
index 000000000..93f7409f8
--- /dev/null
+++ b/docs/zh/guides/12-public-access.md
@@ -0,0 +1,252 @@
+# 公网访问与反向代理
+
+OpenViking 运行两个内部服务:
+
+| 端口 | 服务 | 处理内容 |
+|------|------|---------|
+| 1933 | API 服务 | REST API、MCP、OAuth、`.well-known/*` |
+| 8020 | Console | Web 管理界面,路径前缀 `/console/...` |
+
+自带的 **Caddy 反向代理**将两者合并到一个端口 — **1934** — 客户端只需一个
+URL。`docker compose up` 即可开箱使用。
+
+## 端口总览
+
+```
+ ┌────────────────────────┐
+Internet / LAN ──► │ Caddy :1934 (HTTP) │
+ │ │
+ │ /console/* → :8020 │
+ │ /* → :1933 │
+ └────────────────────────┘
+```
+
+1934 端口是纯 HTTP — 适用于本地开发、内网环境,也可以作为外部 TLS 终止代理
+或 CDN 的上游。
+
+如果需要**公网 HTTPS**(Claude.ai、ChatGPT、Cursor 等 MCP 客户端走 OAuth 时
+必须),Caddy 还能在 443 端口自动签发 Let's Encrypt 证书。见下方
+[添加 HTTPS](#添加-https-公网访问)。
+
+## 快速开始(本地 / 内网)
+
+```bash
+docker compose up -d
+```
+
+两个服务在一个端口上可达:
+
+```bash
+curl http://localhost:1934/health # API 健康检查
+curl http://localhost:1934/api/v1/system/status \
+ -H "X-Api-Key: YOUR_KEY" # REST API
+open http://localhost:1934/console # Web Console
+```
+
+1933 和 8020 仍可直接访问 — `docker-compose.yml` 里保留了端口映射方便调试。
+确认 1934 一切正常后,可以把那两行注释掉。
+
+## 添加 HTTPS(公网访问)
+
+前提:有公网域名、80 + 443 端口可达、DNS 已指向。
+
+### 1. 创建 `.env`
+
+```dotenv
+OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com
[email protected] # 可选;推荐用于 Let's Encrypt
+```
+
+`OPENVIKING_PUBLIC_BASE_URL` 同时被 OpenViking 容器(发布在 OAuth 元数据和
+`WWW-Authenticate` 头中)和 Caddy(作为 HTTPS 站点地址)读取。
+
+### 2. 在 `Caddyfile` 追加域名块
+
+在已有的 `:1934` 块下面添加:
+
+```caddyfile
+{$OPENVIKING_PUBLIC_BASE_URL} {
+ @console path /console /console/*
+ handle @console {
+ reverse_proxy openviking:8020
+ }
+ handle {
+ reverse_proxy openviking:1933
+ }
+ # 绑定 ACME 注册邮箱(可选):
+ # tls {$OV_ACME_EMAIL}
+}
+```
+
+`:1934` 块保留 — 继续为本地/内网提供 HTTP 访问。新块在 443 端口为公网域名
+提供 HTTPS。
+
+### 3. 取消 `docker-compose.yml` 中的 HTTPS 注释
+
+三处:
+
+```yaml
+# caddy.ports 里取消注释:
+- "80:80"
+- "443:443"
+
+# caddy.volumes 里取消注释:
+- caddy_data:/data
+- caddy_config:/config
+
+# 文件末尾取消注释:
+volumes:
+ caddy_data:
+ caddy_config:
+```
+
+### 4. 启动
+
+```bash
+docker compose up -d
+```
+
+首次 HTTPS 请求触发 ACME 证书签发,后续使用缓存。Caddy 自动续期。
+
+### 5. 验证
+
+```bash
+curl https://ov.your-domain.com/health
+# {"status": "ok"}
+
+# OAuth 元数据(如果 oauth.enabled = true):
+curl https://ov.your-domain.com/.well-known/oauth-authorization-server
+```
+
+## 使用自己的反向代理
+
+如果你已有 nginx、Traefik 或其他 TLS 终止代理,直接指向 1934 端口,不用分别
+处理 1933 + 8020。1934 内部已经做好了路径路由。
+
+### nginx(TLS 在 nginx 终止,HTTP 到 1934)
+
+```nginx
+server {
+ listen 443 ssl http2;
+ server_name ov.your-domain.com;
+
+ ssl_certificate /etc/letsencrypt/live/ov.your-domain.com/fullchain.pem;
+ ssl_certificate_key /etc/letsencrypt/live/ov.your-domain.com/privkey.pem;
+
+ location / {
+ proxy_pass http://127.0.0.1:1934;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+}
+
+server {
+ listen 80;
+ server_name ov.your-domain.com;
+ return 301 https://$host$request_uri;
+}
+```
+
+这种方案下,Caddyfile 只保留 `:1934` 块,不加域名块。
+
+### Caddy(宿主机运行,不走 compose)
+
+```caddyfile
+ov.your-domain.com {
+ reverse_proxy 127.0.0.1:1934
+}
+```
+
+### Cloudflare / CDN
+
+CDN 源站指向 `http://your-server-ip:1934`。设置
+`OPENVIKING_PUBLIC_BASE_URL=https://ov.your-domain.com` 让服务端知道自己的公网
+地址。确保 CDN 转发 `Host`、`X-Forwarded-Proto`、`X-Forwarded-Host` 头。
+
+## 告诉服务端公网 URL
+
+OAuth 元数据、`WWW-Authenticate` 头、资源 URL 都需要包含公网 origin。
+解析顺序(**优先级从高到低**):
+
+1. `OPENVIKING_PUBLIC_BASE_URL` 环境变量
+2. `ov.conf` 里的 `oauth.issuer`
+3. `X-Forwarded-Proto` + `X-Forwarded-Host` 请求头
+4. 请求的 `Host` 头
+
+在反代后面,务必显式设置选项 1:
+
+```bash
+export OPENVIKING_PUBLIC_BASE_URL="https://ov.your-domain.com"
+```
+
+或者 `ov.conf`:
+
+```jsonc
+{
+ "oauth": {
+ "enabled": true,
+ "issuer": "https://ov.your-domain.com"
+ }
+}
+```
+
+## HTTPS 与 OAuth
+
+OAuth 2.1(以及 MCP SDK)对非 localhost 的 issuer **强制要求 HTTPS**。
+如果服务端发布的 origin 是非回环地址的 `http://`,MCP 客户端会拒绝连接并报
+"Issuer URL must be HTTPS"。
+
+这是协议层面的要求,不是 OpenViking 的限制。本地测试时
+`http://127.0.0.1:1934` 无需 HTTPS。其他场景请按上面的方式配置 TLS。
+
+非 OAuth 的 API 访问(API Key 认证)在 HTTP 下也能正常工作 — 协议本身不强制
+bearer token 走 TLS,用户自行评估风险。
+
+## 不用 Docker
+
+如果直接运行 `openviking-server` 和 console(systemd、裸机等),在宿主机装
+Caddy 并使用相同的 Caddyfile 模式,上游改为 `127.0.0.1`:
+
+```caddyfile
+:1934 {
+ @console path /console /console/*
+ handle @console {
+ reverse_proxy 127.0.0.1:8020
+ }
+ handle {
+ reverse_proxy 127.0.0.1:1933
+ }
+}
+
+# 需要 HTTPS 时追加域名块:
+# ov.your-domain.com { ... }
+```
+
+或者 nginx:
+
+```nginx
+server {
+ listen 1934;
+
+ location /console {
+ proxy_pass http://127.0.0.1:8020;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+
+ location / {
+ proxy_pass http://127.0.0.1:1933;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header X-Forwarded-Host $host;
+ }
+}
+```
+
+## 相关文档
+
+- [部署指南](03-deployment.md) — Docker、systemd、Kubernetes
+- [OAuth 指南](11-oauth.md) — OAuth 2.1 配置与客户端接入
+- [认证](04-authentication.md) — API Key 管理
diff --git a/openviking/console/app.py b/openviking/console/app.py
index 145c78c45..03f7f5ff9 100644
--- a/openviking/console/app.py
+++ b/openviking/console/app.py
@@ -260,6 +260,21 @@ def _create_proxy_router() -> APIRouter:
return invalid
return await _forward_request(request, f"/api/v1/observer/{component}")
+ @router.post("/ov/auth/otp")
+ async def issue_otp(request: Request):
+ # OTP issuance binds to the caller's existing API key identity, so it
+ # uses the same auth flow as any other read endpoint. Not gated by
+ # write_enabled — minting an authentication artifact for yourself is
+ # not a data mutation.
+ return await _forward_request(request, "/api/v1/auth/otp")
+
+ @router.post("/ov/auth/oauth-verify")
+ async def oauth_verify(request: Request):
+ # Confirm a pending OAuth authorization (device-flow style). The
+ # caller is the console-authenticated user; the API key in their
+ # session storage is what binds the issuing identity.
+ return await _forward_request(request, "/api/v1/auth/oauth-verify")
+
# ---- Write routes ----
@router.post("/ov/fs/mkdir")
diff --git a/openviking/console/static/app.js b/openviking/console/static/app.js
index d0b0a64be..26fd86ea4 100644
--- a/openviking/console/static/app.js
+++ b/openviking/console/static/app.js
@@ -61,6 +61,15 @@ const elements = {
saveKeyBtn: document.getElementById("saveKeyBtn"),
clearKeyBtn: document.getElementById("clearKeyBtn"),
connectionHint: document.getElementById("connectionHint"),
+ getOtpBtn: document.getElementById("getOtpBtn"),
+ otpBox: document.getElementById("otpBox"),
+ otpValue: document.getElementById("otpValue"),
+ otpCopyBtn: document.getElementById("otpCopyBtn"),
+ otpExpiry: document.getElementById("otpExpiry"),
+ oauthVerifyInput: document.getElementById("oauthVerifyInput"),
+ oauthVerifyBtn: document.getElementById("oauthVerifyBtn"),
+ oauthDenyBtn: document.getElementById("oauthDenyBtn"),
+ oauthVerifyHint: document.getElementById("oauthVerifyHint"),
writeBadge: document.getElementById("writeBadge"),
output: document.getElementById("output"),
tabs: document.querySelectorAll(".tab"),
@@ -1531,6 +1540,124 @@ function bindConnection() {
updateConnectionHint();
setOutput("Connection settings cleared from browser storage.");
});
+
+ if (elements.getOtpBtn) {
+ elements.getOtpBtn.addEventListener("click", async () => {
+ if (!getApiKey()) {
+ setOutput("Save an API key first — OTP issuance requires authentication.");
+ return;
+ }
+ elements.getOtpBtn.disabled = true;
+ const originalLabel = elements.getOtpBtn.textContent;
+ elements.getOtpBtn.textContent = "Generating…";
+ try {
+ const payload = await callConsole("/ov/auth/otp", {
+ method: "POST",
+ body: JSON.stringify({}),
+ });
+ const result = payload && payload.result ? payload.result : payload;
+ const otp = result && (result.otp || result.code);
+ if (!otp) {
+ throw new Error("Server did not return an OTP");
+ }
+ elements.otpValue.textContent = otp;
+ const ttl = result.ttl_seconds || 300;
+ const expiresAt = result.expires_at
+ ? new Date(result.expires_at * 1000).toLocaleTimeString()
+ : null;
+ elements.otpExpiry.textContent = expiresAt
+ ? `Expires at ${expiresAt} (${ttl}s). One-time use.`
+ : `Expires in ${ttl}s. One-time use.`;
+ elements.otpBox.hidden = false;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ setOutput(`Failed to generate OTP: ${message}`);
+ } finally {
+ elements.getOtpBtn.disabled = false;
+ elements.getOtpBtn.textContent = originalLabel;
+ }
+ });
+ }
+
+ if (elements.otpCopyBtn) {
+ elements.otpCopyBtn.addEventListener("click", async () => {
+ const otp = elements.otpValue.textContent.trim();
+ if (!otp) {
+ return;
+ }
+ try {
+ await navigator.clipboard.writeText(otp);
+ const originalLabel = elements.otpCopyBtn.textContent;
+ elements.otpCopyBtn.textContent = "Copied";
+ setTimeout(() => {
+ elements.otpCopyBtn.textContent = originalLabel;
+ }, 1500);
+ } catch (_error) {
+ setOutput("Could not copy to clipboard — long-press the code to copy manually.");
+ }
+ });
+ }
+
+ // OAuth verification (device-flow style: user reads code from the MCP
+ // client's authorize page and pastes it here).
+ async function submitOAuthVerify(decision) {
+ if (!getApiKey()) {
+ elements.oauthVerifyHint.textContent =
+ "Save an API key first — verification requires authentication.";
+ return;
+ }
+ const code = (elements.oauthVerifyInput.value || "").trim().toUpperCase();
+ if (!code) {
+ elements.oauthVerifyHint.textContent = "Enter the 6-character code shown on the authorize page.";
+ return;
+ }
+ elements.oauthVerifyBtn.disabled = true;
+ elements.oauthDenyBtn.disabled = true;
+ elements.oauthVerifyHint.textContent = decision === "deny" ? "Denying…" : "Authorizing…";
+ try {
+ const payload = await callConsole("/ov/auth/oauth-verify", {
+ method: "POST",
+ body: JSON.stringify({ code, decision }),
+ });
+ const result = payload && payload.result ? payload.result : payload;
+ const status = result && result.status;
+ if (status === "approved") {
+ const name = (result && result.client_name) || "the client";
+ elements.oauthVerifyHint.textContent =
+ `Authorized ${name}. Switch back to the client tab — it will continue automatically.`;
+ elements.oauthVerifyInput.value = "";
+ } else if (status === "denied") {
+ elements.oauthVerifyHint.textContent = "Denied. The client will see an error.";
+ elements.oauthVerifyInput.value = "";
+ } else {
+ elements.oauthVerifyHint.textContent =
+ "Server returned an unexpected response — check the result panel.";
+ setOutput(payload);
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ elements.oauthVerifyHint.textContent = `Failed: ${message}`;
+ } finally {
+ elements.oauthVerifyBtn.disabled = false;
+ elements.oauthDenyBtn.disabled = false;
+ }
+ }
+
+ if (elements.oauthVerifyBtn) {
+ elements.oauthVerifyBtn.addEventListener("click", () => submitOAuthVerify("approve"));
+ }
+ if (elements.oauthDenyBtn) {
+ elements.oauthDenyBtn.addEventListener("click", () => submitOAuthVerify("deny"));
+ }
+ if (elements.oauthVerifyInput) {
+ elements.oauthVerifyInput.addEventListener("keydown", (event) => {
+ if (event.key !== "Enter") {
+ return;
+ }
+ event.preventDefault();
+ submitOAuthVerify("approve");
+ });
+ }
}
function bindFilesystem() {
diff --git a/openviking/console/static/index.html b/openviking/console/static/index.html
index 6278a7749..346ee6422 100644
--- a/openviking/console/static/index.html
+++ b/openviking/console/static/index.html
@@ -342,6 +342,40 @@
<button id="clearKeyBtn" class="ghost">Clear</button>
</div>
<p id="connectionHint" class="muted">No API key in session.</p>
+
+ <h3 style="margin-top: 1.75rem;">Authorize an MCP client</h3>
+ <p class="muted" style="margin-top: -0.25rem;">
+ Confirm a pending OAuth authorization for Claude.ai / Claude Desktop /
+ ChatGPT / Cursor. The client shows a 6-character verification code
+ on its authorize page — paste it here and click Authorize.
+ </p>
+ <label for="oauthVerifyInput">Verification code</label>
+ <input id="oauthVerifyInput" type="text" maxlength="12"
+ autocomplete="off" placeholder="ABC234"
+ style="font-family: ui-monospace, monospace; letter-spacing: 0.15em; text-transform: uppercase;">
+ <div class="row" style="gap: 0.5rem;">
+ <button id="oauthVerifyBtn" type="button">Authorize</button>
+ <button id="oauthDenyBtn" class="ghost" type="button">Deny</button>
+ </div>
+ <p id="oauthVerifyHint" class="muted" style="margin: 0.5rem 0 0; font-size: 0.85rem;"></p>
+
+ <details style="margin-top: 1.25rem;">
+ <summary class="muted" style="cursor: pointer;">Generate OTP for legacy push flow</summary>
+ <p class="muted" style="margin: 0.75rem 0;">
+ For CLI / scripted clients that drive the older push-style flow:
+ generate an OTP here, then paste it on the client side.
+ </p>
+ <div class="row">
+ <button id="getOtpBtn" type="button">Get OTP</button>
+ </div>
+ <div id="otpBox" hidden style="margin-top: 0.75rem; padding: 0.75rem; border-radius: 6px; background: var(--surface-soft, #f5f5f7);">
+ <div class="row" style="gap: 0.5rem; align-items: center;">
+ <code id="otpValue" style="font-size: 1.4rem; letter-spacing: 0.15em; padding: 4px 10px; border-radius: 4px; background: var(--surface, white);"></code>
+ <button id="otpCopyBtn" class="ghost" type="button">Copy</button>
+ </div>
+ <p id="otpExpiry" class="muted" style="margin: 0.5rem 0 0; font-size: 0.85rem;"></p>
+ </div>
+ </details>
</section>
</div>
diff --git a/openviking/server/api_keys/legacy.py b/openviking/server/api_keys/legacy.py
index 3d59cacef..681e7376f 100644
--- a/openviking/server/api_keys/legacy.py
+++ b/openviking/server/api_keys/legacy.py
@@ -3,6 +3,7 @@
"""Legacy API Key management (original implementation)."""
import fnmatch
+import hashlib
import hmac
import json
import secrets
@@ -567,6 +568,35 @@ class LegacyAPIKeyManager:
return Role.USER
return Role(user.get("role", "user"))
+ def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:
+ """Return SHA-256 hex digest of the user's stored API key value, or None.
+
+ The "stored value" is whatever is persisted in ``user_info["key"]``:
+ either the plaintext API key (when hashing is disabled) or its
+ Argon2id hash (when hashing is enabled). Both are stable per
+ key-generation — they are written once on create / regenerate and
+ never mutate in place — so the fingerprint is stable as long as the
+ key is unchanged, and changes the moment ``regenerate_key`` runs.
+
+ Used by OAuth to bind issued tokens to the API key that authorized
+ them: at OTP / authorize time we record this fingerprint; at every
+ OAuth bearer auth we recompute and compare. Mismatch (rotation) or
+ ``None`` (user removed) fails the request closed.
+
+ Returns None when the account or user does not exist, or when the
+ stored value is empty (no fingerprint to bind to).
+ """
+ account = self._accounts.get(account_id)
+ if account is None:
+ return None
+ user = account.users.get(user_id)
+ if user is None:
+ return None
+ stored = user.get("key", "")
+ if not stored:
+ return None
+ return hashlib.sha256(stored.encode("utf-8")).hexdigest()
+
# ---- internal helpers ----
def _generate_api_key(self) -> str:
diff --git a/openviking/server/api_keys/new.py b/openviking/server/api_keys/new.py
index 9d62392f4..426c19e35 100644
--- a/openviking/server/api_keys/new.py
+++ b/openviking/server/api_keys/new.py
@@ -410,6 +410,14 @@ class NewAPIKeyManager:
"""
return self._legacy.get_user_role(account_id, user_id)
+ def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:
+ """SHA-256 hex digest of the user's stored API key value, or None.
+
+ Delegates to legacy. See ``LegacyAPIKeyManager.get_user_key_fingerprint``
+ for the rotation/deletion semantics OAuth relies on.
+ """
+ return self._legacy.get_user_key_fingerprint(account_id, user_id)
+
# ---- Property proxies for backward compatibility with tests ----
@property
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 0ff18f192..3bb3dae77 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -25,7 +25,7 @@ from openviking.server.config import (
)
from openviking.server.dependencies import set_service
from openviking.server.error_mapping import map_exception
-from openviking.server.identity import AuthMode
+from openviking.server.identity import AuthMode, Role
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
from openviking.server.routers import (
admin_router,
@@ -50,6 +50,7 @@ from openviking.service.core import OpenVikingService
from openviking.service.task_tracker import get_task_tracker
from openviking_cli.exceptions import OpenVikingError
from openviking_cli.utils import get_logger
+from openviking_cli.utils.config import get_openviking_config
from openviking_cli.utils.logger import init_otel_log_handler_from_server_config
logger = get_logger(__name__)
@@ -218,6 +219,29 @@ def create_app(
if config.observability.metrics.enabled:
logger.info("Prometheus metrics enabled at /metrics")
+ # Initialize OAuth 2.1 store + provider when enabled in OpenViking config.
+ # The store + provider instances were already constructed at app
+ # creation time so the SDK routes could capture them; here we just
+ # async-initialize the SQLite connection on the same instance.
+ oauth_store = getattr(app.state, "oauth_store", None)
+ oauth_gc_task: Optional[asyncio.Task] = None
+ if oauth_store is not None:
+ await oauth_store.initialize()
+
+ async def _oauth_gc_loop(store) -> None: # noqa: ANN001
+ while True:
+ try:
+ await asyncio.sleep(60)
+ await store.gc_expired()
+ except asyncio.CancelledError:
+ raise
+ except Exception as e: # noqa: BLE001
+ logger.warning("OAuth GC loop error: %s", e)
+
+ oauth_gc_task = asyncio.create_task(_oauth_gc_loop(oauth_store))
+ app.state.oauth_gc_task = oauth_gc_task
+ logger.info("OAuth 2.1 store initialized at %s", oauth_store._db_path)
+
# Start TaskTracker cleanup loop
task_tracker = get_task_tracker()
task_tracker.start_cleanup_loop()
@@ -252,6 +276,18 @@ def create_app(
await shutdown_metrics_async(app=app)
task_tracker.stop_cleanup_loop()
+ if oauth_gc_task is not None:
+ oauth_gc_task.cancel()
+ try:
+ await oauth_gc_task
+ except (asyncio.CancelledError, Exception):
+ pass
+ oauth_store_state = getattr(app.state, "oauth_store", None)
+ if oauth_store_state is not None:
+ try:
+ await oauth_store_state.close()
+ except Exception as e: # noqa: BLE001
+ logger.warning("OAuth store close failed: %s", e)
if owns_service and service:
try:
await service.close()
@@ -449,6 +485,85 @@ def create_app(
app.include_router(webdav_router)
app.include_router(bot_router, prefix="/bot/v1")
+ # OAuth 2.1: when enabled, mount the official MCP SDK auth routes
+ # (DCR / authorize / token / metadata) plus our authorize page + OTP
+ # issuance endpoint. The Provider that backs the SDK routes is built
+ # in the lifespan; here we only register the route handlers, since the
+ # SDK routes inspect request.app.state at call time.
+ try:
+ ov_cfg = get_openviking_config()
+ if ov_cfg.oauth.enabled:
+ from mcp.server.auth.routes import create_auth_routes
+ from mcp.server.auth.settings import ClientRegistrationOptions, RevocationOptions
+ from pydantic import AnyHttpUrl
+
+ from openviking.server.oauth.router import router as oauth_router
+
+ # Custom routes (authorize page + /api/v1/auth/otp).
+ app.include_router(oauth_router)
+
+ # SDK-owned routes (DCR / authorize / token / metadata / revoke).
+ # We need a live Provider here; create_auth_routes captures it by
+ # reference. Re-build the same construction the lifespan does so
+ # the routes work as soon as they're hit (lifespan re-binds the
+ # same instance to app.state for the OTP / authorize-page path).
+ from pathlib import Path as _Path
+
+ from openviking.server.oauth.provider import OpenVikingOAuthProvider
+ from openviking.server.oauth.storage import OAuthStore
+
+ _workspace = _Path(ov_cfg.storage.workspace).expanduser().resolve()
+ _workspace.mkdir(parents=True, exist_ok=True)
+ _route_store = OAuthStore(_workspace / ov_cfg.oauth.db_filename)
+ # Resolution order for the AS issuer URL:
+ # 1. OPENVIKING_PUBLIC_BASE_URL env var (deployment override)
+ # 2. oauth.issuer in ov.conf (operator config)
+ # 3. http://127.0.0.1:1933 (dev default; SDK accepts loopback http)
+ import os as _os
+
+ _route_issuer = (
+ _os.environ.get("OPENVIKING_PUBLIC_BASE_URL", "").strip().rstrip("/")
+ or ov_cfg.oauth.issuer
+ or "http://127.0.0.1:1933"
+ )
+
+ # Late-binding role resolver: app.state.api_key_manager is wired
+ # during lifespan, after the provider is constructed. Lambda
+ # closes over `app` and looks up at call time.
+ def _current_role(account_id: str, user_id: str) -> Role:
+ mgr = getattr(app.state, "api_key_manager", None)
+ if mgr is None or not hasattr(mgr, "get_user_role"):
+ return Role.USER
+ return mgr.get_user_role(account_id, user_id)
+
+ _route_provider = OpenVikingOAuthProvider(
+ store=_route_store,
+ issuer=_route_issuer,
+ access_token_ttl_seconds=ov_cfg.oauth.access_token_ttl_seconds,
+ refresh_token_ttl_seconds=ov_cfg.oauth.refresh_token_ttl_seconds,
+ auth_code_ttl_seconds=ov_cfg.oauth.auth_code_ttl_seconds,
+ role_resolver=_current_role,
+ )
+ # Stash the route-time instances; the lifespan replaces these with
+ # initialized copies before the first request lands.
+ app.state.oauth_store = _route_store
+ app.state.oauth_provider = _route_provider
+
+ sdk_routes = create_auth_routes(
+ provider=_route_provider,
+ issuer_url=AnyHttpUrl(_route_issuer),
+ client_registration_options=ClientRegistrationOptions(enabled=True),
+ revocation_options=RevocationOptions(enabled=True),
+ )
+ app.routes.extend(sdk_routes)
+ app.state.oauth_config = ov_cfg.oauth
+ logger.info(
+ "OAuth 2.1 routes mounted (SDK + authorize-page + otp): %s",
+ [r.path for r in sdk_routes],
+ )
+ except Exception as e: # noqa: BLE001
+ logger.warning("Skipping OAuth router registration: %s", e)
+
# Favicon: shared with the console static assets so 1933/console use the same logo.
_static_dir = Path(__file__).resolve().parent.parent / "console" / "static"
_favicon_headers = {"Cache-Control": "public, max-age=86400"}
diff --git a/openviking/server/auth.py b/openviking/server/auth.py
index 32c525fbd..9ea7d9d26 100644
--- a/openviking/server/auth.py
+++ b/openviking/server/auth.py
@@ -7,7 +7,13 @@ from typing import Optional
from fastapi import Depends, Header, Request
-from openviking.server.identity import AuthMode, RequestContext, ResolvedIdentity, Role
+from openviking.server.identity import (
+ AccountNamespacePolicy,
+ AuthMode,
+ RequestContext,
+ ResolvedIdentity,
+ Role,
+)
from openviking.telemetry.span_models import update_root_span_identity
from openviking_cli.exceptions import (
InvalidArgumentError,
@@ -16,6 +22,13 @@ from openviking_cli.exceptions import (
)
from openviking_cli.session.user_id import UserIdentifier
+# Privilege ranking for role-downgrade detection in OAuth bearer auth. Higher
+# rank ⇒ more privilege. Used to compare an OAuth token's embedded role
+# against the user's current role: a token whose role outranks the current
+# role is a stale token from before a `set_role` demotion and must be rejected.
+_ROLE_RANK = {Role.USER: 0, Role.ADMIN: 1, Role.ROOT: 2}
+
+
_ROOT_IMPLICIT_TENANT_ALLOWED_PATHS = {
"/api/v1/system/status",
"/api/v1/system/wait",
@@ -110,6 +123,119 @@ def _explicit_identity_from_request(request: Request) -> tuple[Optional[str], Op
return account_id, user_id
+async def _try_resolve_oauth_token(
+ request: Request,
+ api_key: str,
+ *,
+ x_openviking_account: Optional[str],
+ x_openviking_user: Optional[str],
+ x_openviking_agent: Optional[str],
+) -> Optional[ResolvedIdentity]:
+ """Attempt to verify the bearer as an OAuth-issued opaque access token.
+
+ Returns the resolved identity on success. Returns None when the bearer
+ doesn't carry the OAuth access-token prefix or when OAuth isn't enabled
+ (caller falls back to the API-key path). Raises UnauthenticatedError
+ when the bearer IS prefix-tagged but lookup fails — fail-closed.
+ """
+ from openviking.server.oauth.provider import ACCESS_TOKEN_PREFIX
+
+ if not api_key.startswith(ACCESS_TOKEN_PREFIX):
+ return None
+ provider = getattr(request.app.state, "oauth_provider", None)
+ if provider is None:
+ return None
+
+ record = await provider.load_access_token(api_key)
+ if record is None:
+ raise UnauthenticatedError("OAuth access token is invalid, expired, or revoked")
+
+ # Lifecycle binding: every OAuth token carries the SHA-256 fingerprint of
+ # the API key that authorized it. We recompute the user's current key fp
+ # and demand strict equality. If the user removed (no fp) or rotated
+ # (different fp) the authorizing key, the token must die — this is the
+ # invariant "OAuth lifetime ≤ authorizing key lifetime". Tokens missing a
+ # recorded fp also fail closed: there is no way to validate them safely.
+ api_key_manager = getattr(request.app.state, "api_key_manager", None)
+ recorded_fp = record.authorizing_key_fp
+ current_fp: Optional[str] = None
+ if api_key_manager is not None and hasattr(api_key_manager, "get_user_key_fingerprint"):
+ current_fp = api_key_manager.get_user_key_fingerprint(record.account_id, record.user_id)
+ if not recorded_fp or not current_fp or not hmac.compare_digest(recorded_fp, current_fp):
+ raise UnauthenticatedError(
+ "OAuth token's authorizing API key has been rotated or revoked; "
+ "please re-authorize the client."
+ )
+
+ try:
+ role = Role(record.role)
+ except ValueError as exc:
+ raise UnauthenticatedError(f"OAuth token has unknown role: {record.role}") from exc
+
+ # Role downgrade protection: fp binds to the key value, but `set_role`
+ # changes role without rotating the key. Re-fetch the user's current
+ # role and reject the token if its embedded role exceeds it (demotion).
+ # Promotion is harmless — the embedded lower privilege is still valid —
+ # so only downgrades trigger rejection.
+ if api_key_manager is not None and hasattr(api_key_manager, "get_user_role"):
+ try:
+ current_role = api_key_manager.get_user_role(record.account_id, record.user_id)
+ except Exception: # noqa: BLE001
+ current_role = role
+ if _ROLE_RANK[role] > _ROLE_RANK[current_role]:
+ raise UnauthenticatedError(
+ "OAuth token's embedded role exceeds the user's current role; "
+ "please re-authorize the client."
+ )
+
+ account_id = record.account_id
+ user_id = record.user_id
+
+ # Header overrides mirror the API-key path: ROOT may override identity;
+ # ADMIN may override user and agent (within its own account); USER may
+ # override only agent. The OAuth claims pin the issuing identity, so any
+ # cross-account/user override beyond what each role can do is a 403.
+ if role == Role.ROOT:
+ effective_account = x_openviking_account or account_id
+ effective_user = x_openviking_user or user_id
+ elif role == Role.ADMIN:
+ if x_openviking_account and x_openviking_account != account_id:
+ raise PermissionDeniedError(
+ "X-OpenViking-Account cannot override the account for ADMIN OAuth tokens."
+ )
+ effective_account = account_id
+ effective_user = x_openviking_user or user_id
+ else: # Role.USER
+ if x_openviking_account and x_openviking_account != account_id:
+ raise PermissionDeniedError(
+ "X-OpenViking-Account cannot override the account for USER OAuth tokens."
+ )
+ if x_openviking_user and x_openviking_user != user_id:
+ raise PermissionDeniedError(
+ "X-OpenViking-User cannot override the user for USER OAuth tokens."
+ )
+ effective_account = account_id
+ effective_user = user_id
+
+ effective_agent = x_openviking_agent or "default"
+
+ namespace_policy = AccountNamespacePolicy()
+ if api_key_manager is not None and hasattr(api_key_manager, "get_account_policy"):
+ try:
+ namespace_policy = api_key_manager.get_account_policy(effective_account)
+ except Exception: # noqa: BLE001
+ pass
+
+ return ResolvedIdentity(
+ role=role,
+ account_id=effective_account,
+ user_id=effective_user,
+ agent_id=effective_agent,
+ namespace_policy=namespace_policy,
+ from_oauth=True,
+ )
+
+
async def resolve_identity(
request: Request,
x_api_key: Optional[str] = Header(None),
@@ -209,6 +335,21 @@ async def resolve_identity(
if not api_key:
raise UnauthenticatedError("Missing API Key when resolving identity.")
+ # OAuth 2.1 fast path: bearer tokens minted by our OAuth provider carry
+ # a recognizable prefix; look them up directly and skip the API-key path.
+ # Failure is fail-closed — a forged token claiming the prefix cannot be
+ # retried as a plain key. When OAuth is disabled or the bearer lacks the
+ # prefix, this returns None and the API-key path runs.
+ oauth_identity = await _try_resolve_oauth_token(
+ request,
+ api_key,
+ x_openviking_account=x_openviking_account,
+ x_openviking_user=x_openviking_user,
+ x_openviking_agent=x_openviking_agent,
+ )
+ if oauth_identity is not None:
+ return oauth_identity
+
identity = api_key_manager.resolve(api_key)
if identity.role == Role.ROOT:
identity.account_id = x_openviking_account or identity.account_id or "default"
@@ -245,7 +386,12 @@ async def get_request_context(
path = request.url.path
auth_mode = _auth_mode(request)
api_key_manager = getattr(request.app.state, "api_key_manager", None)
- if auth_mode == AuthMode.API_KEY and api_key_manager is not None and identity.role == Role.ROOT:
+ if (
+ auth_mode == AuthMode.API_KEY
+ and api_key_manager is not None
+ and identity.role == Role.ROOT
+ and not identity.from_oauth
+ ):
account_header = request.headers.get("X-OpenViking-Account")
if _root_request_requires_explicit_account_only(path):
if not account_header:
@@ -282,6 +428,7 @@ async def get_request_context(
if api_key_manager is not None and hasattr(api_key_manager, "get_account_policy")
else identity.namespace_policy
),
+ from_oauth=identity.from_oauth,
)
# Update the unified root observability context after authentication succeeds.
update_root_span_identity(
diff --git a/openviking/server/identity.py b/openviking/server/identity.py
index f1179b505..e9a5a9c0b 100644
--- a/openviking/server/identity.py
+++ b/openviking/server/identity.py
@@ -60,6 +60,11 @@ class ResolvedIdentity:
user_id: Optional[str] = None
agent_id: Optional[str] = None
namespace_policy: AccountNamespacePolicy = field(default_factory=AccountNamespacePolicy)
+ # True when this identity was minted from an OAuth-issued bearer token;
+ # downstream checks (e.g. ROOT-requires-explicit-tenant headers) can skip
+ # rules that target raw API-key auth, since OAuth claims already pin
+ # account/user.
+ from_oauth: bool = False
@dataclass
@@ -69,6 +74,11 @@ class RequestContext:
user: UserIdentifier
role: Role
namespace_policy: AccountNamespacePolicy = field(default_factory=AccountNamespacePolicy)
+ # Mirrors ResolvedIdentity.from_oauth. Routes that mint OAuth state
+ # (OTP issuance, oauth-verify) reject callers with from_oauth=True to
+ # prevent a stolen access token from laundering itself into a long-lived
+ # refresh-token chain.
+ from_oauth: bool = False
@property
def account_id(self) -> str:
@@ -98,7 +108,6 @@ class RequestContext:
class ToolContext:
"""Tool-level context, containing request context and additional tool-specific information."""
-
viking_fs: VikingFS
request_ctx: RequestContext
default_search_uris: List[str] = field(default_factory=list)
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index cb3306655..9b1a5cd94 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -55,6 +55,52 @@ def _get_ctx() -> RequestContext:
return ctx
+def _scope_to_origin(scope: Scope) -> Optional[str]:
+ """Derive the public-facing origin (scheme://host) from an ASGI scope.
+
+ Resolution order matches openviking.server.oauth.router._public_origin:
+ 1. ``OPENVIKING_PUBLIC_BASE_URL`` environment variable
+ 2. ``app.state.oauth_config.issuer`` (if OAuth enabled)
+ 3. ``X-Forwarded-Proto`` / ``X-Forwarded-Host``
+ 4. scope's own scheme + Host header
+ """
+ import os as _os
+
+ env_value = _os.environ.get("OPENVIKING_PUBLIC_BASE_URL", "").strip()
+ if env_value:
+ return env_value.rstrip("/")
+
+ app = scope.get("app")
+ if app is not None:
+ cfg = getattr(app.state, "oauth_config", None)
+ configured = getattr(cfg, "issuer", None) if cfg else None
+ if configured:
+ return configured.rstrip("/")
+
+ headers = {
+ k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])
+ }
+ proto = headers.get("x-forwarded-proto") or scope.get("scheme") or "http"
+ proto = proto.split(",", 1)[0].strip()
+ host = headers.get("x-forwarded-host") or headers.get("host")
+ if not host:
+ server = scope.get("server")
+ if isinstance(server, (list, tuple)) and len(server) >= 2:
+ host = f"{server[0]}:{server[1]}" if server[1] else str(server[0])
+ if not host:
+ return None
+ host = host.split(",", 1)[0].strip()
+ return f"{proto}://{host}"
+
+
+def _oauth_enabled(scope: Scope) -> bool:
+ """Return True if app.state has an oauth_provider (i.e. OAuth is configured)."""
+ app = scope.get("app")
+ if app is None:
+ return False
+ return getattr(app.state, "oauth_provider", None) is not None
+
+
class _IdentityASGIMiddleware:
"""ASGI middleware: delegates to auth.resolve_identity (the same function
used by all REST API routes) so authentication logic is never duplicated."""
@@ -82,9 +128,21 @@ class _IdentityASGIMiddleware:
if isinstance(exc, UnauthenticatedError)
else (403 if isinstance(exc, PermissionDeniedError) else 400)
)
+ headers: dict[str, str] = {}
+ # When OAuth is enabled and the request is unauthenticated, advertise
+ # the OAuth 2.0 protected resource metadata so MCP clients (Claude.ai,
+ # Claude Desktop, etc.) can auto-discover the authorization server
+ # per RFC 9728 §5.1.
+ if status == 401 and _oauth_enabled(scope):
+ origin = _scope_to_origin(scope)
+ if origin:
+ headers["WWW-Authenticate"] = (
+ f'Bearer resource_metadata="{origin}/.well-known/oauth-protected-resource"'
+ )
resp = JSONResponse(
{"jsonrpc": "2.0", "id": None, "error": {"code": -32001, "message": str(exc)}},
status_code=status,
+ headers=headers,
)
return await resp(scope, receive, send)
diff --git a/openviking/server/oauth/__init__.py b/openviking/server/oauth/__init__.py
new file mode 100644
index 000000000..32469ca19
--- /dev/null
+++ b/openviking/server/oauth/__init__.py
@@ -0,0 +1,3 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""OAuth 2.1 (MCP-flavored) server package — Phase 1: OTP-only authorization."""
diff --git a/openviking/server/oauth/otp.py b/openviking/server/oauth/otp.py
new file mode 100644
index 000000000..38f5272f6
--- /dev/null
+++ b/openviking/server/oauth/otp.py
@@ -0,0 +1,29 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""OTP and short-code utilities for the OAuth 2.1 Phase-1 OTP grant."""
+
+from __future__ import annotations
+
+import hashlib
+import secrets
+
+# 32-character alphabet (24 letters + 8 digits) with visually ambiguous
+# glyphs removed: O / 0 / I / 1. Used for the human-typed OTPs.
+_OTP_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
+OTP_LENGTH = 6
+
+
+def generate_otp(length: int = OTP_LENGTH) -> str:
+ """Generate a cryptographically random OTP from the unambiguous alphabet."""
+ if length < 4:
+ raise ValueError("OTP length must be at least 4")
+ return "".join(secrets.choice(_OTP_ALPHABET) for _ in range(length))
+
+
+def hash_secret(plain: str) -> str:
+ """SHA-256 hex digest used to index OTPs / auth codes / refresh tokens.
+
+ All three are high-entropy random tokens (≥ 128 bits), so a fast unsalted
+ digest is sufficient — Argon2 is reserved for low-entropy user passwords.
+ """
+ return hashlib.sha256(plain.encode("utf-8")).hexdigest()
diff --git a/openviking/server/oauth/provider.py b/openviking/server/oauth/provider.py
new file mode 100644
index 000000000..f0045b306
--- /dev/null
+++ b/openviking/server/oauth/provider.py
@@ -0,0 +1,420 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Adapter that bridges the official MCP SDK OAuth provider Protocol to OpenViking's
+``OAuthStore``.
+
+The SDK ships a stdlib-only OAuth 2.1 server (RFC 6749 / 7591 / 8414) under
+``mcp.server.auth``. It validates PKCE, parses grants, and emits standard
+errors itself; we just supply a Provider implementation that knows how to
+persist and retrieve the protocol's data structures. Tokens are opaque random
+strings keyed by their SHA-256 hash, so this module contains no cryptography.
+"""
+
+from __future__ import annotations
+
+import logging
+import secrets
+from typing import Callable, Optional
+from urllib.parse import urlencode
+
+from mcp.server.auth.provider import (
+ AccessToken,
+ AuthorizationCode,
+ AuthorizationParams,
+ OAuthAuthorizationServerProvider,
+ RefreshToken,
+ RegistrationError,
+ TokenError,
+)
+from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
+from pydantic import AnyUrl
+
+from openviking.server.identity import Role
+from openviking.server.oauth.otp import generate_otp
+from openviking.server.oauth.storage import OAuthStore
+
+# Mirrors auth.py:_ROLE_RANK; duplicated here to avoid the import cycle
+# (auth.py already depends on this module via the Provider Protocol).
+_ROLE_RANK = {Role.USER: 0, Role.ADMIN: 1, Role.ROOT: 2}
+
+logger = logging.getLogger(__name__)
+
+# Access tokens carry this prefix so the auth.py bearer router can cheaply
+# discriminate them from API keys without an extra DB lookup. The prefix is
+# advisory (the actual auth is the DB lookup), but it keeps the hot path fast.
+ACCESS_TOKEN_PREFIX = "ovat_"
+REFRESH_TOKEN_PREFIX = "ovrt_"
+AUTH_CODE_PREFIX = "ovac_"
+
+
+class OVAuthorizationCode(AuthorizationCode):
+ """AuthorizationCode subtype that pins the issuing identity."""
+
+ account_id: str
+ user_id: str
+ role: str
+ # SHA-256 fp of the API key that authorized this code; copied forward
+ # into refresh/access tokens so rotation invalidates the entire chain.
+ authorizing_key_fp: str | None = None
+
+
+class OVRefreshToken(RefreshToken):
+ account_id: str
+ user_id: str
+ role: str
+ resource: str | None = None
+ authorizing_key_fp: str | None = None
+
+
+class OVAccessToken(AccessToken):
+ account_id: str
+ user_id: str
+ role: str
+ authorizing_key_fp: str | None = None
+
+
+class OpenVikingOAuthProvider(
+ OAuthAuthorizationServerProvider[OVAuthorizationCode, OVRefreshToken, OVAccessToken]
+):
+ """OpenViking implementation of the MCP SDK OAuth provider Protocol."""
+
+ def __init__(
+ self,
+ *,
+ store: OAuthStore,
+ issuer: str,
+ access_token_ttl_seconds: int = 3600,
+ refresh_token_ttl_seconds: int = 30 * 24 * 3600,
+ auth_code_ttl_seconds: int = 300,
+ authorize_page_path: str = "/oauth/authorize/page",
+ role_resolver: Optional[Callable[[str, str], "Role"]] = None,
+ ) -> None:
+ self._store = store
+ self._issuer = issuer.rstrip("/")
+ self._access_ttl = access_token_ttl_seconds
+ self._refresh_ttl = refresh_token_ttl_seconds
+ self._code_ttl = auth_code_ttl_seconds
+ self._authorize_page = authorize_page_path
+ # Optional callback to look up a user's current role at refresh time.
+ # When supplied, exchange_refresh_token will reject if the embedded
+ # role outranks the current role — mirrors the bearer-auth check so
+ # that `set_role` demotion can't be laundered through token rotation.
+ # Wired in app.py from the APIKeyManager.
+ self._role_resolver = role_resolver
+
+ # ---- Clients (DCR) ----
+
+ async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:
+ record = await self._store.get_client(client_id)
+ if record is None:
+ return None
+ return OAuthClientInformationFull(
+ client_id=record["client_id"],
+ client_secret=None, # we never expose stored secret hash; auth uses the hash check
+ redirect_uris=[AnyUrl(u) for u in record["redirect_uris"]],
+ token_endpoint_auth_method=record["token_endpoint_auth_method"],
+ grant_types=record["grant_types"],
+ response_types=record["response_types"],
+ client_name=record.get("client_name"),
+ client_id_issued_at=record["created_at"],
+ )
+
+ async def register_client(self, client_info: OAuthClientInformationFull) -> None:
+ if client_info.client_id is None: # pragma: no cover — SDK always sets it
+ raise RegistrationError(
+ error="invalid_client_metadata",
+ error_description="client_id is required",
+ )
+ # OpenViking treats every registered client as public + PKCE.
+ # We do not enforce client_secret on the token endpoint — get_client
+ # returns client_secret=None unconditionally, so the SDK's
+ # ClientAuthenticator skips secret validation regardless of what
+ # auth method was declared. To prevent confidential clients from
+ # *thinking* they're getting secret-based auth (silent security
+ # downgrade), we normalize whatever the registrar requested to
+ # "none" and log a warning. Real MCP clients use "none" anyway —
+ # RFC 8252 §8.4 says native apps MUST NOT use client_secret —
+ # but the OAuth 2.0 default that some SDKs fill in is
+ # "client_secret_basic", which would otherwise fail the gate.
+ requested = client_info.token_endpoint_auth_method
+ if requested and requested != "none":
+ logger.warning(
+ "DCR: client %s requested token_endpoint_auth_method=%s; "
+ "downgrading to 'none' (OpenViking only supports public PKCE clients).",
+ client_info.client_id,
+ requested,
+ )
+ auth_method = "none"
+ try:
+ await self._store.register_client(
+ client_id=client_info.client_id,
+ redirect_uris=[str(u) for u in (client_info.redirect_uris or [])],
+ client_name=client_info.client_name,
+ token_endpoint_auth_method=auth_method,
+ grant_types=list(client_info.grant_types) if client_info.grant_types else None,
+ response_types=list(client_info.response_types)
+ if client_info.response_types
+ else None,
+ client_secret=None, # public client; never stored
+ )
+ except ValueError as exc:
+ raise RegistrationError(
+ error="invalid_client_metadata", error_description=str(exc)
+ ) from exc
+
+ # ---- Authorize ----
+
+ async def authorize(
+ self, client: OAuthClientInformationFull, params: AuthorizationParams
+ ) -> str:
+ """Mint a verification code and stash the AuthorizationParams.
+
+ Returns the URL of our authorize page, which displays a 6-character
+ verification code. The user re-types that code into the OpenViking
+ console (where they're already authenticated), the console calls our
+ ``/api/v1/auth/oauth-verify`` endpoint to bind the caller's identity
+ to the pending row, and the page polls until verified to redirect
+ back to the client's redirect_uri.
+ """
+ assert client.client_id is not None
+ display_code = generate_otp()
+ pending_id = await self._store.create_pending_authorization(
+ client_id=client.client_id,
+ redirect_uri=str(params.redirect_uri),
+ redirect_uri_provided_explicitly=params.redirect_uri_provided_explicitly,
+ code_challenge=params.code_challenge,
+ scopes=params.scopes,
+ resource=params.resource,
+ state=params.state,
+ display_code=display_code,
+ ttl_seconds=600,
+ )
+ return f"{self._issuer}{self._authorize_page}?{urlencode({'pending': pending_id})}"
+
+ # ---- Authorization code lifecycle ----
+
+ async def load_authorization_code(
+ self, client: OAuthClientInformationFull, authorization_code: str
+ ) -> OVAuthorizationCode | None:
+ # We don't consume yet — SDK's TokenHandler verifies PKCE first, then
+ # calls exchange_authorization_code. Use a non-destructive lookup.
+ record = await self._store.peek_auth_code(authorization_code)
+ if record is None:
+ return None
+ if record.get("client_id") != client.client_id:
+ return None
+ return OVAuthorizationCode(
+ code=authorization_code,
+ scopes=(record.get("scope") or "").split() if record.get("scope") else [],
+ expires_at=float(record["expires_at"]),
+ client_id=record["client_id"],
+ code_challenge=record["code_challenge"],
+ redirect_uri=AnyUrl(record["redirect_uri"]),
+ redirect_uri_provided_explicitly=True,
+ resource=record.get("resource"),
+ account_id=record["account_id"],
+ user_id=record["user_id"],
+ role=record["role"],
+ authorizing_key_fp=record.get("authorizing_key_fp"),
+ )
+
+ async def exchange_authorization_code(
+ self,
+ client: OAuthClientInformationFull,
+ authorization_code: OVAuthorizationCode,
+ ) -> OAuthToken:
+ # One-shot consumption: this is what binds the code to a single exchange.
+ consumed = await self._store.consume_auth_code(authorization_code.code)
+ if consumed is None:
+ raise TokenError(error="invalid_grant", error_description="code is invalid or reused")
+ return await self._issue_token_pair(
+ client_id=authorization_code.client_id,
+ account_id=authorization_code.account_id,
+ user_id=authorization_code.user_id,
+ role=authorization_code.role,
+ scope=" ".join(authorization_code.scopes) if authorization_code.scopes else None,
+ resource=authorization_code.resource,
+ authorizing_key_fp=authorization_code.authorizing_key_fp,
+ )
+
+ # ---- Refresh tokens ----
+
+ async def load_refresh_token(
+ self, client: OAuthClientInformationFull, refresh_token: str
+ ) -> OVRefreshToken | None:
+ record = await self._store.peek_refresh(refresh_token)
+ if record is None:
+ return None
+ if record.get("client_id") != client.client_id:
+ return None
+ return OVRefreshToken(
+ token=refresh_token,
+ client_id=record["client_id"],
+ scopes=(record.get("scope") or "").split() if record.get("scope") else [],
+ expires_at=record.get("expires_at"),
+ account_id=record["account_id"],
+ user_id=record["user_id"],
+ role=record["role"],
+ resource=record.get("resource"),
+ authorizing_key_fp=record.get("authorizing_key_fp"),
+ )
+
+ async def exchange_refresh_token(
+ self,
+ client: OAuthClientInformationFull,
+ refresh_token: OVRefreshToken,
+ scopes: list[str],
+ ) -> OAuthToken:
+ # Role downgrade gate: if the embedded role outranks the user's
+ # current role (post-`set_role` demotion), refuse to rotate. Same
+ # invariant the bearer-auth path enforces; checked here so a
+ # demoted user can't keep minting fresh access tokens at the old
+ # privilege level just because they hold a long-lived refresh.
+ if self._role_resolver is not None:
+ try:
+ token_role = Role(refresh_token.role)
+ current_role = self._role_resolver(refresh_token.account_id, refresh_token.user_id)
+ except (ValueError, Exception): # noqa: BLE001
+ token_role = None
+ current_role = None
+ if (
+ token_role is not None
+ and current_role is not None
+ and _ROLE_RANK[token_role] > _ROLE_RANK[current_role]
+ ):
+ raise TokenError(
+ error="invalid_grant",
+ error_description=(
+ "user role has been downgraded; please re-authorize the client"
+ ),
+ )
+ new_refresh = self._mint_refresh()
+ consumed = await self._store.consume_refresh(
+ token_plain=refresh_token.token, replaced_by_plain=new_refresh
+ )
+ if consumed is None:
+ # Replay detection: if a previously-issued refresh token is being
+ # reused after consumption, RFC 9700 §4.14 requires invalidating
+ # the entire token family. We go broader than per-(client, account,
+ # user) chain and revoke ALL outstanding access + refresh + auth
+ # codes for the (account, user) pair — replay implies the chain is
+ # compromised, and we'd rather force a full reauthorization than
+ # risk leaving sibling tokens live.
+ if await self._store.is_refresh_known_but_consumed(refresh_token.token):
+ logger.warning(
+ "OAuth refresh replay detected for client_id=%s account=%s user=%s",
+ client.client_id,
+ refresh_token.account_id,
+ refresh_token.user_id,
+ )
+ await self._store.revoke_user_tokens(
+ account_id=refresh_token.account_id,
+ user_id=refresh_token.user_id,
+ )
+ raise TokenError(error="invalid_grant", error_description="refresh token invalid")
+ scope = " ".join(scopes) if scopes else None
+ return await self._issue_token_pair(
+ client_id=refresh_token.client_id,
+ account_id=refresh_token.account_id,
+ user_id=refresh_token.user_id,
+ role=refresh_token.role,
+ scope=scope or (refresh_token.scopes and " ".join(refresh_token.scopes)) or None,
+ resource=refresh_token.resource,
+ authorizing_key_fp=refresh_token.authorizing_key_fp,
+ new_refresh_override=new_refresh,
+ )
+
+ # ---- Access tokens ----
+
+ async def load_access_token(self, token: str) -> OVAccessToken | None:
+ if not token.startswith(ACCESS_TOKEN_PREFIX):
+ return None
+ record = await self._store.load_access(token)
+ if record is None:
+ return None
+ return OVAccessToken(
+ token=token,
+ client_id=record["client_id"],
+ scopes=(record.get("scope") or "").split() if record.get("scope") else [],
+ expires_at=record["expires_at"],
+ resource=record.get("resource"),
+ account_id=record["account_id"],
+ user_id=record["user_id"],
+ role=record["role"],
+ authorizing_key_fp=record.get("authorizing_key_fp"),
+ )
+
+ async def revoke_token(self, token: OVAccessToken | OVRefreshToken) -> None:
+ # Idempotent — no error if already revoked / unknown.
+ if isinstance(token, AccessToken):
+ await self._store.revoke_access(token.token)
+ else:
+ await self._store.consume_refresh(token_plain=token.token, replaced_by_plain=None)
+
+ # ---- Helpers ----
+
+ def _mint_access(self) -> str:
+ return ACCESS_TOKEN_PREFIX + secrets.token_urlsafe(40)
+
+ def _mint_refresh(self) -> str:
+ return REFRESH_TOKEN_PREFIX + secrets.token_urlsafe(40)
+
+ async def _issue_token_pair(
+ self,
+ *,
+ client_id: str,
+ account_id: str,
+ user_id: str,
+ role: str,
+ scope: Optional[str],
+ resource: Optional[str],
+ authorizing_key_fp: Optional[str],
+ new_refresh_override: Optional[str] = None,
+ ) -> OAuthToken:
+ access = self._mint_access()
+ refresh = new_refresh_override or self._mint_refresh()
+ # ``authorizing_key_fp`` should always be set — every legitimate flow
+ # records the fingerprint at OTP/oauth-verify time. We tolerate None
+ # only because the dataclass default is None for upgrade safety; the
+ # bearer-auth path will fail-closed against a NULL stored value, so a
+ # missing fp here just makes the resulting token unusable rather than
+ # silently bypassing the binding.
+ fp = authorizing_key_fp or ""
+ await self._store.insert_access(
+ token_plain=access,
+ client_id=client_id,
+ account_id=account_id,
+ user_id=user_id,
+ role=role,
+ scope=scope,
+ resource=resource,
+ authorizing_key_fp=fp,
+ ttl_seconds=self._access_ttl,
+ )
+ await self._store.insert_refresh(
+ token_plain=refresh,
+ client_id=client_id,
+ account_id=account_id,
+ user_id=user_id,
+ role=role,
+ scope=scope,
+ resource=resource,
+ authorizing_key_fp=fp,
+ ttl_seconds=self._refresh_ttl,
+ )
+ return OAuthToken(
+ access_token=access,
+ token_type="Bearer",
+ expires_in=self._access_ttl,
+ scope=scope,
+ refresh_token=refresh,
+ )
+
+ # ---- Custom flow methods used by /oauth/authorize/page ----
+
+ def mint_authorization_code(self) -> str:
+ return AUTH_CODE_PREFIX + secrets.token_urlsafe(40)
+
+ @property
+ def code_ttl_seconds(self) -> int:
+ return self._code_ttl
diff --git a/openviking/server/oauth/router.py b/openviking/server/oauth/router.py
new file mode 100644
index 000000000..f7ea777a2
--- /dev/null
+++ b/openviking/server/oauth/router.py
@@ -0,0 +1,556 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""OpenViking-side OAuth routes.
+
+The OAuth 2.1 protocol surface (DCR, /authorize parsing, /token, well-known
+metadata) is delegated to the official ``mcp.server.auth`` SDK (mounted from
+``app.py``). This module only owns:
+
+- ``/oauth/authorize/page`` — HTML form where the user submits an OTP. The
+ SDK's AuthorizationHandler returns this URL from ``provider.authorize()``;
+ on successful OTP submission we mint an authorization code and 302 back
+ to the client's redirect_uri.
+- ``POST /api/v1/auth/otp`` — short-code issuance, authenticated with the
+ caller's existing API key. The OTP is bound to that API key's identity
+ (account / user / role) so it can be redeemed on the authorize page.
+"""
+
+from __future__ import annotations
+
+import html
+import logging
+import os
+from typing import Optional
+from urllib.parse import urlencode
+
+from fastapi import APIRouter, Depends, Request
+from fastapi.responses import HTMLResponse, JSONResponse
+from mcp.shared.auth import ProtectedResourceMetadata
+from pydantic import AnyHttpUrl, BaseModel, Field
+
+from openviking.server.auth import get_request_context
+from openviking.server.identity import RequestContext
+from openviking.server.oauth.otp import generate_otp
+from openviking.server.oauth.provider import OpenVikingOAuthProvider
+from openviking.server.oauth.storage import OAuthStore
+from openviking_cli.exceptions import (
+ InvalidArgumentError,
+ PermissionDeniedError,
+ UnavailableError,
+)
+
+logger = logging.getLogger(__name__)
+
+
+router = APIRouter(tags=["oauth"])
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _get_store_and_provider(request: Request) -> tuple[OAuthStore, OpenVikingOAuthProvider]:
+ store: Optional[OAuthStore] = getattr(request.app.state, "oauth_store", None)
+ provider: Optional[OpenVikingOAuthProvider] = getattr(request.app.state, "oauth_provider", None)
+ if store is None or provider is None:
+ raise UnavailableError(service="oauth", reason="OAuth subsystem is not enabled")
+ return store, provider
+
+
+_AUTHORIZE_PAGE_TEMPLATE = """<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Authorize {client_name}</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <style>
+ body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ background: #f5f5f7; margin: 0; padding: 2rem 1rem; color: #1d1d1f; }}
+ .card {{ max-width: 460px; margin: 4rem auto; background: white;
+ border-radius: 12px; padding: 2rem; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }}
+ h1 {{ font-size: 1.25rem; margin: 0 0 0.5rem; }}
+ .client {{ font-weight: 600; }}
+ p {{ color: #515154; line-height: 1.5; margin: 0.75rem 0; }}
+ .codebox {{ background: #f5f5f7; border-radius: 8px; padding: 1.25rem;
+ margin: 1.5rem 0 1rem; text-align: center; }}
+ .code {{ font-family: ui-monospace, monospace; font-size: 2.4rem;
+ letter-spacing: 0.4rem; font-weight: 600; color: #1d1d1f; }}
+ .console-link {{ display: inline-block; margin-top: 0.5rem; padding: 0.4rem 0.85rem;
+ border-radius: 6px; background: #0071e3; color: white;
+ text-decoration: none; font-size: 0.9rem; }}
+ .console-link:hover {{ background: #0077ed; }}
+ .hint {{ font-size: 0.85rem; color: #86868b; margin-top: 1rem; }}
+ code {{ background: #f5f5f7; padding: 1px 6px; border-radius: 4px;
+ font-family: ui-monospace, monospace; font-size: 0.85rem; }}
+ .same-origin-panel {{ display: none; background: #f1f8e9; border: 1px solid #c5e1a5;
+ border-radius: 8px; padding: 1rem; margin: 1rem 0; }}
+ .same-origin-panel.visible {{ display: block; }}
+ .same-origin-panel h2 {{ margin: 0 0 0.5rem; font-size: 1rem; color: #33691e; }}
+ .same-origin-panel button {{ margin-top: 0.75rem; padding: 0.6rem 1.25rem; border: 0;
+ border-radius: 6px; background: #33691e; color: white;
+ font-size: 0.95rem; cursor: pointer; }}
+ .same-origin-panel button:hover {{ background: #3d7a22; }}
+ .same-origin-panel button:disabled {{ background: #aab; cursor: not-allowed; }}
+ .status {{ margin-top: 1rem; padding: 0.6rem 0.75rem; border-radius: 6px;
+ font-size: 0.9rem; display: none; }}
+ .status.visible {{ display: block; }}
+ .status.error {{ background: #fff1f0; color: #b91c1c; }}
+ .status.info {{ background: #e3f2fd; color: #1565c0; }}
+ </style>
+</head>
+<body>
+ <div class="card">
+ <h1>Authorize <span class="client">{client_name}</span></h1>
+ <p>This client is requesting access to your OpenViking workspace. To continue,
+ go to the OpenViking console and enter the verification code below.</p>
+
+ <div class="codebox">
+ <div class="code" id="displayCode">{display_code}</div>
+ <a class="console-link" href="{public_base_url}/console" target="_blank" rel="noopener">
+ Open OpenViking console →
+ </a>
+ </div>
+
+ <div class="same-origin-panel" id="sameOriginPanel">
+ <h2>Quick authorize</h2>
+ <p style="margin: 0;">You're signed in to the console in this browser.
+ Click below to authorize <strong>{client_name}</strong> with that identity.</p>
+ <button id="quickAuthBtn" type="button">Authorize</button>
+ </div>
+
+ <div class="status" id="statusBox"></div>
+
+ <p class="hint">Waiting for verification… this page will redirect automatically once you confirm.</p>
+ </div>
+
+ <script>
+ (function() {{
+ const PENDING = "{pending_id}";
+ const DISPLAY_CODE = "{display_code}";
+ const STATUS_URL = "/oauth/authorize/page/status?pending=" + encodeURIComponent(PENDING);
+ // Same-origin verify endpoint exposed by the 8020 console proxy. When the
+ // console isn't reverse-proxied to the same origin as this page, the
+ // detection below will simply not find a key and the panel stays hidden.
+ const VERIFY_URL = "/console/api/v1/ov/auth/oauth-verify";
+ const SESSION_KEY = "ov_console_api_key";
+ const statusEl = document.getElementById("statusBox");
+ const panelEl = document.getElementById("sameOriginPanel");
+ const buttonEl = document.getElementById("quickAuthBtn");
+
+ function showStatus(msg, kind) {{
+ statusEl.textContent = msg;
+ statusEl.className = "status visible " + (kind || "info");
+ }}
+ function clearStatus() {{
+ statusEl.className = "status";
+ }}
+
+ // Show the quick-authorize panel only if we can find an API key in this
+ // browser's localStorage (i.e. the console is on the same origin and
+ // the user is signed in). The console persists the API key here for
+ // cross-tab use; sessionStorage holds a per-tab copy that this page
+ // (a different tab) can't see, so we deliberately read localStorage.
+ // Click still requires explicit confirmation.
+ let sameOriginKey = null;
+ try {{
+ sameOriginKey = window.localStorage.getItem(SESSION_KEY)
+ || window.sessionStorage.getItem(SESSION_KEY);
+ }} catch (e) {{ /* storage may be unavailable; ignore */ }}
+ if (sameOriginKey) {{
+ panelEl.classList.add("visible");
+ buttonEl.addEventListener("click", async function() {{
+ buttonEl.disabled = true;
+ clearStatus();
+ try {{
+ const resp = await fetch(VERIFY_URL, {{
+ method: "POST",
+ headers: {{
+ "Content-Type": "application/json",
+ "X-Api-Key": sameOriginKey,
+ }},
+ body: JSON.stringify({{code: DISPLAY_CODE, decision: "approve"}}),
+ }});
+ if (!resp.ok) {{
+ const text = await resp.text();
+ showStatus("Authorize failed: " + text.slice(0, 200), "error");
+ buttonEl.disabled = false;
+ return;
+ }}
+ showStatus("Authorized — redirecting…", "info");
+ }} catch (err) {{
+ showStatus("Network error: " + err.message, "error");
+ buttonEl.disabled = false;
+ }}
+ }});
+ }}
+
+ // Poll the status endpoint until verified, then redirect.
+ async function pollOnce() {{
+ try {{
+ const resp = await fetch(STATUS_URL, {{cache: "no-store"}});
+ if (resp.status === 410) {{
+ showStatus("This authorization has expired. Restart from your client.", "error");
+ return false;
+ }}
+ const body = await resp.json();
+ if (body.status === "approved" && body.redirect_url) {{
+ window.location.replace(body.redirect_url);
+ return false;
+ }}
+ }} catch (e) {{ /* transient failure; retry */ }}
+ return true;
+ }}
+ (async function loop() {{
+ while (await pollOnce()) {{
+ await new Promise(function(r) {{ setTimeout(r, 2000); }});
+ }}
+ }})();
+ }})();
+ </script>
+</body>
+</html>"""
+
+
+def _render_page(
+ *,
+ pending_id: str,
+ display_code: str,
+ client_name: Optional[str],
+ public_base_url: str,
+) -> HTMLResponse:
+ body = _AUTHORIZE_PAGE_TEMPLATE.format(
+ client_name=html.escape(client_name or "MCP Client"),
+ pending_id=html.escape(pending_id),
+ display_code=html.escape(display_code),
+ public_base_url=html.escape(public_base_url),
+ )
+ return HTMLResponse(
+ body,
+ headers={
+ "Cache-Control": "no-store",
+ # Allow inline script + style for our self-contained page; same-origin
+ # only. frame-ancestors 'none' protects against clickjacking.
+ "Content-Security-Policy": (
+ "default-src 'self'; "
+ "style-src 'unsafe-inline'; "
+ "script-src 'unsafe-inline'; "
+ "connect-src 'self'; "
+ "form-action 'self'; "
+ "frame-ancestors 'none'"
+ ),
+ "X-Frame-Options": "DENY",
+ },
+ )
+
+
+# ---------------------------------------------------------------------------
+# /.well-known/oauth-protected-resource (RFC 9728)
+# ---------------------------------------------------------------------------
+
+
+PUBLIC_BASE_URL_ENV = "OPENVIKING_PUBLIC_BASE_URL"
+
+
+def _public_origin(request: Request) -> str:
+ """Pick the public-facing origin for metadata responses.
+
+ Resolution order:
+ 1. ``OPENVIKING_PUBLIC_BASE_URL`` environment variable (operator override)
+ 2. ``oauth.issuer`` from OAuthConfig if explicitly set
+ 3. ``X-Forwarded-Proto`` / ``X-Forwarded-Host`` (reverse-proxy chain)
+ 4. Request scheme + ``Host`` header (direct hit)
+
+ The same helper is used by every URL the server publishes to clients
+ (issuer, PRM resource, WWW-Authenticate, authorize-page links) so they
+ all agree on a single public address.
+ """
+ env_value = os.environ.get(PUBLIC_BASE_URL_ENV, "").strip()
+ if env_value:
+ return env_value.rstrip("/")
+ cfg = getattr(request.app.state, "oauth_config", None)
+ configured = getattr(cfg, "issuer", None) if cfg else None
+ if configured:
+ return configured.rstrip("/")
+ proto = request.headers.get("x-forwarded-proto") or request.url.scheme or "http"
+ host = request.headers.get("x-forwarded-host") or request.headers.get("host")
+ if not host:
+ host = request.url.netloc or "localhost"
+ return f"{proto.split(',', 1)[0].strip()}://{host.split(',', 1)[0].strip()}"
+
+
[email protected]("/.well-known/oauth-protected-resource")
+async def oauth_protected_resource(request: Request) -> JSONResponse:
+ """RFC 9728 — protected resource metadata for /mcp.
+
+ MCP clients reach this URL via the ``WWW-Authenticate: Bearer
+ resource_metadata=..."`` hint emitted by the /mcp 401 path. The body
+ points them at our authorization server so they can run discovery
+ against /.well-known/oauth-authorization-server.
+ """
+ cfg = getattr(request.app.state, "oauth_config", None)
+ issuer = (cfg.issuer if cfg and cfg.issuer else _public_origin(request)).rstrip("/")
+ resource = f"{_public_origin(request)}/mcp"
+
+ metadata = ProtectedResourceMetadata(
+ resource=AnyHttpUrl(resource),
+ authorization_servers=[AnyHttpUrl(issuer)],
+ bearer_methods_supported=["header"],
+ resource_name="OpenViking MCP",
+ )
+ return JSONResponse(
+ metadata.model_dump(mode="json", exclude_none=True),
+ headers={"Cache-Control": "public, max-age=3600"},
+ )
+
+
+# ---------------------------------------------------------------------------
+# /oauth/authorize/page
+# ---------------------------------------------------------------------------
+
+
[email protected]("/oauth/authorize/page")
+async def authorize_page_get(request: Request, pending: str = "") -> HTMLResponse:
+ store, provider = _get_store_and_provider(request)
+ if not pending:
+ return HTMLResponse(
+ "<h1>Bad request</h1><p>Missing 'pending' parameter.</p>", status_code=400
+ )
+ record = await store.load_pending_authorization(pending)
+ if record is None:
+ return HTMLResponse(
+ "<h1>Authorization expired</h1><p>Please restart the connection from your client.</p>",
+ status_code=410,
+ )
+ client = await provider.get_client(record["client_id"])
+ return _render_page(
+ pending_id=pending,
+ display_code=record["display_code"],
+ client_name=client.client_name if client else None,
+ public_base_url=_public_origin(request),
+ )
+
+
[email protected]("/oauth/authorize/page/status")
+async def authorize_page_status(request: Request, pending: str = "") -> JSONResponse:
+ """Polled by the authorize page until verification + auth-code mint.
+
+ Status values:
+ - ``pending``: not yet verified
+ - ``approved``: caller confirmed; ``redirect_url`` carries the auth code
+ - ``expired``: pending row gone (TTL or denied)
+ """
+ store, provider = _get_store_and_provider(request)
+ if not pending:
+ return JSONResponse({"status": "expired"}, status_code=410)
+
+ record = await store.load_pending_authorization(pending)
+ if record is None:
+ return JSONResponse({"status": "expired"}, status_code=410)
+
+ if not record["verified"]:
+ return JSONResponse({"status": "pending"}, headers={"Cache-Control": "no-store"})
+
+ # Verified — mint auth code and tear down pending row.
+ auth_code = provider.mint_authorization_code()
+ scope_str = " ".join(record["scopes"]) if record.get("scopes") else None
+ await store.insert_auth_code(
+ code_plain=auth_code,
+ client_id=record["client_id"],
+ redirect_uri=record["redirect_uri"],
+ code_challenge=record["code_challenge"],
+ code_challenge_method="S256",
+ scope=scope_str,
+ resource=record.get("resource"),
+ account_id=record["verified_account_id"],
+ user_id=record["verified_user_id"],
+ role=record["verified_role"],
+ # Carry the verifier's API key fingerprint forward so every token
+ # derived from this code is bound to the same key lifecycle.
+ authorizing_key_fp=record.get("verified_key_fp") or "",
+ ttl_seconds=provider.code_ttl_seconds,
+ )
+ await store.delete_pending_authorization(pending)
+
+ params: dict[str, str] = {"code": auth_code}
+ if record.get("state"):
+ params["state"] = record["state"]
+ sep = "&" if "?" in record["redirect_uri"] else "?"
+ return JSONResponse(
+ {
+ "status": "approved",
+ "redirect_url": f"{record['redirect_uri']}{sep}{urlencode(params)}",
+ },
+ headers={"Cache-Control": "no-store"},
+ )
+
+
+# ---------------------------------------------------------------------------
+# POST /api/v1/auth/oauth-verify (authenticated; binds caller identity)
+# ---------------------------------------------------------------------------
+
+
+class OAuthVerifyRequest(BaseModel):
+ code: str = Field(..., description="The 6-character display code from the authorize page")
+ decision: str = Field(
+ default="approve",
+ description="'approve' to authorize the client, 'deny' to reject",
+ )
+
+
+class OAuthVerifyResponse(BaseModel):
+ status: str # "approved" | "denied"
+ client_id: Optional[str] = None
+ client_name: Optional[str] = None
+
+
[email protected]("/api/v1/auth/oauth-verify", response_model=OAuthVerifyResponse)
+async def oauth_verify(
+ request: Request,
+ body: OAuthVerifyRequest,
+ ctx: RequestContext = Depends(get_request_context),
+) -> JSONResponse:
+ """Bind the caller's identity to a pending OAuth authorization.
+
+ The user reads a 6-character verification code off the MCP client's
+ authorize page, then submits it here from a session that's already
+ authenticated (typically via the OpenViking console). On approve we
+ write the caller's (account, user, role) into the pending row; the
+ authorize page's polling then catches that and redirects the client
+ back to ``redirect_uri`` with a fresh authorization code.
+ """
+ store, provider = _get_store_and_provider(request)
+
+ # Privilege-elevation gate: an OAuth-issued access token must NOT be
+ # able to mint new OAuth state. Otherwise a stolen short-lived bearer
+ # could launder itself into a fresh 30-day refresh chain whose fp is
+ # bound to the still-valid key. Force this endpoint to require primary
+ # auth (raw API key or console session, both of which set
+ # from_oauth=False).
+ if ctx.from_oauth:
+ raise PermissionDeniedError(
+ "OAuth-issued tokens cannot authorize new OAuth clients. "
+ "Use your API key or sign in to the console to verify."
+ )
+
+ decision = body.decision.lower().strip()
+ if decision not in {"approve", "deny"}:
+ raise InvalidArgumentError("decision must be 'approve' or 'deny'")
+
+ record = await store.find_pending_by_display_code(body.code)
+ if record is None:
+ raise InvalidArgumentError("Invalid or expired verification code")
+
+ if decision == "deny":
+ await store.delete_pending_authorization(record["pending_id"])
+ return JSONResponse({"status": "denied"})
+
+ # Bind the verifier's current API-key fingerprint into the pending row.
+ # The fp is propagated through auth_code → access/refresh tokens, and
+ # every OAuth bearer auth re-checks it against the user's current key.
+ # If the verifier has no resolvable key (ROOT, trusted-mode requester
+ # without a real key), refuse to mint OAuth: there's no key to bind to,
+ # so we cannot honor the "OAuth lifetime ≤ key lifetime" invariant.
+ api_key_manager = getattr(request.app.state, "api_key_manager", None)
+ verifier_fp: Optional[str] = None
+ if api_key_manager is not None and hasattr(api_key_manager, "get_user_key_fingerprint"):
+ verifier_fp = api_key_manager.get_user_key_fingerprint(
+ ctx.user.account_id, ctx.user.user_id
+ )
+ if not verifier_fp:
+ raise InvalidArgumentError(
+ "OAuth authorization requires a verifier with a registered API key "
+ "(ROOT or trusted-mode identities cannot authorize OAuth clients)."
+ )
+
+ ok = await store.mark_pending_verified(
+ pending_id=record["pending_id"],
+ account_id=ctx.user.account_id,
+ user_id=ctx.user.user_id,
+ role=ctx.role.value,
+ verified_key_fp=verifier_fp,
+ )
+ if not ok:
+ raise InvalidArgumentError("Verification raced — please restart from the authorize page")
+
+ client = await provider.get_client(record["client_id"])
+ return JSONResponse(
+ {
+ "status": "approved",
+ "client_id": record["client_id"],
+ "client_name": client.client_name if client else None,
+ }
+ )
+
+
+# ---------------------------------------------------------------------------
+# POST /api/v1/auth/otp
+# ---------------------------------------------------------------------------
+
+
+class OTPRequest(BaseModel):
+ ttl_seconds: Optional[int] = Field(
+ default=None, ge=60, le=600, description="Override OTP lifetime (60-600 seconds)"
+ )
+
+
+class OTPResponse(BaseModel):
+ otp: str
+ expires_at: int
+ ttl_seconds: int
+
+
[email protected]("/api/v1/auth/otp", response_model=OTPResponse)
+async def issue_otp(
+ request: Request,
+ body: Optional[OTPRequest] = None,
+ ctx: RequestContext = Depends(get_request_context),
+) -> JSONResponse:
+ """Issue a one-time passcode bound to the caller's identity.
+
+ The caller must already be authenticated with an API key (or other
+ bearer accepted by ``resolve_identity``); the resulting OTP carries
+ that account / user / role triple, so any OAuth client that submits
+ the OTP on the authorize page is granted that identity.
+ """
+ store, provider = _get_store_and_provider(request)
+
+ # Same gate as oauth_verify: an OAuth-issued bearer cannot mint a new
+ # OTP and re-launch the authorization flow. See router note on
+ # /api/v1/auth/oauth-verify.
+ if ctx.from_oauth:
+ raise PermissionDeniedError(
+ "OAuth-issued tokens cannot issue OTPs. Use your API key or sign in to the console."
+ )
+
+ cfg = getattr(request.app.state, "oauth_config", None)
+ default_ttl = getattr(cfg, "otp_ttl_seconds", 300) if cfg else 300
+ ttl = body.ttl_seconds if body and body.ttl_seconds else default_ttl
+ if ttl < 60 or ttl > 600:
+ raise InvalidArgumentError("ttl_seconds must be between 60 and 600")
+
+ # See oauth_verify for the rationale: an OTP that can't be tied back to
+ # a real, current API key cannot uphold the lifecycle-binding invariant.
+ api_key_manager = getattr(request.app.state, "api_key_manager", None)
+ caller_fp: Optional[str] = None
+ if api_key_manager is not None and hasattr(api_key_manager, "get_user_key_fingerprint"):
+ caller_fp = api_key_manager.get_user_key_fingerprint(ctx.user.account_id, ctx.user.user_id)
+ if not caller_fp:
+ raise InvalidArgumentError(
+ "OTP issuance requires a caller with a registered API key "
+ "(ROOT or trusted-mode identities cannot issue OAuth OTPs)."
+ )
+
+ otp = generate_otp()
+ expires_at = await store.insert_otp(
+ otp_plain=otp,
+ account_id=ctx.user.account_id,
+ user_id=ctx.user.user_id,
+ role=ctx.role.value,
+ authorizing_key_fp=caller_fp,
+ ttl_seconds=ttl,
+ )
+ return JSONResponse(
+ {"otp": otp, "expires_at": expires_at, "ttl_seconds": ttl},
+ headers={"Cache-Control": "no-store"},
+ )
diff --git a/openviking/server/oauth/storage.py b/openviking/server/oauth/storage.py
new file mode 100644
index 000000000..30e09f715
--- /dev/null
+++ b/openviking/server/oauth/storage.py
@@ -0,0 +1,855 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""SQLite-backed OAuth state storage.
+
+Holds three tables — DCR clients, short-lived codes (auth codes + OTPs share
+this table, distinguished by ``kind``), and refresh tokens. Uses stdlib
+``sqlite3`` wrapped in ``asyncio.to_thread`` for async ergonomics; Phase 1
+QPS doesn't justify the new ``aiosqlite`` dependency.
+
+Concurrency: a single ``sqlite3.Connection`` is shared across worker threads
+(``check_same_thread=False``). Every DB access — both reads and writes —
+serializes through ``self._lock``, because the stdlib connection's cursor
+state is not safe for concurrent use across threads. With ``isolation_level=
+None`` each statement is autocommitted, so the lock granularity is per-call.
+
+Atomicity guarantee: one-shot consumption (OTP / auth code / refresh) is done
+via a single ``UPDATE ... WHERE used = 0 RETURNING ...`` so that two concurrent
+consumers cannot both succeed — the loser sees zero rows and is rejected.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import secrets
+import sqlite3
+import time
+from pathlib import Path
+from typing import Any, Iterable, Optional
+
+from openviking.server.oauth.otp import hash_secret
+
+logger = logging.getLogger(__name__)
+
+
+_SCHEMA = """
+CREATE TABLE IF NOT EXISTS oauth_clients (
+ client_id TEXT PRIMARY KEY,
+ client_secret_hash TEXT,
+ redirect_uris TEXT NOT NULL, -- JSON array
+ token_endpoint_auth_method TEXT NOT NULL DEFAULT 'none',
+ grant_types TEXT NOT NULL DEFAULT '["authorization_code","refresh_token"]',
+ response_types TEXT NOT NULL DEFAULT '["code"]',
+ client_name TEXT,
+ created_at INTEGER NOT NULL
+);
+
+CREATE TABLE IF NOT EXISTS oauth_codes (
+ code_hash TEXT PRIMARY KEY,
+ kind TEXT NOT NULL CHECK (kind IN ('otp', 'code')),
+ client_id TEXT,
+ redirect_uri TEXT,
+ code_challenge TEXT,
+ code_challenge_method TEXT,
+ scope TEXT,
+ resource TEXT,
+ account_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ -- SHA-256 hex of the API key value that authorized this row. Recorded at
+ -- OTP issuance / oauth-verify time and copied forward into refresh/access
+ -- so that key rotation or deletion invalidates every derived OAuth token.
+ -- Nullable only for backwards compat with rows written before this field
+ -- existed; auth path treats NULL as fail-closed.
+ authorizing_key_fp TEXT,
+ expires_at INTEGER NOT NULL,
+ used INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_oauth_codes_expires ON oauth_codes(expires_at);
+CREATE INDEX IF NOT EXISTS idx_oauth_codes_user ON oauth_codes(account_id, user_id);
+
+CREATE TABLE IF NOT EXISTS oauth_refresh_tokens (
+ token_hash TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ account_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ scope TEXT,
+ resource TEXT,
+ authorizing_key_fp TEXT, -- see oauth_codes for semantics
+ expires_at INTEGER NOT NULL,
+ consumed INTEGER NOT NULL DEFAULT 0,
+ replaced_by TEXT,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_oauth_refresh_expires ON oauth_refresh_tokens(expires_at);
+CREATE INDEX IF NOT EXISTS idx_oauth_refresh_user ON oauth_refresh_tokens(account_id, user_id);
+
+CREATE TABLE IF NOT EXISTS oauth_pending_authorizations (
+ pending_id TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ redirect_uri TEXT NOT NULL,
+ redirect_uri_provided_explicitly INTEGER NOT NULL,
+ code_challenge TEXT NOT NULL,
+ scopes TEXT,
+ resource TEXT,
+ state TEXT,
+ display_code TEXT NOT NULL DEFAULT '',
+ verified INTEGER NOT NULL DEFAULT 0,
+ verified_account_id TEXT,
+ verified_user_id TEXT,
+ verified_role TEXT,
+ -- Recorded at oauth-verify time from the verifier's API key; copied
+ -- into the auth code on mint, then into refresh/access on exchange.
+ verified_key_fp TEXT,
+ expires_at INTEGER NOT NULL,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_oauth_pending_expires ON oauth_pending_authorizations(expires_at);
+CREATE INDEX IF NOT EXISTS idx_oauth_pending_display ON oauth_pending_authorizations(display_code);
+
+CREATE TABLE IF NOT EXISTS oauth_access_tokens (
+ token_hash TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ account_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ scope TEXT,
+ resource TEXT,
+ authorizing_key_fp TEXT, -- see oauth_codes for semantics
+ expires_at INTEGER NOT NULL,
+ revoked INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_oauth_access_expires ON oauth_access_tokens(expires_at);
+CREATE INDEX IF NOT EXISTS idx_oauth_access_user ON oauth_access_tokens(account_id, user_id);
+"""
+
+
+def _row_to_dict(cursor: sqlite3.Cursor, row: tuple) -> dict[str, Any]:
+ return {col[0]: row[idx] for idx, col in enumerate(cursor.description)}
+
+
+class OAuthStore:
+ """Async wrapper around a single sqlite3 connection (WAL mode)."""
+
+ def __init__(self, db_path: Path) -> None:
+ self._db_path = Path(db_path)
+ self._conn: Optional[sqlite3.Connection] = None
+ self._lock = asyncio.Lock()
+
+ async def initialize(self) -> None:
+ await asyncio.to_thread(self._initialize_sync)
+
+ def _initialize_sync(self) -> None:
+ self._db_path.parent.mkdir(parents=True, exist_ok=True)
+ conn = sqlite3.connect(
+ self._db_path,
+ isolation_level=None, # autocommit; we manage transactions explicitly
+ check_same_thread=False,
+ )
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA synchronous=NORMAL")
+ conn.execute("PRAGMA foreign_keys=ON")
+ conn.executescript(_SCHEMA)
+ self._migrate(conn)
+ self._conn = conn
+
+ def _migrate(self, conn: sqlite3.Connection) -> None:
+ """Idempotent column additions for dev DBs that predate a field.
+
+ ``CREATE TABLE IF NOT EXISTS`` does not retrofit columns onto an
+ existing table, so for any field added after the original schema we
+ ALTER TABLE ADD COLUMN guarded by a ``PRAGMA table_info`` check.
+ """
+ column_additions = (
+ ("oauth_codes", "authorizing_key_fp", "TEXT"),
+ ("oauth_pending_authorizations", "verified_key_fp", "TEXT"),
+ ("oauth_refresh_tokens", "authorizing_key_fp", "TEXT"),
+ ("oauth_access_tokens", "authorizing_key_fp", "TEXT"),
+ )
+ for table, column, decl in column_additions:
+ cur = conn.execute(f"PRAGMA table_info({table})")
+ existing = {row[1] for row in cur.fetchall()}
+ if column not in existing:
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {decl}")
+
+ async def close(self) -> None:
+ await asyncio.to_thread(self._close_sync)
+
+ def _close_sync(self) -> None:
+ if self._conn is not None:
+ self._conn.close()
+ self._conn = None
+
+ # ---- DCR ----
+
+ async def register_client(
+ self,
+ *,
+ client_id: Optional[str] = None,
+ redirect_uris: list[str],
+ client_name: Optional[str] = None,
+ token_endpoint_auth_method: str = "none",
+ grant_types: Optional[list[str]] = None,
+ response_types: Optional[list[str]] = None,
+ client_secret: Optional[str] = None,
+ ) -> dict[str, Any]:
+ """Persist a freshly registered client and return the public record.
+
+ ``client_id`` may be supplied by the caller (e.g. the MCP SDK's
+ RegistrationHandler generates one via uuid4); otherwise we mint a
+ URL-safe random ID for in-process callers.
+ """
+ if not redirect_uris:
+ raise ValueError("redirect_uris must be non-empty")
+ if client_id is None:
+ client_id = secrets.token_urlsafe(16)
+ secret_hash = hash_secret(client_secret) if client_secret else None
+ now = int(time.time())
+ record = {
+ "client_id": client_id,
+ "client_secret_hash": secret_hash,
+ "redirect_uris": list(redirect_uris),
+ "token_endpoint_auth_method": token_endpoint_auth_method,
+ "grant_types": grant_types or ["authorization_code", "refresh_token"],
+ "response_types": response_types or ["code"],
+ "client_name": client_name,
+ "created_at": now,
+ }
+
+ def _insert() -> None:
+ assert self._conn is not None
+ self._conn.execute(
+ "INSERT INTO oauth_clients "
+ "(client_id, client_secret_hash, redirect_uris, "
+ "token_endpoint_auth_method, grant_types, response_types, "
+ "client_name, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ record["client_id"],
+ record["client_secret_hash"],
+ json.dumps(record["redirect_uris"]),
+ record["token_endpoint_auth_method"],
+ json.dumps(record["grant_types"]),
+ json.dumps(record["response_types"]),
+ record["client_name"],
+ record["created_at"],
+ ),
+ )
+
+ async with self._lock:
+ await asyncio.to_thread(_insert)
+ return record
+
+ async def get_client(self, client_id: str) -> Optional[dict[str, Any]]:
+ def _query() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "SELECT * FROM oauth_clients WHERE client_id = ?", (client_id,)
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ record = _row_to_dict(cur, row)
+ record["redirect_uris"] = json.loads(record["redirect_uris"])
+ record["grant_types"] = json.loads(record["grant_types"])
+ record["response_types"] = json.loads(record["response_types"])
+ return record
+
+ async with self._lock:
+ return await asyncio.to_thread(_query)
+
+ # ---- OTPs ----
+
+ async def insert_otp(
+ self,
+ *,
+ otp_plain: str,
+ account_id: str,
+ user_id: str,
+ role: str,
+ authorizing_key_fp: str,
+ ttl_seconds: int,
+ ) -> int:
+ """Insert an OTP row and return its expires_at timestamp.
+
+ ``authorizing_key_fp`` is the SHA-256 fingerprint of the API key the
+ caller presented when requesting the OTP. It is propagated forward to
+ any auth code / access / refresh token derived from this OTP so that
+ rotating or removing the key invalidates the entire downstream chain.
+ """
+ now = int(time.time())
+ expires_at = now + ttl_seconds
+
+ def _insert() -> None:
+ assert self._conn is not None
+ self._conn.execute(
+ "INSERT INTO oauth_codes "
+ "(code_hash, kind, account_id, user_id, role, "
+ "authorizing_key_fp, expires_at, created_at) "
+ "VALUES (?, 'otp', ?, ?, ?, ?, ?, ?)",
+ (
+ hash_secret(otp_plain),
+ account_id,
+ user_id,
+ role,
+ authorizing_key_fp,
+ expires_at,
+ now,
+ ),
+ )
+
+ async with self._lock:
+ await asyncio.to_thread(_insert)
+ return expires_at
+
+ async def consume_otp(self, otp_plain: str) -> Optional[dict[str, Any]]:
+ """Atomically mark an OTP used and return its identity claims, or None."""
+ return await self._atomic_consume_code(otp_plain, expected_kind="otp")
+
+ # ---- Auth codes ----
+
+ async def insert_auth_code(
+ self,
+ *,
+ code_plain: str,
+ client_id: str,
+ redirect_uri: str,
+ code_challenge: str,
+ code_challenge_method: str,
+ scope: Optional[str],
+ resource: Optional[str],
+ account_id: str,
+ user_id: str,
+ role: str,
+ authorizing_key_fp: str,
+ ttl_seconds: int,
+ ) -> int:
+ now = int(time.time())
+ expires_at = now + ttl_seconds
+
+ def _insert() -> None:
+ assert self._conn is not None
+ self._conn.execute(
+ "INSERT INTO oauth_codes "
+ "(code_hash, kind, client_id, redirect_uri, code_challenge, "
+ "code_challenge_method, scope, resource, account_id, user_id, "
+ "role, authorizing_key_fp, expires_at, created_at) "
+ "VALUES (?, 'code', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ hash_secret(code_plain),
+ client_id,
+ redirect_uri,
+ code_challenge,
+ code_challenge_method,
+ scope,
+ resource,
+ account_id,
+ user_id,
+ role,
+ authorizing_key_fp,
+ expires_at,
+ now,
+ ),
+ )
+
+ async with self._lock:
+ await asyncio.to_thread(_insert)
+ return expires_at
+
+ async def consume_auth_code(self, code_plain: str) -> Optional[dict[str, Any]]:
+ return await self._atomic_consume_code(code_plain, expected_kind="code")
+
+ async def peek_auth_code(self, code_plain: str) -> Optional[dict[str, Any]]:
+ """Non-destructive lookup of an unused, unexpired auth code.
+
+ Used by the SDK to inspect the code (e.g. read code_challenge for PKCE)
+ before deciding whether to exchange. Pairs with ``consume_auth_code``,
+ which is the only one-shot operation.
+ """
+ return await self._peek_code(code_plain, expected_kind="code")
+
+ async def _peek_code(self, plain: str, *, expected_kind: str) -> Optional[dict[str, Any]]:
+ code_hash = hash_secret(plain)
+ now = int(time.time())
+
+ def _q() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "SELECT client_id, redirect_uri, code_challenge, "
+ "code_challenge_method, scope, resource, account_id, user_id, role, "
+ "authorizing_key_fp, expires_at, created_at FROM oauth_codes "
+ "WHERE code_hash = ? AND kind = ? AND used = 0 AND expires_at > ?",
+ (code_hash, expected_kind, now),
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ return _row_to_dict(cur, row)
+
+ async with self._lock:
+ return await asyncio.to_thread(_q)
+
+ async def _atomic_consume_code(
+ self, plain: str, *, expected_kind: str
+ ) -> Optional[dict[str, Any]]:
+ code_hash = hash_secret(plain)
+ now = int(time.time())
+
+ def _consume() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "UPDATE oauth_codes SET used = 1 "
+ "WHERE code_hash = ? AND kind = ? AND used = 0 AND expires_at > ? "
+ "RETURNING client_id, redirect_uri, code_challenge, "
+ "code_challenge_method, scope, resource, account_id, user_id, role, "
+ "authorizing_key_fp, expires_at, created_at",
+ (code_hash, expected_kind, now),
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ return _row_to_dict(cur, row)
+
+ async with self._lock:
+ return await asyncio.to_thread(_consume)
+
+ # ---- Refresh tokens ----
+
+ async def insert_refresh(
+ self,
+ *,
+ token_plain: str,
+ client_id: str,
+ account_id: str,
+ user_id: str,
+ role: str,
+ scope: Optional[str],
+ resource: Optional[str],
+ authorizing_key_fp: str,
+ ttl_seconds: int,
+ ) -> int:
+ now = int(time.time())
+ expires_at = now + ttl_seconds
+
+ def _insert() -> None:
+ assert self._conn is not None
+ self._conn.execute(
+ "INSERT INTO oauth_refresh_tokens "
+ "(token_hash, client_id, account_id, user_id, role, scope, "
+ "resource, authorizing_key_fp, expires_at, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ hash_secret(token_plain),
+ client_id,
+ account_id,
+ user_id,
+ role,
+ scope,
+ resource,
+ authorizing_key_fp,
+ expires_at,
+ now,
+ ),
+ )
+
+ async with self._lock:
+ await asyncio.to_thread(_insert)
+ return expires_at
+
+ async def peek_refresh(self, token_plain: str) -> Optional[dict[str, Any]]:
+ """Non-destructive lookup of a still-active refresh token."""
+ token_hash = hash_secret(token_plain)
+ now = int(time.time())
+
+ def _q() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "SELECT client_id, account_id, user_id, role, scope, resource, "
+ "authorizing_key_fp, expires_at, created_at FROM oauth_refresh_tokens "
+ "WHERE token_hash = ? AND consumed = 0 AND expires_at > ?",
+ (token_hash, now),
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ return _row_to_dict(cur, row)
+
+ async with self._lock:
+ return await asyncio.to_thread(_q)
+
+ async def consume_refresh(
+ self,
+ *,
+ token_plain: str,
+ replaced_by_plain: Optional[str],
+ ) -> Optional[dict[str, Any]]:
+ """Mark refresh token consumed (and link to its replacement) atomically.
+
+ Returns the original token's identity/scope claims, or None if the
+ token is unknown/expired/already consumed. Reuse detection: callers
+ that get None for a previously-known token MUST call ``revoke_chain``
+ to invalidate the entire family — see RFC 9700 §4.14.
+ """
+ token_hash = hash_secret(token_plain)
+ replaced_hash = hash_secret(replaced_by_plain) if replaced_by_plain else None
+ now = int(time.time())
+
+ def _consume() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "UPDATE oauth_refresh_tokens SET consumed = 1, replaced_by = ? "
+ "WHERE token_hash = ? AND consumed = 0 AND expires_at > ? "
+ "RETURNING client_id, account_id, user_id, role, scope, resource, "
+ "authorizing_key_fp, expires_at, created_at",
+ (replaced_hash, token_hash, now),
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ return _row_to_dict(cur, row)
+
+ async with self._lock:
+ return await asyncio.to_thread(_consume)
+
+ async def is_refresh_known_but_consumed(self, token_plain: str) -> bool:
+ """Return True if the token exists and has already been consumed (replay)."""
+ token_hash = hash_secret(token_plain)
+
+ def _q() -> bool:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "SELECT consumed FROM oauth_refresh_tokens WHERE token_hash = ?",
+ (token_hash,),
+ )
+ row = cur.fetchone()
+ return bool(row and row[0])
+
+ async with self._lock:
+ return await asyncio.to_thread(_q)
+
+ async def revoke_chain(self, *, client_id: str, account_id: str, user_id: str) -> int:
+ """Revoke every refresh token for (client, account, user). Returns count."""
+
+ def _revoke() -> int:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "UPDATE oauth_refresh_tokens SET consumed = 1 "
+ "WHERE client_id = ? AND account_id = ? AND user_id = ? AND consumed = 0",
+ (client_id, account_id, user_id),
+ )
+ return cur.rowcount
+
+ async with self._lock:
+ return await asyncio.to_thread(_revoke)
+
+ # ---- Access tokens ----
+
+ async def insert_access(
+ self,
+ *,
+ token_plain: str,
+ client_id: str,
+ account_id: str,
+ user_id: str,
+ role: str,
+ scope: Optional[str],
+ resource: Optional[str],
+ authorizing_key_fp: str,
+ ttl_seconds: int,
+ ) -> int:
+ now = int(time.time())
+ expires_at = now + ttl_seconds
+
+ def _insert() -> None:
+ assert self._conn is not None
+ self._conn.execute(
+ "INSERT INTO oauth_access_tokens "
+ "(token_hash, client_id, account_id, user_id, role, scope, "
+ "resource, authorizing_key_fp, expires_at, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ hash_secret(token_plain),
+ client_id,
+ account_id,
+ user_id,
+ role,
+ scope,
+ resource,
+ authorizing_key_fp,
+ expires_at,
+ now,
+ ),
+ )
+
+ async with self._lock:
+ await asyncio.to_thread(_insert)
+ return expires_at
+
+ async def load_access(self, token_plain: str) -> Optional[dict[str, Any]]:
+ """Return the access token's claims dict, or None if invalid/expired/revoked."""
+ token_hash = hash_secret(token_plain)
+ now = int(time.time())
+
+ def _q() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "SELECT client_id, account_id, user_id, role, scope, resource, "
+ "authorizing_key_fp, expires_at, created_at FROM oauth_access_tokens "
+ "WHERE token_hash = ? AND revoked = 0 AND expires_at > ?",
+ (token_hash, now),
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ return _row_to_dict(cur, row)
+
+ async with self._lock:
+ return await asyncio.to_thread(_q)
+
+ async def revoke_access(self, token_plain: str) -> bool:
+ token_hash = hash_secret(token_plain)
+
+ def _revoke() -> bool:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "UPDATE oauth_access_tokens SET revoked = 1 WHERE token_hash = ? AND revoked = 0",
+ (token_hash,),
+ )
+ return cur.rowcount > 0
+
+ async with self._lock:
+ return await asyncio.to_thread(_revoke)
+
+ async def revoke_user_tokens(self, *, account_id: str, user_id: str) -> dict[str, int]:
+ """Revoke all access + refresh tokens for a (account, user) pair.
+
+ Used when an API key for that user is rotated / deleted: every OAuth
+ token derived from that user identity gets invalidated. Auth codes
+ and OTPs for the same user are also wiped to prevent in-flight
+ completion of an exchange started before the revocation.
+ """
+
+ def _revoke() -> dict[str, int]:
+ assert self._conn is not None
+ access = self._conn.execute(
+ "UPDATE oauth_access_tokens SET revoked = 1 "
+ "WHERE account_id = ? AND user_id = ? AND revoked = 0",
+ (account_id, user_id),
+ ).rowcount
+ refresh = self._conn.execute(
+ "UPDATE oauth_refresh_tokens SET consumed = 1 "
+ "WHERE account_id = ? AND user_id = ? AND consumed = 0",
+ (account_id, user_id),
+ ).rowcount
+ codes = self._conn.execute(
+ "UPDATE oauth_codes SET used = 1 WHERE account_id = ? AND user_id = ? AND used = 0",
+ (account_id, user_id),
+ ).rowcount
+ return {
+ "access_tokens_revoked": access,
+ "refresh_tokens_revoked": refresh,
+ "codes_revoked": codes,
+ }
+
+ async with self._lock:
+ return await asyncio.to_thread(_revoke)
+
+ # ---- Pending authorizations (carry OAuth params across the OTP page) ----
+
+ async def create_pending_authorization(
+ self,
+ *,
+ client_id: str,
+ redirect_uri: str,
+ redirect_uri_provided_explicitly: bool,
+ code_challenge: str,
+ scopes: Optional[list[str]],
+ resource: Optional[str],
+ state: Optional[str],
+ display_code: str,
+ ttl_seconds: int = 600,
+ ) -> str:
+ """Stash the AuthorizationParams under a fresh pending_id and return it.
+
+ ``display_code`` is the human-readable verification code that will be
+ shown on the authorize page; the user re-types it into the console
+ verify form and the server resolves the pending row by it.
+ """
+ pending_id = secrets.token_urlsafe(16)
+ now = int(time.time())
+
+ def _insert() -> None:
+ assert self._conn is not None
+ self._conn.execute(
+ "INSERT INTO oauth_pending_authorizations "
+ "(pending_id, client_id, redirect_uri, redirect_uri_provided_explicitly, "
+ "code_challenge, scopes, resource, state, display_code, expires_at, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ pending_id,
+ client_id,
+ redirect_uri,
+ int(redirect_uri_provided_explicitly),
+ code_challenge,
+ json.dumps(scopes) if scopes else None,
+ resource,
+ state,
+ display_code,
+ now + ttl_seconds,
+ now,
+ ),
+ )
+
+ async with self._lock:
+ await asyncio.to_thread(_insert)
+ return pending_id
+
+ async def load_pending_authorization(self, pending_id: str) -> Optional[dict[str, Any]]:
+ now = int(time.time())
+
+ def _q() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "SELECT * FROM oauth_pending_authorizations "
+ "WHERE pending_id = ? AND expires_at > ?",
+ (pending_id, now),
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ record = _row_to_dict(cur, row)
+ record["redirect_uri_provided_explicitly"] = bool(
+ record["redirect_uri_provided_explicitly"]
+ )
+ record["verified"] = bool(record.get("verified", 0))
+ record["scopes"] = json.loads(record["scopes"]) if record["scopes"] else None
+ return record
+
+ async with self._lock:
+ return await asyncio.to_thread(_q)
+
+ async def find_pending_by_display_code(self, display_code: str) -> Optional[dict[str, Any]]:
+ """Return the pending row whose display_code matches, or None."""
+ if not display_code:
+ return None
+ normalized = display_code.strip().upper()
+ now = int(time.time())
+
+ def _q() -> Optional[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "SELECT * FROM oauth_pending_authorizations "
+ "WHERE display_code = ? AND expires_at > ? AND verified = 0",
+ (normalized, now),
+ )
+ row = cur.fetchone()
+ if row is None:
+ return None
+ record = _row_to_dict(cur, row)
+ record["redirect_uri_provided_explicitly"] = bool(
+ record["redirect_uri_provided_explicitly"]
+ )
+ record["verified"] = bool(record.get("verified", 0))
+ record["scopes"] = json.loads(record["scopes"]) if record["scopes"] else None
+ return record
+
+ async with self._lock:
+ return await asyncio.to_thread(_q)
+
+ async def mark_pending_verified(
+ self,
+ *,
+ pending_id: str,
+ account_id: str,
+ user_id: str,
+ role: str,
+ verified_key_fp: str,
+ ) -> bool:
+ """Atomically mark a pending authorization as verified and bind identity.
+
+ ``verified_key_fp`` is the SHA-256 fingerprint of the API key behind
+ the verifying request — every OAuth token derived from this pending
+ row inherits it for lifecycle binding.
+
+ Returns True on success, False if the row is missing, expired, or
+ already verified (one-shot).
+ """
+ now = int(time.time())
+
+ def _u() -> bool:
+ assert self._conn is not None
+ cur = self._conn.execute(
+ "UPDATE oauth_pending_authorizations SET verified = 1, "
+ "verified_account_id = ?, verified_user_id = ?, verified_role = ?, "
+ "verified_key_fp = ? "
+ "WHERE pending_id = ? AND verified = 0 AND expires_at > ?",
+ (account_id, user_id, role, verified_key_fp, pending_id, now),
+ )
+ return cur.rowcount > 0
+
+ async with self._lock:
+ return await asyncio.to_thread(_u)
+
+ async def delete_pending_authorization(self, pending_id: str) -> None:
+ def _del() -> None:
+ assert self._conn is not None
+ self._conn.execute(
+ "DELETE FROM oauth_pending_authorizations WHERE pending_id = ?",
+ (pending_id,),
+ )
+
+ async with self._lock:
+ await asyncio.to_thread(_del)
+
+ # ---- Maintenance ----
+
+ async def gc_expired(self) -> dict[str, int]:
+ now = int(time.time())
+
+ def _gc() -> dict[str, int]:
+ assert self._conn is not None
+ codes = self._conn.execute(
+ "DELETE FROM oauth_codes WHERE expires_at < ? OR used = 1", (now,)
+ ).rowcount
+ # Refresh tombstones (consumed=1) are KEPT until the row's natural
+ # expires_at. Replay detection (RFC 9700 §4.14) depends on being
+ # able to distinguish "I've seen this token, it was consumed" from
+ # "never seen this token" — deleting tombstones early collapses
+ # those two cases and silently breaks family revocation. Storage
+ # cost is bounded by the refresh TTL (default 30d).
+ refreshes = self._conn.execute(
+ "DELETE FROM oauth_refresh_tokens WHERE expires_at < ?",
+ (now,),
+ ).rowcount
+ access = self._conn.execute(
+ "DELETE FROM oauth_access_tokens WHERE expires_at < ? OR revoked = 1",
+ (now,),
+ ).rowcount
+ pending = self._conn.execute(
+ "DELETE FROM oauth_pending_authorizations WHERE expires_at < ?",
+ (now,),
+ ).rowcount
+ return {
+ "codes_deleted": codes,
+ "refresh_tokens_deleted": refreshes,
+ "access_tokens_deleted": access,
+ "pending_authorizations_deleted": pending,
+ }
+
+ async with self._lock:
+ return await asyncio.to_thread(_gc)
+
+ # ---- Test helpers (no-op in production paths) ----
+
+ async def _all_codes_for_test(self) -> Iterable[dict[str, Any]]:
+ def _q() -> list[dict[str, Any]]:
+ assert self._conn is not None
+ cur = self._conn.execute("SELECT * FROM oauth_codes")
+ return [_row_to_dict(cur, r) for r in cur.fetchall()]
+
+ async with self._lock:
+ return await asyncio.to_thread(_q)
diff --git a/openviking_cli/utils/config/oauth_config.py b/openviking_cli/utils/config/oauth_config.py
new file mode 100644
index 000000000..abf8f7974
--- /dev/null
+++ b/openviking_cli/utils/config/oauth_config.py
@@ -0,0 +1,75 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""OAuth 2.1 configuration.
+
+All issued tokens (access, refresh, authorization code, OTP) are opaque random
+strings stored as SHA-256 hashes in ``{workspace}/oauth.db``. Access tokens
+carry an ``ovat_`` prefix used as a fast-path discriminator in the bearer
+auth path.
+"""
+
+from typing import Optional
+
+from pydantic import BaseModel, Field
+
+
+class OAuthConfig(BaseModel):
+ """OAuth 2.1 server configuration.
+
+ OAuth is layered on top of `AuthMode.API_KEY`: when enabled, the existing
+ `Authorization: Bearer <token>` path is augmented with a prefix
+ discriminator (``ovat_``) that resolves OAuth-issued tokens via SQLite
+ lookup to the same `ResolvedIdentity` shape. Disabled by default — turning
+ it on registers `/oauth/*` routes and the well-known metadata endpoints.
+ """
+
+ enabled: bool = Field(
+ default=False,
+ description="Enable OAuth 2.1 endpoints (DCR, authorize, token, well-known metadata).",
+ )
+
+ issuer: Optional[str] = Field(
+ default=None,
+ description=(
+ "Public issuer URL (e.g. 'https://ov.example.com'). Resolution order: the "
+ "OPENVIKING_PUBLIC_BASE_URL environment variable wins; otherwise this field; "
+ "otherwise the request's X-Forwarded-Proto/Host headers; otherwise the Host "
+ "header. Strongly recommended to set one of (env var, this field) when deployed "
+ "behind a reverse proxy or any host other than localhost."
+ ),
+ )
+
+ access_token_ttl_seconds: int = Field(
+ default=3600,
+ ge=60,
+ le=24 * 3600,
+ description="Lifetime of issued opaque access tokens in seconds.",
+ )
+
+ refresh_token_ttl_seconds: int = Field(
+ default=30 * 24 * 3600,
+ ge=3600,
+ le=365 * 24 * 3600,
+ description="Lifetime of refresh tokens in seconds.",
+ )
+
+ auth_code_ttl_seconds: int = Field(
+ default=300,
+ ge=30,
+ le=600,
+ description="Lifetime of authorization codes in seconds (RFC 6749 recommends short).",
+ )
+
+ otp_ttl_seconds: int = Field(
+ default=300,
+ ge=60,
+ le=600,
+ description="Lifetime of one-time passcodes in seconds.",
+ )
+
+ db_filename: str = Field(
+ default="oauth.db",
+ description="SQLite database filename (relative to OpenVikingConfig.storage.workspace).",
+ )
+
+ model_config = {"extra": "forbid"}
diff --git a/openviking_cli/utils/config/open_viking_config.py b/openviking_cli/utils/config/open_viking_config.py
index c8058e056..9ebaa905b 100644
--- a/openviking_cli/utils/config/open_viking_config.py
+++ b/openviking_cli/utils/config/open_viking_config.py
@@ -23,6 +23,7 @@ from .embedding_config import EmbeddingConfig
from .encryption_config import EncryptionConfig
from .log_config import LogConfig
from .memory_config import MemoryConfig
+from .oauth_config import OAuthConfig
from .parser_config import (
AudioConfig,
CodeConfig,
@@ -169,6 +170,11 @@ class OpenVikingConfig(BaseModel):
memory: MemoryConfig = Field(default_factory=MemoryConfig, description="Memory configuration")
+ oauth: OAuthConfig = Field(
+ default_factory=OAuthConfig,
+ description="OAuth 2.1 (MCP) configuration",
+ )
+
telemetry: "TelemetryConfig" = Field(
default_factory=TelemetryConfig, description="Telemetry configuration"
)
diff --git a/tests/server/oauth/__init__.py b/tests/server/oauth/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/server/oauth/test_auth_integration.py b/tests/server/oauth/test_auth_integration.py
new file mode 100644
index 000000000..202ee916d
--- /dev/null
+++ b/tests/server/oauth/test_auth_integration.py
@@ -0,0 +1,363 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Integration tests for the OAuth opaque-token discriminator in auth.py."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+import pytest
+import pytest_asyncio
+from fastapi import FastAPI
+from starlette.requests import Request
+
+from openviking.server.auth import resolve_identity
+from openviking.server.config import ServerConfig
+from openviking.server.identity import Role
+from openviking.server.oauth.provider import (
+ ACCESS_TOKEN_PREFIX,
+ OpenVikingOAuthProvider,
+)
+from openviking.server.oauth.storage import OAuthStore
+from openviking_cli.exceptions import PermissionDeniedError, UnauthenticatedError
+
+
+def _make_request(
+ *,
+ bearer: Optional[str],
+ api_key_manager,
+ oauth_provider: Optional[OpenVikingOAuthProvider],
+ extra_headers: Optional[dict[str, str]] = None,
+ path: str = "/api/v1/system/status",
+) -> Request:
+ raw_headers = []
+ if bearer:
+ raw_headers.append((b"authorization", f"Bearer {bearer}".encode()))
+ for k, v in (extra_headers or {}).items():
+ raw_headers.append((k.lower().encode(), v.encode()))
+ app = FastAPI()
+ app.state.config = ServerConfig(auth_mode="api_key", root_api_key="root-test-1234567890abcd")
+ app.state.api_key_manager = api_key_manager
+ if oauth_provider is not None:
+ app.state.oauth_provider = oauth_provider
+ scope = {
+ "type": "http",
+ "path": path,
+ "query_string": b"",
+ "headers": raw_headers,
+ "app": app,
+ }
+ return Request(scope)
+
+
+_TEST_FP = "f" * 64 # stand-in sha256 fingerprint shared across tests
+
+
+class _StubKeyManager:
+ """API-key manager that asserts when reached unexpectedly.
+
+ Tests for the OAuth path want to assert API-key fallback is *not* taken;
+ backwards-compat tests flip ``raise_on_resolve`` to False.
+
+ ``fingerprints`` maps (account_id, user_id) → fp. Defaults to a permissive
+ map that returns ``_TEST_FP`` for any user, so existing tests don't have
+ to know about the binding. Tests that exercise rotation / deletion pass
+ a sparser map.
+ """
+
+ def __init__(
+ self,
+ raise_on_resolve: bool = True,
+ fingerprints: Optional[dict[tuple[str, str], str]] = None,
+ default_fingerprint: Optional[str] = _TEST_FP,
+ roles: Optional[dict[tuple[str, str], Role]] = None,
+ default_role: Role = Role.USER,
+ ):
+ self._raise = raise_on_resolve
+ self._fps = fingerprints
+ self._default_fp = default_fingerprint
+ self._roles = roles
+ self._default_role = default_role
+
+ def resolve(self, key: str): # noqa: D401
+ if self._raise:
+ raise AssertionError(f"API-key path should not be reached for {key!r}")
+ from openviking.server.identity import ResolvedIdentity
+
+ return ResolvedIdentity(role=Role.USER, account_id="api-acct", user_id="api-user")
+
+ def get_account_policy(self, account_id):
+ from openviking.server.identity import AccountNamespacePolicy
+
+ return AccountNamespacePolicy()
+
+ def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:
+ if self._fps is None:
+ return self._default_fp
+ return self._fps.get((account_id, user_id))
+
+ def get_user_role(self, account_id: str, user_id: str) -> Role:
+ if self._roles is None:
+ return self._default_role
+ return self._roles.get((account_id, user_id), self._default_role)
+
+
+@pytest_asyncio.fixture
+async def store(tmp_path):
+ s = OAuthStore(tmp_path / "oauth.db")
+ await s.initialize()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+@pytest_asyncio.fixture
+async def provider(store):
+ return OpenVikingOAuthProvider(store=store, issuer="https://ov.test")
+
+
+async def _mint_token(provider: OpenVikingOAuthProvider, store: OAuthStore, **identity) -> str:
+ """Helper: directly insert an access token bound to the given identity."""
+ token = provider._mint_access()
+ await store.insert_access(
+ token_plain=token,
+ client_id="test-client",
+ account_id=identity["account_id"],
+ user_id=identity["user_id"],
+ role=identity["role"],
+ scope=identity.get("scope"),
+ resource=identity.get("resource"),
+ authorizing_key_fp=identity.get("authorizing_key_fp", _TEST_FP),
+ ttl_seconds=3600,
+ )
+ return token
+
+
+async def test_oauth_token_resolves_to_bound_identity(provider, store):
+ token = await _mint_token(provider, store, account_id="tenant-a", user_id="alice", role="user")
+ request = _make_request(
+ bearer=token,
+ api_key_manager=_StubKeyManager(),
+ oauth_provider=provider,
+ )
+ identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
+ assert identity.role == Role.USER
+ assert identity.account_id == "tenant-a"
+ assert identity.user_id == "alice"
+ assert identity.from_oauth is True
+
+
+async def test_unknown_oauth_token_fails_closed(provider):
+ """A bearer with the OAuth prefix but unknown to the store must NOT fall back to API key."""
+ bogus = ACCESS_TOKEN_PREFIX + "not-a-real-token"
+ request = _make_request(
+ bearer=bogus,
+ api_key_manager=_StubKeyManager(raise_on_resolve=True),
+ oauth_provider=provider,
+ )
+ with pytest.raises(UnauthenticatedError, match="OAuth access token"):
+ await resolve_identity(request, x_api_key=None, authorization=f"Bearer {bogus}")
+
+
+async def test_revoked_oauth_token_rejected(provider, store):
+ token = await _mint_token(provider, store, account_id="acct", user_id="alice", role="user")
+ await store.revoke_access(token)
+ request = _make_request(
+ bearer=token,
+ api_key_manager=_StubKeyManager(raise_on_resolve=True),
+ oauth_provider=provider,
+ )
+ with pytest.raises(UnauthenticatedError):
+ await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
+
+
+async def test_non_prefixed_bearer_falls_through_to_api_key(provider):
+ """A plain API key (no OAuth prefix) must still resolve via APIKeyManager."""
+ plain_key = "ov_user_NOTAOATAH_abcdefghijklmnop"
+ request = _make_request(
+ bearer=plain_key,
+ api_key_manager=_StubKeyManager(raise_on_resolve=False),
+ oauth_provider=provider,
+ )
+ identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {plain_key}")
+ assert identity.role == Role.USER
+ assert identity.account_id == "api-acct"
+ assert identity.from_oauth is False
+
+
+async def test_oauth_path_skipped_when_disabled(store):
+ """If no oauth_provider on app.state, prefixed tokens go to API-key path."""
+ plain_key = ACCESS_TOKEN_PREFIX + "anything"
+ request = _make_request(
+ bearer=plain_key,
+ api_key_manager=_StubKeyManager(raise_on_resolve=False),
+ oauth_provider=None,
+ )
+ identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {plain_key}")
+ # Falls through to API key; stub returns USER identity.
+ assert identity.from_oauth is False
+
+
+async def test_oauth_user_role_rejects_account_override(provider, store):
+ """A USER OAuth token cannot impersonate another tenant via header."""
+ token = await _mint_token(provider, store, account_id="tenant-a", user_id="alice", role="user")
+ request = _make_request(
+ bearer=token,
+ api_key_manager=_StubKeyManager(),
+ oauth_provider=provider,
+ extra_headers={"x-openviking-account": "tenant-b"},
+ )
+ with pytest.raises(PermissionDeniedError):
+ await resolve_identity(
+ request,
+ x_api_key=None,
+ authorization=f"Bearer {token}",
+ x_openviking_account="tenant-b",
+ )
+
+
+async def test_oauth_root_can_be_used_without_explicit_tenant_headers(provider, store):
+ """ROOT OAuth tokens carry account/user in claims — no header requirement."""
+ token = await _mint_token(provider, store, account_id="tenant-a", user_id="alice", role="root")
+ # Manager must report alice as ROOT so the role-downgrade gate passes.
+ request = _make_request(
+ bearer=token,
+ api_key_manager=_StubKeyManager(default_role=Role.ROOT),
+ oauth_provider=provider,
+ )
+ identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
+ assert identity.role == Role.ROOT
+ assert identity.from_oauth is True
+
+
+# ---------------------------------------------------------------------------
+# Lifecycle binding: OAuth lifetime ≤ authorizing key lifetime.
+# ---------------------------------------------------------------------------
+
+
+async def test_oauth_token_rejected_when_authorizing_key_rotated(provider, store):
+ """Rotating the user's API key must invalidate every derived OAuth token."""
+ token = await _mint_token(
+ provider,
+ store,
+ account_id="tenant-a",
+ user_id="alice",
+ role="user",
+ authorizing_key_fp=_TEST_FP,
+ )
+ # Simulate rotation: the manager now reports a different fingerprint.
+ rotated_manager = _StubKeyManager(
+ raise_on_resolve=True,
+ fingerprints={("tenant-a", "alice"): "9" * 64},
+ )
+ request = _make_request(
+ bearer=token,
+ api_key_manager=rotated_manager,
+ oauth_provider=provider,
+ )
+ with pytest.raises(UnauthenticatedError, match="rotated or revoked"):
+ await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
+
+
+async def test_oauth_token_rejected_when_authorizing_user_removed(provider, store):
+ """Removing the user (fp lookup → None) invalidates the token."""
+ token = await _mint_token(
+ provider,
+ store,
+ account_id="tenant-a",
+ user_id="alice",
+ role="user",
+ authorizing_key_fp=_TEST_FP,
+ )
+ # Sparse map ⇒ no fp for (tenant-a, alice) ⇒ user is gone.
+ removed_manager = _StubKeyManager(raise_on_resolve=True, fingerprints={})
+ request = _make_request(
+ bearer=token,
+ api_key_manager=removed_manager,
+ oauth_provider=provider,
+ )
+ with pytest.raises(UnauthenticatedError, match="rotated or revoked"):
+ await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
+
+
+async def test_oauth_token_rejected_after_role_downgrade(provider, store):
+ """set_role demotion must invalidate OAuth tokens whose embedded role
+ outranks the user's current role — fp alone won't catch this because
+ the key value is unchanged."""
+ token = await _mint_token(
+ provider,
+ store,
+ account_id="tenant-a",
+ user_id="alice",
+ role="admin", # token issued when alice was admin
+ authorizing_key_fp=_TEST_FP,
+ )
+ # Manager now reports alice as USER (post-set_role demotion).
+ demoted_manager = _StubKeyManager(
+ raise_on_resolve=True,
+ roles={("tenant-a", "alice"): Role.USER},
+ )
+ request = _make_request(
+ bearer=token,
+ api_key_manager=demoted_manager,
+ oauth_provider=provider,
+ )
+ with pytest.raises(UnauthenticatedError, match="exceeds the user's current role"):
+ await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
+
+
+async def test_oauth_token_survives_role_promotion(provider, store):
+ """Promotion (current role > token role) is harmless — token's lower
+ privilege is still authorized. Only downgrades trigger rejection."""
+ token = await _mint_token(
+ provider,
+ store,
+ account_id="tenant-a",
+ user_id="alice",
+ role="user",
+ authorizing_key_fp=_TEST_FP,
+ )
+ promoted_manager = _StubKeyManager(
+ raise_on_resolve=True,
+ roles={("tenant-a", "alice"): Role.ADMIN},
+ )
+ request = _make_request(
+ bearer=token,
+ api_key_manager=promoted_manager,
+ oauth_provider=provider,
+ )
+ identity = await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
+ # Token's USER role is preserved — promotion doesn't auto-elevate.
+ assert identity.role == Role.USER
+
+
+async def test_oauth_token_without_recorded_fp_fails_closed(provider, store):
+ """Tokens missing a recorded fingerprint (legacy / stub) must NOT validate."""
+ token = await _mint_token(
+ provider,
+ store,
+ account_id="tenant-a",
+ user_id="alice",
+ role="user",
+ authorizing_key_fp="", # writes empty fp into the row
+ )
+ request = _make_request(
+ bearer=token,
+ api_key_manager=_StubKeyManager(raise_on_resolve=True),
+ oauth_provider=provider,
+ )
+ with pytest.raises(UnauthenticatedError, match="rotated or revoked"):
+ await resolve_identity(request, x_api_key=None, authorization=f"Bearer {token}")
diff --git a/tests/server/oauth/test_mcp_www_authenticate.py b/tests/server/oauth/test_mcp_www_authenticate.py
new file mode 100644
index 000000000..4bb52b9b8
--- /dev/null
+++ b/tests/server/oauth/test_mcp_www_authenticate.py
@@ -0,0 +1,96 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Tests for the WWW-Authenticate hint emitted by the MCP middleware on 401.
+
+Ensures Claude.ai / Claude Desktop can auto-discover the OAuth authorization
+server per RFC 9728 §5.1.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from openviking.server.config import ServerConfig
+from openviking.server.mcp_endpoint import _IdentityASGIMiddleware
+from openviking.server.oauth.provider import OpenVikingOAuthProvider
+from openviking.server.oauth.storage import OAuthStore
+
+
+async def _noop_app(scope, receive, send):
+ """Minimal downstream ASGI app that asserts the middleware never reaches it."""
+ raise AssertionError("Downstream app should not be called for unauthenticated requests")
+
+
+def _build_test_app(*, oauth_enabled: bool, tmp_path=None) -> FastAPI:
+ app = FastAPI()
+ app.state.config = ServerConfig(auth_mode="api_key", root_api_key="root-test-1234567890abcd")
+ app.state.api_key_manager = object() # presence triggers API_KEY auth path
+ if oauth_enabled:
+ # Provider just needs to exist on app.state to flag oauth as enabled —
+ # the bearer middleware emits WWW-Authenticate based on its presence,
+ # not on any specific verifier behavior.
+ app.state.oauth_provider = OpenVikingOAuthProvider(
+ store=OAuthStore(tmp_path / "oauth.db") if tmp_path else None,
+ issuer="http://ov.test",
+ )
+ return app
+
+
+def _mount_mcp(app: FastAPI) -> None:
+ """Mount a tiny ASGI route at /mcp wrapped in _IdentityASGIMiddleware."""
+ from starlette.routing import Route
+
+ handler = _IdentityASGIMiddleware(_noop_app)
+ app.routes.append(Route("/mcp", endpoint=handler, methods=["GET", "POST"]))
+
+
+async def test_unauthenticated_request_includes_www_authenticate_when_oauth_enabled():
+ app = _build_test_app(oauth_enabled=True)
+ _mount_mcp(app)
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ resp = await client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "ping"})
+ assert resp.status_code == 401
+ auth_header = resp.headers.get("www-authenticate", "")
+ assert auth_header.startswith("Bearer "), auth_header
+ assert "resource_metadata=" in auth_header
+ assert "/.well-known/oauth-protected-resource" in auth_header
+ # The origin is derived from the request Host header.
+ assert "ov.test" in auth_header
+
+
+async def test_unauthenticated_request_omits_header_when_oauth_disabled():
+ """If OAuth is not configured, the 401 body still appears but the hint is absent."""
+ app = _build_test_app(oauth_enabled=False)
+ _mount_mcp(app)
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ resp = await client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "ping"})
+ assert resp.status_code == 401
+ assert "www-authenticate" not in {k.lower() for k in resp.headers.keys()}
+
+
+async def test_www_authenticate_honors_x_forwarded_proto():
+ app = _build_test_app(oauth_enabled=True)
+ _mount_mcp(app)
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ resp = await client.post(
+ "/mcp",
+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
+ headers={
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-Host": "public.example.com",
+ },
+ )
+ assert resp.status_code == 401
+ auth_header = resp.headers.get("www-authenticate", "")
+ assert "https://public.example.com/.well-known/oauth-protected-resource" in auth_header
diff --git a/tests/server/oauth/test_router.py b/tests/server/oauth/test_router.py
new file mode 100644
index 000000000..35d54ce49
--- /dev/null
+++ b/tests/server/oauth/test_router.py
@@ -0,0 +1,609 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""End-to-end tests for the OAuth flow: DCR → OTP → authorize page → token → /mcp.
+
+The flow is:
+
+1. Caller registers a client (SDK's RegistrationHandler).
+2. Caller, holding a valid API key, requests an OTP from /api/v1/auth/otp.
+3. Caller hits /authorize, which redirects to /oauth/authorize/page?pending=...
+4. Caller submits the OTP on the authorize page; we 302 back to redirect_uri
+ with a fresh ?code=...
+5. Caller exchanges the code at /token (PKCE S256) for an opaque access+refresh.
+6. Access token is opaque ovat_-prefixed and resolves through auth.py.
+"""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import secrets
+from dataclasses import dataclass
+from typing import Optional
+
+import httpx
+import pytest
+import pytest_asyncio
+from fastapi import FastAPI
+from fastapi.responses import JSONResponse
+from mcp.server.auth.routes import create_auth_routes
+from mcp.server.auth.settings import ClientRegistrationOptions, RevocationOptions
+from pydantic import AnyHttpUrl
+
+from openviking.server.auth import get_request_context
+from openviking.server.config import ServerConfig
+from openviking.server.identity import Role
+from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS
+from openviking.server.oauth.provider import OpenVikingOAuthProvider
+from openviking.server.oauth.router import router as oauth_router
+from openviking.server.oauth.storage import OAuthStore
+from openviking_cli.exceptions import OpenVikingError
+
+
+class _FpOnlyKeyManager:
+ """Minimal stand-in: returns SHA-256 fingerprints for known (account, user) pairs.
+
+ Router code only touches ``get_user_key_fingerprint`` on this object; the
+ full APIKeyManager surface is irrelevant for OAuth flow tests because
+ ``get_request_context`` is dependency-overridden to a fixed identity.
+ """
+
+ def __init__(self, fingerprints: dict[tuple[str, str], str]):
+ self._fps = fingerprints
+
+ def get_user_key_fingerprint(self, account_id: str, user_id: str) -> Optional[str]:
+ return self._fps.get((account_id, user_id))
+
+
+@dataclass
+class _StubOAuthCfg:
+ # Leave issuer unset so _public_origin falls through to the
+ # request's X-Forwarded-*/Host headers — that path is what we want
+ # to exercise in PRM tests. Tests that need a fixed issuer can set it
+ # directly on the fixture's app.state.oauth_config.
+ issuer: Optional[str] = None
+ access_token_ttl_seconds: int = 3600
+ refresh_token_ttl_seconds: int = 86400
+ auth_code_ttl_seconds: int = 300
+ otp_ttl_seconds: int = 300
+
+
+@pytest_asyncio.fixture
+async def app_with_oauth(tmp_path):
+ """FastAPI app wired with the SDK auth routes + OpenViking authorize page."""
+ store = OAuthStore(tmp_path / "oauth.db")
+ await store.initialize()
+ issuer = "http://127.0.0.1"
+ provider = OpenVikingOAuthProvider(store=store, issuer=issuer)
+
+ app = FastAPI()
+ app.state.config = ServerConfig(auth_mode="api_key", root_api_key="root-test-1234567890abcd")
+ # OTP / oauth-verify routes look up the caller's API key fingerprint via
+ # ``api_key_manager.get_user_key_fingerprint(account_id, user_id)`` and
+ # refuse to issue OAuth state if the call returns None. Provide a tiny
+ # stub that returns a stable fingerprint for the fixture's identity.
+ app.state.api_key_manager = _FpOnlyKeyManager({("acct1", "alice"): "f" * 64})
+ app.state.oauth_store = store
+ app.state.oauth_provider = provider
+ app.state.oauth_config = _StubOAuthCfg()
+
+ @app.exception_handler(OpenVikingError)
+ async def _err(request, exc): # noqa: ANN001
+ return JSONResponse(
+ {"error": exc.code, "error_description": exc.message},
+ status_code=ERROR_CODE_TO_HTTP_STATUS.get(exc.code, 500),
+ )
+
+ # Override get_request_context so /api/v1/auth/otp can be hit without
+ # a real APIKeyManager. Returns a fixed identity.
+ from openviking.server.identity import RequestContext
+ from openviking_cli.session.user_id import UserIdentifier
+
+ def _fixed_ctx() -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("acct1", "alice", "default"),
+ role=Role.USER,
+ )
+
+ app.dependency_overrides[get_request_context] = _fixed_ctx
+ app.include_router(oauth_router)
+
+ sdk_routes = create_auth_routes(
+ provider=provider,
+ issuer_url=AnyHttpUrl(issuer),
+ client_registration_options=ClientRegistrationOptions(enabled=True),
+ revocation_options=RevocationOptions(enabled=True),
+ )
+ app.routes.extend(sdk_routes)
+
+ try:
+ yield app, store, provider
+ finally:
+ await store.close()
+
+
+@pytest_asyncio.fixture
+async def client(app_with_oauth):
+ app, _, _ = app_with_oauth
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://127.0.0.1") as c:
+ yield c
+
+
+def _pkce_pair() -> tuple[str, str]:
+ verifier = secrets.token_urlsafe(64)[:64]
+ digest = hashlib.sha256(verifier.encode()).digest()
+ challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
+ return verifier, challenge
+
+
+# ---------------------------------------------------------------------------
+# DCR + metadata
+# ---------------------------------------------------------------------------
+
+
+async def test_metadata_endpoint(client):
+ resp = await client.get("/.well-known/oauth-authorization-server")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["issuer"].rstrip("/") == "http://127.0.0.1"
+ assert "S256" in body["code_challenge_methods_supported"]
+ assert "authorization_code" in body["grant_types_supported"]
+ assert "refresh_token" in body["grant_types_supported"]
+ assert body["registration_endpoint"]
+
+
+async def test_protected_resource_metadata(client):
+ resp = await client.get("/.well-known/oauth-protected-resource")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["resource"].endswith("/mcp")
+ assert body["authorization_servers"]
+ assert "header" in body["bearer_methods_supported"]
+ # Must be cacheable.
+ assert "max-age" in resp.headers.get("cache-control", "")
+
+
+async def test_protected_resource_metadata_honors_x_forwarded(client):
+ resp = await client.get(
+ "/.well-known/oauth-protected-resource",
+ headers={"X-Forwarded-Proto": "https", "X-Forwarded-Host": "public.example"},
+ )
+ body = resp.json()
+ assert body["resource"] == "https://public.example/mcp"
+
+
+async def test_protected_resource_metadata_honors_public_base_url_env(client, monkeypatch):
+ """OPENVIKING_PUBLIC_BASE_URL must override X-Forwarded-* and Host header."""
+ monkeypatch.setenv("OPENVIKING_PUBLIC_BASE_URL", "https://override.example")
+ resp = await client.get(
+ "/.well-known/oauth-protected-resource",
+ headers={"X-Forwarded-Proto": "http", "X-Forwarded-Host": "ignored.example"},
+ )
+ body = resp.json()
+ assert body["resource"] == "https://override.example/mcp"
+ assert body["authorization_servers"][0].rstrip("/") == "https://override.example"
+
+
+async def test_dcr_registers_client(client):
+ # OpenViking only accepts public clients (PKCE). Real MCP clients
+ # always send "none" — the SDK's OAuth 2.0 default is client_secret_post,
+ # which we deliberately reject (see test_dcr_rejects_confidential_auth_methods).
+ resp = await client.post(
+ "/register",
+ json={
+ "redirect_uris": ["https://claude.ai/cb"],
+ "client_name": "Claude",
+ "token_endpoint_auth_method": "none",
+ },
+ )
+ assert resp.status_code == 201, resp.text
+ body = resp.json()
+ assert body["client_id"]
+ assert body["redirect_uris"] == ["https://claude.ai/cb"]
+
+
+# ---------------------------------------------------------------------------
+# OTP issuance
+# ---------------------------------------------------------------------------
+
+
+async def test_otp_endpoint_returns_code(client):
+ resp = await client.post("/api/v1/auth/otp", json={})
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert len(body["otp"]) == 6
+ assert body["ttl_seconds"] == 300
+ assert body["expires_at"] > 0
+
+
+async def test_otp_endpoint_rejects_bad_ttl(client):
+ resp = await client.post("/api/v1/auth/otp", json={"ttl_seconds": 5})
+ assert resp.status_code in (400, 422)
+
+
+# ---------------------------------------------------------------------------
+# Authorize page + OTP submit + token exchange (full happy path)
+# ---------------------------------------------------------------------------
+
+
+async def _start_authorize(client, *, redirect_uri="https://claude.ai/cb", state=None):
+ """Helper: register a client, kick off /authorize, return (client_id, pending_id, page_url, verifier)."""
+ reg = await client.post(
+ "/register",
+ json={
+ "redirect_uris": [redirect_uri],
+ "client_name": "Claude",
+ "token_endpoint_auth_method": "none",
+ },
+ )
+ assert reg.status_code == 201, reg.text
+ client_id = reg.json()["client_id"]
+ verifier, challenge = _pkce_pair()
+ params = {
+ "client_id": client_id,
+ "response_type": "code",
+ "redirect_uri": redirect_uri,
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ }
+ if state:
+ params["state"] = state
+ authorize = await client.get("/authorize", params=params, follow_redirects=False)
+ assert authorize.status_code == 302, authorize.text
+ page_url = authorize.headers["location"]
+ pending_id = page_url.split("pending=")[1].split("&")[0]
+ return client_id, pending_id, page_url, verifier
+
+
+async def test_full_device_flow(app_with_oauth, client):
+ """End-to-end: authorize → page shows display_code → console verifies →
+ page polls status → 302 → token exchange → access_token resolves."""
+ _, store, provider = app_with_oauth
+
+ client_id, pending_id, page_url, verifier = await _start_authorize(
+ client, redirect_uri="https://claude.ai/cb", state="xyz"
+ )
+
+ # Page renders with the display_code visible.
+ page_resp = await client.get(page_url)
+ assert page_resp.status_code == 200
+ assert "Authorize" in page_resp.text
+ pending_record = await store.load_pending_authorization(pending_id)
+ assert pending_record is not None
+ display_code = pending_record["display_code"]
+ assert display_code in page_resp.text
+
+ # Status before verify: pending.
+ pre = await client.get("/oauth/authorize/page/status", params={"pending": pending_id})
+ assert pre.status_code == 200
+ assert pre.json()["status"] == "pending"
+
+ # User confirms in console (auth identity comes from get_request_context override).
+ verify = await client.post(
+ "/api/v1/auth/oauth-verify",
+ json={"code": display_code, "decision": "approve"},
+ )
+ assert verify.status_code == 200, verify.text
+ body = verify.json()
+ assert body["status"] == "approved"
+ assert body["client_id"] == client_id
+ assert body["client_name"] == "Claude"
+
+ # Status after verify: approved + redirect_url with code/state.
+ post = await client.get("/oauth/authorize/page/status", params={"pending": pending_id})
+ assert post.status_code == 200
+ body = post.json()
+ assert body["status"] == "approved"
+ redirect_url = body["redirect_url"]
+ assert redirect_url.startswith("https://claude.ai/cb?")
+ assert "code=" in redirect_url
+ assert "state=xyz" in redirect_url
+
+ # Polling again after pending row was consumed: gone (410).
+ again = await client.get("/oauth/authorize/page/status", params={"pending": pending_id})
+ assert again.status_code == 410
+
+ # Token exchange.
+ auth_code = redirect_url.split("code=")[1].split("&")[0]
+ token_resp = await client.post(
+ "/token",
+ data={
+ "grant_type": "authorization_code",
+ "code": auth_code,
+ "redirect_uri": "https://claude.ai/cb",
+ "client_id": client_id,
+ "code_verifier": verifier,
+ },
+ )
+ assert token_resp.status_code == 200, token_resp.text
+ tokens = token_resp.json()
+ assert tokens["access_token"].startswith("ovat_")
+ assert tokens["refresh_token"].startswith("ovrt_")
+
+ # Access token resolves to the verified identity (acct1/alice/user from fixture).
+ record = await provider.load_access_token(tokens["access_token"])
+ assert record is not None
+ assert record.account_id == "acct1"
+ assert record.user_id == "alice"
+ assert record.role == "user"
+
+
+async def test_oauth_verify_unknown_code(app_with_oauth, client):
+ _, _, _ = app_with_oauth
+ resp = await client.post(
+ "/api/v1/auth/oauth-verify",
+ json={"code": "BOGUS1", "decision": "approve"},
+ )
+ assert resp.status_code == 400
+ body = resp.json()
+ assert "Invalid" in body.get("error_description", "") or "Invalid" in body.get("message", "")
+
+
+async def test_oauth_verify_deny_destroys_pending(app_with_oauth, client):
+ _, store, _ = app_with_oauth
+ _, pending_id, _, _ = await _start_authorize(client, redirect_uri="https://x.test/cb")
+ record = await store.load_pending_authorization(pending_id)
+ code = record["display_code"]
+
+ resp = await client.post(
+ "/api/v1/auth/oauth-verify",
+ json={"code": code, "decision": "deny"},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "denied"
+ # Pending row gone — page polling now returns 410.
+ status = await client.get("/oauth/authorize/page/status", params={"pending": pending_id})
+ assert status.status_code == 410
+
+
+async def test_status_unknown_pending_returns_410(client):
+ resp = await client.get("/oauth/authorize/page/status", params={"pending": "doesnotexist"})
+ assert resp.status_code == 410
+
+
+async def test_oauth_verify_idempotency(app_with_oauth, client):
+ """A second verify with the same code must fail — pending is one-shot."""
+ _, store, _ = app_with_oauth
+ _, pending_id, _, _ = await _start_authorize(client)
+ record = await store.load_pending_authorization(pending_id)
+ code = record["display_code"]
+
+ first = await client.post(
+ "/api/v1/auth/oauth-verify", json={"code": code, "decision": "approve"}
+ )
+ assert first.status_code == 200
+ second = await client.post(
+ "/api/v1/auth/oauth-verify", json={"code": code, "decision": "approve"}
+ )
+ # The pending row's verified flag now blocks find_pending_by_display_code.
+ assert second.status_code == 400
+
+
+async def test_refresh_token_rotation(app_with_oauth, client):
+ _, store, _ = app_with_oauth
+ client_id, pending_id, _, verifier = await _start_authorize(
+ client, redirect_uri="https://x.test/cb"
+ )
+ code = (await store.load_pending_authorization(pending_id))["display_code"]
+
+ await client.post("/api/v1/auth/oauth-verify", json={"code": code, "decision": "approve"})
+ status = await client.get("/oauth/authorize/page/status", params={"pending": pending_id})
+ auth_code = status.json()["redirect_url"].split("code=")[1].split("&")[0]
+ token_resp = await client.post(
+ "/token",
+ data={
+ "grant_type": "authorization_code",
+ "code": auth_code,
+ "redirect_uri": "https://x.test/cb",
+ "client_id": client_id,
+ "code_verifier": verifier,
+ },
+ )
+ rt1 = token_resp.json()["refresh_token"]
+ at1 = token_resp.json()["access_token"]
+
+ rotated = await client.post(
+ "/token",
+ data={"grant_type": "refresh_token", "refresh_token": rt1, "client_id": client_id},
+ )
+ assert rotated.status_code == 200
+ rt2 = rotated.json()["refresh_token"]
+ at2 = rotated.json()["access_token"]
+ assert rt2 != rt1 and at2 != at1
+
+ # Replay rejected.
+ replay = await client.post(
+ "/token",
+ data={"grant_type": "refresh_token", "refresh_token": rt1, "client_id": client_id},
+ )
+ assert replay.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# Authorizing-key fingerprint binding (router level).
+# ---------------------------------------------------------------------------
+
+
+async def test_otp_endpoint_rejects_caller_without_fingerprint(app_with_oauth, client):
+ """If the API-key manager has no fingerprint for the caller (e.g. ROOT or
+ trusted-mode identity), OTP issuance must refuse — there's no key whose
+ lifetime we could bind the resulting OAuth tokens to."""
+ app, _, _ = app_with_oauth
+ # Swap in an empty fingerprint map so get_user_key_fingerprint returns None
+ # for the fixture's (acct1, alice) identity.
+ app.state.api_key_manager = _FpOnlyKeyManager({})
+ resp = await client.post("/api/v1/auth/otp", json={})
+ assert resp.status_code == 400, resp.text
+ body = resp.json()
+ msg = body.get("error_description") or body.get("message") or ""
+ assert "registered API key" in msg
+
+
+async def test_oauth_verify_rejects_verifier_without_fingerprint(app_with_oauth, client):
+ """oauth-verify must refuse to bind OAuth state to an identity that has
+ no fingerprint — same invariant as OTP issuance."""
+ app, store, _ = app_with_oauth
+ _, pending_id, _, _ = await _start_authorize(client, redirect_uri="https://x.test/cb")
+ code = (await store.load_pending_authorization(pending_id))["display_code"]
+
+ app.state.api_key_manager = _FpOnlyKeyManager({}) # verifier has no key
+ resp = await client.post(
+ "/api/v1/auth/oauth-verify",
+ json={"code": code, "decision": "approve"},
+ )
+ assert resp.status_code == 400
+ msg = resp.json().get("error_description") or resp.json().get("message") or ""
+ assert "registered API key" in msg
+
+
+async def test_dcr_downgrades_confidential_auth_to_public(app_with_oauth, client):
+ """OpenViking treats every client as public+PKCE. A registrar that asks
+ for client_secret_basic / client_secret_post is silently downgraded to
+ 'none' so that the OAuth 2.0 default (client_secret_basic, which some
+ SDKs fill in unconditionally) does not break compatibility — but the
+ stored record reflects the actual authentication contract.
+ """
+ _, store, _ = app_with_oauth
+ for method in ("client_secret_basic", "client_secret_post"):
+ resp = await client.post(
+ "/register",
+ json={
+ "redirect_uris": ["https://x.test/cb"],
+ "client_name": "Confidential",
+ "token_endpoint_auth_method": method,
+ },
+ )
+ assert resp.status_code == 201, f"{method}: {resp.text}"
+ client_id = resp.json()["client_id"]
+ record = await store.get_client(client_id)
+ # Stored auth method is forced to "none"; client_secret never persisted.
+ assert record["token_endpoint_auth_method"] == "none"
+ assert record.get("client_secret_hash") is None
+
+
+async def test_otp_rejects_oauth_issued_caller(app_with_oauth, client):
+ """A caller authenticated via an OAuth bearer (from_oauth=True) MUST
+ NOT be able to mint new OTPs — that would let a stolen access token
+ launder itself into a fresh refresh-token chain."""
+ app, _, _ = app_with_oauth
+ from openviking.server.identity import RequestContext
+ from openviking_cli.session.user_id import UserIdentifier
+
+ def _oauth_ctx() -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("acct1", "alice", "default"),
+ role=Role.USER,
+ from_oauth=True,
+ )
+
+ app.dependency_overrides[get_request_context] = _oauth_ctx
+ try:
+ resp = await client.post("/api/v1/auth/otp", json={})
+ assert resp.status_code == 403, resp.text
+ msg = resp.json().get("error_description") or resp.json().get("message") or ""
+ assert "OAuth-issued tokens" in msg
+ finally:
+ # Reset to the fixture's default (non-OAuth) ctx for other tests.
+ def _fixed_ctx() -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("acct1", "alice", "default"),
+ role=Role.USER,
+ )
+
+ app.dependency_overrides[get_request_context] = _fixed_ctx
+
+
+async def test_oauth_verify_rejects_oauth_issued_caller(app_with_oauth, client):
+ """Same gate as OTP issuance: oauth-verify with an OAuth-issued ctx
+ must be refused, otherwise short-lived bearers can launder into
+ long-lived refresh tokens."""
+ app, store, _ = app_with_oauth
+ from openviking.server.identity import RequestContext
+ from openviking_cli.session.user_id import UserIdentifier
+
+ _, pending_id, _, _ = await _start_authorize(client, redirect_uri="https://x.test/cb")
+ code = (await store.load_pending_authorization(pending_id))["display_code"]
+
+ def _oauth_ctx() -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("acct1", "alice", "default"),
+ role=Role.USER,
+ from_oauth=True,
+ )
+
+ app.dependency_overrides[get_request_context] = _oauth_ctx
+ try:
+ resp = await client.post(
+ "/api/v1/auth/oauth-verify",
+ json={"code": code, "decision": "approve"},
+ )
+ assert resp.status_code == 403, resp.text
+ msg = resp.json().get("error_description") or resp.json().get("message") or ""
+ assert "OAuth-issued tokens" in msg
+ finally:
+
+ def _fixed_ctx() -> RequestContext:
+ return RequestContext(
+ user=UserIdentifier("acct1", "alice", "default"),
+ role=Role.USER,
+ )
+
+ app.dependency_overrides[get_request_context] = _fixed_ctx
+
+
+async def test_oauth_token_carries_authorizing_key_fp(app_with_oauth, client):
+ """Happy path: every minted token records the verifier's fp; rotation of
+ that fingerprint at the manager level invalidates the token at bearer
+ auth time. Here we just verify the fp is correctly recorded — auth-time
+ rejection has its own coverage in test_auth_integration."""
+ app, store, provider = app_with_oauth
+ expected_fp = "f" * 64
+
+ client_id, pending_id, _, verifier = await _start_authorize(
+ client, redirect_uri="https://x.test/cb"
+ )
+ code = (await store.load_pending_authorization(pending_id))["display_code"]
+
+ await client.post("/api/v1/auth/oauth-verify", json={"code": code, "decision": "approve"})
+ pending = await store.load_pending_authorization(pending_id)
+ # After verify, the pending row carries the verifier's fp.
+ assert pending["verified_key_fp"] == expected_fp
+
+ status = await client.get("/oauth/authorize/page/status", params={"pending": pending_id})
+ auth_code = status.json()["redirect_url"].split("code=")[1].split("&")[0]
+ token_resp = await client.post(
+ "/token",
+ data={
+ "grant_type": "authorization_code",
+ "code": auth_code,
+ "redirect_uri": "https://x.test/cb",
+ "client_id": client_id,
+ "code_verifier": verifier,
+ },
+ )
+ access_token = token_resp.json()["access_token"]
+ record = await provider.load_access_token(access_token)
+ assert record is not None
+ assert record.authorizing_key_fp == expected_fp
+ refresh_record = await store.peek_refresh(token_resp.json()["refresh_token"])
+ assert refresh_record["authorizing_key_fp"] == expected_fp
diff --git a/tests/server/oauth/test_storage.py b/tests/server/oauth/test_storage.py
new file mode 100644
index 000000000..f91947a57
--- /dev/null
+++ b/tests/server/oauth/test_storage.py
@@ -0,0 +1,465 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Tests for openviking/server/oauth/storage.py."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+
+import pytest
+import pytest_asyncio
+
+from openviking.server.oauth.otp import generate_otp, hash_secret
+from openviking.server.oauth.storage import OAuthStore
+
+# Test stand-in for an API key fingerprint. Real fps come from
+# APIKeyManager.get_user_key_fingerprint() — sha256 hex, 64 chars.
+_FP = "a" * 64
+_FP_OTHER = "b" * 64
+
+
+@pytest_asyncio.fixture
+async def store(tmp_path):
+ s = OAuthStore(tmp_path / "oauth.db")
+ await s.initialize()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+async def test_refresh_path_role_downgrade_rejected():
+ """Provider's exchange_refresh_token must refuse to mint new tokens
+ when the user's role has been downgraded since the refresh was issued.
+ Mirrors the bearer-auth role check; covered here because the refresh
+ path lives in provider.py, not in the storage layer."""
+ import tempfile
+ from pathlib import Path
+
+ from mcp.server.auth.provider import TokenError
+ from mcp.shared.auth import OAuthClientInformationFull
+ from pydantic import AnyUrl
+
+ from openviking.server.identity import Role
+ from openviking.server.oauth.provider import OpenVikingOAuthProvider, OVRefreshToken
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ store = OAuthStore(Path(tmpdir) / "oauth.db")
+ await store.initialize()
+ try:
+ # role_resolver reports current role as USER (post-demotion).
+ current_roles = {("acct", "alice"): Role.USER}
+ provider = OpenVikingOAuthProvider(
+ store=store,
+ issuer="https://ov.test",
+ role_resolver=lambda a, u: current_roles.get((a, u), Role.USER),
+ )
+ await store.register_client(
+ client_id="cx",
+ redirect_uris=["https://x.test/cb"],
+ )
+ rt = "rt-admin-era"
+ await store.insert_refresh(
+ token_plain=rt,
+ client_id="cx",
+ account_id="acct",
+ user_id="alice",
+ role="admin", # token issued when alice was admin
+ scope=None,
+ resource=None,
+ authorizing_key_fp="f" * 64,
+ ttl_seconds=86400,
+ )
+ client = OAuthClientInformationFull(
+ client_id="cx",
+ redirect_uris=[AnyUrl("https://x.test/cb")],
+ )
+ refresh_obj = OVRefreshToken(
+ token=rt,
+ client_id="cx",
+ scopes=[],
+ expires_at=None,
+ account_id="acct",
+ user_id="alice",
+ role="admin",
+ resource=None,
+ authorizing_key_fp="f" * 64,
+ )
+ with pytest.raises(TokenError) as exc_info:
+ await provider.exchange_refresh_token(client, refresh_obj, scopes=[])
+ assert exc_info.value.error == "invalid_grant"
+ assert "downgraded" in (exc_info.value.error_description or "")
+ finally:
+ await store.close()
+
+
+async def test_register_and_get_client(store):
+ record = await store.register_client(
+ redirect_uris=["https://claude.ai/api/mcp/auth_callback"],
+ client_name="Claude.ai",
+ )
+ assert record["client_id"]
+ assert record["redirect_uris"] == ["https://claude.ai/api/mcp/auth_callback"]
+ assert record["token_endpoint_auth_method"] == "none"
+ fetched = await store.get_client(record["client_id"])
+ assert fetched is not None
+ assert fetched["redirect_uris"] == ["https://claude.ai/api/mcp/auth_callback"]
+ assert fetched["client_name"] == "Claude.ai"
+ assert "authorization_code" in fetched["grant_types"]
+
+
+async def test_get_client_missing(store):
+ assert await store.get_client("nope") is None
+
+
+async def test_otp_consume_returns_identity(store):
+ otp = generate_otp()
+ await store.insert_otp(
+ otp_plain=otp,
+ account_id="acct1",
+ user_id="user1",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+ claims = await store.consume_otp(otp)
+ assert claims is not None
+ assert claims["account_id"] == "acct1"
+ assert claims["user_id"] == "user1"
+ assert claims["role"] == "user"
+ assert claims["authorizing_key_fp"] == _FP
+
+
+async def test_otp_double_consume_only_one_wins(store):
+ otp = generate_otp()
+ await store.insert_otp(
+ otp_plain=otp,
+ account_id="a",
+ user_id="u",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+ first = await store.consume_otp(otp)
+ second = await store.consume_otp(otp)
+ assert first is not None
+ assert second is None # one-shot
+
+
+async def test_otp_concurrent_consume_race(store):
+ """Two coroutines racing to consume the same OTP — exactly one wins."""
+ otp = generate_otp()
+ await store.insert_otp(
+ otp_plain=otp,
+ account_id="a",
+ user_id="u",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+ results = await asyncio.gather(store.consume_otp(otp), store.consume_otp(otp))
+ winners = [r for r in results if r is not None]
+ assert len(winners) == 1
+
+
+async def test_otp_expired_rejected(store):
+ otp = generate_otp()
+ # ttl=60 but we monkey-patch expiry by inserting and waiting — instead,
+ # directly insert a stale row using a tiny ttl plus manual time travel.
+ await store.insert_otp(
+ otp_plain=otp,
+ account_id="a",
+ user_id="u",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=60,
+ )
+ # Fast path: forge expiry by editing the row to be in the past.
+ assert store._conn is not None
+ store._conn.execute(
+ "UPDATE oauth_codes SET expires_at = ? WHERE used = 0",
+ (int(time.time()) - 10,),
+ )
+ assert await store.consume_otp(otp) is None
+
+
+async def test_consume_unknown_otp_returns_none(store):
+ assert await store.consume_otp("NOTREAL") is None
+
+
+async def test_otp_kind_isolation(store):
+ """An OTP cannot be consumed via the auth-code path or vice versa."""
+ otp = generate_otp()
+ await store.insert_otp(
+ otp_plain=otp,
+ account_id="a",
+ user_id="u",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+ # Trying to consume as auth code must fail (kind mismatch) and leave OTP usable.
+ assert await store.consume_auth_code(otp) is None
+ assert await store.consume_otp(otp) is not None
+
+
+async def test_auth_code_roundtrip(store):
+ code = "code-secret"
+ await store.insert_auth_code(
+ code_plain=code,
+ client_id="client-x",
+ redirect_uri="https://example.com/cb",
+ code_challenge="challenge-xyz",
+ code_challenge_method="S256",
+ scope="mcp",
+ resource="https://example.com/mcp",
+ account_id="a",
+ user_id="u",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+ record = await store.consume_auth_code(code)
+ assert record is not None
+ assert record["client_id"] == "client-x"
+ assert record["redirect_uri"] == "https://example.com/cb"
+ assert record["code_challenge"] == "challenge-xyz"
+ assert record["scope"] == "mcp"
+ assert record["resource"] == "https://example.com/mcp"
+ assert record["authorizing_key_fp"] == _FP
+ # Second consume rejected
+ assert await store.consume_auth_code(code) is None
+
+
+async def test_refresh_token_roundtrip(store):
+ rt = "rt-secret-1"
+ await store.insert_refresh(
+ token_plain=rt,
+ client_id="client-x",
+ account_id="a",
+ user_id="u",
+ role="user",
+ scope="mcp",
+ resource=None,
+ authorizing_key_fp=_FP,
+ ttl_seconds=86400,
+ )
+ record = await store.consume_refresh(token_plain=rt, replaced_by_plain="rt-secret-2")
+ assert record is not None
+ assert record["client_id"] == "client-x"
+ assert record["authorizing_key_fp"] == _FP
+ # Reuse detection: second use returns None but the row is still flagged consumed.
+ assert await store.consume_refresh(token_plain=rt, replaced_by_plain=None) is None
+ assert await store.is_refresh_known_but_consumed(rt) is True
+
+
+async def test_refresh_replay_revokes_chain(store):
+ """Reusing a consumed refresh must allow the caller to revoke the family."""
+ rt1 = "rt-1"
+ rt2 = "rt-2"
+ rt3 = "rt-3"
+ for rt in (rt1, rt2, rt3):
+ await store.insert_refresh(
+ token_plain=rt,
+ client_id="cx",
+ account_id="acct",
+ user_id="user",
+ role="user",
+ scope=None,
+ resource=None,
+ authorizing_key_fp=_FP,
+ ttl_seconds=86400,
+ )
+ # Consume rt1 (rotate to rt2). Then attacker replays rt1.
+ assert await store.consume_refresh(token_plain=rt1, replaced_by_plain=rt2) is not None
+ assert await store.consume_refresh(token_plain=rt1, replaced_by_plain=None) is None
+ # Detection — caller now revokes the chain.
+ revoked = await store.revoke_chain(client_id="cx", account_id="acct", user_id="user")
+ assert revoked >= 2 # rt2 and rt3 still active before revoke
+ # Both rt2 and rt3 must now be unusable.
+ assert await store.consume_refresh(token_plain=rt2, replaced_by_plain=None) is None
+ assert await store.consume_refresh(token_plain=rt3, replaced_by_plain=None) is None
+
+
+async def test_access_token_load_and_revoke(store):
+ token = "at-secret"
+ await store.insert_access(
+ token_plain=token,
+ client_id="cx",
+ account_id="acct",
+ user_id="alice",
+ role="user",
+ scope="mcp",
+ resource="https://ov.test/mcp",
+ authorizing_key_fp=_FP,
+ ttl_seconds=3600,
+ )
+ record = await store.load_access(token)
+ assert record is not None
+ assert record["account_id"] == "acct"
+ assert record["user_id"] == "alice"
+ assert record["scope"] == "mcp"
+ assert record["resource"] == "https://ov.test/mcp"
+ assert record["authorizing_key_fp"] == _FP
+ # Revoke and confirm it's invisible.
+ assert await store.revoke_access(token) is True
+ assert await store.load_access(token) is None
+ # Idempotent revoke.
+ assert await store.revoke_access(token) is False
+
+
+async def test_access_token_expired_invisible(store):
+ token = "at-stale"
+ await store.insert_access(
+ token_plain=token,
+ client_id="cx",
+ account_id="acct",
+ user_id="alice",
+ role="user",
+ scope=None,
+ resource=None,
+ authorizing_key_fp=_FP,
+ ttl_seconds=60,
+ )
+ assert store._conn is not None
+ store._conn.execute(
+ "UPDATE oauth_access_tokens SET expires_at = ? WHERE token_hash = ?",
+ (int(time.time()) - 10, hash_secret(token)),
+ )
+ assert await store.load_access(token) is None
+
+
+async def test_revoke_user_tokens_cascades(store):
+ """Revoking a user wipes their access, refresh, and unused codes."""
+ await store.insert_access(
+ token_plain="at-1",
+ client_id="cx",
+ account_id="acct",
+ user_id="alice",
+ role="user",
+ scope=None,
+ resource=None,
+ authorizing_key_fp=_FP,
+ ttl_seconds=3600,
+ )
+ await store.insert_access(
+ token_plain="at-other",
+ client_id="cx",
+ account_id="acct",
+ user_id="bob", # different user — must NOT be revoked
+ role="user",
+ scope=None,
+ resource=None,
+ authorizing_key_fp=_FP_OTHER,
+ ttl_seconds=3600,
+ )
+ await store.insert_refresh(
+ token_plain="rt-1",
+ client_id="cx",
+ account_id="acct",
+ user_id="alice",
+ role="user",
+ scope=None,
+ resource=None,
+ authorizing_key_fp=_FP,
+ ttl_seconds=3600,
+ )
+ otp = generate_otp()
+ await store.insert_otp(
+ otp_plain=otp,
+ account_id="acct",
+ user_id="alice",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+
+ counts = await store.revoke_user_tokens(account_id="acct", user_id="alice")
+ assert counts["access_tokens_revoked"] == 1
+ assert counts["refresh_tokens_revoked"] == 1
+ assert counts["codes_revoked"] == 1
+
+ # Alice's everything dead, Bob's untouched.
+ assert await store.load_access("at-1") is None
+ assert await store.load_access("at-other") is not None
+ assert await store.consume_otp(otp) is None
+
+
+async def test_gc_keeps_refresh_tombstones_until_natural_expiry(store):
+ """RFC 9700 §4.14 replay detection needs consumed-but-unexpired tombstones
+ to stick around — only after the original expires_at can we GC them."""
+ rt = "rt-tomb"
+ await store.insert_refresh(
+ token_plain=rt,
+ client_id="cx",
+ account_id="acct",
+ user_id="alice",
+ role="user",
+ scope=None,
+ resource=None,
+ authorizing_key_fp=_FP,
+ ttl_seconds=86400, # 1 day, well beyond GC window
+ )
+ # Consume (rotate) — row now has consumed=1 but is still within expires_at.
+ consumed = await store.consume_refresh(token_plain=rt, replaced_by_plain="rt-next")
+ assert consumed is not None
+ # GC must NOT delete the tombstone yet.
+ await store.gc_expired()
+ assert await store.is_refresh_known_but_consumed(rt) is True
+ # Backdate to past expiry — only now should GC reap it.
+ assert store._conn is not None
+ store._conn.execute(
+ "UPDATE oauth_refresh_tokens SET expires_at = ? WHERE token_hash = ?",
+ (int(time.time()) - 10, hash_secret(rt)),
+ )
+ await store.gc_expired()
+ assert await store.is_refresh_known_but_consumed(rt) is False # row truly gone now
+
+
+async def test_gc_expired_removes_stale_rows(store):
+ fresh = generate_otp()
+ stale = generate_otp()
+ await store.insert_otp(
+ otp_plain=fresh,
+ account_id="a",
+ user_id="u",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+ await store.insert_otp(
+ otp_plain=stale,
+ account_id="a",
+ user_id="u",
+ role="user",
+ authorizing_key_fp=_FP,
+ ttl_seconds=300,
+ )
+ # Backdate stale row
+ assert store._conn is not None
+ store._conn.execute(
+ "UPDATE oauth_codes SET expires_at = ? WHERE code_hash = ?",
+ (int(time.time()) - 100, hash_secret(stale)),
+ )
+ deleted = await store.gc_expired()
+ assert deleted["codes_deleted"] >= 1
+ # Fresh row still consumable.
+ assert await store.consume_otp(fresh) is not None
diff --git a/tests/server/test_api_key_manager.py b/tests/server/test_api_key_manager.py
index b86a1fb21..46ff06ee2 100644
--- a/tests/server/test_api_key_manager.py
+++ b/tests/server/test_api_key_manager.py
@@ -178,6 +178,34 @@ async def test_regenerate_key(manager: APIKeyManager):
assert identity.account_id == acct
+async def test_get_user_key_fingerprint_changes_on_rotation(manager: APIKeyManager):
+ """fp must change when the key is regenerated and disappear when user is removed."""
+ acct = _uid()
+ await manager.create_account(acct, "alice")
+ await manager.register_user(acct, "bob", "user")
+
+ fp1 = manager.get_user_key_fingerprint(acct, "bob")
+ assert fp1 is not None
+ assert len(fp1) == 64 # sha256 hex
+
+ # Same call should be deterministic.
+ assert manager.get_user_key_fingerprint(acct, "bob") == fp1
+
+ # Rotation flips the stored value → fp must change.
+ await manager.regenerate_key(acct, "bob")
+ fp2 = manager.get_user_key_fingerprint(acct, "bob")
+ assert fp2 is not None
+ assert fp2 != fp1
+
+ # Removal → no fp at all.
+ await manager.remove_user(acct, "bob")
+ assert manager.get_user_key_fingerprint(acct, "bob") is None
+
+
+async def test_get_user_key_fingerprint_unknown_returns_none(manager: APIKeyManager):
+ assert manager.get_user_key_fingerprint("nope", "nobody") is None
+
+
async def test_set_role(manager: APIKeyManager):
"""set_role should update user's role in both storage and index."""
acct = _uid()