File size: 4,008 Bytes
2bb5af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""Token verification.

The project migrated its Supabase signing key to ES256 on a P-256 curve. The
verifier originally accepted HS256 only, so every real token was rejected with
"the specified alg value is not allowed" and no screen could load.

These tests pin the two things that matter: an asymmetric token verifies
against the published public key, and nothing else gets in - in particular a
caller cannot pick the weaker algorithm by asking for it.
"""

from __future__ import annotations

import time

import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric import ec

from app.core import auth
from app.core.auth import AuthError, decode_token


def claims(**over) -> dict:
    return {
        "sub": "3f6f3a4e-6f1e-4a1a-9c2e-2f7a1b8c9d01",
        "aud": "authenticated",
        "exp": int(time.time()) + 600,
        "email": "person@example.test",
        **over,
    }


@pytest.fixture
def es256(monkeypatch):
    """Stand in for Supabase's JWKS with a key generated here."""
    private = ec.generate_private_key(ec.SECP256R1())

    class FakeKey:
        key = private.public_key()

    class FakeClient:
        def get_signing_key_from_jwt(self, _token):
            return FakeKey()

    monkeypatch.setattr(auth, "_jwks_client", lambda: FakeClient())
    return private


def test_asymmetric_token_is_accepted(es256, monkeypatch):
    monkeypatch.setattr(auth.settings, "supabase_url", "https://project.supabase.co")
    token = jwt.encode(claims(), es256, algorithm="ES256")

    decoded = decode_token(token)

    assert decoded["email"] == "person@example.test"


def test_a_token_signed_by_a_different_key_is_rejected(es256, monkeypatch):
    monkeypatch.setattr(auth.settings, "supabase_url", "https://project.supabase.co")
    other = ec.generate_private_key(ec.SECP256R1())
    token = jwt.encode(claims(), other, algorithm="ES256")

    with pytest.raises(AuthError, match="invalid token"):
        decode_token(token)


def test_symmetric_tokens_still_verify_against_the_shared_secret(monkeypatch):
    """Projects that have not migrated their signing key still work."""
    secret = "a-shared-secret-long-enough-for-sha256"
    monkeypatch.setattr(auth.settings, "supabase_jwt_secret", secret)
    token = jwt.encode(claims(), secret, algorithm="HS256")

    assert decode_token(token)["sub"].startswith("3f6f3a4e")


def test_the_algorithm_is_chosen_by_the_header_not_by_falling_through(monkeypatch):
    """An HS256 token must never be checked against the public key material.

    If the verifier tried each algorithm in turn, a caller could sign with the
    public key as if it were an HMAC secret and be let in.
    """
    monkeypatch.setattr(auth.settings, "supabase_jwt_secret", "")
    token = jwt.encode(claims(), "anything", algorithm="HS256")

    with pytest.raises(AuthError, match="not configured"):
        decode_token(token)


def test_unsigned_tokens_are_refused(monkeypatch):
    monkeypatch.setattr(auth.settings, "supabase_jwt_secret", "x" * 40)
    token = jwt.encode(claims(), key="", algorithm="none")

    with pytest.raises(AuthError, match="unsupported signing algorithm"):
        decode_token(token)


def test_expired_tokens_say_so(monkeypatch):
    secret = "a-shared-secret-long-enough-for-sha256"
    monkeypatch.setattr(auth.settings, "supabase_jwt_secret", secret)
    token = jwt.encode(claims(exp=int(time.time()) - 60), secret, algorithm="HS256")

    with pytest.raises(AuthError, match="expired"):
        decode_token(token)


def test_a_token_for_another_audience_is_rejected(monkeypatch):
    secret = "a-shared-secret-long-enough-for-sha256"
    monkeypatch.setattr(auth.settings, "supabase_jwt_secret", secret)
    token = jwt.encode(claims(aud="anon"), secret, algorithm="HS256")

    with pytest.raises(AuthError, match="invalid token"):
        decode_token(token)


def test_garbage_is_not_mistaken_for_a_token():
    with pytest.raises(AuthError, match="malformed token"):
        decode_token("not-a-jwt")