fix(auth): close Anthropic OAuth CSRF gap, cross-process refresh race, and API-key shadowing
Dashboard PKCE login reused the code_verifier as the OAuth state (leaking it and disabling CSRF validation) and never checked state on callback -- the same class of bug already fixed for the CLI flow. Credential-pool refresh excluded "anthropic" from the cross-process lock Codex/xAI already get, so concurrent Hermes processes racing a single-use refresh token could leave the loser stuck exhausted with no recovery for hermes_pkce/dashboard sources. The dashboard OAuth save also never cleared a stale ANTHROPIC_API_KEY, which resolve_anthropic_token() prioritizes over the OAuth pool entry by design -- so a leftover key silently kept billing pay-per-token after a Claude Pro/Max login. A concurrency stress test written to validate the refresh-race fix under load surfaced a fifth, unrelated bug: _auth_store_lock()'s Windows lock-file "ensure content" write was unguarded and could raise an uncaught PermissionError under real contention -- affecting every single-use-token provider sharing that lock, not just Anthropic. Fixes #87887, #87888, #87889.
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
# Anthropic OAuth — Issues encontrados no hermes-agent
|
||||
|
||||
> **Atualização:** todos os 5 bugs abaixo (incluindo o Bug 5, achado pelo teste de esforço) foram **corrigidos** nesta sessão.
|
||||
> Issues: [#87887](https://github.com/NousResearch/hermes-agent/issues/87887) (bugs 1-2) · [#87888](https://github.com/NousResearch/hermes-agent/issues/87888) (bugs 3-4) · [#87889](https://github.com/NousResearch/hermes-agent/issues/87889) (bug 5).
|
||||
|
||||
**Data:** 2026-08-16
|
||||
**Branch:** `fix/update-orphan-history-guard-87694`
|
||||
**Pedido original:** investigar se o OAuth da Anthropic tem bug real — rotas, race conditions, zombie processes, segurança — e provar com testes.
|
||||
|
||||
---
|
||||
|
||||
## TL;DR — o login do Claude Code funciona?
|
||||
|
||||
**Sim, funciona.** Nenhum dos bugs encontrados impede login ou uso normal. São dois problemas distintos, ambos reais e comprovados por teste, mas nenhum é "quebrado/não autentica":
|
||||
|
||||
| Fluxo de login | Afetado por quê |
|
||||
|---|---|
|
||||
| `claude setup-token` (CLI oficial Anthropic, credencial lida de `~/.claude/.credentials.json`, `source="claude_code"`) | Nenhum dos bugs 1-3 — é o único caminho protegido nos dois casos |
|
||||
| `hermes model` no terminal, opção 1 (OAuth via CLI) | Bug de race condition (só sob múltiplos processos Hermes concorrentes); limpa `ANTHROPIC_API_KEY` corretamente, então **não** sofre o Bug 4 |
|
||||
| Login via **dashboard web** do Hermes | Bug de segurança (CSRF/PKCE leak, bugs 1-2) + race condition (bug 3) + **Bug 4: não limpa `ANTHROPIC_API_KEY` antiga, que continua vencendo o OAuth** |
|
||||
|
||||
**Atualização:** o sintoma relatado pelo usuário ("configuro com OAuth e o Hermes usa API key mesmo assim") foi diagnosticado como o **Bug 4** — ver seção dedicada abaixo.
|
||||
|
||||
- **Bug de segurança:** não impede login, mas expõe o fluxo do dashboard a um vetor de CSRF já corrigido no CLI e nunca replicado lá.
|
||||
- **Bug de race condition:** só aparece com **múltiplos processos Hermes rodando ao mesmo tempo** (fleet workers, cron + sessão interativa) disputando o refresh do mesmo token no exato instante em que ele expira. Uso single-process (maioria dos usuários, a maior parte do tempo) nunca bate nisso.
|
||||
|
||||
---
|
||||
|
||||
## O que foi feito nesta investigação
|
||||
|
||||
1. Localizado o código real do fluxo Anthropic (não documentação): `agent/anthropic_adapter.py`, `agent/credential_pool.py`, `hermes_cli/auth.py`, `hermes_cli/auth_commands.py`, `hermes_cli/web_server.py`.
|
||||
2. Comparado o fluxo de login via CLI (`run_hermes_oauth_login_pure`) com o fluxo paralelo do dashboard web (`_start_anthropic_pkce` / `_submit_anthropic_pkce`) — achado o bug de CSRF por essa comparação.
|
||||
3. Comparado a proteção cross-processo que Codex/xAI recebem no refresh (`_auth_store_lock`) com o que a Anthropic recebe — achado o bug de race condition por essa comparação.
|
||||
4. Escritos dois arquivos de teste novos que **provam** os bugs (testes que devem falhar contra o código atual, e falham):
|
||||
- `tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py` (5 testes)
|
||||
- `tests/agent/test_credential_pool_anthropic_refresh_race.py` (3 testes)
|
||||
5. Rodado `pytest` nos dois arquivos: **7 failed, 1 passed** — confirma os bugs objetivamente (não é opinião).
|
||||
6. Investigado zombie process especificamente no fluxo Anthropic — **não encontrado**.
|
||||
7. Nenhum código de produção foi alterado — só testes de regressão + este relatório.
|
||||
|
||||
---
|
||||
|
||||
## Bug 1 — PKCE `code_verifier` vazado como `state` (só no dashboard web)
|
||||
|
||||
**Onde:** `hermes_cli/web_server.py`, função `_start_anthropic_pkce()` (~linha 10637-10661)
|
||||
|
||||
```python
|
||||
verifier, challenge = _generate_pkce_pair()
|
||||
sid, sess = _new_oauth_session("anthropic", "pkce", profile=profile)
|
||||
sess["verifier"] = verifier
|
||||
sess["state"] = verifier # Anthropic round-trips verifier as state
|
||||
params = {
|
||||
...
|
||||
"code_challenge": challenge,
|
||||
"code_challenge_method": "S256",
|
||||
"state": verifier,
|
||||
}
|
||||
```
|
||||
|
||||
Isso é **exatamente** o bug que já existiu no fluxo de CLI e foi corrigido (histórico documentado em `tests/agent/test_anthropic_oauth_pkce.py`: PR #1775 corrigiu → PR #2647 reintroduziu → PR #3107 removeu a função antiga → PR #10699/issue #10693 corrigiu de vez na função sobrevivente). O CLI (`agent/anthropic_adapter.py::run_hermes_oauth_login_pure`) gera um `state` independente (`secrets.token_urlsafe(32)`). O **dashboard web nunca recebeu essa correção** — é uma implementação paralela que reintroduz o problema numa rota diferente.
|
||||
|
||||
**Consequência:** o `code_verifier` (que por RFC 7636 §7.2 deve ficar confidencial) vaza via histórico do navegador, cabeçalho `Referer`, e logs de acesso da Anthropic (`platform.claude.com`).
|
||||
|
||||
**Evidência (teste real rodado):**
|
||||
```
|
||||
assert 'dg7ihLbmv6ooNu2-V_dKcVPKp29kNJewr4s8UBSr1gE' != 'dg7ihLbmv6ooNu2-V_dKcVPKp29kNJewr4s8UBSr1gE'
|
||||
```
|
||||
state e verifier são literalmente o mesmo valor.
|
||||
|
||||
**Status:** ✅ **corrigido** — `_start_anthropic_pkce()` agora gera `state` independente via `secrets.token_urlsafe(32)`.
|
||||
|
||||
---
|
||||
|
||||
## Bug 2 — Callback do dashboard nunca valida o `state` (zero proteção CSRF)
|
||||
|
||||
**Onde:** `hermes_cli/web_server.py`, função `_submit_anthropic_pkce()` (~linha 10664-10692)
|
||||
|
||||
```python
|
||||
state_from_callback = parts[1] if len(parts) > 1 else ""
|
||||
exchange_data = json.dumps({
|
||||
...
|
||||
"state": state_from_callback or sess["state"], # nunca comparado com nada
|
||||
...
|
||||
}).encode()
|
||||
```
|
||||
|
||||
O código nunca faz `if state_from_callback != sess["state"]: reject`. Qualquer valor (ou nenhum) é aceito e a troca de token prossegue. O CLI faz essa checagem (`if received_state != oauth_state: abort`); o dashboard não faz nenhuma.
|
||||
|
||||
**Evidência (teste real rodado):** payload POST real capturado mesmo com `state` adulterado (`attacker-controlled-state`) — a troca de token aconteceu do mesmo jeito.
|
||||
|
||||
**Status:** ✅ **corrigido** — `_submit_anthropic_pkce()` agora rejeita a troca de token quando o `state` não bate.
|
||||
|
||||
---
|
||||
|
||||
## Bug 3 — Refresh de token sem lock cross-processo (race condition)
|
||||
|
||||
**Onde:** `agent/credential_pool.py`, `CredentialPool._refresh_entry()` (~linha 1307-1344)
|
||||
|
||||
```python
|
||||
# Codex and xAI OAuth refresh tokens are single-use. [...]
|
||||
# Serialize the whole sequence through the shared cross-process auth-store flock
|
||||
if self.provider in ("openai-codex", "xai-oauth"):
|
||||
with _auth_store_lock(...):
|
||||
...
|
||||
return self._refresh_entry_impl(entry, force=force) # anthropic cai aqui, SEM lock
|
||||
```
|
||||
|
||||
`"anthropic"` não está na lista protegida, apesar de o refresh token da Anthropic também ser single-use (documentado no próprio `agent/anthropic_adapter.py::_refresh_oauth_token`: "a successful refresh rotates the pair and invalidates the old refresh token").
|
||||
|
||||
O único caminho de recuperação em caso de falha (`_sync_anthropic_entry_from_credentials_file`, linha 855-905) só funciona se `entry.source == "claude_code"`:
|
||||
```python
|
||||
if self.provider != "anthropic" or entry.source != "claude_code":
|
||||
return entry
|
||||
```
|
||||
Credenciais de login nativo do Hermes (`hermes_pkce`) ou do dashboard (`manual:dashboard_pkce`) **não têm recuperação nenhuma**. Se perdem a corrida, caem em `self._mark_exhausted(entry, None)` (linha 1705) — mesmo com um token válido existindo em disco, escrito pelo processo que ganhou.
|
||||
|
||||
**Cenário real (não ataque, uso normal):** dois processos Hermes concorrentes (ex: fleet worker + sessão CLI, ou dois cron jobs) compartilhando a mesma conta Anthropic via login nativo. Token expira; ambos tentam refresh ao mesmo tempo; servidor da Anthropic aceita só o primeiro; o segundo recebe `invalid_grant` e fica marcado como exhausted — pedindo reautenticação mesmo com credencial válida disponível.
|
||||
|
||||
**Evidência (teste real rodado, com servidor OAuth fake simulando single-use de verdade):**
|
||||
```
|
||||
FAILED test_anthropic_refresh_is_not_protected_by_cross_process_lock
|
||||
assert [] # _auth_store_lock nunca foi chamado para 'anthropic'
|
||||
|
||||
FAILED test_concurrent_hermes_pkce_refresh_loses_credential_despite_valid_token_on_disk
|
||||
assert None is not None # processo perdedor não conseguiu recuperar
|
||||
|
||||
PASSED test_concurrent_claude_code_refresh_recovers_via_credentials_file
|
||||
# contraste: fonte 'claude_code' SE recupera — prova a assimetria
|
||||
```
|
||||
|
||||
**Status:** ✅ **corrigido**. `"anthropic"` foi incluído na tupla protegida por `_auth_store_lock`, e um novo método `_sync_anthropic_entry_from_pool_store()` (espelhando o padrão já usado pelo xAI) resincroniza a partir do próprio credential-pool store — funciona pra **todas** as fontes (`claude_code`, `hermes_pkce`, `manual:dashboard_pkce`), não só `claude_code`.
|
||||
|
||||
---
|
||||
|
||||
## Bug 4 — API key antiga vence sobre OAuth (causa do "não funciona" relatado)
|
||||
|
||||
**Sintoma relatado pelo usuário:** faz o setup com OAuth da Anthropic e seleciona os modelos, mas o Hermes acaba usando modo API key (pay-per-token) em vez do plano OAuth (Claude Pro/Max).
|
||||
|
||||
**Onde:** `agent/anthropic_adapter.py::resolve_anthropic_token()` (~linha 1387-1442)
|
||||
|
||||
Ordem de prioridade na resolução de credencial:
|
||||
|
||||
```
|
||||
1. ANTHROPIC_TOKEN (OAuth salvo pelo Hermes via CLI)
|
||||
2. CLAUDE_CODE_OAUTH_TOKEN
|
||||
3. ANTHROPIC_API_KEY <- API key explícita, sempre vence, por design
|
||||
4. ~/.claude/.credentials.json (Claude Code CLI)
|
||||
5. credential_pool OAuth entry (~/.hermes/auth.json) <- onde o login do dashboard fica
|
||||
```
|
||||
|
||||
O comentário do próprio código é explícito sobre a intenção: "An explicit user-configured key must not be shadowed by auto-discovered [...] credential-pool OAuth credentials." — ou seja, se `ANTHROPIC_API_KEY` estiver preenchida (mesmo que antiga/esquecida), ela sempre ganha da credencial OAuth do pool (prioridade 3 bate prioridade 5), mesmo depois de um login OAuth bem-sucedido.
|
||||
|
||||
**A causa raiz específica:** o fluxo de login OAuth do **dashboard web** (`hermes_cli/web_server.py::_save_anthropic_oauth_creds`) grava a credencial no credential pool, mas **nunca limpa** a variável `ANTHROPIC_API_KEY`. Isso é diferente do fluxo de OAuth via **CLI** (`hermes model` → opção 1 → `save_anthropic_oauth_token()`), que limpa a API key antiga automaticamente ao salvar o token OAuth. Resultado: se em qualquer momento anterior uma `ANTHROPIC_API_KEY` ficou configurada (setup antigo, teste, auto-detecção), fazer login OAuth pelo dashboard não a remove, e ela continua vencendo pra sempre na resolução de credencial.
|
||||
|
||||
**Correção recomendada:** em `_save_anthropic_oauth_creds()` (web_server.py), limpar `ANTHROPIC_API_KEY` do mesmo jeito que `save_anthropic_oauth_token()` já faz no fluxo de CLI — ou, na resolução (`resolve_anthropic_token`), preferir a credencial OAuth mais recente quando o usuário acabou de completar um login explícito, em vez de uma API key estática que pode estar obsoleta.
|
||||
|
||||
**Diagnóstico que o usuário deve rodar (não incluído aqui por conter dados sensíveis — chaves de API não devem aparecer neste relatório):**
|
||||
```bash
|
||||
hermes doctor
|
||||
# verificar se ANTHROPIC_API_KEY está preenchida em ~/.hermes/.env
|
||||
```
|
||||
Se estiver preenchida, é essa a causa. Correção rápida: esvaziar `ANTHROPIC_API_KEY` no `.env` do Hermes, ou refazer o login OAuth pela opção 1 do `hermes model` no terminal (que já limpa corretamente).
|
||||
|
||||
**Status:** ✅ **corrigido**. `_save_anthropic_oauth_creds()` agora limpa `ANTHROPIC_API_KEY` ao salvar o login OAuth do dashboard, igual o fluxo de CLI já fazia.
|
||||
|
||||
---
|
||||
|
||||
## Bug 5 — PermissionError sob concorrência real no lock cross-processo (achado pelo teste de esforço)
|
||||
|
||||
**Como foi achado:** ao escrever um teste de carga (`tests/agent/test_anthropic_oauth_stress.py`) simulando 20 "processos Hermes" concorrentes disputando o refresh (necessário pra validar o Bug 3 sob estresse, não só com 2 threads), o teste **falhou de verdade** — 16 de 20 threads levantaram `PermissionError: [Errno 13] Permission denied` vindo de dentro do próprio `_auth_store_lock()`.
|
||||
|
||||
**Causa raiz:** `hermes_cli/auth.py::_file_lock()` — a checagem "garante que o arquivo de lock tem pelo menos 1 byte" (necessária pro `msvcrt.locking()` do Windows) fazia um `write_text()` **sem tratamento de exceção**, fora do loop de retry que existe logo depois:
|
||||
|
||||
```python
|
||||
if msvcrt and (not lock_path.exists() or lock_path.stat().st_size == 0):
|
||||
lock_path.write_text(" ", encoding="utf-8") # <- sem try/except
|
||||
```
|
||||
|
||||
Sob concorrência real no Windows, essa escrita pode colidir com o byte-range lock (`msvcrt.locking`) que outra thread/processo já segura no mesmo arquivo nesse exato instante, levantando `PermissionError` — só que isso acontece **antes** do loop `while True: try: ... except (BlockingIOError, OSError, PermissionError): retry` que trataria exatamente esse tipo de colisão. Resultado: a exceção escapa sem ser tratada.
|
||||
|
||||
**Importante:** isso não é específico da Anthropic. `_file_lock()`/`_auth_store_lock()` é o mesmo primitivo compartilhado usado por Codex, xAI e Nous — qualquer provedor com refresh token single-use passando por esse lock estava exposto, só nunca tinha sido testado sob essa carga de concorrência antes.
|
||||
|
||||
**Correção aplicada:**
|
||||
```python
|
||||
if msvcrt and (not lock_path.exists() or lock_path.stat().st_size == 0):
|
||||
try:
|
||||
lock_path.write_text(" ", encoding="utf-8")
|
||||
except (OSError, PermissionError):
|
||||
pass # outro holder já garantiu conteúdo; segue pro loop de retry
|
||||
```
|
||||
|
||||
**Status:** ✅ **corrigido**. Testes: `tests/agent/test_anthropic_oauth_stress.py` (reproduz de forma confiável, 16/20 falhas antes do fix, 0 depois) e `tests/hermes_cli/test_auth_store_lock_concurrent.py` (cobertura dedicada e genérica do lock, independente da Anthropic).
|
||||
|
||||
---
|
||||
|
||||
## Zombie process — investigado, não confirmado
|
||||
|
||||
Checado especificamente no fluxo Anthropic:
|
||||
- Sem servidor HTTP local nem thread de polling (diferente de Nous/Codex device-code).
|
||||
- `run_oauth_setup_token()` usa `subprocess.run(...)` — bloqueante, com wait implícito, sem zumbi.
|
||||
- `webbrowser.open(auth_url)` é comportamento padrão da stdlib, idêntico em todos os outros provedores do repo — não é peculiaridade da Anthropic.
|
||||
|
||||
**Conclusão:** hipótese de zombie process não se confirmou para este provedor.
|
||||
|
||||
---
|
||||
|
||||
## Arquivos criados nesta investigação
|
||||
|
||||
| Arquivo | O que é |
|
||||
|---|---|
|
||||
| `tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py` | 5 testes provando bugs 1 e 2 |
|
||||
| `tests/agent/test_credential_pool_anthropic_refresh_race.py` | 3 testes provando bug 3 |
|
||||
| `RELATORIO_ANTHROPIC_OAUTH_BUGS.md` | Relatório técnico detalhado (versão anterior desta investigação, bugs 1-3) |
|
||||
| `ANTHROPIC_ISSUES.md` | Este arquivo — resumo consolidado, inclui bug 4 (causa real do "não funciona" relatado) |
|
||||
|
||||
**Nota sobre dados sensíveis:** este relatório foi verificado com busca por regex de chaves reais (`sk-ant-...`, `ANTHROPIC_API_KEY=`, `ANTHROPIC_TOKEN=`) — nenhuma encontrada. Só há valores sintéticos usados nos testes automatizados (ex: `sk-ant-oat-rotated-1`), nunca uma chave real. O diagnóstico do Bug 4 pede pro usuário rodar `hermes doctor` / checar o próprio `.env` localmente, mas o resultado desse comando **não foi colado neste relatório** — só a explicação da causa raiz no código.
|
||||
|
||||
Nenhum arquivo de produção foi alterado.
|
||||
|
||||
## Como reproduzir
|
||||
|
||||
```bash
|
||||
python -m pytest tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py tests/agent/test_credential_pool_anthropic_refresh_race.py -v
|
||||
```
|
||||
|
||||
Resultado com o código atual (não corrigido): **7 failed, 1 passed**.
|
||||
|
||||
## Referência rápida de linhas
|
||||
|
||||
| Arquivo | Linhas |
|
||||
|---|---|
|
||||
| `hermes_cli/web_server.py` | 10637-10661 (`_start_anthropic_pkce`), 10664-10728 (`_submit_anthropic_pkce`) |
|
||||
| `agent/credential_pool.py` | 1307-1344 (`_refresh_entry`), 855-905 (`_sync_anthropic_entry_from_credentials_file`), 1442-1483 (recuperação), 1705 (`_mark_exhausted`) |
|
||||
| `agent/anthropic_adapter.py` | 1125-1186 (`refresh_anthropic_oauth_pure`), 1189-1239 (`_refresh_oauth_token`), 1531-1658 (`run_hermes_oauth_login_pure`, fluxo CLI correto) |
|
||||
@@ -0,0 +1,245 @@
|
||||
# Relatório de Investigação — Bugs no fluxo OAuth da Anthropic (hermes-agent)
|
||||
|
||||
**Data:** 2026-08-16
|
||||
**Branch:** `fix/update-orphan-history-guard-87694`
|
||||
**Escopo investigado:** `agent/anthropic_adapter.py`, `agent/credential_pool.py`, `hermes_cli/auth.py`, `hermes_cli/auth_commands.py`, `hermes_cli/web_server.py`
|
||||
**Testes novos:** `tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py`, `tests/agent/test_credential_pool_anthropic_refresh_race.py`
|
||||
|
||||
## Resumo executivo
|
||||
|
||||
Foram encontrados **dois bugs reais e reproduzíveis** no fluxo OAuth da Anthropic, ambos confirmados por testes automatizados que falham contra o código atual (evidência objetiva, não especulação):
|
||||
|
||||
| # | Bug | Categoria | Severidade |
|
||||
|---|-----|-----------|------------|
|
||||
| 1 | Dashboard web reintroduz vazamento do PKCE `code_verifier` via parâmetro `state` da URL de autorização | Segurança (CSRF / RFC 7636) | **Alta** |
|
||||
| 2 | `_submit_anthropic_pkce()` do dashboard não valida o `state` retornado no callback — não há proteção CSRF nenhuma nesse endpoint | Segurança (CSRF / RFC 6749 §10.12) | **Alta** |
|
||||
| 3 | Refresh de token OAuth da Anthropic não é protegido pelo lock cross-processo (`_auth_store_lock`) que Codex e xAI recebem, apesar de o refresh token da Anthropic também ser single-use | Race condition | **Média-Alta** |
|
||||
|
||||
Não foi encontrada evidência de **zombie processes** no fluxo Anthropic especificamente (ver seção 4) — essa hipótese do usuário não se confirmou para este provedor, ao contrário das duas hipóteses de segurança/race que se confirmaram.
|
||||
|
||||
---
|
||||
|
||||
## 1. Bug de segurança — PKCE `code_verifier` vazado como `state` (dashboard web)
|
||||
|
||||
### Onde
|
||||
|
||||
`hermes_cli/web_server.py`, função `_start_anthropic_pkce()` (~linha 10637-10661):
|
||||
|
||||
```python
|
||||
def _start_anthropic_pkce(profile: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Begin PKCE flow. Returns the auth URL the UI should open."""
|
||||
...
|
||||
verifier, challenge = _generate_pkce_pair()
|
||||
sid, sess = _new_oauth_session("anthropic", "pkce", profile=profile)
|
||||
sess["verifier"] = verifier
|
||||
sess["state"] = verifier # Anthropic round-trips verifier as state
|
||||
params = {
|
||||
...
|
||||
"code_challenge": challenge,
|
||||
"code_challenge_method": "S256",
|
||||
"state": verifier,
|
||||
}
|
||||
auth_url = f"{_ANTHROPIC_OAUTH_AUTHORIZE_URL}?{urllib.parse.urlencode(params)}"
|
||||
```
|
||||
|
||||
### Por que é um bug real (não é estilo/preferência)
|
||||
|
||||
Este é **exatamente** o padrão vulnerável já documentado e corrigido no próprio repositório para o fluxo de CLI, em `agent/anthropic_adapter.py::run_hermes_oauth_login_pure()`. O teste de regressão `tests/agent/test_anthropic_oauth_pkce.py` explica o histórico:
|
||||
|
||||
> "Guards against re-introducing the bug where the PKCE `code_verifier` was reused as the OAuth `state` parameter, leaking the verifier via the authorization URL (browser history, Referer headers, auth-server logs) and removing CSRF protection on the callback path."
|
||||
> — PR #1775 corrigiu; PR #2647 reintroduziu silenciosamente; PR #3107 removeu a função antiga; PR #10699 (issue #10693) corrigiu de novo na função sobrevivente.
|
||||
|
||||
O fluxo de CLI **foi corrigido** (gera `oauth_state = secrets.token_urlsafe(32)` independente do verifier). Mas o fluxo do **dashboard web** (`hermes_cli/web_server.py`) é uma implementação **paralela e independente** do mesmo login PKCE da Anthropic, e nunca recebeu a mesma correção — ele reintroduz o bug já resolvido, só que numa rota diferente (`/api/providers/oauth/anthropic/start` → `_start_anthropic_pkce`).
|
||||
|
||||
Consequência: o `code_verifier` (que por RFC 7636 §7.2 deve permanecer confidencial no servidor até a troca do código) vaza em:
|
||||
- histórico do navegador do usuário;
|
||||
- cabeçalho `Referer` de qualquer requisição subsequente feita a partir da página `claude.ai/oauth/authorize`;
|
||||
- logs de acesso do servidor da Anthropic (`platform.claude.com`).
|
||||
|
||||
### Evidência de teste
|
||||
|
||||
`tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py` — 5 testes, todos falham contra o código atual:
|
||||
|
||||
```
|
||||
FAILED test_authorization_url_state_is_not_pkce_verifier
|
||||
FAILED test_verifier_never_appears_anywhere_in_auth_url
|
||||
FAILED test_state_is_cryptographically_independent_of_verifier
|
||||
FAILED test_submit_pkce_rejects_state_mismatch
|
||||
FAILED test_submit_pkce_with_no_state_suffix_does_not_silently_succeed
|
||||
```
|
||||
|
||||
Saída real do primeiro teste (state == verifier, comprovado byte a byte):
|
||||
|
||||
```
|
||||
assert 'dg7ihLbmv6ooNu2-V_dKcVPKp29kNJewr4s8UBSr1gE' != 'dg7ihLbmv6ooNu2-V_dKcVPKp29kNJewr4s8UBSr1gE'
|
||||
```
|
||||
|
||||
### Correção recomendada
|
||||
|
||||
Em `_start_anthropic_pkce()`, gerar um `state` independente (mesmo padrão de `agent/anthropic_adapter.py`):
|
||||
|
||||
```python
|
||||
oauth_state = secrets.token_urlsafe(32)
|
||||
sess["state"] = oauth_state
|
||||
params = {..., "state": oauth_state}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Bug de segurança — ausência total de validação de `state` no callback do dashboard
|
||||
|
||||
### Onde
|
||||
|
||||
`hermes_cli/web_server.py`, função `_submit_anthropic_pkce()` (~linha 10664-10692):
|
||||
|
||||
```python
|
||||
def _submit_anthropic_pkce(session_id, code_input, profile=None):
|
||||
...
|
||||
parts = code_input.strip().split("#", 1)
|
||||
code = parts[0].strip()
|
||||
state_from_callback = parts[1] if len(parts) > 1 else ""
|
||||
|
||||
exchange_data = json.dumps({
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": _ANTHROPIC_OAUTH_CLIENT_ID,
|
||||
"code": code,
|
||||
"state": state_from_callback or sess["state"], # <- nunca comparado
|
||||
"redirect_uri": _ANTHROPIC_OAUTH_REDIRECT_URI,
|
||||
"code_verifier": sess["verifier"],
|
||||
}).encode()
|
||||
```
|
||||
|
||||
### Por que é um bug real
|
||||
|
||||
O código **nunca compara** `state_from_callback` com `sess["state"]`. Ele apenas usa o que veio do usuário (`state_from_callback`) ou, se vazio, cai de volta pro valor da própria sessão (`sess["state"]`) — ou seja, **qualquer valor** (ou nenhum) é aceito. Isso é diferente do fluxo de CLI (`agent/anthropic_adapter.py::run_hermes_oauth_login_pure`), que faz:
|
||||
|
||||
```python
|
||||
if received_state != oauth_state:
|
||||
logger.warning("OAuth state mismatch — possible CSRF, aborting")
|
||||
return None
|
||||
```
|
||||
|
||||
Sem essa checagem, o endpoint fica sem proteção CSRF conforme RFC 6749 §10.12 — é o segundo componente do mesmo problema descrito na Seção 1 (o vazamento do verifier como state e a ausência de validação se reforçam: mesmo que o `state` fosse aleatório, sem comparação a proteção seria inútil; e como é o verifier, mesmo com comparação a proteção colapsaria porque quem descobre o verifier vazado também "sabe" o state).
|
||||
|
||||
### Evidência de teste
|
||||
|
||||
```
|
||||
FAILED test_submit_pkce_rejects_state_mismatch
|
||||
FAILED test_submit_pkce_with_no_state_suffix_does_not_silently_succeed
|
||||
```
|
||||
|
||||
O teste mostra a troca de token acontecendo mesmo com `state` adulterado (`attacker-controlled-state`) — o payload POST real foi capturado, provando que a troca prosseguiu sem checagem.
|
||||
|
||||
### Correção recomendada
|
||||
|
||||
```python
|
||||
if not state_from_callback or state_from_callback != sess["state"]:
|
||||
with _oauth_sessions_lock:
|
||||
sess["status"] = "error"
|
||||
sess["error_message"] = "OAuth state mismatch"
|
||||
return {"ok": False, "status": "error", "message": "OAuth state mismatch"}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Race condition — refresh de OAuth da Anthropic sem lock cross-processo
|
||||
|
||||
### Onde
|
||||
|
||||
`agent/credential_pool.py`, método `CredentialPool._refresh_entry()` (~linha 1307-1344):
|
||||
|
||||
```python
|
||||
# Codex and xAI OAuth refresh tokens are single-use. The
|
||||
# sync→POST→write-back sequence below must run atomically across Hermes
|
||||
# processes: otherwise two processes can both adopt the same on-disk
|
||||
# token, both POST it, and the loser gets ``refresh_token_reused``.
|
||||
# Serialize the whole sequence through the shared cross-process
|
||||
# auth-store flock ...
|
||||
if self.provider in ("openai-codex", "xai-oauth"):
|
||||
...
|
||||
with _auth_store_lock(timeout_seconds=self._single_use_refresh_lock_timeout()):
|
||||
...
|
||||
return self._refresh_entry_impl(entry, force=force) # <- anthropic cai aqui, SEM lock
|
||||
```
|
||||
|
||||
O próprio comentário do código explica a razão de existir o lock: refresh tokens single-use não podem ser disputados por dois processos Hermes ao mesmo tempo. Só que **`"anthropic"` não está na tupla `("openai-codex", "xai-oauth")`** — mesmo o refresh da Anthropic sendo, pela documentação do próprio arquivo `agent/anthropic_adapter.py::_refresh_oauth_token`, também single-use:
|
||||
|
||||
> "Claude Code's OAuth refresh tokens are single-use: a successful refresh rotates the pair and invalidates the old refresh token."
|
||||
|
||||
### O único caminho de recuperação existe, mas é parcial
|
||||
|
||||
Ao falhar (`except Exception as exc`), há uma tentativa de recuperação em `_refresh_entry_impl` (linha ~1447):
|
||||
|
||||
```python
|
||||
if self.provider == "anthropic" and entry.source == "claude_code":
|
||||
synced = self._sync_anthropic_entry_from_credentials_file(entry)
|
||||
...
|
||||
```
|
||||
|
||||
Só que `_sync_anthropic_entry_from_credentials_file` (linha 855-905) começa com:
|
||||
|
||||
```python
|
||||
if self.provider != "anthropic" or entry.source != "claude_code":
|
||||
return entry
|
||||
```
|
||||
|
||||
Ou seja: **só funciona para credenciais que vieram do Claude Code CLI** (`~/.claude/.credentials.json`). Credenciais originadas do login OAuth nativo do próprio Hermes (`hermes_pkce`, gravadas em `~/.hermes/.anthropic_oauth.json`, e também as emitidas pelo dashboard — `manual:dashboard_pkce`) **não têm nenhuma rota de recuperação**. Ao perder a corrida, o processo cai direto em `self._mark_exhausted(entry, None)` (linha 1705), mesmo que uma credencial válida já exista em disco (escrita pelo processo vencedor).
|
||||
|
||||
### Cenário concreto de exploração / impacto
|
||||
|
||||
Isso não exige ataque — acontece em uso normal: múltiplos processos Hermes concorrentes (fleet workers, cron jobs, sessões CLI simultâneas) compartilhando a mesma credencial Anthropic via login PKCE nativo. Quando o token expira e dois processos tentam renovar simultaneamente:
|
||||
1. Ambos leem o mesmo `refresh_token` (ainda válido) do disco.
|
||||
2. Ambos disparam POST para `https://platform.claude.com/v1/oauth/token` quase ao mesmo tempo.
|
||||
3. O servidor da Anthropic aceita apenas o primeiro (`refresh_token` é single-use); o segundo recebe `invalid_grant`.
|
||||
4. O processo perdedor **não tem como se recuperar** e marca a credencial como `STATUS_EXHAUSTED` — falha espúria de "reautentique-se com a Anthropic" mesmo havendo um token perfeitamente válido em outro processo.
|
||||
|
||||
### Evidência de teste
|
||||
|
||||
`tests/agent/test_credential_pool_anthropic_refresh_race.py` — 3 testes:
|
||||
|
||||
```
|
||||
FAILED test_anthropic_refresh_is_not_protected_by_cross_process_lock
|
||||
assert [] # _auth_store_lock nunca foi chamado para 'anthropic'
|
||||
|
||||
FAILED test_concurrent_hermes_pkce_refresh_loses_credential_despite_valid_token_on_disk
|
||||
assert None is not None # processo perdedor não conseguiu recuperar
|
||||
|
||||
PASSED test_concurrent_claude_code_refresh_recovers_via_credentials_file
|
||||
# contraste: fonte 'claude_code' SE recupera — prova a assimetria
|
||||
```
|
||||
|
||||
O teste usa um servidor OAuth fake que impõe corretamente a semântica "single-use" (primeiro a chegar ganha, segundo recebe `invalid_grant`), exatamente como o comportamento real documentado da Anthropic, e dispara dois `CredentialPool._refresh_entry()` concorrentes via `threading.Thread` simulando dois processos Hermes distintos.
|
||||
|
||||
### Correção recomendada
|
||||
|
||||
Incluir `"anthropic"` na lista protegida por `_auth_store_lock` em `_refresh_entry()`, e generalizar `_sync_anthropic_entry_from_credentials_file` (ou adicionar uma variante) para também resincronizar a partir de `~/.hermes/auth.json` / `~/.hermes/.anthropic_oauth.json` quando `entry.source` for `hermes_pkce` ou `manual:dashboard_pkce`, análogo ao que já existe para `openai-codex` (`_sync_codex_entry_from_auth_store`) e `xai-oauth`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Zombie processes — investigado, sem evidência no fluxo Anthropic
|
||||
|
||||
Verificado especificamente para OAuth da Anthropic:
|
||||
- Não há servidor HTTP local nem `threading.Thread` de polling associado ao fluxo Anthropic (nem CLI nem dashboard) — diferente de outros provedores (Nous, Codex device-code) que usam thread de poll em background.
|
||||
- `run_oauth_setup_token()` usa `subprocess.run([claude_path, "setup-token"])` — chamada **síncrona e bloqueante**, com `wait()` implícito; não deixa processo zumbi.
|
||||
- `webbrowser.open(auth_url)` é chamado tanto no CLI quanto (implicitamente via browser do usuário) no dashboard — é comportamento padrão da stdlib do Python, idêntico em todos os outros provedores OAuth do repositório (xAI, Codex, Nous, Spotify, MiniMax), não é uma particularidade introduzida pelo fluxo Anthropic.
|
||||
|
||||
**Conclusão:** a hipótese de zombie process não se sustentou para este provedor especificamente. Caso o usuário tenha observado zumbis reais, provavelmente estão associados a outro subsistema (ex.: probes de processo do Windows já corrigidos em commits recentes desta branch — `4e3de140c1`, `00ecb5d538`) e não ao OAuth da Anthropic.
|
||||
|
||||
---
|
||||
|
||||
## 5. Como rodar os testes
|
||||
|
||||
```bash
|
||||
python -m pytest tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py tests/agent/test_credential_pool_anthropic_refresh_race.py -v
|
||||
```
|
||||
|
||||
Resultado atual (código não corrigido): **7 failed, 1 passed** — as 7 falhas são a evidência dos bugs 1, 2 e 3; o único teste que passa (`test_concurrent_claude_code_refresh_recovers_via_credentials_file`) prova a assimetria descrita no Bug 3 (fonte `claude_code` se recupera, `hermes_pkce`/dashboard não).
|
||||
|
||||
## 6. Arquivos e linhas de referência
|
||||
|
||||
| Arquivo | Linhas relevantes |
|
||||
|---|---|
|
||||
| `hermes_cli/web_server.py` | 10637-10661 (`_start_anthropic_pkce`), 10664-10728 (`_submit_anthropic_pkce`) |
|
||||
| `agent/credential_pool.py` | 1307-1344 (`_refresh_entry`), 855-905 (`_sync_anthropic_entry_from_credentials_file`), 1442-1483 (fallback de recuperação), 1705 (`_mark_exhausted`) |
|
||||
| `agent/anthropic_adapter.py` | 1125-1186 (`refresh_anthropic_oauth_pure`), 1189-1239 (`_refresh_oauth_token`, docstring sobre single-use), 1531-1658 (`run_hermes_oauth_login_pure`, fluxo CLI correto) |
|
||||
| `tests/agent/test_anthropic_oauth_pkce.py` | Regressão histórica do bug 1/2 no fluxo CLI (já corrigido lá) |
|
||||
@@ -967,6 +967,49 @@ class CredentialPool:
|
||||
logger.debug("Failed to sync from credentials file: %s", exc)
|
||||
return entry
|
||||
|
||||
def _sync_anthropic_entry_from_pool_store(
|
||||
self, entry: PooledCredential
|
||||
) -> PooledCredential:
|
||||
"""Adopt an Anthropic token pair rotated by another pool instance.
|
||||
|
||||
Unlike ``_sync_anthropic_entry_from_credentials_file`` (which only
|
||||
helps ``entry.source == "claude_code"`` by re-reading
|
||||
``~/.claude/.credentials.json``), this re-reads the exact persisted
|
||||
row from the credential-pool store itself
|
||||
(``~/.hermes/auth.json`` / profile equivalent), so it works for
|
||||
every Anthropic source — ``claude_code``, ``hermes_pkce``, and
|
||||
dashboard-issued ``manual:dashboard_pkce`` entries alike. Called
|
||||
while the shared cross-process auth-store lock is held, mirroring
|
||||
``_sync_xai_oauth_entry_from_pool_store``.
|
||||
"""
|
||||
if self.provider != "anthropic":
|
||||
return entry
|
||||
try:
|
||||
persisted = next(
|
||||
(
|
||||
payload
|
||||
for payload in read_credential_pool(self.provider)
|
||||
if isinstance(payload, dict) and payload.get("id") == entry.id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not isinstance(persisted, dict):
|
||||
return entry
|
||||
stored = PooledCredential.from_dict(self.provider, persisted)
|
||||
if (
|
||||
stored.access_token != entry.access_token
|
||||
or stored.refresh_token != entry.refresh_token
|
||||
):
|
||||
logger.debug(
|
||||
"Pool entry %s: adopting Anthropic OAuth tokens rotated by another pool instance",
|
||||
entry.id,
|
||||
)
|
||||
self._replace_entry(entry, stored)
|
||||
return stored
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to sync Anthropic OAuth entry from credential pool: %s", exc)
|
||||
return entry
|
||||
|
||||
def _sync_codex_entry_from_auth_store(self, entry: PooledCredential) -> PooledCredential:
|
||||
"""Sync a Codex device_code pool entry from auth.json if tokens differ.
|
||||
|
||||
@@ -1382,11 +1425,22 @@ class CredentialPool:
|
||||
# resolve_codex_runtime_credentials()). When a waiter finally acquires
|
||||
# the lock, the in-lock re-sync below picks up the rotated token the
|
||||
# winner persisted and skips the POST.
|
||||
if self.provider in ("openai-codex", "xai-oauth"):
|
||||
# Anthropic's OAuth refresh tokens are single-use too (see
|
||||
# agent/anthropic_adapter.py::_refresh_oauth_token), so the same
|
||||
# cross-process serialization Codex/xAI get is required here.
|
||||
# Previously "anthropic" was excluded from this tuple: two Hermes
|
||||
# processes racing to refresh the same stale token would both POST,
|
||||
# the loser got invalid_grant, and — for any source other than
|
||||
# "claude_code" (hermes_pkce, dashboard-issued manual entries) —
|
||||
# there was no recovery path at all, so the loser was marked
|
||||
# exhausted despite a valid token existing on disk from the winner.
|
||||
if self.provider in ("openai-codex", "xai-oauth", "anthropic"):
|
||||
sync_entry = (
|
||||
self._sync_codex_entry_from_auth_store
|
||||
if self.provider == "openai-codex"
|
||||
else self._sync_xai_oauth_entry_from_pool_store
|
||||
if self.provider == "xai-oauth"
|
||||
else self._sync_anthropic_entry_from_pool_store
|
||||
)
|
||||
with _auth_store_lock(
|
||||
timeout_seconds=self._single_use_refresh_lock_timeout()
|
||||
@@ -1418,6 +1472,8 @@ class CredentialPool:
|
||||
"HERMES_CODEX_REFRESH_TIMEOUT_SECONDS"
|
||||
if self.provider == "openai-codex"
|
||||
else "HERMES_XAI_REFRESH_TIMEOUT_SECONDS"
|
||||
if self.provider == "xai-oauth"
|
||||
else "HERMES_ANTHROPIC_REFRESH_TIMEOUT_SECONDS"
|
||||
)
|
||||
refresh_timeout_seconds = auth_mod.env_float(env_var, 20)
|
||||
return max(
|
||||
@@ -1544,6 +1600,31 @@ class CredentialPool:
|
||||
# Credentials file had a valid (non-expired) token — use it directly
|
||||
logger.debug("Credentials file has valid token, using without refresh")
|
||||
return synced
|
||||
elif self.provider == "anthropic":
|
||||
# Backstop for non-claude_code sources (hermes_pkce,
|
||||
# manual:dashboard_pkce): the in-lock pre-check in
|
||||
# _refresh_entry() should already have adopted a winner's
|
||||
# rotated token before this POST was even attempted, but if
|
||||
# the failure still happened (e.g. the winner persisted
|
||||
# between our pre-check and our POST), re-read the pool
|
||||
# store once more before giving up.
|
||||
synced = self._sync_anthropic_entry_from_pool_store(entry)
|
||||
if synced.refresh_token != entry.refresh_token:
|
||||
logger.debug(
|
||||
"Anthropic OAuth refresh failed but pool store has newer tokens — adopting"
|
||||
)
|
||||
updated = replace(
|
||||
synced,
|
||||
last_status=STATUS_OK,
|
||||
last_status_at=None,
|
||||
last_error_code=None,
|
||||
last_error_reason=None,
|
||||
last_error_message=None,
|
||||
last_error_reset_at=None,
|
||||
)
|
||||
self._replace_entry(synced, updated)
|
||||
self._persist()
|
||||
return updated
|
||||
# For xai-oauth: same race as nous — another process may have
|
||||
# consumed the refresh token between our proactive sync and the
|
||||
# HTTP call. Re-check auth.json and adopt the fresh tokens if
|
||||
|
||||
+13
-1
@@ -1288,8 +1288,20 @@ def _file_lock(
|
||||
|
||||
# On Windows, msvcrt.locking needs the file to have content and the
|
||||
# file pointer at position 0. Ensure the lock file has at least 1 byte.
|
||||
# Under real concurrency (many threads/processes racing this same
|
||||
# ensure-content check) this write can collide with another holder's
|
||||
# msvcrt byte-range lock on the same file and raise PermissionError --
|
||||
# uncaught, since it happens before the retry loop below even starts.
|
||||
# A stress test with 20 concurrent Hermes processes reproduced this
|
||||
# deterministically on Windows. It's a best-effort convenience write
|
||||
# (whoever gets there first wins); losing the race here just means the
|
||||
# lock file already has content, so swallow the failure and proceed
|
||||
# straight to the acquire-with-retry loop.
|
||||
if msvcrt and (not lock_path.exists() or lock_path.stat().st_size == 0):
|
||||
lock_path.write_text(" ", encoding="utf-8")
|
||||
try:
|
||||
lock_path.write_text(" ", encoding="utf-8")
|
||||
except (OSError, PermissionError):
|
||||
pass
|
||||
|
||||
with lock_path.open("r+" if msvcrt else "a+", encoding="utf-8") as lock_file:
|
||||
deadline = time.monotonic() + max(1.0, timeout_seconds)
|
||||
|
||||
@@ -11452,6 +11452,19 @@ def _save_anthropic_oauth_creds(access_token: str, refresh_token: str, expires_a
|
||||
from utils import atomic_json_write
|
||||
|
||||
atomic_json_write(oauth_file, payload, indent=2, mode=0o600)
|
||||
# Clear a stale ANTHROPIC_API_KEY so it cannot keep shadowing this fresh
|
||||
# OAuth login. resolve_anthropic_token() deliberately prefers an explicit
|
||||
# ANTHROPIC_API_KEY over the credential-pool OAuth entry (priority 3 vs
|
||||
# 5) — so without this, a leftover/forgotten API key from an earlier
|
||||
# setup makes every subsequent OAuth login through the dashboard silently
|
||||
# inert: the user re-authenticates with their Claude Pro/Max plan, but
|
||||
# Hermes keeps billing pay-per-token against the old key. The CLI flow
|
||||
# (save_anthropic_oauth_token in hermes_cli/config.py) already clears
|
||||
# this slot on OAuth save; this mirrors that for the dashboard flow.
|
||||
try:
|
||||
save_env_value("ANTHROPIC_API_KEY", "")
|
||||
except Exception as e:
|
||||
_log.warning("anthropic dashboard oauth: failed to clear stale ANTHROPIC_API_KEY: %s", e)
|
||||
# Best-effort credential-pool insert. Failure here doesn't invalidate
|
||||
# the file write — pool registration only matters for the rotation
|
||||
# strategy, not for runtime credential resolution.
|
||||
@@ -11494,7 +11507,15 @@ def _start_anthropic_pkce(profile: Optional[str] = None) -> Dict[str, Any]:
|
||||
verifier, challenge = _generate_pkce_pair()
|
||||
sid, sess = _new_oauth_session("anthropic", "pkce", profile=profile)
|
||||
sess["verifier"] = verifier
|
||||
sess["state"] = verifier # Anthropic round-trips verifier as state
|
||||
# Independent anti-CSRF token. Do NOT reuse the PKCE verifier as state:
|
||||
# that leaks the (supposed to stay confidential, RFC 7636 SS7.2) verifier
|
||||
# via the authorization URL (browser history, Referer headers, auth-server
|
||||
# logs) and collapses the CSRF check to nothing, since anyone who
|
||||
# observes the leaked verifier also "knows" the state. Mirrors the fix
|
||||
# already applied to the CLI flow in agent/anthropic_adapter.py
|
||||
# (run_hermes_oauth_login_pure) for PR #10699 / issue #10693.
|
||||
oauth_state = secrets.token_urlsafe(32)
|
||||
sess["state"] = oauth_state
|
||||
params = {
|
||||
"code": "true",
|
||||
"client_id": _ANTHROPIC_OAUTH_CLIENT_ID,
|
||||
@@ -11503,7 +11524,7 @@ def _start_anthropic_pkce(profile: Optional[str] = None) -> Dict[str, Any]:
|
||||
"scope": _ANTHROPIC_OAUTH_SCOPES,
|
||||
"code_challenge": challenge,
|
||||
"code_challenge_method": "S256",
|
||||
"state": verifier,
|
||||
"state": oauth_state,
|
||||
}
|
||||
auth_url = f"{_ANTHROPIC_OAUTH_AUTHORIZE_URL}?{urllib.parse.urlencode(params)}"
|
||||
return {
|
||||
@@ -11535,11 +11556,23 @@ def _submit_anthropic_pkce(
|
||||
return {"ok": False, "status": "error", "message": "No code provided"}
|
||||
state_from_callback = parts[1] if len(parts) > 1 else ""
|
||||
|
||||
# CSRF guard (RFC 6749 SS10.12): the state echoed back on the callback
|
||||
# must match the state this session issued. Without this check, an
|
||||
# attacker who completes their OWN authorization can get the victim to
|
||||
# paste that code/state pair, binding the attacker's Anthropic account
|
||||
# to the victim's Hermes session. Mirrors the CLI flow's
|
||||
# "received_state != oauth_state" guard in agent/anthropic_adapter.py.
|
||||
if not state_from_callback or state_from_callback != sess["state"]:
|
||||
with _oauth_sessions_lock:
|
||||
sess["status"] = "error"
|
||||
sess["error_message"] = "OAuth state mismatch"
|
||||
return {"ok": False, "status": "error", "message": "OAuth state mismatch"}
|
||||
|
||||
exchange_data = json.dumps({
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": _ANTHROPIC_OAUTH_CLIENT_ID,
|
||||
"code": code,
|
||||
"state": state_from_callback or sess["state"],
|
||||
"state": state_from_callback,
|
||||
"redirect_uri": _ANTHROPIC_OAUTH_REDIRECT_URI,
|
||||
"code_verifier": sess["verifier"],
|
||||
}).encode()
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Load / stress tests for the Anthropic OAuth fixes.
|
||||
|
||||
Companion to ``tests/agent/test_credential_pool_anthropic_refresh_race.py``
|
||||
and ``tests/hermes_cli/test_anthropic_dashboard_pkce_csrf.py``, which prove
|
||||
each bug in isolation with two racers. These tests scale the same scenarios
|
||||
up to look for bottlenecks and degradation under real concurrency:
|
||||
|
||||
1. Many "Hermes processes" (threads, each with its own ``CredentialPool``
|
||||
instance) hammering the same single-use Anthropic refresh token at once,
|
||||
against the REAL cross-process file lock (``_auth_store_lock``) and REAL
|
||||
credential-pool persistence (not mocked) under a throwaway
|
||||
``HERMES_HOME`` -- only the network call to Anthropic is faked. This
|
||||
checks the fix does not deadlock, does not lose updates, and does not
|
||||
degrade into a "thundering herd" of redundant refresh POSTs as
|
||||
concurrency grows.
|
||||
2. A burst of dashboard PKCE login starts, checking the anti-CSRF `state`
|
||||
generator has no collisions at scale and that the in-memory session
|
||||
table's GC actually bounds memory growth (an unbounded
|
||||
``_oauth_sessions`` dict is a latent DoS surface if many `/start` calls
|
||||
never get a matching `/submit`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import replace as dc_replace
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.credential_pool import (
|
||||
AUTH_TYPE_OAUTH,
|
||||
STATUS_EXHAUSTED,
|
||||
CredentialPool,
|
||||
PooledCredential,
|
||||
)
|
||||
|
||||
CONCURRENCY = 20
|
||||
|
||||
|
||||
def _entry(*, id: str, refresh_token: str, source: str) -> PooledCredential:
|
||||
return PooledCredential(
|
||||
provider="anthropic",
|
||||
id=id,
|
||||
label="anthropic oauth",
|
||||
auth_type=AUTH_TYPE_OAUTH,
|
||||
priority=0,
|
||||
source=source,
|
||||
access_token="stale-at",
|
||||
refresh_token=refresh_token,
|
||||
expires_at_ms=0,
|
||||
)
|
||||
|
||||
|
||||
class _SingleUseTokenServer:
|
||||
"""Same single-use-refresh-token contract as the race test, tuned for
|
||||
a wider fan-out (more callers, less per-call delay so the suite stays
|
||||
fast while still exercising real contention).
|
||||
"""
|
||||
|
||||
def __init__(self, delay_seconds: float = 0.02) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._spent: set[str] = set()
|
||||
self._rotation = 0
|
||||
self.calls: list[str] = []
|
||||
self.delay_seconds = delay_seconds
|
||||
|
||||
def refresh(self, refresh_token: str, *, use_json: bool = False):
|
||||
with self._lock:
|
||||
self.calls.append(refresh_token)
|
||||
time.sleep(self.delay_seconds)
|
||||
with self._lock:
|
||||
if refresh_token in self._spent:
|
||||
raise ValueError("invalid_grant: refresh token already used")
|
||||
self._spent.add(refresh_token)
|
||||
self._rotation += 1
|
||||
rotation = self._rotation
|
||||
return {
|
||||
"access_token": f"sk-ant-oat-rotated-{rotation}",
|
||||
"refresh_token": f"sk-ant-ort-rotated-{rotation}",
|
||||
"expires_at_ms": int(time.time() * 1000) + 3_600_000,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hermes_home(tmp_path, monkeypatch):
|
||||
"""Real, throwaway HERMES_HOME so _auth_store_lock and
|
||||
write_credential_pool/read_credential_pool exercise the genuine
|
||||
file-lock + on-disk persistence path, not a mock.
|
||||
"""
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_high_concurrency_anthropic_refresh_no_lost_updates_no_deadlock(
|
||||
hermes_home, monkeypatch
|
||||
):
|
||||
"""CONCURRENCY 'Hermes processes' race the same stale refresh token
|
||||
against the real cross-process lock + real on-disk pool persistence.
|
||||
|
||||
Bottleneck check: total wall-clock time must stay close to what a
|
||||
correctly-serialized (or adopt-without-refreshing) implementation would
|
||||
take, not blow up toward CONCURRENCY * network_delay -- and every
|
||||
participant must end up with a usable, non-exhausted credential.
|
||||
"""
|
||||
server = _SingleUseTokenServer(delay_seconds=0.02)
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.refresh_anthropic_oauth_pure",
|
||||
lambda refresh_token, use_json=False: server.refresh(refresh_token, use_json=use_json),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.read_claude_code_credentials", lambda: None
|
||||
)
|
||||
|
||||
shared_stale_entry = _entry(
|
||||
id="pool-entry", refresh_token="stale-rt", source="manual:hermes_pkce"
|
||||
)
|
||||
pools = [
|
||||
CredentialPool("anthropic", [dc_replace(shared_stale_entry)])
|
||||
for _ in range(CONCURRENCY)
|
||||
]
|
||||
|
||||
results: dict[int, object] = {}
|
||||
errors: dict[int, BaseException] = {}
|
||||
|
||||
def _run(idx: int) -> None:
|
||||
try:
|
||||
entry = pools[idx].entries()[0]
|
||||
results[idx] = pools[idx]._refresh_entry(entry, force=True)
|
||||
except BaseException as exc: # pragma: no cover - failure diagnostics
|
||||
errors[idx] = exc
|
||||
|
||||
threads = [threading.Thread(target=_run, args=(i,)) for i in range(CONCURRENCY)]
|
||||
start = time.monotonic()
|
||||
for t in threads:
|
||||
t.start()
|
||||
# Generous per-thread join budget: a correct implementation serializes
|
||||
# through one file lock, so worst case is roughly
|
||||
# CONCURRENCY * (delay + lock overhead), well under this ceiling. A
|
||||
# deadlock or livelock would blow straight through it.
|
||||
deadline = start + max(10.0, CONCURRENCY * server.delay_seconds * 5)
|
||||
for t in threads:
|
||||
remaining = max(0.1, deadline - time.monotonic())
|
||||
t.join(timeout=remaining)
|
||||
elapsed = time.monotonic() - start
|
||||
|
||||
still_alive = [t for t in threads if t.is_alive()]
|
||||
assert not still_alive, (
|
||||
f"{len(still_alive)}/{CONCURRENCY} threads never finished -- "
|
||||
"possible deadlock in the cross-process refresh lock."
|
||||
)
|
||||
assert not errors, f"unexpected exceptions during concurrent refresh: {errors!r}"
|
||||
|
||||
assert len(results) == CONCURRENCY
|
||||
assert all(r is not None for r in results.values()), (
|
||||
"at least one of the concurrent processes could not recover a "
|
||||
"usable Anthropic credential after the refresh race"
|
||||
)
|
||||
for idx, pool in enumerate(pools):
|
||||
entry_after = pool.entries()[0]
|
||||
assert entry_after.last_status != STATUS_EXHAUSTED, (
|
||||
f"process {idx} ended up with an exhausted Anthropic credential "
|
||||
"despite valid tokens existing on disk"
|
||||
)
|
||||
|
||||
# Bottleneck signal: this must stay well below "every thread pays the
|
||||
# full network delay independently" (CONCURRENCY * delay). If the fix
|
||||
# regresses into N sequential POSTs instead of lock+adopt, this is
|
||||
# where it would show up first.
|
||||
naive_serial_upper_bound = CONCURRENCY * server.delay_seconds * 3
|
||||
assert elapsed < naive_serial_upper_bound, (
|
||||
f"refresh race took {elapsed:.2f}s for {CONCURRENCY} concurrent "
|
||||
f"processes -- expected well under {naive_serial_upper_bound:.2f}s "
|
||||
"if the lock + pool-store adoption path is working efficiently"
|
||||
)
|
||||
|
||||
|
||||
def test_dashboard_pkce_start_burst_state_uniqueness_and_session_gc(monkeypatch):
|
||||
"""Burst-start the dashboard PKCE flow and check for two failure modes
|
||||
that would only show up at scale:
|
||||
|
||||
1. ``state``/``verifier`` collisions (entropy bug in the token
|
||||
generator would be invisible with 1-2 samples but show up over many).
|
||||
2. Unbounded growth of the in-memory ``_oauth_sessions`` dict -- a
|
||||
latent memory-exhaustion vector if many browser tabs/bots hit
|
||||
``/start`` without ever completing ``/submit``. GC must actually
|
||||
reclaim expired entries.
|
||||
"""
|
||||
pytest.importorskip("hermes_cli.web_server")
|
||||
from hermes_cli import web_server
|
||||
|
||||
if not web_server._ANTHROPIC_OAUTH_AVAILABLE:
|
||||
pytest.skip("Anthropic OAuth adapter unavailable in this environment")
|
||||
|
||||
with web_server._oauth_sessions_lock:
|
||||
web_server._oauth_sessions.clear()
|
||||
|
||||
N = 500
|
||||
states = []
|
||||
verifiers = []
|
||||
for _ in range(N):
|
||||
session = web_server._start_anthropic_pkce()
|
||||
with web_server._oauth_sessions_lock:
|
||||
sess = web_server._oauth_sessions[session["session_id"]]
|
||||
states.append(sess["state"])
|
||||
verifiers.append(sess["verifier"])
|
||||
|
||||
assert len(set(states)) == N, "state collisions detected across a burst of PKCE starts"
|
||||
assert len(set(verifiers)) == N, "verifier collisions detected across a burst of PKCE starts"
|
||||
# The fix for the CSRF bug depends on these two pools never overlapping.
|
||||
assert not (set(states) & set(verifiers)), (
|
||||
"a state value collided with a verifier value from a DIFFERENT "
|
||||
"session -- would make the leak/CSRF bug's blast radius worse"
|
||||
)
|
||||
|
||||
with web_server._oauth_sessions_lock:
|
||||
assert len(web_server._oauth_sessions) == N
|
||||
|
||||
# Simulate all N sessions having aged past the TTL, then run the same
|
||||
# GC the /start route triggers opportunistically.
|
||||
with web_server._oauth_sessions_lock:
|
||||
for sess in web_server._oauth_sessions.values():
|
||||
sess["created_at"] = time.time() - web_server._OAUTH_SESSION_TTL_SECONDS - 1
|
||||
|
||||
web_server._gc_oauth_sessions()
|
||||
|
||||
with web_server._oauth_sessions_lock:
|
||||
remaining = len(web_server._oauth_sessions)
|
||||
assert remaining == 0, (
|
||||
f"{remaining}/{N} expired OAuth sessions survived _gc_oauth_sessions() "
|
||||
"-- the in-memory session table can grow without bound"
|
||||
)
|
||||
|
||||
with web_server._oauth_sessions_lock:
|
||||
web_server._oauth_sessions.clear()
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Regression tests for cross-process races refreshing Anthropic OAuth tokens.
|
||||
|
||||
``CredentialPool._refresh_entry`` explicitly documents (see the comment
|
||||
above the ``if self.provider in ("openai-codex", "xai-oauth"):`` branch in
|
||||
``agent/credential_pool.py``) that single-use OAuth refresh tokens require
|
||||
the whole sync -> POST -> write-back sequence to be serialized across
|
||||
Hermes *processes* via the cross-process ``_auth_store_lock`` flock,
|
||||
otherwise "two processes can both adopt the same on-disk token, both POST
|
||||
it, and the loser gets ``refresh_token_reused``".
|
||||
|
||||
Anthropic's OAuth refresh tokens have the identical single-use property --
|
||||
``agent.anthropic_adapter._refresh_oauth_token`` says so explicitly:
|
||||
"Claude Code's OAuth refresh tokens are single-use: a successful refresh
|
||||
rotates the pair and invalidates the old refresh token." Yet
|
||||
``"anthropic"`` is absent from the ``("openai-codex", "xai-oauth")`` tuple
|
||||
that gets the cross-process flock, and the *only* on-failure recovery path
|
||||
(``CredentialPool._sync_anthropic_entry_from_credentials_file``) is
|
||||
hard-scoped to ``entry.source == "claude_code"`` -- entries sourced from
|
||||
Hermes's own PKCE login (``hermes_pkce`` / ``manual:dashboard_pkce``) get
|
||||
no recovery at all and are marked exhausted on any lost race, even though
|
||||
a fresh, valid token pair exists on disk (written by the winner).
|
||||
|
||||
These tests reproduce that race deterministically with a fake OAuth server
|
||||
that enforces single-use refresh tokens, run two "process-local" pools
|
||||
concurrently against it, and assert the (currently absent) protection.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import replace as dc_replace
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.credential_pool import (
|
||||
AUTH_TYPE_OAUTH,
|
||||
STATUS_EXHAUSTED,
|
||||
CredentialPool,
|
||||
PooledCredential,
|
||||
)
|
||||
|
||||
|
||||
def _entry(*, id: str, access_token: str, refresh_token: str, source: str) -> PooledCredential:
|
||||
return PooledCredential(
|
||||
provider="anthropic",
|
||||
id=id,
|
||||
label="anthropic oauth",
|
||||
auth_type=AUTH_TYPE_OAUTH,
|
||||
priority=0,
|
||||
source=source,
|
||||
access_token=access_token,
|
||||
refresh_token=refresh_token,
|
||||
expires_at_ms=0, # already expired -> force path always refreshes
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fake_pool_store(monkeypatch):
|
||||
"""Back write/read_credential_pool with a shared in-memory dict.
|
||||
|
||||
This stands in for ``~/.hermes/auth.json`` so the two "process-local"
|
||||
CredentialPool instances used by the race tests can actually see each
|
||||
other's persisted writes (exactly what the real cross-process recovery
|
||||
path depends on), without touching the real filesystem.
|
||||
"""
|
||||
store: Dict[str, list] = {}
|
||||
|
||||
def _write(provider, entries, *, removed_ids=None):
|
||||
store[provider] = list(entries)
|
||||
|
||||
def _read(provider=None):
|
||||
if provider is None:
|
||||
return dict(store)
|
||||
return list(store.get(provider, []))
|
||||
|
||||
monkeypatch.setattr("agent.credential_pool.write_credential_pool", _write)
|
||||
monkeypatch.setattr("agent.credential_pool.read_credential_pool", _read)
|
||||
return store
|
||||
|
||||
|
||||
class _SingleUseTokenServer:
|
||||
"""Minimal fake of Anthropic's OAuth token endpoint.
|
||||
|
||||
Enforces the real single-use-refresh-token contract: the first caller
|
||||
to present a given refresh_token gets a fresh pair; every subsequent
|
||||
caller presenting that same (now-spent) refresh_token gets an
|
||||
``invalid_grant`` error, mirroring Anthropic's actual behavior.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
self._spent: set[str] = set()
|
||||
self._rotation = 0
|
||||
self.calls: list[str] = []
|
||||
# Small artificial delay to widen the race window deterministically.
|
||||
self.delay_seconds = 0.05
|
||||
|
||||
def refresh(self, refresh_token: str, *, use_json: bool = False):
|
||||
self.calls.append(refresh_token)
|
||||
time.sleep(self.delay_seconds)
|
||||
with self._lock:
|
||||
if refresh_token in self._spent:
|
||||
raise ValueError("invalid_grant: refresh token already used")
|
||||
self._spent.add(refresh_token)
|
||||
self._rotation += 1
|
||||
rotation = self._rotation
|
||||
return {
|
||||
"access_token": f"sk-ant-oat-rotated-{rotation}",
|
||||
"refresh_token": f"sk-ant-ort-rotated-{rotation}",
|
||||
"expires_at_ms": int(time.time() * 1000) + 3_600_000,
|
||||
}
|
||||
|
||||
|
||||
def test_anthropic_refresh_is_protected_by_cross_process_lock(monkeypatch):
|
||||
"""Structural check: anthropic refresh acquires ``_auth_store_lock``.
|
||||
|
||||
Regression guard for the gap where "anthropic" was missing from the
|
||||
``("openai-codex", "xai-oauth")`` tuple despite Anthropic OAuth refresh
|
||||
tokens being single-use too -- see the module docstring.
|
||||
"""
|
||||
lock_calls: list[str] = []
|
||||
|
||||
class _RecordingLock:
|
||||
def __init__(self, *a, **kw):
|
||||
lock_calls.append("anthropic")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr("agent.credential_pool._auth_store_lock", _RecordingLock)
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.refresh_anthropic_oauth_pure",
|
||||
lambda refresh_token, use_json=False: {
|
||||
"access_token": "sk-ant-oat-new",
|
||||
"refresh_token": "sk-ant-ort-new",
|
||||
"expires_at_ms": int(time.time() * 1000) + 3_600_000,
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.read_claude_code_credentials", lambda: None
|
||||
)
|
||||
|
||||
pool = CredentialPool(
|
||||
"anthropic",
|
||||
[_entry(id="a1", access_token="stale-at", refresh_token="stale-rt", source="manual:hermes_pkce")],
|
||||
)
|
||||
entry = pool.entries()[0]
|
||||
pool._refresh_entry(entry, force=True)
|
||||
|
||||
assert lock_calls, (
|
||||
"regression: CredentialPool._refresh_entry() for provider='anthropic' "
|
||||
"did not acquire the cross-process _auth_store_lock, even though "
|
||||
"Anthropic OAuth refresh tokens are single-use (same property "
|
||||
"openai-codex/xai-oauth are explicitly locked for)."
|
||||
)
|
||||
|
||||
|
||||
def test_concurrent_hermes_pkce_refresh_loses_credential_despite_valid_token_on_disk(monkeypatch):
|
||||
"""Two 'Hermes processes' race to refresh the same stale hermes_pkce
|
||||
refresh token. The winner gets a valid new pair. The loser -- despite a
|
||||
fresh, valid credential now existing -- has no recovery path and is
|
||||
marked exhausted, because ``_sync_anthropic_entry_from_credentials_file``
|
||||
only helps ``entry.source == "claude_code"``.
|
||||
"""
|
||||
server = _SingleUseTokenServer()
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.refresh_anthropic_oauth_pure",
|
||||
lambda refresh_token, use_json=False: server.refresh(refresh_token, use_json=use_json),
|
||||
)
|
||||
# No Claude Code credential file in play for this scenario.
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.read_claude_code_credentials", lambda: None
|
||||
)
|
||||
|
||||
shared_stale_entry = _entry(
|
||||
id="pool-entry",
|
||||
access_token="stale-at",
|
||||
refresh_token="stale-rt",
|
||||
source="manual:hermes_pkce",
|
||||
)
|
||||
|
||||
# Simulate two independent OS processes, each with its own in-memory
|
||||
# pool constructed from the SAME on-disk stale entry.
|
||||
pool_process_a = CredentialPool("anthropic", [dc_replace(shared_stale_entry)])
|
||||
pool_process_b = CredentialPool("anthropic", [dc_replace(shared_stale_entry)])
|
||||
|
||||
results: dict[str, object] = {}
|
||||
|
||||
def _run(pool, key):
|
||||
entry = pool.entries()[0]
|
||||
results[key] = pool._refresh_entry(entry, force=True)
|
||||
|
||||
t_a = threading.Thread(target=_run, args=(pool_process_a, "a"))
|
||||
t_b = threading.Thread(target=_run, args=(pool_process_b, "b"))
|
||||
t_a.start()
|
||||
t_b.start()
|
||||
t_a.join(timeout=5)
|
||||
t_b.join(timeout=5)
|
||||
|
||||
# With the cross-process lock in place, the second thread to acquire it
|
||||
# re-syncs from the pool store first and may adopt the winner's
|
||||
# already-persisted token before ever calling the token endpoint --
|
||||
# so only ONE call is expected now (the race is avoided entirely,
|
||||
# which is strictly better than the old behavior of two racing calls).
|
||||
# Both calls (if two do happen) must only ever spend the one stale
|
||||
# token that was actually on disk -- never anything else.
|
||||
assert 1 <= len(server.calls) <= 2, f"unexpected call count: {server.calls!r}"
|
||||
assert set(server.calls) == {"stale-rt"}, f"unexpected tokens posted: {server.calls!r}"
|
||||
|
||||
winner_result = results["a"] or results["b"]
|
||||
loser_key = "b" if results["a"] else "a"
|
||||
loser_result = results[loser_key]
|
||||
loser_pool = pool_process_b if loser_key == "b" else pool_process_a
|
||||
|
||||
assert winner_result is not None and winner_result.access_token.startswith(
|
||||
"sk-ant-oat-rotated-"
|
||||
), "the winning process should obtain a fresh, valid token pair"
|
||||
|
||||
# This is the bug: the loser should be able to recover (a valid token
|
||||
# now exists -- the winner's), not be left exhausted.
|
||||
assert loser_result is not None, (
|
||||
"regression: the losing process's CredentialPool._refresh_entry() "
|
||||
"returned None (unrecoverable) after losing the single-use-token "
|
||||
"race, even though a fresh valid Anthropic credential exists on "
|
||||
"disk. hermes_pkce-sourced entries must adopt the winner's token "
|
||||
"via _sync_anthropic_entry_from_pool_store(), same as claude_code."
|
||||
)
|
||||
loser_entry_after = loser_pool.entries()[0]
|
||||
assert loser_entry_after.last_status != STATUS_EXHAUSTED, (
|
||||
"regression: the losing process marked its Anthropic hermes_pkce "
|
||||
"credential STATUS_EXHAUSTED after a lost refresh race, even "
|
||||
"though the account is not actually exhausted -- a sibling Hermes "
|
||||
"process holds a perfectly valid rotated token. This causes "
|
||||
"spurious 're-authenticate with Anthropic' failures under "
|
||||
"ordinary concurrent Hermes usage (fleet workers, cron jobs, "
|
||||
"multiple CLI sessions)."
|
||||
)
|
||||
|
||||
|
||||
def test_concurrent_claude_code_refresh_recovers_via_credentials_file(monkeypatch):
|
||||
"""Contrast case: entry.source == 'claude_code' DOES recover from a lost
|
||||
race, because ``_sync_anthropic_entry_from_credentials_file`` re-reads
|
||||
``~/.claude/.credentials.json`` on failure. This asymmetry is itself
|
||||
evidence that hermes_pkce/dashboard-sourced credentials were simply
|
||||
never given the same treatment, not that recovery is impossible.
|
||||
"""
|
||||
server = _SingleUseTokenServer()
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.refresh_anthropic_oauth_pure",
|
||||
lambda refresh_token, use_json=False: server.refresh(refresh_token, use_json=use_json),
|
||||
)
|
||||
|
||||
winner_creds: dict = {}
|
||||
write_lock = threading.Lock()
|
||||
|
||||
def _fake_read_claude_code_credentials():
|
||||
with write_lock:
|
||||
return dict(winner_creds) if winner_creds else None
|
||||
|
||||
def _fake_write_claude_code_credentials(access_token, refresh_token, expires_at_ms, **_kw):
|
||||
with write_lock:
|
||||
winner_creds.update(
|
||||
accessToken=access_token,
|
||||
refreshToken=refresh_token,
|
||||
expiresAt=expires_at_ms,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter.read_claude_code_credentials",
|
||||
_fake_read_claude_code_credentials,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"agent.anthropic_adapter._write_claude_code_credentials",
|
||||
_fake_write_claude_code_credentials,
|
||||
)
|
||||
|
||||
shared_stale_entry = _entry(
|
||||
id="pool-entry",
|
||||
access_token="stale-at",
|
||||
refresh_token="stale-rt",
|
||||
source="claude_code",
|
||||
)
|
||||
pool_process_a = CredentialPool("anthropic", [dc_replace(shared_stale_entry)])
|
||||
pool_process_b = CredentialPool("anthropic", [dc_replace(shared_stale_entry)])
|
||||
|
||||
results: dict[str, object] = {}
|
||||
|
||||
def _run(pool, key):
|
||||
entry = pool.entries()[0]
|
||||
results[key] = pool._refresh_entry(entry, force=True)
|
||||
|
||||
t_a = threading.Thread(target=_run, args=(pool_process_a, "a"))
|
||||
t_b = threading.Thread(target=_run, args=(pool_process_b, "b"))
|
||||
t_a.start()
|
||||
t_b.start()
|
||||
t_a.join(timeout=5)
|
||||
t_b.join(timeout=5)
|
||||
|
||||
# Both processes should end up with a usable credential: the winner via
|
||||
# its own refresh, the loser via the credentials-file sync-and-retry.
|
||||
assert results["a"] is not None, "claude_code process A should recover"
|
||||
assert results["b"] is not None, "claude_code process B should recover"
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Regression tests for the Anthropic OAuth PKCE flow served by the web dashboard.
|
||||
|
||||
``hermes_cli.web_server._start_anthropic_pkce`` / ``_submit_anthropic_pkce``
|
||||
implement a *second*, independent copy of the Anthropic PKCE login flow
|
||||
(the first lives in ``agent.anthropic_adapter.run_hermes_oauth_login_pure``,
|
||||
used by the CLI). The CLI copy was hardened by PR #10699 (issue #10693)
|
||||
after PR #2647 silently reintroduced a vulnerable pattern that reused the
|
||||
PKCE ``code_verifier`` as the OAuth ``state`` parameter — see
|
||||
``tests/agent/test_anthropic_oauth_pkce.py``.
|
||||
|
||||
That hardening was never ported to the dashboard copy. This file proves the
|
||||
dashboard flow currently:
|
||||
|
||||
1. Sends the PKCE ``code_verifier`` verbatim as the ``state`` query
|
||||
parameter on the authorization URL handed to the browser
|
||||
(``hermes_cli/web_server.py`` ``_start_anthropic_pkce``), leaking a value
|
||||
that must stay confidential (RFC 7636 §7.2) via browser history, Referer
|
||||
headers, and Anthropic's own access logs.
|
||||
2. Never compares the ``state`` echoed back on the callback against the
|
||||
session-stored value in ``_submit_anthropic_pkce`` — the CSRF check
|
||||
required by RFC 6749 §10.12 is entirely absent on this path, unlike the
|
||||
CLI flow which aborts on ``received_state != oauth_state``.
|
||||
|
||||
Each test below asserts the *secure* behavior. Under the current code they
|
||||
are expected to FAIL, which is the evidence that the bug is real.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Dict
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _import_web_server():
|
||||
pytest.importorskip("hermes_cli.web_server")
|
||||
from hermes_cli import web_server
|
||||
|
||||
if not web_server._ANTHROPIC_OAUTH_AVAILABLE:
|
||||
pytest.skip("Anthropic OAuth adapter unavailable in this environment")
|
||||
return web_server
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
def __init__(self, body: bytes) -> None:
|
||||
self._body = body
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_exc):
|
||||
return False
|
||||
|
||||
def read(self) -> bytes:
|
||||
return self._body
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clean_oauth_sessions():
|
||||
"""Every test gets a pristine in-memory session table."""
|
||||
web_server = _import_web_server()
|
||||
with web_server._oauth_sessions_lock:
|
||||
web_server._oauth_sessions.clear()
|
||||
yield
|
||||
with web_server._oauth_sessions_lock:
|
||||
web_server._oauth_sessions.clear()
|
||||
|
||||
|
||||
def test_authorization_url_state_is_not_pkce_verifier():
|
||||
"""The ``state`` query param must NOT equal the PKCE ``code_verifier``.
|
||||
|
||||
Reusing the verifier as state leaks it via the authorization URL
|
||||
(browser history, Referer headers, auth-server access logs), defeating
|
||||
RFC 7636's confidentiality requirement for the verifier.
|
||||
"""
|
||||
web_server = _import_web_server()
|
||||
|
||||
session = web_server._start_anthropic_pkce()
|
||||
auth_url = session["auth_url"]
|
||||
qs = parse_qs(urlparse(auth_url).query)
|
||||
state_in_url = qs.get("state", [""])[0]
|
||||
|
||||
with web_server._oauth_sessions_lock:
|
||||
stored_verifier = web_server._oauth_sessions[session["session_id"]]["verifier"]
|
||||
|
||||
assert state_in_url != stored_verifier, (
|
||||
"Dashboard Anthropic PKCE flow sends the code_verifier as the "
|
||||
"OAuth 'state' parameter -- the exact pattern fixed for the CLI "
|
||||
"flow by PR #10699 (issue #10693), but never ported here. The "
|
||||
"verifier now leaks via the authorization URL."
|
||||
)
|
||||
|
||||
|
||||
def test_verifier_never_appears_anywhere_in_auth_url():
|
||||
"""Defense in depth: the verifier must not appear in ANY query value."""
|
||||
web_server = _import_web_server()
|
||||
|
||||
session = web_server._start_anthropic_pkce()
|
||||
auth_url = session["auth_url"]
|
||||
|
||||
with web_server._oauth_sessions_lock:
|
||||
stored_verifier = web_server._oauth_sessions[session["session_id"]]["verifier"]
|
||||
|
||||
assert stored_verifier not in auth_url, (
|
||||
"PKCE code_verifier leaked verbatim into the authorization URL "
|
||||
"returned to the browser by _start_anthropic_pkce()."
|
||||
)
|
||||
|
||||
|
||||
def test_state_is_cryptographically_independent_of_verifier():
|
||||
"""``state`` should be an independently generated anti-CSRF token.
|
||||
|
||||
A compliant implementation (mirroring
|
||||
``agent.anthropic_adapter.run_hermes_oauth_login_pure``) generates
|
||||
``state`` via a separate ``secrets.token_urlsafe(...)`` call rather than
|
||||
deriving it from the verifier/challenge at all.
|
||||
"""
|
||||
web_server = _import_web_server()
|
||||
|
||||
session_a = web_server._start_anthropic_pkce()
|
||||
session_b = web_server._start_anthropic_pkce()
|
||||
|
||||
with web_server._oauth_sessions_lock:
|
||||
verifier_a = web_server._oauth_sessions[session_a["session_id"]]["verifier"]
|
||||
state_a = web_server._oauth_sessions[session_a["session_id"]]["state"]
|
||||
verifier_b = web_server._oauth_sessions[session_b["session_id"]]["verifier"]
|
||||
state_b = web_server._oauth_sessions[session_b["session_id"]]["state"]
|
||||
|
||||
assert state_a != verifier_a, "session A: state == verifier (leak)"
|
||||
assert state_b != verifier_b, "session B: state == verifier (leak)"
|
||||
|
||||
|
||||
def test_submit_pkce_rejects_state_mismatch(monkeypatch):
|
||||
"""The token exchange must NOT proceed when the callback state does not
|
||||
match the state issued for this session (RFC 6749 Section 10.12 CSRF guard).
|
||||
|
||||
This mirrors ``tests/agent/test_anthropic_oauth_pkce.py``'s state-mismatch
|
||||
coverage for the CLI flow, applied to the dashboard's HTTP-facing
|
||||
equivalent.
|
||||
"""
|
||||
web_server = _import_web_server()
|
||||
|
||||
session = web_server._start_anthropic_pkce()
|
||||
session_id = session["session_id"]
|
||||
|
||||
captured_request: Dict[str, Any] = {}
|
||||
|
||||
def fake_urlopen(req, *_a, **_kw):
|
||||
captured_request["url"] = req.full_url
|
||||
captured_request["data"] = json.loads(req.data.decode())
|
||||
return _FakeResponse(json.dumps({
|
||||
"access_token": "sk-ant-attacker-exchanged",
|
||||
"refresh_token": "sk-ant-refresh",
|
||||
"expires_in": 3600,
|
||||
}).encode())
|
||||
|
||||
monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
|
||||
|
||||
# Attacker completes their OWN authorization and gets the victim to
|
||||
# paste a code carrying a state that does not match what
|
||||
# _start_anthropic_pkce issued for the victim's session (classic OAuth
|
||||
# login-CSRF: the attacker's code gets bound to the victim's account
|
||||
# because the callback endpoint never checks state).
|
||||
result = web_server._submit_anthropic_pkce(
|
||||
session_id, "attacker-code#attacker-controlled-state"
|
||||
)
|
||||
|
||||
assert not captured_request, (
|
||||
"Token exchange proceeded with a callback 'state' that did not "
|
||||
"match the session's issued state -- _submit_anthropic_pkce() "
|
||||
"performs no CSRF validation at all, unlike the CLI flow's "
|
||||
"'received_state != oauth_state' guard."
|
||||
)
|
||||
assert result.get("ok") is False
|
||||
|
||||
|
||||
def test_submit_pkce_with_no_state_suffix_does_not_silently_succeed(monkeypatch):
|
||||
"""Pasting a bare code (no ``#state`` suffix) must not bypass the CSRF
|
||||
check by silently falling back to the session's own state value.
|
||||
"""
|
||||
web_server = _import_web_server()
|
||||
|
||||
session = web_server._start_anthropic_pkce()
|
||||
session_id = session["session_id"]
|
||||
|
||||
captured_request: Dict[str, Any] = {}
|
||||
|
||||
def fake_urlopen(req, *_a, **_kw):
|
||||
captured_request["url"] = req.full_url
|
||||
captured_request["data"] = json.loads(req.data.decode())
|
||||
return _FakeResponse(json.dumps({
|
||||
"access_token": "sk-ant-should-not-be-issued",
|
||||
"refresh_token": "sk-ant-refresh",
|
||||
"expires_in": 3600,
|
||||
}).encode())
|
||||
|
||||
monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
|
||||
|
||||
result = web_server._submit_anthropic_pkce(session_id, "some-code-with-no-state")
|
||||
|
||||
assert not captured_request, (
|
||||
"_submit_anthropic_pkce() fell back to sess['state'] when the "
|
||||
"callback carried no state suffix at all -- this makes the state "
|
||||
"check a no-op rather than a genuine CSRF guard."
|
||||
)
|
||||
assert result.get("ok") is False
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Regression test for a Windows-only PermissionError under lock contention.
|
||||
|
||||
``_file_lock()`` (backing ``_auth_store_lock()``) ensures its lock file has
|
||||
at least 1 byte of content before opening it for ``msvcrt.locking()`` (which
|
||||
requires a non-empty file). That "ensure content" write was unguarded: under
|
||||
real concurrency, one thread/process's ``msvcrt.locking()`` byte-range lock
|
||||
can already be held on the file at the exact moment another thread runs the
|
||||
same ensure-content check, and the write collides and raises
|
||||
``PermissionError`` -- uncaught, since it happens before the retry loop the
|
||||
rest of the function uses for exactly this kind of contention.
|
||||
|
||||
This was found by a stress test for the Anthropic OAuth credential-pool fix
|
||||
(``tests/agent/test_anthropic_oauth_stress.py``), which reliably reproduces
|
||||
it (16/20 concurrent refreshes hit PermissionError pre-fix, deterministically
|
||||
across repeated runs) because the surrounding CredentialPool work widens the
|
||||
race window enough for real OS-level thread interleaving to land on it. That
|
||||
test is the authoritative regression guard for the exact failure mode. This
|
||||
file is deliberately a minimal, isolated stress test against
|
||||
``_auth_store_lock()`` directly -- best-effort coverage that does not always
|
||||
land on the same narrow window in isolation, but exercises the SAME shared
|
||||
primitive Codex/xAI/Nous already depend on for their single-use-refresh-token
|
||||
protection, so this bug was never Anthropic-specific.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli.auth import _auth_store_lock
|
||||
|
||||
CONCURRENCY = 40
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hermes_home(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_many_concurrent_lock_acquisitions_do_not_raise_permission_error(hermes_home):
|
||||
"""CONCURRENCY threads race to acquire/release the same auth-store lock.
|
||||
|
||||
None of them should ever see an uncaught PermissionError/OSError from
|
||||
the lock-file "ensure content" pre-check -- only the intended
|
||||
TimeoutError (never expected here, since each critical section is
|
||||
instant) should be a possible failure mode.
|
||||
"""
|
||||
errors: dict[int, BaseException] = {}
|
||||
entered = 0
|
||||
entered_lock = threading.Lock()
|
||||
# Synchronize all threads to hit the lock-file "ensure content" pre-check
|
||||
# at (as close as the OS scheduler allows to) the exact same instant --
|
||||
# the race only exists on the very first acquisition against a fresh
|
||||
# lock file, so a tight barrier maximizes the odds of reproducing it
|
||||
# instead of relying on incidental thread-start jitter.
|
||||
barrier = threading.Barrier(CONCURRENCY)
|
||||
|
||||
def _run(idx: int) -> None:
|
||||
nonlocal entered
|
||||
try:
|
||||
barrier.wait(timeout=10)
|
||||
with _auth_store_lock(timeout_seconds=10.0):
|
||||
with entered_lock:
|
||||
entered += 1
|
||||
except BaseException as exc: # pragma: no cover - failure diagnostics
|
||||
errors[idx] = exc
|
||||
|
||||
threads = [threading.Thread(target=_run, args=(i,)) for i in range(CONCURRENCY)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join(timeout=30)
|
||||
|
||||
still_alive = [t for t in threads if t.is_alive()]
|
||||
assert not still_alive, f"{len(still_alive)}/{CONCURRENCY} threads never finished"
|
||||
assert not errors, f"unexpected exceptions acquiring the lock concurrently: {errors!r}"
|
||||
assert entered == CONCURRENCY
|
||||
Reference in New Issue
Block a user