File size: 5,749 Bytes
5de6e8f
 
 
 
 
8b35696
5de6e8f
 
e90638c
5de6e8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e90638c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5de6e8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b35696
 
 
 
 
 
 
 
 
 
 
 
 
e90638c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""Tests for authenticated HF token propagation through backend dependencies."""

import sys
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qs, urlparse

import pytest
from fastapi import HTTPException

_BACKEND_DIR = Path(__file__).resolve().parent.parent.parent / "backend"
if str(_BACKEND_DIR) not in sys.path:
    sys.path.insert(0, str(_BACKEND_DIR))

import dependencies  # noqa: E402
from routes import auth  # noqa: E402


@pytest.mark.asyncio
async def test_current_user_carries_internal_hf_token(monkeypatch):
    monkeypatch.setattr(dependencies, "AUTH_ENABLED", True)
    dependencies._token_cache.clear()

    async def fake_validate_token(token):
        assert token == "hf-user-token"
        return {"sub": "user-id", "preferred_username": "alice"}

    async def fake_fetch_user_plan(token):
        assert token == "hf-user-token"
        return "pro"

    monkeypatch.setattr(dependencies, "_validate_token", fake_validate_token)
    monkeypatch.setattr(dependencies, "_fetch_user_plan", fake_fetch_user_plan)

    request = SimpleNamespace(
        headers={"Authorization": "Bearer hf-user-token"},
        cookies={},
    )

    user = await dependencies.get_current_user(request)

    assert user["user_id"] == "user-id"
    assert user["username"] == "alice"
    assert user["plan"] == "pro"
    assert user[dependencies.INTERNAL_HF_TOKEN_KEY] == "hf-user-token"


@pytest.mark.asyncio
async def test_cookie_auth_requires_current_oauth_scope_marker(monkeypatch):
    monkeypatch.setattr(dependencies, "AUTH_ENABLED", True)

    request = SimpleNamespace(
        headers={},
        cookies={"hf_access_token": "hf-user-token"},
    )

    with pytest.raises(HTTPException) as exc_info:
        await dependencies.get_current_user(request)

    assert exc_info.value.status_code == 401
    assert "scopes changed" in exc_info.value.detail


@pytest.mark.asyncio
async def test_cookie_auth_accepts_current_oauth_scope_marker(monkeypatch):
    monkeypatch.setattr(dependencies, "AUTH_ENABLED", True)
    dependencies._token_cache.clear()

    async def fake_validate_token(token):
        assert token == "hf-user-token"
        return {"sub": "user-id", "preferred_username": "alice"}

    async def fake_fetch_user_plan(token):
        assert token == "hf-user-token"
        return "pro"

    monkeypatch.setattr(dependencies, "_validate_token", fake_validate_token)
    monkeypatch.setattr(dependencies, "_fetch_user_plan", fake_fetch_user_plan)

    request = SimpleNamespace(
        headers={},
        cookies={
            "hf_access_token": "hf-user-token",
            dependencies.OAUTH_SCOPE_COOKIE: dependencies.oauth_scope_fingerprint(),
        },
    )

    user = await dependencies.get_current_user(request)

    assert user["user_id"] == "user-id"
    assert user[dependencies.INTERNAL_HF_TOKEN_KEY] == "hf-user-token"


@pytest.mark.asyncio
async def test_auth_me_does_not_expose_internal_hf_token():
    user = {
        "user_id": "user-id",
        "username": "alice",
        "authenticated": True,
        dependencies.INTERNAL_HF_TOKEN_KEY: "hf-user-token",
    }

    response = await auth.get_me(user)

    assert response == {
        "user_id": "user-id",
        "username": "alice",
        "authenticated": True,
    }


@pytest.mark.asyncio
async def test_oauth_login_requests_collection_write_scope(monkeypatch):
    monkeypatch.setattr(auth, "OAUTH_CLIENT_ID", "oauth-client")
    monkeypatch.setenv("SPACE_HOST", "example.hf.space")
    auth.oauth_states.clear()

    response = await auth.oauth_login(SimpleNamespace())
    params = parse_qs(urlparse(response.headers["location"]).query)
    scopes = set(params["scope"][0].split())

    assert "write-collections" in scopes


def test_oauth_callback_detects_missing_required_collection_scope():
    granted = [scope for scope in auth.OAUTH_SCOPES if scope != "write-collections"]

    assert auth._missing_required_scopes({"scope": " ".join(granted)}) == {
        "write-collections"
    }


def test_oauth_callback_treats_absent_scope_as_full_grant():
    assert auth._missing_required_scopes({}) == set()


@pytest.mark.asyncio
async def test_oauth_callback_sets_scope_marker_cookie(monkeypatch):
    monkeypatch.setenv("SPACE_HOST", "example.hf.space")
    auth.oauth_states.clear()
    auth.oauth_states["state"] = {
        "redirect_uri": "https://example.hf.space/auth/callback",
        "expires_at": 9999999999,
    }

    class FakeResponse:
        def __init__(self, payload):
            self._payload = payload

        def raise_for_status(self):
            return None

        def json(self):
            return self._payload

    class FakeAsyncClient:
        def __init__(self, *args, **kwargs):
            pass

        async def __aenter__(self):
            return self

        async def __aexit__(self, *args):
            return None

        async def post(self, *args, **kwargs):
            return FakeResponse(
                {
                    "access_token": "hf-user-token",
                    "scope": " ".join(auth.OAUTH_SCOPES),
                }
            )

        async def get(self, *args, **kwargs):
            return FakeResponse({})

    monkeypatch.setattr(auth.httpx, "AsyncClient", FakeAsyncClient)

    response = await auth.oauth_callback(SimpleNamespace(), code="code", state="state")
    set_cookies = [
        value.decode("latin-1")
        for key, value in response.raw_headers
        if key == b"set-cookie"
    ]

    expected = (
        f"{dependencies.OAUTH_SCOPE_COOKIE}="
        f"{dependencies.oauth_scope_fingerprint(auth.OAUTH_SCOPES)}"
    )
    assert any(cookie.startswith(expected) for cookie in set_cookies)