From 4602bb9494cb4f061e84f17e8638c6acb4c30ac7 Mon Sep 17 00:00:00 2001 From: shay Date: Sun, 19 Apr 2026 18:49:39 -0400 Subject: [PATCH] test(auth): unit tests for require_github_owner and require_same_origin --- generator/tests/test_auth.py | 69 ++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 generator/tests/test_auth.py diff --git a/generator/tests/test_auth.py b/generator/tests/test_auth.py new file mode 100644 index 0000000..1efa0bb --- /dev/null +++ b/generator/tests/test_auth.py @@ -0,0 +1,69 @@ +"""Unit tests for auth helpers (no network).""" +import pytest +from flask import Flask, jsonify + +from src import auth, config + + +@pytest.fixture +def app(monkeypatch): + monkeypatch.setattr(config, "ALLOWED_ORIGINS", ("https://gh-stats.com",)) + app = Flask(__name__) + app.secret_key = "test-secret" + + @app.route("/protected/", methods=["POST"]) + @auth.require_same_origin + @auth.require_github_owner + def protected(username): + return jsonify({"ok": True, "you": auth.current_login()}) + + return app + + +def _good_hdrs(): + return {"Origin": "https://gh-stats.com"} + + +def test_current_login_none_by_default(app): + with app.test_request_context("/"): + assert auth.current_login() is None + + +def test_require_github_owner_401_without_session(app): + with app.test_client() as c: + r = c.post("/protected/alice", headers=_good_hdrs()) + assert r.status_code == 401 + assert r.get_json()["error"] == "login_required" + + +def test_require_github_owner_403_on_mismatch(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "bob" + r = c.post("/protected/alice", headers=_good_hdrs()) + assert r.status_code == 403 + + +def test_require_github_owner_passes_with_matching_login(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "Alice" # stored mixed-case on purpose + r = c.post("/protected/alice", headers=_good_hdrs()) + assert r.status_code == 200 + assert r.get_json()["you"] == "alice" + + +def test_require_same_origin_rejects_bad_origin(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "alice" + r = c.post("/protected/alice", headers={"Origin": "https://evil.example"}) + assert r.status_code == 403 + + +def test_require_same_origin_rejects_missing_origin(app): + with app.test_client() as c: + with c.session_transaction() as s: + s["gh_login"] = "alice" + r = c.post("/protected/alice") + assert r.status_code == 403