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"""Unit tests for request logging middleware identity extraction."""
from datetime import UTC, datetime
from types import SimpleNamespace
import pytest
from src.auth.base import Identity
from src.middleware.logging_middleware import _identity_fields
pytestmark = pytest.mark.unit
def _request(**state_attrs):
"""Minimal stand-in for a Request: only request.state is accessed."""
return SimpleNamespace(state=SimpleNamespace(**state_attrs))
def _identity() -> Identity:
now = datetime.now(UTC)
return Identity(
sub="zach",
email="zach@example.com",
name="Zach",
provider_id="basic",
issued_at=now,
expires_at=now,
)
def test_anonymous_request_yields_no_fields():
assert _identity_fields(_request()) == {}
def test_session_identity_surfaces_user_fields():
fields = _identity_fields(_request(identity=_identity()))
assert fields == {
"user_sub": "zach",
"user_email": "zach@example.com",
"user_provider": "basic",
}
def test_api_key_label_surfaces_without_session_identity():
fields = _identity_fields(_request(api_key_label="daisy"))
assert fields == {"api_key_label": "daisy"}
def test_session_and_api_key_both_surface():
fields = _identity_fields(_request(identity=_identity(), api_key_label="svc"))
assert fields["user_sub"] == "zach"
assert fields["api_key_label"] == "svc"
def test_non_identity_value_is_ignored():
# A truthy non-Identity (e.g. a MagicMock in upstream tests) must not
# be mistaken for a real identity.
fields = _identity_fields(_request(identity="not-an-identity", api_key_label=123))
assert fields == {}