File size: 2,010 Bytes
aee78d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2020c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Minimal tests for auth proxy behavior.

These tests focus on authorization gate decisions only (unit-level),
not full end-to-end proxy networking.
"""

from fastapi.testclient import TestClient
from src.foodwise.mcp_server.auth_proxy import app


def test_health_no_auth_required():
    client = TestClient(app)
    resp = client.get("/health")
    assert resp.status_code == 200
    assert resp.json() == {"status": "ok"}


def test_unauthorized_without_token(monkeypatch):
    # Configure a token and ensure missing creds yields 401
    monkeypatch.setenv("MCP_AUTH_TOKEN", "secret-token")
    client = TestClient(app)
    resp = client.get("/mcp/")
    assert resp.status_code == 401
    assert resp.headers.get("WWW-Authenticate") == "Bearer"


def test_authorized_with_bearer_header(monkeypatch):
    monkeypatch.setenv("MCP_AUTH_TOKEN", "secret-token")
    client = TestClient(app)
    # We don't hit the upstream in this unit test; ensure auth layer allows request to proceed to proxy layer
    resp = client.get("/mcp/", headers={"Authorization": "Bearer secret-token"})
    # Upstream is not running in tests; expect Bad Gateway (proxy attempted forward)
    assert resp.status_code in (502, 503)


def test_authorized_with_query_key(monkeypatch):
    monkeypatch.setenv("MCP_AUTH_TOKEN", "secret-token")
    client = TestClient(app)
    resp = client.get("/mcp/?key=secret-token")
    # Upstream is not running in tests; expect Bad Gateway (proxy attempted forward)
    assert resp.status_code in (502, 503)


def test_multiple_tokens_supported(monkeypatch):
    # Multiple tokens accepted via MCP_AUTH_TOKENS
    monkeypatch.delenv("MCP_AUTH_TOKEN", raising=False)
    monkeypatch.setenv("MCP_AUTH_TOKENS", "alpha, beta , gamma")
    client = TestClient(app)

    # Wrong token → 401
    resp1 = client.get("/mcp/?key=delta")
    assert resp1.status_code == 401

    # Any listed token → forward attempted
    resp2 = client.get("/mcp/?key=beta")
    assert resp2.status_code in (502, 503)