|
| 1 | +"""Tests for CEL guard.""" |
| 2 | + |
| 3 | +import pytest |
| 4 | +from fastapi.testclient import TestClient |
| 5 | +from utils import AppFactory |
| 6 | + |
| 7 | +app_factory = AppFactory( |
| 8 | + oidc_discovery_url="https://samples.auth0.com/.well-known/openid-configuration", |
| 9 | + default_public=False, |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +@pytest.mark.parametrize( |
| 14 | + "endpoint, expected_status_code", |
| 15 | + [ |
| 16 | + ("/", 403), |
| 17 | + ("/?foo=xyz", 403), |
| 18 | + ("/?bar=foo", 403), |
| 19 | + ("/?foo=bar", 200), |
| 20 | + ("/?foo=xyz&foo=bar", 200), # Only the last value is checked |
| 21 | + ("/?foo=bar&foo=xyz", 403), # Only the last value is checked |
| 22 | + ], |
| 23 | +) |
| 24 | +def test_guard_query_params( |
| 25 | + source_api_server, |
| 26 | + token_builder, |
| 27 | + endpoint, |
| 28 | + expected_status_code, |
| 29 | +): |
| 30 | + """Test guard with query parameters.""" |
| 31 | + app = app_factory( |
| 32 | + upstream_url=source_api_server, |
| 33 | + guard={ |
| 34 | + "cls": "stac_auth_proxy.guards.cel", |
| 35 | + "args": ('has(req.query_params.foo) && req.query_params.foo == "bar"',), |
| 36 | + }, |
| 37 | + ) |
| 38 | + client = TestClient(app, headers={"Authorization": f"Bearer {token_builder({})}"}) |
| 39 | + response = client.get(endpoint) |
| 40 | + assert response.status_code == expected_status_code |
| 41 | + |
| 42 | + |
| 43 | +@pytest.mark.parametrize( |
| 44 | + "token_payload, expected_status_code", |
| 45 | + [ |
| 46 | + ({"foo": "bar"}, 403), |
| 47 | + ({"collections": []}, 403), |
| 48 | + ({"collections": ["foo", "bar"]}, 403), |
| 49 | + ({"collections": ["xyz"]}, 200), |
| 50 | + ({"collections": ["foo", "xyz"]}, 200), |
| 51 | + ], |
| 52 | +) |
| 53 | +def test_guard_auth_token( |
| 54 | + source_api_server, |
| 55 | + token_builder, |
| 56 | + token_payload, |
| 57 | + expected_status_code, |
| 58 | +): |
| 59 | + """Test guard with auth token.""" |
| 60 | + app = app_factory( |
| 61 | + upstream_url=source_api_server, |
| 62 | + guard={ |
| 63 | + "cls": "stac_auth_proxy.guards.cel", |
| 64 | + "args": ( |
| 65 | + """ |
| 66 | + has(req.path_params.collection_id) && has(token.collections) && |
| 67 | + req.path_params.collection_id in (token.collections) |
| 68 | + """, |
| 69 | + ), |
| 70 | + }, |
| 71 | + ) |
| 72 | + client = TestClient( |
| 73 | + app, headers={"Authorization": f"Bearer {token_builder(token_payload)}"} |
| 74 | + ) |
| 75 | + response = client.get("/collections/xyz") |
| 76 | + assert response.status_code == expected_status_code |
0 commit comments