File size: 6,961 Bytes
6049960
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e880b2b
6049960
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e880b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io, time, os
from pathlib import Path
from fastapi.testclient import TestClient
from app.server import create_app
from app import access

def owner_cookie(app, user="2Btainment"):
    s = access.Sessions(app.state.service.base_root)
    return s.sign({"kind": "hf", "user": user, "sid": "a"*32, "exp": int(time.time()) + 3600})

def test_isolation(tmp_path):
    app = create_app(tmp_path)
    owner = TestClient(app); owner.cookies.set(access.COOKIE, owner_cookie(app))
    assert owner.get("/api/v1/me").json()["owner"] is True
    wav = (Path(__file__).parents[1] / "app/static/demo.wav").read_bytes()
    pid = owner.post("/api/v1/projects", json={"name": "rob"}).json()["id"]
    assert owner.post("/api/v1/assets", data={"project_id": pid}, files={"file": ("d.wav", wav, "audio/wav")}).status_code == 201
    assert (tmp_path / pid / "manifest.json").is_file()
    oj = owner.post("/api/v1/jobs/separate", json={"project_id": pid, "model": "hpss"}).json()
    for client in (TestClient(app), ):
        client.get("/api/v1/me"); me = client.get("/api/v1/me").json()
        assert me["owner"] is False and me["namespace"] == "guest"
        assert client.get("/api/v1/projects").json()["projects"] == []
        for r in (client.get(f"/api/v1/projects/{pid}"), client.get(f"/api/v1/projects/{pid}/audio/original"),
                  client.get(f"/api/v1/projects/{pid}/export"), client.get(f"/api/v1/projects/{pid}/stems"),
                  client.patch(f"/api/v1/projects/{pid}", json={"name": "x"}),
                  client.post("/api/v1/jobs/separate", json={"project_id": pid, "model": "demucs"}),
                  client.post("/api/v1/jobs/mix", json={"project_id": pid}),
                  client.post("/api/v1/jobs/fusion", json={"project_id": pid}),
                  client.get(f"/api/v1/jobs/{oj['id']}")):
            assert r.status_code in (403, 404), (r.request.url, r.status_code)
        g = client.post("/api/v1/projects", json={"name": "guest"}).json()["id"]
        assert client.post("/api/v1/assets", data={"project_id": g}, files={"file": ("d.wav", wav, "audio/wav")}).status_code == 201
        assert not (tmp_path / g).exists() and list((tmp_path / "guests").glob(f"*/{g}/manifest.json"))
        assert [p["id"] for p in client.get("/api/v1/projects").json()["projects"]] == [g]
        assert all(p["id"] != g for p in owner.get("/api/v1/projects").json()["projects"])
        assert owner.get(f"/api/v1/projects/{g}").status_code == 404
        other = TestClient(app); other.get("/api/v1/me")
        assert other.get(f"/api/v1/projects/{g}").status_code == 404
        j = client.post("/api/v1/jobs/separate", json={"project_id": g, "model": "hpss"}).json()
        assert other.get(f"/api/v1/jobs/{j['id']}").status_code == 404
        for _ in range(200):
            st = client.get(f"/api/v1/jobs/{j['id']}").json()
            if st["status"] in ("done", "failed"): break
            time.sleep(0.1)
        assert st["status"] == "done", st
        assert list((tmp_path / "guests").glob(f"*/{g}/stems/*.wav"))
    assert owner.get(f"/api/v1/projects/{pid}").json()["name"] == "rob"

def test_owner_check(tmp_path):
    s = access.Sessions(tmp_path)
    assert s.is_owner({"kind": "hf", "user": "2Btainment"})
    for bad in ({"kind": "hf", "user": "2btainment"}, {"kind": "hf", "user": "eve"},
                {"kind": "anon", "user": "2Btainment"}, None, {}):
        assert not s.is_owner(bad)
    tok = s.sign({"kind": "hf", "user": "eve", "exp": int(time.time()) + 60})
    body, mac = tok.rsplit(".", 1)
    forged = access._b64(b'{"kind":"hf","user":"2Btainment","exp":9999999999}') + "." + mac
    assert s.verify(forged) is None
    assert s.verify(s.sign({"kind": "hf", "user": "x", "exp": 1})) is None
    assert s.namespace({"kind": "hf", "user": "2Btainment"})[1] == tmp_path
    assert s.namespace({"kind": "hf", "user": "eve"})[1] == tmp_path / "guests" / "hf-eve"

def test_cleanup_only_guests(tmp_path):
    s = access.Sessions(tmp_path)
    owner_proj = tmp_path / "11111111-1111-1111-1111-111111111111"; owner_proj.mkdir()
    (owner_proj / "manifest.json").write_text("{}"); os.utime(owner_proj / "manifest.json", (0, 0))
    old = tmp_path / "guests" / "anon-ab" / "p1"; old.mkdir(parents=True); (old / "manifest.json").write_text("{}")
    os.utime(old / "manifest.json", (0, 0))
    new = tmp_path / "guests" / "anon-cd" / "p2"; new.mkdir(parents=True); (new / "manifest.json").write_text("{}")
    assert s.cleanup() == 1
    assert owner_proj.exists() and new.exists() and not old.exists()

def test_oauth_flow_simulated(tmp_path, monkeypatch):
    monkeypatch.setenv("OAUTH_CLIENT_ID", "cid"); monkeypatch.setenv("OAUTH_CLIENT_SECRET", "sec")
    monkeypatch.setenv("SPACE_HOST", "example.hf.space")
    app = create_app(tmp_path); c = TestClient(app)
    r = c.get("/login", follow_redirects=False)
    assert r.status_code == 302 and r.headers["location"].startswith("https://huggingface.co/oauth/authorize?client_id=cid")
    assert "redirect_uri=https%3A%2F%2Fexample.hf.space%2Flogin%2Fcallback" in r.headers["location"]
    state = c.cookies.get("omega_oauth_state")
    assert c.get("/login/callback?code=x&state=wrong", follow_redirects=False).status_code == 400
    for user, is_owner in (("eve", False), ("2Btainment", True)):
        monkeypatch.setattr(access, "exchange_code", lambda cfg, code, red: "tok")
        monkeypatch.setattr(access, "fetch_username", lambda cfg, tok, u=user: u)
        c.cookies.set("omega_oauth_state", state)
        r = c.get(f"/login/callback?code=x&state={state}", follow_redirects=False)
        assert r.status_code == 302
        c.cookies.set(access.COOKIE, r.cookies.get(access.COOKIE) or r.headers["set-cookie"].split(";")[0].split("=",1)[1])
        me = c.get("/api/v1/me").json()
        assert me["owner"] is is_owner and me["user"] == user

def test_fusion_scoped_to_guest(tmp_path):
    app = create_app(tmp_path)
    wav = (Path(__file__).parents[1] / "app/static/demo.wav").read_bytes()
    g = TestClient(app); g.get("/api/v1/me")
    pid = g.post("/api/v1/projects", json={"name": "g"}).json()["id"]
    g.post("/api/v1/assets", data={"project_id": pid}, files={"file": ("d.wav", wav, "audio/wav")})
    other = TestClient(app); other.get("/api/v1/me")
    assert other.post("/api/v1/jobs/fusion", json={"project_id": pid}).status_code == 404
    r = g.post("/api/v1/jobs/fusion", json={"project_id": pid, "mode": "auto"})
    assert r.status_code == 202 and "ns_root" not in r.json()
    jid = r.json()["id"]
    assert other.get(f"/api/v1/jobs/{jid}").status_code == 404
    for _ in range(600):
        st = g.get(f"/api/v1/jobs/{jid}").json()
        if st["status"] in ("done", "failed"): break
        time.sleep(0.1)
    assert st["status"] == "done", st
    m = g.get(f"/api/v1/projects/{pid}").json()
    assert m["fusion"]["stems"] and m["fusion"]["mixture_consistent"]
    assert not (tmp_path / pid).exists()