|
| 1 | +""" |
| 2 | +CQL2 filter factories. |
| 3 | +
|
| 4 | +These classes will be initialized at the startup of the STAC Auth Proxy service and will |
| 5 | +be called for each request to collections/items endpoints in order to generate CQL2 |
| 6 | +filters based on the JWT permissions. |
| 7 | +
|
| 8 | +docs: https://developmentseed.org/stac-auth-proxy/user-guide/record-level-auth/ |
| 9 | +""" |
| 10 | + |
| 11 | +import asyncio |
| 12 | +import dataclasses |
| 13 | +import os |
| 14 | +import time |
| 15 | +import logging |
| 16 | +from typing import Any, Literal, Optional, Sequence |
| 17 | + |
| 18 | +import httpx |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | +if not (UPSTREAM_URL := os.environ.get("UPSTREAM_URL")): |
| 23 | + raise ValueError("Failed to retrieve upstream URL") |
| 24 | + |
| 25 | + |
| 26 | +def cql2_in_query( |
| 27 | + variable: Literal["collection", "id"], collection_ids: Sequence[str] |
| 28 | +) -> str: |
| 29 | + """ |
| 30 | + Generate CQL2 query to see if value of variable matches any element of sequence of |
| 31 | + strings. Due to CQL2 syntax ambiguities around single element arrays with the "in" |
| 32 | + operator, we use a direct comparison when there's only one permitted collection. |
| 33 | + """ |
| 34 | + if not collection_ids: |
| 35 | + return "1=0" |
| 36 | + |
| 37 | + if len(collection_ids) == 1: |
| 38 | + return f"{variable} = " + repr(list(collection_ids)[0]) |
| 39 | + |
| 40 | + return f"{variable} IN ({','.join(repr(c_id) for c_id in collection_ids)})" |
| 41 | + |
| 42 | + |
| 43 | +@dataclasses.dataclass |
| 44 | +class CollectionsFilter: |
| 45 | + """ |
| 46 | + CQL2 filter factory for collections based on JWT permissions. |
| 47 | + """ |
| 48 | + |
| 49 | + collections_claim: str = "collections" # JWT claim with allowed collection IDs |
| 50 | + admin_claim: str = "superuser" # JWT claim indicating superuser status |
| 51 | + public_collections_filter: str = "(private IS NULL OR private = false)" |
| 52 | + |
| 53 | + async def __call__(self, context: dict[str, Any]) -> str: |
| 54 | + jwt_payload: Optional[dict[str, Any]] = context.get("payload") |
| 55 | + |
| 56 | + # Anonymous: no data |
| 57 | + if not jwt_payload: |
| 58 | + logger.debug("Anonymous user, no collections permitted to be viewed") |
| 59 | + return "1=0" |
| 60 | + |
| 61 | + # Superuser: all data |
| 62 | + if jwt_payload.get(self.admin_claim) == "true": |
| 63 | + logger.debug( |
| 64 | + f"Superuser detected for sub {jwt_payload.get('sub')}, " |
| 65 | + "no filter applied for collections" |
| 66 | + ) |
| 67 | + return "1=1" # No filter for superusers |
| 68 | + |
| 69 | + # Authenticated user: Allowed to access collections mentioned in JWT |
| 70 | + permitted_collections = jwt_payload.get(self.collections_claim, []) |
| 71 | + return " OR ".join( |
| 72 | + [ |
| 73 | + self.public_collections_filter, |
| 74 | + cql2_in_query("id", permitted_collections), |
| 75 | + ] |
| 76 | + ) |
| 77 | + |
| 78 | + |
| 79 | +@dataclasses.dataclass |
| 80 | +class ItemsFilter: |
| 81 | + """ |
| 82 | + CQL2 filter factory for items based on JWT permissions. |
| 83 | + """ |
| 84 | + |
| 85 | + collections_claim: str = "collections" # JWT claim with allowed collection IDs |
| 86 | + admin_claim: str = "superuser" # JWT claim indicating superuser status |
| 87 | + public_collections_filter: str = "(private IS NULL OR private = false)" |
| 88 | + |
| 89 | + cache_ttl: int = 30 # TTL for caching public collections, in seconds |
| 90 | + _client: httpx.AsyncClient = dataclasses.field( |
| 91 | + init=False, |
| 92 | + repr=False, |
| 93 | + default_factory=lambda: httpx.AsyncClient(base_url=UPSTREAM_URL), |
| 94 | + ) |
| 95 | + _public_collections_cache: Optional[list[str]] = dataclasses.field( |
| 96 | + init=False, default=None, repr=False |
| 97 | + ) |
| 98 | + _cache_expiry: float = dataclasses.field(init=False, default=0, repr=False) |
| 99 | + _cache_lock: asyncio.Lock = dataclasses.field( |
| 100 | + init=False, repr=False, default_factory=asyncio.Lock |
| 101 | + ) |
| 102 | + |
| 103 | + @property |
| 104 | + def _cached_public_collections(self) -> Optional[list[str]]: |
| 105 | + """Return cached public collections if still valid, otherwise None.""" |
| 106 | + if time.time() < self._cache_expiry: |
| 107 | + return self._public_collections_cache |
| 108 | + return None |
| 109 | + |
| 110 | + @_cached_public_collections.setter |
| 111 | + def _cached_public_collections(self, value: list[str]) -> None: |
| 112 | + """Set the cache with a new value and expiry time.""" |
| 113 | + self._public_collections_cache = value |
| 114 | + self._cache_expiry = time.time() + self.cache_ttl |
| 115 | + |
| 116 | + async def _get_public_collections_ids(self) -> list[str]: |
| 117 | + """ |
| 118 | + Retrieve IDs of public collections from the upstream API. |
| 119 | + Uses a lock to prevent concurrent requests from fetching the same data. |
| 120 | + """ |
| 121 | + # Return cached value if still valid (fast path without lock) |
| 122 | + if (cached := self._cached_public_collections) is not None: |
| 123 | + logger.debug("Using cached public collections") |
| 124 | + return cached |
| 125 | + |
| 126 | + # Acquire lock to prevent concurrent fetches |
| 127 | + async with self._cache_lock: |
| 128 | + # Double-check cache after acquiring lock |
| 129 | + # Another coroutine might have populated it while we waited |
| 130 | + if (cached := self._cached_public_collections) is not None: |
| 131 | + logger.debug("Using cached public collections (after lock)") |
| 132 | + return cached |
| 133 | + |
| 134 | + logger.debug("Fetching public collections from upstream API") |
| 135 | + |
| 136 | + # First request uses params dict |
| 137 | + url: Optional[str] = "/collections" |
| 138 | + params: Optional[dict[str, Any]] = { |
| 139 | + "filter": self.public_collections_filter, |
| 140 | + "limit": 100, |
| 141 | + } |
| 142 | + |
| 143 | + ids = [] |
| 144 | + while url: |
| 145 | + try: |
| 146 | + response = await self._client.get(url, params=params) |
| 147 | + response.raise_for_status() |
| 148 | + data = response.json() |
| 149 | + except httpx.HTTPError: |
| 150 | + logger.exception(f"Failed to fetch {url!r}.") |
| 151 | + raise |
| 152 | + ids.extend(collection["id"] for collection in data["collections"]) |
| 153 | + |
| 154 | + # Subsequent requests use the "next" link URL directly (already has params) |
| 155 | + url = next( |
| 156 | + (link["href"] for link in data["links"] if link["rel"] == "next"), |
| 157 | + None, |
| 158 | + ) |
| 159 | + params = None # Clear params after first request |
| 160 | + |
| 161 | + # Update cache |
| 162 | + self._cached_public_collections = ids |
| 163 | + return ids |
| 164 | + |
| 165 | + async def __call__(self, context: dict[str, Any]) -> str: |
| 166 | + jwt_payload: Optional[dict[str, Any]] = context.get("payload") |
| 167 | + |
| 168 | + # Anonymous: no data |
| 169 | + if not jwt_payload: |
| 170 | + logger.debug("Anonymous user, no items permitted to be viewed") |
| 171 | + return "1=0" |
| 172 | + |
| 173 | + # Superuser: all data |
| 174 | + if jwt_payload.get(self.admin_claim) == "true": |
| 175 | + logger.debug( |
| 176 | + f"Superuser detected for sub {jwt_payload.get('sub')}, " |
| 177 | + "no filter applied for items" |
| 178 | + ) |
| 179 | + return "1=1" |
| 180 | + |
| 181 | + # Everyone: Allowed access to items in public collections |
| 182 | + try: |
| 183 | + permitted_collections = set(await self._get_public_collections_ids()) |
| 184 | + except httpx.HTTPError: |
| 185 | + logger.warning("Failed to fetch public collections.") |
| 186 | + permitted_collections = set() |
| 187 | + |
| 188 | + # Authenticated user: Allowed to access items in collections mentioned in JWT |
| 189 | + if jwt_payload: |
| 190 | + permitted_collections.update(jwt_payload.get(self.collections_claim, [])) |
| 191 | + |
| 192 | + return cql2_in_query("collection", permitted_collections) |
0 commit comments