-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add first pass of using CEL for custom auth policies
- Loading branch information
Showing
7 changed files
with
332 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
from dataclasses import dataclass | ||
from typing import Any | ||
|
||
from fastapi import Request, Depends, HTTPException | ||
import celpy | ||
|
||
|
||
@dataclass | ||
class Cel: | ||
"""Custom middleware.""" | ||
|
||
expression: str | ||
token_dependency: Any | ||
|
||
def __post_init__(self): | ||
env = celpy.Environment() | ||
ast = env.compile(self.expression) | ||
self.program = env.program(ast) | ||
|
||
async def check( | ||
request: Request, | ||
auth_token=Depends(self.token_dependency), | ||
): | ||
request_data = { | ||
"path": request.url.path, | ||
"method": request.method, | ||
"query_params": dict(request.query_params), # Convert to a dict | ||
"headers": dict(request.headers), # Convert headers to a dict if needed | ||
# Body may need to be read (await request.json()) or (await request.body()) if needed | ||
"body": ( | ||
await request.json() | ||
if request.headers.get("content-type") == "application/json" | ||
else (await request.body()).decode() | ||
), | ||
} | ||
|
||
activation = {"req": request_data, "token": auth_token} | ||
print(f"{activation=}") | ||
result = self.program.evaluate(celpy.json_to_cel(activation)) | ||
print(f"{result=}") | ||
if not result: | ||
raise HTTPException( | ||
status_code=403, detail="Forbidden (failed CEL check)" | ||
) | ||
|
||
self.check = check |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
"""Tests for OpenAPI spec handling.""" | ||
|
||
import pytest | ||
from fastapi.testclient import TestClient | ||
from utils import AppFactory | ||
|
||
app_factory = AppFactory( | ||
oidc_discovery_url="https://samples.auth0.com/.well-known/openid-configuration", | ||
default_public=False, | ||
) | ||
|
||
|
||
import pytest | ||
from unittest.mock import patch, MagicMock | ||
|
||
|
||
# Fixture to patch OpenIdConnectAuth and mock valid_token_dependency | ||
@pytest.fixture | ||
def skip_auth(): | ||
with patch("eoapi.auth_utils.OpenIdConnectAuth") as MockClass: | ||
# Create a mock instance | ||
mock_instance = MagicMock() | ||
# Set the return value of `valid_token_dependency` | ||
mock_instance.valid_token_dependency.return_value = "constant" | ||
# Assign the mock instance to the patched class's return value | ||
MockClass.return_value = mock_instance | ||
|
||
# Yield the mock instance for use in tests | ||
yield mock_instance | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"endpoint, expected_status_code", | ||
[ | ||
("/", 403), | ||
("/?foo=xyz", 403), | ||
("/?foo=bar", 200), | ||
], | ||
) | ||
def test_guard_query_params( | ||
source_api_server, | ||
token_builder, | ||
endpoint, | ||
expected_status_code, | ||
): | ||
"""When no OpenAPI spec endpoint is set, the proxied OpenAPI spec is unaltered.""" | ||
app = app_factory( | ||
upstream_url=source_api_server, | ||
guard={ | ||
"cls": "stac_auth_proxy.guards.cel.Cel", | ||
"kwargs": { | ||
"expression": '("foo" in req.query_params) && req.query_params.foo == "bar"' | ||
}, | ||
}, | ||
) | ||
client = TestClient(app, headers={"Authorization": f"Bearer {token_builder({})}"}) | ||
response = client.get(endpoint) | ||
assert response.status_code == expected_status_code |
Oops, something went wrong.