← back to Paul Conrad Archive

tests/test_auth.py

44 lines

import base64

import pytest
from fastapi.testclient import TestClient


def _hdr(u, p):
    return {"Authorization": "Basic " + base64.b64encode(f"{u}:{p}".encode()).decode()}


def test_basic_auth_enforced_everywhere(tmpdb, monkeypatch):
    monkeypatch.setenv("CONRAD_BASIC_USER", "steve")
    monkeypatch.setenv("CONRAD_BASIC_PASS", "s3cret")
    from conrad.web.app import create_app
    c = TestClient(create_app())
    for path in ["/", "/api/search?q=nixon", "/api/facets", "/static/app.js", "/cartoon/1"]:
        r = c.get(path)
        assert r.status_code == 401, path
        assert "Basic" in r.headers["www-authenticate"]
        assert r.headers["x-robots-tag"].startswith("noindex")
    assert c.get("/", headers=_hdr("steve", "wrong")).status_code == 401
    ok = c.get("/", headers=_hdr("steve", "s3cret"))
    assert ok.status_code == 200 and 'content="noindex,nofollow"' in ok.text
    assert ok.headers["x-robots-tag"].startswith("noindex")
    assert c.get("/api/search?q=nixon", headers=_hdr("steve", "s3cret")).status_code == 200
    r = c.get("/robots.txt")  # crawlers may read the Disallow without creds
    assert r.status_code == 200 and "Disallow: /" in r.text


def test_require_auth_fails_closed(monkeypatch):
    monkeypatch.delenv("CONRAD_BASIC_USER", raising=False)
    monkeypatch.delenv("CONRAD_BASIC_PASS", raising=False)
    monkeypatch.setenv("CONRAD_REQUIRE_AUTH", "1")
    from conrad.web.app import AuthConfigError, create_app
    with pytest.raises(AuthConfigError):
        create_app()


def test_no_auth_when_unset(tmpdb, monkeypatch):
    for k in ("CONRAD_BASIC_USER", "CONRAD_BASIC_PASS", "CONRAD_REQUIRE_AUTH"):
        monkeypatch.delenv(k, raising=False)
    from conrad.web.app import create_app
    assert TestClient(create_app()).get("/api/stats").status_code == 200