Files
OpenJarvis/tests/server/test_auth_middleware.py
T
928776a71c ci: enforce ruff format in CI, add Makefile matching the CI test lane (#625)
CI's lint job ran ruff check but never ruff format --check, letting format drift land silently (79 files had drifted from the pinned ruff 0.15.1). Add the ruff format --check step to ci.yml, reformat the 79 drifted files with the pinned ruff (mechanical only — verified AST-identical to before across all files, no logic changes), and add a Makefile whose test target mirrors the actual CI lane.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 14:49:18 -07:00

85 lines
2.3 KiB
Python

"""Tests for API key authentication middleware."""
from __future__ import annotations
import pytest
pytest.importorskip("fastapi", reason="openjarvis[server] not installed")
from fastapi import FastAPI
from fastapi.testclient import TestClient
from openjarvis.server.auth_middleware import AuthMiddleware
def _make_app(api_key: str) -> FastAPI:
app = FastAPI()
app.add_middleware(AuthMiddleware, api_key=api_key)
@app.get("/v1/models")
async def models():
return {"models": []}
@app.get("/health")
async def health():
return {"status": "ok"}
@app.post("/webhooks/twilio")
async def twilio_webhook():
return {"status": "received"}
@app.get("/metrics")
async def metrics():
return {"requests": 0}
return app
@pytest.fixture
def client():
return TestClient(_make_app("oj_sk_test123"))
class TestAuthMiddleware:
def test_rejects_missing_auth_header(self, client):
resp = client.get("/v1/models")
assert resp.status_code == 401
assert "missing" in resp.json()["detail"].lower()
def test_rejects_wrong_key(self, client):
resp = client.get(
"/v1/models",
headers={"Authorization": "Bearer wrong"},
)
assert resp.status_code == 401
assert "invalid" in resp.json()["detail"].lower()
def test_accepts_valid_key(self, client):
resp = client.get(
"/v1/models",
headers={"Authorization": "Bearer oj_sk_test123"},
)
assert resp.status_code == 200
def test_health_exempt(self, client):
resp = client.get("/health")
assert resp.status_code == 200
def test_webhooks_exempt(self, client):
resp = client.post("/webhooks/twilio")
assert resp.status_code == 200
def test_metrics_requires_auth(self, client):
resp = client.get("/metrics")
assert resp.status_code == 401
def test_metrics_accepts_valid_key(self, client):
resp = client.get("/metrics", headers={"Authorization": "Bearer oj_sk_test123"})
assert resp.status_code == 200
def test_no_key_configured_allows_all(self):
client = TestClient(_make_app(""))
resp = client.get("/v1/models")
assert resp.status_code == 200
assert client.get("/metrics").status_code == 200