๐Ÿ“ฆ EqualifyEverything / equalify-reflow

๐Ÿ“„ test_apikey_identity_shortcircuit.py ยท 94 lines
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94"""APIKeyAuthMiddleware short-circuits on a real :class:`Identity`.

This pins the security contract: when ``SessionAuthMiddleware`` has
populated ``request.state.identity`` with a real ``Identity`` object, the
api-key middleware treats the request as authenticated. Crucially, a
``MagicMock`` (or any other truthy non-Identity value) must NOT satisfy
the check โ€” earlier iterations of the middleware used a truthy guard and
silently disabled api-key auth in mock-based tests.
"""

from __future__ import annotations

from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock

import pytest
from fastapi import Request
from src.auth.base import Identity
from src.middleware.api_key_auth import APIKeyAuthMiddleware


def _make_request(*, identity: object | None) -> Request:
    """Build a synthetic Request hitting an /api/* path with no API key
    header and no same-origin signals โ€” so the only thing that can satisfy
    ``_is_public_endpoint`` is the identity short-circuit.
    """
    req = MagicMock(spec=Request)
    req.url.path = "/api/v1/feedback/config"
    req.headers = MagicMock()
    req.headers.get = MagicMock(return_value=None)
    req.query_params = {}
    state = MagicMock()
    state.identity = identity
    req.state = state
    return req


def _real_identity() -> Identity:
    now = datetime.now(UTC)
    return Identity(
        sub="alice",
        email=None,
        name="alice",
        provider_id="basic",
        issued_at=now,
        expires_at=now + timedelta(hours=1),
    )


@pytest.fixture
def middleware() -> APIKeyAuthMiddleware:
    return APIKeyAuthMiddleware(MagicMock())


@pytest.mark.unit
def test_real_identity_short_circuits(middleware: APIKeyAuthMiddleware) -> None:
    request = _make_request(identity=_real_identity())
    assert middleware._is_public_endpoint(request) is True


@pytest.mark.unit
def test_no_identity_does_not_short_circuit(middleware: APIKeyAuthMiddleware) -> None:
    request = _make_request(identity=None)
    assert middleware._is_public_endpoint(request) is False


@pytest.mark.unit
def test_magicmock_identity_does_not_short_circuit(
    middleware: APIKeyAuthMiddleware,
) -> None:
    """MagicMock attributes are always truthy. If the middleware ever drops
    its ``isinstance(_, Identity)`` check, this test fails immediately โ€”
    silent-bypass regression caught before it ships.
    """
    request = _make_request(identity=MagicMock())
    assert middleware._is_public_endpoint(request) is False


@pytest.mark.unit
def test_identity_lookalike_does_not_short_circuit(
    middleware: APIKeyAuthMiddleware,
) -> None:
    """A class with the right attribute names but wrong type must not pass.
    Reinforces that we ``isinstance``-check, not duck-type."""

    class FakeIdentity:
        sub = "alice"
        email = None
        name = "alice"
        provider_id = "basic"

    request = _make_request(identity=FakeIdentity())
    assert middleware._is_public_endpoint(request) is False