|
1 | 1 | """Integration with Open Policy Agent (OPA) to generate CQL2 filters for requests to a STAC API.""" |
2 | 2 |
|
3 | | -import dataclasses |
4 | | -from typing import Any |
| 3 | +import logging |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from time import time |
| 6 | +from typing import Any, Callable |
5 | 7 |
|
| 8 | +import httpx |
6 | 9 |
|
7 | | -@dataclasses.dataclass |
| 10 | +logger = logging.getLogger("stac_auth_proxy.opa_integration") |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class cache: |
| 15 | + """Cache results of a method call for a given key.""" |
| 16 | + |
| 17 | + key: Callable[[Any], Any] |
| 18 | + ttl: float = 5.0 |
| 19 | + cache: dict[tuple[Any], tuple[Any, float]] = field(default_factory=dict) |
| 20 | + |
| 21 | + def __call__(self, func): |
| 22 | + """Decorate a function to cache its results.""" |
| 23 | + |
| 24 | + async def wrapped(_self, ctx, *args, **kwargs): |
| 25 | + key = self.key(ctx) |
| 26 | + if key in self.cache: |
| 27 | + result, timestamp = self.cache[key] |
| 28 | + age = time() - timestamp |
| 29 | + if age <= self.ttl: |
| 30 | + logger.debug("%r in cache, returning cached result", key) |
| 31 | + return result |
| 32 | + logger.debug("%r in cache, but expired.", key) |
| 33 | + else: |
| 34 | + logger.debug("%r not in cache, calling function", key) |
| 35 | + result = await func(_self, ctx, *args, **kwargs) |
| 36 | + self.cache[key] = (result, time()) |
| 37 | + self.prune() |
| 38 | + return result |
| 39 | + |
| 40 | + return wrapped |
| 41 | + |
| 42 | + def prune(self): |
| 43 | + """Prune the cache of expired items.""" |
| 44 | + self.cache = {k: v for k, v in self.cache.items() if v[1] > time() - self.ttl} |
| 45 | + |
| 46 | + |
| 47 | +@dataclass |
8 | 48 | class OpaIntegration: |
9 | | - """Integration with Open Policy Agent (OPA) to generate CQL2 filters for requests to a STAC API.""" |
| 49 | + """Call Open Policy Agent (OPA) to generate CQL2 filters from request context.""" |
| 50 | + |
| 51 | + host: str |
| 52 | + decision: str |
| 53 | + |
| 54 | + client: httpx.AsyncClient = field(init=False) |
| 55 | + |
| 56 | + def __post_init__(self): |
| 57 | + """Initialize the client.""" |
| 58 | + self.client = httpx.AsyncClient(base_url=self.host) |
10 | 59 |
|
| 60 | + @cache( |
| 61 | + key=lambda ctx: ctx["payload"]["sub"] if ctx.get("payload") else None, |
| 62 | + ttl=10, |
| 63 | + ) |
11 | 64 | async def __call__(self, context: dict[str, Any]) -> str: |
12 | 65 | """Generate a CQL2 filter for the request.""" |
13 | | - return "(1=1)" |
| 66 | + response = await self.client.post( |
| 67 | + f"/v1/data/{self.decision}", |
| 68 | + json={"input": context}, |
| 69 | + ) |
| 70 | + return response.raise_for_status().json()["result"] |
0 commit comments