Skip to content

stac#

Provider-specific STAC asset signers for EO cloud providers. They implement pyramids' Signer protocol, so they pass straight into pyramids.from_stac(signer=…) / pyramids.open_client(signer=…). See the STAC provider signers guide for per-provider usage.

Signers#

pyramids_eo.stac.signers #

Provider-specific STAC asset signers for EO cloud providers.

pyramids ships the generic signers (AnonymousSigner, AWSRequesterPaysSigner, BearerTokenSigner) and the generic Signer protocol; pyramids-eo owns the provider signers, which encode the semantics of a specific Earth-observation provider's auth (a hardcoded token endpoint, a provider-specific URL carve-out) and so are out of scope for a generic GIS library but squarely in scope for the EO layer (serapeum-org/pyramids-eo#2):

  • PlanetaryComputerSigner — Microsoft Planetary Computer. Mints a per-(account, container) SAS token over stdlib urllib and appends it to the blob href — no planetary-computer SDK required.
  • EarthdataSigner — NASA Earthdata (EDL). Mints / uses a bearer token from the EDL find_or_create_token endpoint, sent as a GDAL Authorization: Bearer header for /vsicurl/ reads of EDL-gated DAAC assets.
  • CDSESigner — Copernicus Data Space (CDSE) Keycloak-OAuth2 bearer signer for the CDSE HTTPS/OData path (password + refresh grant).
  • CdseS3Signer — Copernicus Data Space, the S3-credential variant: CDSE STAC assets resolve to an S3-compatible store at eodata.dataspace.copernicus.eu read with S3 access-key/secret credentials, so this signer is a GDAL-env S3 signer (shaped like AWSRequesterPaysSigner), not a bearer signer — a different mechanism from CDSESigner, so both coexist.
  • BdcTokenSigner — Brazil Data Cube (BDC). Rewrites the asset href to carry an ?access_token=… query parameter; the token is read from $BDC_ACCESS_TOKEN. Used by the token-gated BDC tiers (rare — most BDC collections in the published STAC v1 catalog read anonymously).

Search is anonymous on these providers (sign_request is a no-op); only the asset-read boundary needs credentials. The build_signer factory maps a catalog signer: string to the right object: the anonymous case is the pyramids-eo-local _AnonymousS3Signer (which adds AWS_NO_SIGN_REQUEST and region pinning), while aws-requester-pays reuses the pyramids generic signer.

The name -> object mapping lives in one place, the _SIGNER_FACTORIES registry: build_signer dispatches through it and derives its rejection message from it, and available_signers publishes its keys so a consumer can validate a catalog signer: value at parse time. Adding a provider means adding one entry there.

PlanetaryComputerSigner #

Bases: _BaseSigner

Native Microsoft Planetary Computer SAS signer (no SDK dependency).

PC hosts Sentinel / Landsat / many collections behind short-lived Shared Access Signature (SAS) tokens. This signer mints a token per (account, container) from the PC token endpoint and appends it to the blob href's query string — the same algorithm as planetary_computer.sign but implemented over the standard library (urllib), so pyramids-eo gains PC support without taking the planetary-computer SDK as a dependency.

Because the credential rides the URL, gdal_env is empty: a signed https://<account>.blob.core.windows.net/...?<sas> href is read directly through GDAL /vsicurl/ with no extra config. Wire it in via open_client(..., signer=PlanetaryComputerSigner()) (its sign_item rewrites returned Items) or from_stac(..., signer=PlanetaryComputerSigner()).

Non-PC hrefs, the public ai4edatasetspublicassets bucket, and already-signed URLs pass through unchanged. Tokens are cached until refresh_window seconds before their advertised expiry.

Parameters:

Name Type Description Default
sas_url str | None

SAS token endpoint. Defaults to $PC_SDK_SAS_URL or https://planetarycomputer.microsoft.com/api/sas/v1/token.

None
subscription_key str | None

Optional PC subscription key (raises rate limits), sent as the Ocp-Apim-Subscription-Key header. Defaults to $PC_SDK_SUBSCRIPTION_KEY.

None
refresh_window float

Refetch a cached token when it is within this many seconds of expiry (default 60).

60.0
timeout float

Per-request timeout, in seconds, for the token GET.

30.0

Examples:

  • A non-PC href passes through untouched:
    >>> from pyramids_eo.stac import PlanetaryComputerSigner
    >>> signer = PlanetaryComputerSigner()
    >>> signer.sign_href("https://example.com/scene.tif")
    'https://example.com/scene.tif'
    
  • An already-signed blob href is left as-is:
    >>> from pyramids_eo.stac import PlanetaryComputerSigner
    >>> signed = "https://x.blob.core.windows.net/c/b.tif?se=2034&sig=abc"
    >>> PlanetaryComputerSigner().sign_href(signed) == signed
    True
    
  • The public assets bucket is never signed:
    >>> from pyramids_eo.stac import PlanetaryComputerSigner
    >>> pub = "https://ai4edatasetspublicassets.blob.core.windows.net/c/b.tif"
    >>> PlanetaryComputerSigner().sign_href(pub) == pub
    True
    
Source code in src/pyramids_eo/stac/signers.py
class PlanetaryComputerSigner(_BaseSigner):
    """Native Microsoft Planetary Computer SAS signer (no SDK dependency).

    PC hosts Sentinel / Landsat / many collections behind short-lived Shared
    Access Signature (SAS) tokens. This signer mints a token per
    `(account, container)` from the PC token endpoint and appends it to the
    blob href's query string — the same algorithm as `planetary_computer.sign`
    but implemented over the standard library (`urllib`), so pyramids-eo gains PC
    support without taking the `planetary-computer` SDK as a dependency.

    Because the credential rides the URL, `gdal_env` is empty: a signed
    `https://<account>.blob.core.windows.net/...?<sas>` href is read directly
    through GDAL `/vsicurl/` with no extra config. Wire it in via
    `open_client(..., signer=PlanetaryComputerSigner())` (its `sign_item`
    rewrites returned Items) or `from_stac(..., signer=PlanetaryComputerSigner())`.

    Non-PC hrefs, the public `ai4edatasetspublicassets` bucket, and
    already-signed URLs pass through unchanged. Tokens are cached until
    `refresh_window` seconds before their advertised expiry.

    Args:
        sas_url: SAS token endpoint. Defaults to `$PC_SDK_SAS_URL` or
            `https://planetarycomputer.microsoft.com/api/sas/v1/token`.
        subscription_key: Optional PC subscription key (raises rate limits),
            sent as the `Ocp-Apim-Subscription-Key` header. Defaults to
            `$PC_SDK_SUBSCRIPTION_KEY`.
        refresh_window: Refetch a cached token when it is within this many
            seconds of expiry (default 60).
        timeout: Per-request timeout, in seconds, for the token GET.

    Examples:
        - A non-PC href passes through untouched:
            ```python
            >>> from pyramids_eo.stac import PlanetaryComputerSigner
            >>> signer = PlanetaryComputerSigner()
            >>> signer.sign_href("https://example.com/scene.tif")
            'https://example.com/scene.tif'

            ```
        - An already-signed blob href is left as-is:
            ```python
            >>> from pyramids_eo.stac import PlanetaryComputerSigner
            >>> signed = "https://x.blob.core.windows.net/c/b.tif?se=2034&sig=abc"
            >>> PlanetaryComputerSigner().sign_href(signed) == signed
            True

            ```
        - The public assets bucket is never signed:
            ```python
            >>> from pyramids_eo.stac import PlanetaryComputerSigner
            >>> pub = "https://ai4edatasetspublicassets.blob.core.windows.net/c/b.tif"
            >>> PlanetaryComputerSigner().sign_href(pub) == pub
            True

            ```
    """

    name = "planetary-computer"

    _BLOB_DOMAIN = ".blob.core.windows.net"
    _PUBLIC_HOST = "ai4edatasetspublicassets.blob.core.windows.net"
    _DEFAULT_SAS_URL = "https://planetarycomputer.microsoft.com/api/sas/v1/token"
    _SIGNED_KEYS = frozenset({"st", "se", "sp", "sig"})

    def __init__(
        self,
        *,
        sas_url: str | None = None,
        subscription_key: str | None = None,
        refresh_window: float = 60.0,
        timeout: float = 30.0,
    ) -> None:
        """Store endpoint / auth settings and initialise the token cache.

        Args:
            sas_url: SAS token endpoint (env `PC_SDK_SAS_URL` or the PC
                default when `None`).
            subscription_key: Optional PC subscription key (env
                `PC_SDK_SUBSCRIPTION_KEY` when `None`).
            refresh_window: Seconds-before-expiry at which a cached token is
                refetched.
            timeout: Token-request timeout in seconds.
        """
        self._sas_url = (
            sas_url or os.environ.get("PC_SDK_SAS_URL") or self._DEFAULT_SAS_URL
        ).rstrip("/")
        self._subscription_key = subscription_key or os.environ.get(
            "PC_SDK_SUBSCRIPTION_KEY"
        )
        self._refresh_window = refresh_window
        self._timeout = timeout
        self._cache: dict[tuple[str, str], tuple[str, float]] = {}
        self._lock = threading.Lock()

    def sign_href(self, href: str) -> str:
        """Append a SAS token to a PC blob href; pass non-PC hrefs through.

        Args:
            href: The asset href.

        Returns:
            The href with `?<sas-token>` appended when it is an unsigned PC
            blob URL, otherwise `href` unchanged.
        """
        account, container = self._parse_blob(href)
        if account is None or container is None or self._already_signed(href):
            return href
        token = self._token(account, container)
        # PC blob hrefs are fragment-free Azure URLs, so a plain concat is safe:
        # the SAS token is itself a query string, appended after ? or & (unlike
        # BdcTokenSigner, which must urlsplit to keep a #fragment last).
        sep = "&" if urlparse(href).query else "?"
        return f"{href}{sep}{token}"

    def sign_item(self, item: Any) -> None:
        """Rewrite every asset href on an Item / ItemCollection in place.

        Args:
            item: A STAC Item, an ItemCollection (iterable of Items), or the
                raw-dict equivalent.

        Returns:
            None (pystac-client's `modifier` contract).
        """
        for one in self._iter_signable(item):
            assets = getattr(one, "assets", None)
            if assets is None and isinstance(one, dict):
                assets = one.get("assets")
            if not assets:
                continue
            values = assets.values() if hasattr(assets, "values") else []
            for asset in values:
                href = getattr(asset, "href", None)
                if href is not None:
                    asset.href = self.sign_href(href)
                elif isinstance(asset, dict) and asset.get("href") is not None:
                    asset["href"] = self.sign_href(asset["href"])
        return None

    @staticmethod
    def _iter_signable(item: Any) -> list[Any]:
        """Return `[item]`, or its member items when `item` is a collection."""
        has_assets = getattr(item, "assets", None) is not None or (
            isinstance(item, dict) and "assets" in item
        )
        if has_assets:
            return [item]
        try:
            return list(item)
        except TypeError:
            return [item]

    def _parse_blob(self, href: str) -> tuple[str | None, str | None]:
        """Return `(account, container)` for a signable PC blob href.

        Returns `(None, None)` when `href` is not an Azure blob URL, is the
        public assets bucket, or carries no container path segment.
        """
        parsed = urlparse(href)
        netloc = parsed.netloc.lower()
        if not netloc.endswith(self._BLOB_DOMAIN) or netloc == self._PUBLIC_HOST:
            return None, None
        account = netloc.split(".", 1)[0]
        segments = parsed.path.lstrip("/").split("/", 1)
        container = segments[0] if segments and segments[0] else None
        if not account or not container:
            return None, None
        return account, container

    def _already_signed(self, href: str) -> bool:
        """Return True when `href` already carries SAS query parameters."""
        return bool(self._SIGNED_KEYS & set(parse_qs(urlparse(href).query)))

    def _token(self, account: str, container: str) -> str:
        """Return a cached SAS token, refetching when near expiry (locked)."""
        key = (account, container)

        def fresh(entry: tuple[str, float] | None) -> bool:
            return entry is not None and entry[1] - time.time() > self._refresh_window

        cached = self._cache.get(key)
        if fresh(cached):
            assert cached is not None  # fresh() is False for a None entry
            return cached[0]
        # Double-checked locking: serialise the fetch so concurrent callers for
        # the same (account, container) do not each mint a token.
        with self._lock:
            cached = self._cache.get(key)
            if fresh(cached):
                assert cached is not None  # fresh() is False for a None entry
                return cached[0]
            token, expiry = self._fetch_token(account, container)
            self._cache[key] = (token, expiry)
            return token

    def _fetch_token(self, account: str, container: str) -> tuple[str, float]:
        """GET a fresh SAS token + expiry epoch from the PC token endpoint.

        Args:
            account: Azure storage account name.
            container: Blob container name.

        Returns:
            A `(token, expiry_epoch_seconds)` tuple. When the response carries
            no parseable `msft:expiry` the token is treated as already expired
            so the next call refetches.
        """
        # account / container come from the asset href (semi-trusted catalog
        # data); percent-encode them so a crafted value cannot alter the token
        # endpoint URL's structure.
        url = f"{self._sas_url}/{quote(account, safe='')}/{quote(container, safe='')}"
        request = urllib.request.Request(url)
        if self._subscription_key:
            request.add_header("Ocp-Apim-Subscription-Key", self._subscription_key)
        with urllib.request.urlopen(request, timeout=self._timeout) as response:  # nosec B310 - fixed http(s) endpoint, not attacker-controlled
            body = response.read().decode("utf-8")
        try:
            payload = json.loads(body)
            token = payload["token"]
        except (KeyError, ValueError) as exc:
            raise AuthenticationError(
                "Planetary Computer token endpoint returned a malformed response."
            ) from exc
        expiry = self._parse_expiry(payload.get("msft:expiry"))
        return token, expiry

    @staticmethod
    def _parse_expiry(value: Any) -> float:
        """Parse an RFC 3339 `msft:expiry` string to an epoch (seconds).

        Returns a past timestamp when `value` is missing or unparseable, so the
        caller does not cache an unbounded token.
        """
        if not isinstance(value, str):
            return 0.0
        try:
            parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
        except ValueError:
            return 0.0
        if parsed.tzinfo is None:
            parsed = parsed.replace(tzinfo=UTC)
        return parsed.timestamp()
__init__(*, sas_url=None, subscription_key=None, refresh_window=60.0, timeout=30.0) #

Store endpoint / auth settings and initialise the token cache.

Parameters:

Name Type Description Default
sas_url str | None

SAS token endpoint (env PC_SDK_SAS_URL or the PC default when None).

None
subscription_key str | None

Optional PC subscription key (env PC_SDK_SUBSCRIPTION_KEY when None).

None
refresh_window float

Seconds-before-expiry at which a cached token is refetched.

60.0
timeout float

Token-request timeout in seconds.

30.0
Source code in src/pyramids_eo/stac/signers.py
def __init__(
    self,
    *,
    sas_url: str | None = None,
    subscription_key: str | None = None,
    refresh_window: float = 60.0,
    timeout: float = 30.0,
) -> None:
    """Store endpoint / auth settings and initialise the token cache.

    Args:
        sas_url: SAS token endpoint (env `PC_SDK_SAS_URL` or the PC
            default when `None`).
        subscription_key: Optional PC subscription key (env
            `PC_SDK_SUBSCRIPTION_KEY` when `None`).
        refresh_window: Seconds-before-expiry at which a cached token is
            refetched.
        timeout: Token-request timeout in seconds.
    """
    self._sas_url = (
        sas_url or os.environ.get("PC_SDK_SAS_URL") or self._DEFAULT_SAS_URL
    ).rstrip("/")
    self._subscription_key = subscription_key or os.environ.get(
        "PC_SDK_SUBSCRIPTION_KEY"
    )
    self._refresh_window = refresh_window
    self._timeout = timeout
    self._cache: dict[tuple[str, str], tuple[str, float]] = {}
    self._lock = threading.Lock()
sign_href(href) #

Append a SAS token to a PC blob href; pass non-PC hrefs through.

Parameters:

Name Type Description Default
href str

The asset href.

required

Returns:

Type Description
str

The href with ?<sas-token> appended when it is an unsigned PC

str

blob URL, otherwise href unchanged.

Source code in src/pyramids_eo/stac/signers.py
def sign_href(self, href: str) -> str:
    """Append a SAS token to a PC blob href; pass non-PC hrefs through.

    Args:
        href: The asset href.

    Returns:
        The href with `?<sas-token>` appended when it is an unsigned PC
        blob URL, otherwise `href` unchanged.
    """
    account, container = self._parse_blob(href)
    if account is None or container is None or self._already_signed(href):
        return href
    token = self._token(account, container)
    # PC blob hrefs are fragment-free Azure URLs, so a plain concat is safe:
    # the SAS token is itself a query string, appended after ? or & (unlike
    # BdcTokenSigner, which must urlsplit to keep a #fragment last).
    sep = "&" if urlparse(href).query else "?"
    return f"{href}{sep}{token}"
sign_item(item) #

Rewrite every asset href on an Item / ItemCollection in place.

Parameters:

Name Type Description Default
item Any

A STAC Item, an ItemCollection (iterable of Items), or the raw-dict equivalent.

required

Returns:

Type Description
None

None (pystac-client's modifier contract).

Source code in src/pyramids_eo/stac/signers.py
def sign_item(self, item: Any) -> None:
    """Rewrite every asset href on an Item / ItemCollection in place.

    Args:
        item: A STAC Item, an ItemCollection (iterable of Items), or the
            raw-dict equivalent.

    Returns:
        None (pystac-client's `modifier` contract).
    """
    for one in self._iter_signable(item):
        assets = getattr(one, "assets", None)
        if assets is None and isinstance(one, dict):
            assets = one.get("assets")
        if not assets:
            continue
        values = assets.values() if hasattr(assets, "values") else []
        for asset in values:
            href = getattr(asset, "href", None)
            if href is not None:
                asset.href = self.sign_href(href)
            elif isinstance(asset, dict) and asset.get("href") is not None:
                asset["href"] = self.sign_href(asset["href"])
    return None

EarthdataSigner #

Bases: _BearerProviderSigner

NASA Earthdata (EDL) bearer signer — native, no earthaccess SDK.

Uses a pre-minted token when given (or $EARTHDATA_TOKEN / $EARTHDATA_PAT), otherwise mints one from the EDL find_or_create_token endpoint with HTTP Basic auth ($EARTHDATA_USERNAME / $EARTHDATA_PASSWORD). The token is sent as a GDAL Authorization: Bearer header for /vsicurl/ reads of EDL-gated DAAC assets.

Parameters:

Name Type Description Default
username str | None

EDL username (env EARTHDATA_USERNAME when None).

None
password str | None

EDL password (env EARTHDATA_PASSWORD when None).

None
token str | None

A pre-minted bearer token (env EARTHDATA_TOKEN / EARTHDATA_PAT when None); skips minting entirely.

None
refresh_window float

Seconds-before-expiry at which to refetch a minted token.

300.0
timeout float

Token-request timeout in seconds.

30.0

Examples:

  • A pre-minted token is used directly in the GDAL header:
    >>> from pyramids_eo.stac import EarthdataSigner
    >>> signer = EarthdataSigner(token="edl-tok")
    >>> signer.gdal_env()["GDAL_HTTP_HEADERS"]
    'Authorization: Bearer edl-tok'
    
Source code in src/pyramids_eo/stac/signers.py
class EarthdataSigner(_BearerProviderSigner):
    """NASA Earthdata (EDL) bearer signer — native, no `earthaccess` SDK.

    Uses a pre-minted token when given (or `$EARTHDATA_TOKEN` / `$EARTHDATA_PAT`),
    otherwise mints one from the EDL `find_or_create_token` endpoint with HTTP
    Basic auth (`$EARTHDATA_USERNAME` / `$EARTHDATA_PASSWORD`). The token is sent
    as a GDAL `Authorization: Bearer` header for `/vsicurl/` reads of EDL-gated
    DAAC assets.

    Args:
        username: EDL username (env `EARTHDATA_USERNAME` when `None`).
        password: EDL password (env `EARTHDATA_PASSWORD` when `None`).
        token: A pre-minted bearer token (env `EARTHDATA_TOKEN` / `EARTHDATA_PAT`
            when `None`); skips minting entirely.
        refresh_window: Seconds-before-expiry at which to refetch a minted token.
        timeout: Token-request timeout in seconds.

    Examples:
        - A pre-minted token is used directly in the GDAL header:
            ```python
            >>> from pyramids_eo.stac import EarthdataSigner
            >>> signer = EarthdataSigner(token="edl-tok")
            >>> signer.gdal_env()["GDAL_HTTP_HEADERS"]
            'Authorization: Bearer edl-tok'

            ```
    """

    name = "earthdata"
    _TOKEN_URL = "https://urs.earthdata.nasa.gov/api/users/find_or_create_token"  # nosec B105 - not a secret (public URL / identifier)

    def __init__(
        self,
        *,
        username: str | None = None,
        password: str | None = None,
        token: str | None = None,
        refresh_window: float = 300.0,
        timeout: float = 30.0,
    ) -> None:
        """Store EDL credentials / static token; init the token cache."""
        super().__init__(refresh_window=refresh_window, timeout=timeout)
        self._username = username or os.environ.get("EARTHDATA_USERNAME")
        self._password = password or os.environ.get("EARTHDATA_PASSWORD")
        self._static_token = (
            token
            or os.environ.get("EARTHDATA_TOKEN")
            or os.environ.get("EARTHDATA_PAT")
        )

    def _token(self) -> str:
        """Return the static token when present, else the minted/cached one."""
        if self._static_token:
            return self._static_token
        return super()._token()

    def _fetch_token(self) -> tuple[str, float]:
        """Mint an EDL bearer token via find_or_create_token (HTTP Basic)."""
        if not (self._username and self._password):
            raise AuthenticationError(
                "EarthdataSigner needs a token (EARTHDATA_TOKEN/PAT) or "
                "EARTHDATA_USERNAME + EARTHDATA_PASSWORD."
            )
        creds = base64.b64encode(f"{self._username}:{self._password}".encode()).decode()
        request = urllib.request.Request(self._TOKEN_URL, method="POST")
        request.add_header("Authorization", f"Basic {creds}")
        request.add_header("Accept", "application/json")
        with urllib.request.urlopen(request, timeout=self._timeout) as response:  # nosec B310 - fixed http(s) endpoint, not attacker-controlled
            body = response.read().decode("utf-8")
        try:
            payload = json.loads(body)
            token = payload["access_token"]
        except (KeyError, ValueError) as exc:
            raise AuthenticationError(
                "Earthdata (EDL) token endpoint returned a malformed response."
            ) from exc
        expiry = self._parse_expiry(payload.get("expiration_date"))
        return token, expiry

    @staticmethod
    def _parse_expiry(value: Any) -> float:
        """Parse an EDL `expiration_date` to an epoch; default to now + 1h."""
        if isinstance(value, str):
            try:
                parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
            except ValueError:
                return time.time() + 3600.0
            if parsed.tzinfo is None:
                parsed = parsed.replace(tzinfo=UTC)
            return parsed.timestamp()
        return time.time() + 3600.0
__init__(*, username=None, password=None, token=None, refresh_window=300.0, timeout=30.0) #

Store EDL credentials / static token; init the token cache.

Source code in src/pyramids_eo/stac/signers.py
def __init__(
    self,
    *,
    username: str | None = None,
    password: str | None = None,
    token: str | None = None,
    refresh_window: float = 300.0,
    timeout: float = 30.0,
) -> None:
    """Store EDL credentials / static token; init the token cache."""
    super().__init__(refresh_window=refresh_window, timeout=timeout)
    self._username = username or os.environ.get("EARTHDATA_USERNAME")
    self._password = password or os.environ.get("EARTHDATA_PASSWORD")
    self._static_token = (
        token
        or os.environ.get("EARTHDATA_TOKEN")
        or os.environ.get("EARTHDATA_PAT")
    )

CDSESigner #

Bases: _BearerProviderSigner

Copernicus Data Space Ecosystem (CDSE) bearer signer via Keycloak OAuth2.

Mints an access token from the CDSE Keycloak token endpoint with a password grant ($CDSE_USERNAME / $CDSE_PASSWORD, public client cdse-public), then refreshes it with the refresh-token grant. The access token is sent as a GDAL Authorization: Bearer header for /vsicurl/ reads of CDSE HTTPS/OData assets.

This is the bearer (HTTPS/OData) variant; for the S3-credential variant of CDSE asset reads use CdseS3Signer.

Parameters:

Name Type Description Default
username str | None

CDSE username (env CDSE_USERNAME when None).

None
password str | None

CDSE password (env CDSE_PASSWORD when None).

None
client_id str

Keycloak client id (default "cdse-public").

'cdse-public'
refresh_window float

Seconds-before-expiry at which to refresh (CDSE access tokens live ~600 s).

30.0
timeout float

Token-request timeout in seconds.

30.0
Source code in src/pyramids_eo/stac/signers.py
class CDSESigner(_BearerProviderSigner):
    """Copernicus Data Space Ecosystem (CDSE) bearer signer via Keycloak OAuth2.

    Mints an access token from the CDSE Keycloak token endpoint with a password
    grant (`$CDSE_USERNAME` / `$CDSE_PASSWORD`, public client `cdse-public`), then
    refreshes it with the refresh-token grant. The access token is sent as a GDAL
    `Authorization: Bearer` header for `/vsicurl/` reads of CDSE HTTPS/OData
    assets.

    This is the *bearer* (HTTPS/OData) variant; for the S3-credential variant of
    CDSE asset reads use `CdseS3Signer`.

    Args:
        username: CDSE username (env `CDSE_USERNAME` when `None`).
        password: CDSE password (env `CDSE_PASSWORD` when `None`).
        client_id: Keycloak client id (default `"cdse-public"`).
        refresh_window: Seconds-before-expiry at which to refresh (CDSE access
            tokens live ~600 s).
        timeout: Token-request timeout in seconds.
    """

    name = "cdse"
    _TOKEN_URL = (
        "https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/"  # nosec B105 - not a secret (public URL / identifier)
        "openid-connect/token"
    )

    def __init__(
        self,
        *,
        username: str | None = None,
        password: str | None = None,
        client_id: str = "cdse-public",
        refresh_window: float = 30.0,
        timeout: float = 30.0,
    ) -> None:
        """Store CDSE credentials; init the token + refresh-token cache."""
        super().__init__(refresh_window=refresh_window, timeout=timeout)
        self._username = username or os.environ.get("CDSE_USERNAME")
        self._password = password or os.environ.get("CDSE_PASSWORD")
        self._client_id = client_id
        self._refresh_token: str | None = None

    def _fetch_token(self) -> tuple[str, float]:
        """Mint or refresh an access token, falling back to a password grant.

        Tries the refresh-token grant when a refresh token is held; if that
        fails (the refresh token has expired — CDSE refresh tokens live
        ~3600 s — is rejected, or comes back with a malformed body), the stale
        token is dropped and a fresh password grant is attempted. This lets a
        long-idle, reused signer recover instead of raising on the expired
        refresh token.
        """
        if self._refresh_token is not None:
            try:
                return self._request_token(
                    {
                        "client_id": self._client_id,
                        "grant_type": "refresh_token",
                        "refresh_token": self._refresh_token,
                    }
                )
            except (urllib.error.URLError, AuthenticationError):
                # Refresh token expired / rejected / malformed — re-authenticate.
                self._refresh_token = None
        if not (self._username and self._password):
            raise AuthenticationError("CDSESigner needs CDSE_USERNAME + CDSE_PASSWORD.")
        return self._request_token(
            {
                "client_id": self._client_id,
                "grant_type": "password",
                "username": self._username,
                "password": self._password,
            }
        )

    def _request_token(self, form: dict[str, str]) -> tuple[str, float]:
        """POST a Keycloak token request and return `(access_token, expiry)`.

        Rotates the cached refresh token from the response, and derives the
        access-token expiry from `expires_in` (default 600 s).
        """
        body = urlencode(form).encode("utf-8")
        request = urllib.request.Request(self._TOKEN_URL, data=body, method="POST")
        request.add_header("Content-Type", "application/x-www-form-urlencoded")
        with urllib.request.urlopen(request, timeout=self._timeout) as response:  # nosec B310 - fixed http(s) endpoint, not attacker-controlled
            raw = response.read().decode("utf-8")
        try:
            payload = json.loads(raw)
            access_token = payload["access_token"]
        except (KeyError, ValueError) as exc:
            raise AuthenticationError(
                "CDSE token endpoint returned a malformed response."
            ) from exc
        self._refresh_token = payload.get("refresh_token", self._refresh_token)
        expiry = time.time() + float(payload.get("expires_in", 600))
        return access_token, expiry
__init__(*, username=None, password=None, client_id='cdse-public', refresh_window=30.0, timeout=30.0) #

Store CDSE credentials; init the token + refresh-token cache.

Source code in src/pyramids_eo/stac/signers.py
def __init__(
    self,
    *,
    username: str | None = None,
    password: str | None = None,
    client_id: str = "cdse-public",
    refresh_window: float = 30.0,
    timeout: float = 30.0,
) -> None:
    """Store CDSE credentials; init the token + refresh-token cache."""
    super().__init__(refresh_window=refresh_window, timeout=timeout)
    self._username = username or os.environ.get("CDSE_USERNAME")
    self._password = password or os.environ.get("CDSE_PASSWORD")
    self._client_id = client_id
    self._refresh_token: str | None = None

CdseS3Signer #

Copernicus Data Space (CDSE) signer (S3 GDAL-env credentials).

CDSE STAC assets live on an S3-compatible store; reads are authenticated with S3 access-key/secret credentials supplied through the GDAL environment, and s3://eodata/<key> hrefs are rewritten to the /vsis3/eodata/<key> GDAL VSI path. Search is anonymous.

Attributes:

Name Type Description
name

Stable signer label ("cdse-s3").

Examples:

  • An s3://eodata/... href is rewritten to the GDAL /vsis3/ path:
    >>> from pyramids_eo.stac import CdseS3Signer
    >>> CdseS3Signer("ak", "sk").sign_href("s3://eodata/foo/B04.tif")
    '/vsis3/eodata/foo/B04.tif'
    
  • An https:// href on the CDSE host is rewritten the same way:
    >>> from pyramids_eo.stac import CdseS3Signer
    >>> CdseS3Signer("ak", "sk").sign_href(
    ...     "https://eodata.dataspace.copernicus.eu/foo/B04.tif")
    '/vsis3/eodata/foo/B04.tif'
    
  • The credentials surface through the GDAL S3 environment:
    >>> from pyramids_eo.stac import CdseS3Signer
    >>> env = CdseS3Signer("ak", "sk").gdal_env()
    >>> env["AWS_ACCESS_KEY_ID"]
    'ak'
    >>> env["AWS_S3_ENDPOINT"]
    'eodata.dataspace.copernicus.eu'
    
Source code in src/pyramids_eo/stac/signers.py
class CdseS3Signer:
    """Copernicus Data Space (CDSE) signer (S3 GDAL-env credentials).

    CDSE STAC assets live on an S3-compatible store; reads are authenticated
    with S3 access-key/secret credentials supplied through the GDAL
    environment, and `s3://eodata/<key>` hrefs are rewritten to the
    `/vsis3/eodata/<key>` GDAL VSI path. Search is anonymous.

    Attributes:
        name: Stable signer label (`"cdse-s3"`).

    Examples:
        - An `s3://eodata/...` href is rewritten to the GDAL `/vsis3/` path:
            ```python
            >>> from pyramids_eo.stac import CdseS3Signer
            >>> CdseS3Signer("ak", "sk").sign_href("s3://eodata/foo/B04.tif")
            '/vsis3/eodata/foo/B04.tif'

            ```
        - An `https://` href on the CDSE host is rewritten the same way:
            ```python
            >>> from pyramids_eo.stac import CdseS3Signer
            >>> CdseS3Signer("ak", "sk").sign_href(
            ...     "https://eodata.dataspace.copernicus.eu/foo/B04.tif")
            '/vsis3/eodata/foo/B04.tif'

            ```
        - The credentials surface through the GDAL S3 environment:
            ```python
            >>> from pyramids_eo.stac import CdseS3Signer
            >>> env = CdseS3Signer("ak", "sk").gdal_env()
            >>> env["AWS_ACCESS_KEY_ID"]
            'ak'
            >>> env["AWS_S3_ENDPOINT"]
            'eodata.dataspace.copernicus.eu'

            ```
    """

    name = "cdse-s3"

    #: Canonical CDSE eodata asset host. Only this host and its subdomains (or
    #: the configured `endpoint`) are rewritten to `/vsis3/`; other
    #: `dataspace.copernicus.eu` hosts (e.g. `identity.`, `catalogue.`) and
    #: lookalikes are left untouched.
    _ASSET_HOST = "eodata.dataspace.copernicus.eu"

    def __init__(
        self,
        access_key: str,
        secret_key: str,
        endpoint: str = "eodata.dataspace.copernicus.eu",
    ) -> None:
        """Store the S3 credentials and endpoint.

        Args:
            access_key: CDSE S3 access key id.
            secret_key: CDSE S3 secret key.
            endpoint: S3 endpoint host. Defaults to the CDSE eodata store.
        """
        self._access_key = access_key
        self._secret_key = secret_key
        self._endpoint = endpoint

    def sign_request(self, request: Any) -> None:
        """Leave the outgoing search request unchanged (CDSE search is anonymous)."""
        return None

    def sign_item(self, _item: Any) -> None:
        """Leave returned Items unchanged — asset auth is via the GDAL env, not the href."""
        return None

    def sign_href(self, href: str) -> str:
        """Rewrite a CDSE asset href to the `/vsis3/eodata/<key>` GDAL path.

        CDSE items expose assets both as `s3://eodata/<key>` and as
        `https://<eodata-host>/<key>` (the latter is the common default href,
        with the `s3://` form often only an `alternate`). Either is rewritten to
        the S3 VSI path so the credentials in `gdal_env()` apply; any other host
        is returned unchanged.

        Args:
            href: An asset href (`s3://eodata/...`, an `https://` URL on the
                CDSE endpoint host, or something else).

        Returns:
            The GDAL-readable `/vsis3/...` path, or `href` unchanged when it is
            not a CDSE asset.
        """
        if href.startswith("s3://"):
            return "/vsis3/" + href[len("s3://") :]
        if href.startswith(("https://", "http://")):
            parts = urlsplit(href)
            host = parts.netloc
            if (
                host == self._endpoint
                or host == self._ASSET_HOST
                or host.endswith("." + self._ASSET_HOST)
            ):
                key = parts.path.lstrip("/")
                if key.startswith("eodata/"):
                    return f"/vsis3/{key}"
                return f"/vsis3/eodata/{key}"
        return href

    def gdal_env(self) -> dict[str, str]:
        """Return the GDAL config carrying the CDSE S3 credentials for asset reads.

        Returns:
            A mapping with the S3 endpoint, access-key/secret, virtual-hosting
            off, HTTPS on, and the standard cloud-read knob.
        """
        return {
            "AWS_S3_ENDPOINT": self._endpoint,
            "AWS_ACCESS_KEY_ID": self._access_key,
            "AWS_SECRET_ACCESS_KEY": self._secret_key,
            "AWS_VIRTUAL_HOSTING": "FALSE",
            "AWS_HTTPS": "YES",
            "GDAL_DISABLE_READDIR_ON_OPEN": "EMPTY_DIR",
        }
__init__(access_key, secret_key, endpoint='eodata.dataspace.copernicus.eu') #

Store the S3 credentials and endpoint.

Parameters:

Name Type Description Default
access_key str

CDSE S3 access key id.

required
secret_key str

CDSE S3 secret key.

required
endpoint str

S3 endpoint host. Defaults to the CDSE eodata store.

'eodata.dataspace.copernicus.eu'
Source code in src/pyramids_eo/stac/signers.py
def __init__(
    self,
    access_key: str,
    secret_key: str,
    endpoint: str = "eodata.dataspace.copernicus.eu",
) -> None:
    """Store the S3 credentials and endpoint.

    Args:
        access_key: CDSE S3 access key id.
        secret_key: CDSE S3 secret key.
        endpoint: S3 endpoint host. Defaults to the CDSE eodata store.
    """
    self._access_key = access_key
    self._secret_key = secret_key
    self._endpoint = endpoint
sign_request(request) #

Leave the outgoing search request unchanged (CDSE search is anonymous).

Source code in src/pyramids_eo/stac/signers.py
def sign_request(self, request: Any) -> None:
    """Leave the outgoing search request unchanged (CDSE search is anonymous)."""
    return None
sign_item(_item) #

Leave returned Items unchanged — asset auth is via the GDAL env, not the href.

Source code in src/pyramids_eo/stac/signers.py
def sign_item(self, _item: Any) -> None:
    """Leave returned Items unchanged — asset auth is via the GDAL env, not the href."""
    return None
sign_href(href) #

Rewrite a CDSE asset href to the /vsis3/eodata/<key> GDAL path.

CDSE items expose assets both as s3://eodata/<key> and as https://<eodata-host>/<key> (the latter is the common default href, with the s3:// form often only an alternate). Either is rewritten to the S3 VSI path so the credentials in gdal_env() apply; any other host is returned unchanged.

Parameters:

Name Type Description Default
href str

An asset href (s3://eodata/..., an https:// URL on the CDSE endpoint host, or something else).

required

Returns:

Type Description
str

The GDAL-readable /vsis3/... path, or href unchanged when it is

str

not a CDSE asset.

Source code in src/pyramids_eo/stac/signers.py
def sign_href(self, href: str) -> str:
    """Rewrite a CDSE asset href to the `/vsis3/eodata/<key>` GDAL path.

    CDSE items expose assets both as `s3://eodata/<key>` and as
    `https://<eodata-host>/<key>` (the latter is the common default href,
    with the `s3://` form often only an `alternate`). Either is rewritten to
    the S3 VSI path so the credentials in `gdal_env()` apply; any other host
    is returned unchanged.

    Args:
        href: An asset href (`s3://eodata/...`, an `https://` URL on the
            CDSE endpoint host, or something else).

    Returns:
        The GDAL-readable `/vsis3/...` path, or `href` unchanged when it is
        not a CDSE asset.
    """
    if href.startswith("s3://"):
        return "/vsis3/" + href[len("s3://") :]
    if href.startswith(("https://", "http://")):
        parts = urlsplit(href)
        host = parts.netloc
        if (
            host == self._endpoint
            or host == self._ASSET_HOST
            or host.endswith("." + self._ASSET_HOST)
        ):
            key = parts.path.lstrip("/")
            if key.startswith("eodata/"):
                return f"/vsis3/{key}"
            return f"/vsis3/eodata/{key}"
    return href
gdal_env() #

Return the GDAL config carrying the CDSE S3 credentials for asset reads.

Returns:

Type Description
dict[str, str]

A mapping with the S3 endpoint, access-key/secret, virtual-hosting

dict[str, str]

off, HTTPS on, and the standard cloud-read knob.

Source code in src/pyramids_eo/stac/signers.py
def gdal_env(self) -> dict[str, str]:
    """Return the GDAL config carrying the CDSE S3 credentials for asset reads.

    Returns:
        A mapping with the S3 endpoint, access-key/secret, virtual-hosting
        off, HTTPS on, and the standard cloud-read knob.
    """
    return {
        "AWS_S3_ENDPOINT": self._endpoint,
        "AWS_ACCESS_KEY_ID": self._access_key,
        "AWS_SECRET_ACCESS_KEY": self._secret_key,
        "AWS_VIRTUAL_HOSTING": "FALSE",
        "AWS_HTTPS": "YES",
        "GDAL_DISABLE_READDIR_ON_OPEN": "EMPTY_DIR",
    }

BdcTokenSigner #

Bases: _BaseSigner

Brazil Data Cube (BDC) OAuth-token URL signer.

Some Brazil Data Cube collections (token-gated tiers) require an ?access_token=<token> query parameter on each asset href; open collections (the bulk of the published STAC v1 catalog) are anonymous and do not need a token. BdcTokenSigner rewrites a clean asset href into a token-bearing one for every read, leaving the bare-anonymous BDC reads to the anonymous signer (the endpoint default).

BDC search itself is anonymous — sign_request is a no-op, and sign_item does not mutate returned items. The token rides in the asset URL's query string, not the GDAL environment, so gdal_env is empty: a signed https://data.inpe.br/...tif?access_token=… href is read directly through GDAL /vsicurl/ with no extra config.

The token is read from the BDC_ACCESS_TOKEN environment variable on first use; absent it, sign_href raises AuthenticationError (from pyramids_eo.errors) naming the env var and pointing at an open collection so the user can switch tiers if they want. Wire it in via a per-collection signer: bdc-token override on the token-gated rows of catalog/bdc.yaml.

Parameters:

Name Type Description Default
token str | None

Explicit BDC OAuth token. Defaults to $BDC_ACCESS_TOKEN.

None

Examples:

  • A clean https href becomes a query-bearing one (passing the token explicitly so the example does not mutate the process env):
    >>> from pyramids_eo.stac import BdcTokenSigner
    >>> BdcTokenSigner(token="tok").sign_href("https://data.inpe.br/bdc/data/x.tif")
    'https://data.inpe.br/bdc/data/x.tif?access_token=tok'
    
  • An href that already carries a query gets &access_token=… instead:
    >>> from pyramids_eo.stac import BdcTokenSigner
    >>> BdcTokenSigner(token="tok").sign_href("https://data.inpe.br/bdc/data/x.tif?foo=1")
    'https://data.inpe.br/bdc/data/x.tif?foo=1&access_token=tok'
    
Source code in src/pyramids_eo/stac/signers.py
class BdcTokenSigner(_BaseSigner):
    """Brazil Data Cube (BDC) OAuth-token URL signer.

    Some Brazil Data Cube collections (token-gated tiers) require an
    `?access_token=<token>` query parameter on each asset href; open
    collections (the bulk of the published STAC v1 catalog) are anonymous and
    do not need a token. `BdcTokenSigner` rewrites a clean asset href into a
    token-bearing one for every read, leaving the bare-anonymous BDC reads to
    the `anonymous` signer (the endpoint default).

    BDC search itself is anonymous — `sign_request` is a no-op, and
    `sign_item` does not mutate returned items. The token rides in the asset
    URL's query string, not the GDAL environment, so `gdal_env` is empty: a
    signed `https://data.inpe.br/...tif?access_token=…` href is read directly
    through GDAL `/vsicurl/` with no extra config.

    The token is read from the `BDC_ACCESS_TOKEN` environment variable on
    first use; absent it, `sign_href` raises `AuthenticationError` (from
    `pyramids_eo.errors`) naming the env var and pointing at an open collection
    so the user can switch tiers if they want. Wire it in via a
    per-collection `signer: bdc-token` override on the token-gated rows of
    `catalog/bdc.yaml`.

    Args:
        token: Explicit BDC OAuth token. Defaults to `$BDC_ACCESS_TOKEN`.

    Examples:
        - A clean https href becomes a query-bearing one (passing the token
          explicitly so the example does not mutate the process env):
            ```python
            >>> from pyramids_eo.stac import BdcTokenSigner
            >>> BdcTokenSigner(token="tok").sign_href("https://data.inpe.br/bdc/data/x.tif")
            'https://data.inpe.br/bdc/data/x.tif?access_token=tok'

            ```
        - An href that already carries a query gets `&access_token=…` instead:
            ```python
            >>> from pyramids_eo.stac import BdcTokenSigner
            >>> BdcTokenSigner(token="tok").sign_href("https://data.inpe.br/bdc/data/x.tif?foo=1")
            'https://data.inpe.br/bdc/data/x.tif?foo=1&access_token=tok'

            ```
    """

    name = "bdc-token"

    def __init__(self, token: str | None = None) -> None:
        """Store the explicit token (or defer to `$BDC_ACCESS_TOKEN`)."""
        self._explicit_token = token

    def _token(self) -> str:
        """Return the BDC OAuth token from kwarg or `BDC_ACCESS_TOKEN`."""
        token = self._explicit_token or os.environ.get("BDC_ACCESS_TOKEN")
        if not token:
            raise AuthenticationError(
                "set BDC_ACCESS_TOKEN — this Brazil Data Cube collection requires "
                "an OAuth token; open collections such as CBERS4-WFI-16D-2 do not "
                "need one and read anonymously."
            )
        return token

    def sign_href(self, href: str) -> str:
        """Append `?access_token=<token>` (or `&access_token=`) to the asset href.

        Uses `urlsplit`/`urlunsplit` so the token lands in the URL's query
        component even when the href carries a `#fragment` (a naive
        `"?" in href` check would mistake a fragment for a query and append
        after `#`, where the server never sees it).
        """
        token = quote(self._token(), safe="")
        parts = urlsplit(href)
        new_query = (
            f"{parts.query}&access_token={token}"
            if parts.query
            else f"access_token={token}"
        )
        return urlunsplit(
            (parts.scheme, parts.netloc, parts.path, new_query, parts.fragment)
        )
__init__(token=None) #

Store the explicit token (or defer to $BDC_ACCESS_TOKEN).

Source code in src/pyramids_eo/stac/signers.py
def __init__(self, token: str | None = None) -> None:
    """Store the explicit token (or defer to `$BDC_ACCESS_TOKEN`)."""
    self._explicit_token = token
sign_href(href) #

Append ?access_token=<token> (or &access_token=) to the asset href.

Uses urlsplit/urlunsplit so the token lands in the URL's query component even when the href carries a #fragment (a naive "?" in href check would mistake a fragment for a query and append after #, where the server never sees it).

Source code in src/pyramids_eo/stac/signers.py
def sign_href(self, href: str) -> str:
    """Append `?access_token=<token>` (or `&access_token=`) to the asset href.

    Uses `urlsplit`/`urlunsplit` so the token lands in the URL's query
    component even when the href carries a `#fragment` (a naive
    `"?" in href` check would mistake a fragment for a query and append
    after `#`, where the server never sees it).
    """
    token = quote(self._token(), safe="")
    parts = urlsplit(href)
    new_query = (
        f"{parts.query}&access_token={token}"
        if parts.query
        else f"access_token={token}"
    )
    return urlunsplit(
        (parts.scheme, parts.netloc, parts.path, new_query, parts.fragment)
    )

available_signers() #

Return the signer names a catalog signer: field may carry.

Lets a consumer validate a catalog value when the catalog is parsed, rather than discovering a typo as a ValueError from :func:build_signer at the moment a read is attempted.

Returns:

Type Description
str

tuple[str, ...]: Every known signer name, in declaration order (the two

...

generic signers first, then the provider signers).

Examples:

  • The generic signers lead and every name is a valid build_signer key:
    >>> from pyramids_eo.stac import available_signers
    >>> available_signers()[:2]
    ('anonymous', 'aws-requester-pays')
    >>> all(n in available_signers() for n in ("mpc-sas", "cdse-s3"))
    True
    
  • Use it to validate a catalog value before building anything:
    >>> from pyramids_eo.stac import available_signers
    >>> "mpc_sas" in available_signers()  # a typo for 'mpc-sas'
    False
    
See Also

build_signer: Builds the signer one of these names refers to.

Source code in src/pyramids_eo/stac/signers.py
def available_signers() -> tuple[str, ...]:
    """Return the signer names a catalog `signer:` field may carry.

    Lets a consumer validate a catalog value when the catalog is parsed, rather
    than discovering a typo as a `ValueError` from :func:`build_signer` at the
    moment a read is attempted.

    Returns:
        tuple[str, ...]: Every known signer name, in declaration order (the two
        generic signers first, then the provider signers).

    Examples:
        - The generic signers lead and every name is a valid `build_signer` key:
            ```python
            >>> from pyramids_eo.stac import available_signers
            >>> available_signers()[:2]
            ('anonymous', 'aws-requester-pays')
            >>> all(n in available_signers() for n in ("mpc-sas", "cdse-s3"))
            True

            ```
        - Use it to validate a catalog value before building anything:
            ```python
            >>> from pyramids_eo.stac import available_signers
            >>> "mpc_sas" in available_signers()  # a typo for 'mpc-sas'
            False

            ```

    See Also:
        build_signer: Builds the signer one of these names refers to.

    """
    return tuple(_SIGNER_FACTORIES)

build_signer(signer_type, **creds) #

Build the signer named by a catalog signer: field.

Dispatches through :data:_SIGNER_FACTORIES. The anonymous signer is the pyramids-eo-local _AnonymousS3Signer and the aws-requester-pays signer comes from pyramids.stac (imported inside its factory, so importing this module pulls in no STAC stack); the mpc-sas / earthdata / cdse / cdse-s3 / bdc-token provider signers are the pyramids-eo-local classes above.

Parameters:

Name Type Description Default
signer_type str

A name from :func:available_signers — "anonymous", "aws-requester-pays", "mpc-sas", "earthdata", "cdse", "cdse-s3" or "bdc-token".

required
**creds Any

Extra credentials forwarded to the selected signer — region for anonymous (pins GDAL at an opt-in region's S3 endpoint) and aws-requester-pays; username / password / token for earthdata; username / password / client_id for cdse; the CDSE S3 credential resolution kwargs for cdse-s3 (see auth_cdse.s3_credentials); token for bdc-token (defaults to $BDC_ACCESS_TOKEN).

{}

Returns:

Type Description
Any

A signer satisfying the pyramids.stac.Signer protocol.

Raises:

Type Description
ValueError

When signer_type is not a known signer name — including when it is not a string at all, or is unhashable (a list or dict from a malformed catalog). A TypeError raised by a custom __hash__ or __eq__ is indistinguishable from an unhashable type and is converted too; any other exception from them propagates, since widening the except clause further would mask real faults.

Examples:

  • The MPC key maps to the native SAS signer (no SDK):
    >>> from pyramids_eo.stac import build_signer
    >>> build_signer("mpc-sas").name
    'planetary-computer'
    
  • Build the CDSE S3 signer from explicit S3 keys:
    >>> from pyramids_eo.stac import build_signer
    >>> build_signer("cdse-s3", access_key="ak", secret_key="sk").gdal_env()["AWS_ACCESS_KEY_ID"]
    'ak'
    
  • Build the BDC token signer with an explicit token:
    >>> from pyramids_eo.stac import build_signer
    >>> build_signer("bdc-token", token="abc").name
    'bdc-token'
    
  • An unknown signer name is rejected:
    >>> from pyramids_eo.stac import build_signer
    >>> build_signer("nope")  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: unknown signer_type 'nope'; expected one of ... 'bdc-token'.
    
See Also

available_signers: The names this factory accepts, for validating a catalog value before building anything.

Source code in src/pyramids_eo/stac/signers.py
def build_signer(signer_type: str, **creds: Any) -> Any:
    """Build the signer named by a catalog `signer:` field.

    Dispatches through :data:`_SIGNER_FACTORIES`. The `anonymous` signer is the
    pyramids-eo-local `_AnonymousS3Signer` and the `aws-requester-pays` signer
    comes from `pyramids.stac` (imported inside its factory, so importing this
    module pulls in no STAC stack); the `mpc-sas` / `earthdata` / `cdse` / `cdse-s3` /
    `bdc-token` provider signers are the pyramids-eo-local classes above.

    Args:
        signer_type: A name from :func:`available_signers` — `"anonymous"`,
            `"aws-requester-pays"`, `"mpc-sas"`, `"earthdata"`, `"cdse"`,
            `"cdse-s3"` or `"bdc-token"`.
        **creds: Extra credentials forwarded to the selected signer — `region`
            for `anonymous` (pins GDAL at an opt-in region's S3 endpoint) and
            `aws-requester-pays`; `username` / `password` / `token` for
            `earthdata`; `username` / `password` / `client_id` for `cdse`; the
            CDSE S3 credential resolution kwargs for `cdse-s3` (see
            `auth_cdse.s3_credentials`); `token` for `bdc-token` (defaults to
            `$BDC_ACCESS_TOKEN`).

    Returns:
        A signer satisfying the `pyramids.stac.Signer` protocol.

    Raises:
        ValueError: When `signer_type` is not a known signer name — including
            when it is not a string at all, or is unhashable (a list or dict
            from a malformed catalog). A `TypeError` raised by a custom
            `__hash__` or `__eq__` is indistinguishable from an unhashable
            type and is converted too; any *other* exception from them
            propagates, since widening the except clause further would mask
            real faults.

    Examples:
        - The MPC key maps to the native SAS signer (no SDK):
            ```python
            >>> from pyramids_eo.stac import build_signer
            >>> build_signer("mpc-sas").name
            'planetary-computer'

            ```
        - Build the CDSE S3 signer from explicit S3 keys:
            ```python
            >>> from pyramids_eo.stac import build_signer
            >>> build_signer("cdse-s3", access_key="ak", secret_key="sk").gdal_env()["AWS_ACCESS_KEY_ID"]
            'ak'

            ```
        - Build the BDC token signer with an explicit token:
            ```python
            >>> from pyramids_eo.stac import build_signer
            >>> build_signer("bdc-token", token="abc").name
            'bdc-token'

            ```
        - An unknown signer name is rejected:
            ```python
            >>> from pyramids_eo.stac import build_signer
            >>> build_signer("nope")  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: unknown signer_type 'nope'; expected one of ... 'bdc-token'.

            ```

    See Also:
        available_signers: The names this factory accepts, for validating a
            catalog value before building anything.

    """
    try:
        factory = _SIGNER_FACTORIES[signer_type]
    except (KeyError, TypeError):
        # TypeError covers an unhashable `signer_type` (a list or dict from a
        # malformed catalog) and a TypeError out of a custom `__hash__`/`__eq__`,
        # which is not distinguishable from it. The pre-registry `if/elif` chain
        # compared with `==`, which tolerates any type, so both must still raise
        # ValueError. Anything else from `__hash__` propagates.
        names = ", ".join(repr(name) for name in available_signers())
        raise ValueError(
            f"unknown signer_type {signer_type!r}; expected one of {names}."
        ) from None
    return factory(**creds)

CDSE S3 credentials#

pyramids_eo.stac.auth_cdse #

CDSE S3 credential resolution for the STAC backend's cdse-s3 signer.

Copernicus Data Space (CDSE) STAC search is anonymous, but the asset bytes live on an S3-compatible store at eodata.dataspace.copernicus.eu that needs S3 access-key/secret credentials. Two ways to obtain them:

  • (a) Dashboard keys — long-lived S3 keys generated in the CDSE dashboard (the robust default). Supplied via the CDSE_S3_ACCESS_KEY / CDSE_S3_SECRET_KEY env vars or explicit kwargs.
  • (b) Keycloak token → temporary S3 creds — exchanged from an OAuth password grant when only CDSE_USERNAME / CDSE_PASSWORD are available.

s3_credentials resolves (a) first (kwarg → env). Path (b) is a planned fallback (see planning/stac/stac-completion.md G4); until its token / exchange endpoints are pinned, supplying only username/password raises a clear AuthenticationError naming the dashboard URL.

s3_credentials(access_key=None, secret_key=None, **_ignored) #

Resolve CDSE S3 (access_key, secret_key) for the cdse-s3 signer.

Resolution order: explicit kwargs, then the CDSE_S3_ACCESS_KEY / CDSE_S3_SECRET_KEY env vars. Extra keyword arguments are ignored so the build_signer(**creds) call site can forward a superset of kwargs.

Parameters:

Name Type Description Default
access_key str | None

CDSE S3 access key id, or None to read the env var.

None
secret_key str | None

CDSE S3 secret key, or None to read the env var.

None
**_ignored object

Ignored extra kwargs (forwarded by build_signer).

{}

Returns:

Type Description
tuple[str, str]

The resolved (access_key, secret_key) pair.

Raises:

Type Description
AuthenticationError

When neither kwargs nor env vars supply both halves of the credential pair. The message names the dashboard URL where keys are generated and the env vars to set.

Examples:

  • Explicit keys are returned as a pair (kwargs win over the env):
    >>> from pyramids_eo.stac import auth_cdse
    >>> auth_cdse.s3_credentials(access_key="ak", secret_key="sk")
    ('ak', 'sk')
    
  • Extra kwargs that build_signer forwards are ignored:
    >>> from pyramids_eo.stac import auth_cdse
    >>> auth_cdse.s3_credentials(access_key="ak", secret_key="sk", region="eu")
    ('ak', 'sk')
    
Source code in src/pyramids_eo/stac/auth_cdse.py
def s3_credentials(
    access_key: str | None = None,
    secret_key: str | None = None,
    **_ignored: object,
) -> tuple[str, str]:
    """Resolve CDSE S3 `(access_key, secret_key)` for the `cdse-s3` signer.

    Resolution order: explicit kwargs, then the `CDSE_S3_ACCESS_KEY` /
    `CDSE_S3_SECRET_KEY` env vars. Extra keyword arguments are ignored so the
    `build_signer(**creds)` call site can forward a superset of kwargs.

    Args:
        access_key: CDSE S3 access key id, or `None` to read the env var.
        secret_key: CDSE S3 secret key, or `None` to read the env var.
        **_ignored: Ignored extra kwargs (forwarded by `build_signer`).

    Returns:
        The resolved `(access_key, secret_key)` pair.

    Raises:
        AuthenticationError: When neither kwargs nor env vars supply both
            halves of the credential pair. The message names the dashboard
            URL where keys are generated and the env vars to set.

    Examples:
        - Explicit keys are returned as a pair (kwargs win over the env):
            ```python
            >>> from pyramids_eo.stac import auth_cdse
            >>> auth_cdse.s3_credentials(access_key="ak", secret_key="sk")
            ('ak', 'sk')

            ```
        - Extra kwargs that `build_signer` forwards are ignored:
            ```python
            >>> from pyramids_eo.stac import auth_cdse
            >>> auth_cdse.s3_credentials(access_key="ak", secret_key="sk", region="eu")
            ('ak', 'sk')

            ```
    """
    resolved_access = access_key or os.environ.get("CDSE_S3_ACCESS_KEY")
    resolved_secret = secret_key or os.environ.get("CDSE_S3_SECRET_KEY")
    if resolved_access and resolved_secret:
        return resolved_access, resolved_secret

    has_login = os.environ.get("CDSE_USERNAME") and os.environ.get("CDSE_PASSWORD")
    extra = (
        " A CDSE_USERNAME/CDSE_PASSWORD token exchange is not yet wired; "
        "generate dashboard S3 keys for now."
        if has_login
        else ""
    )
    raise AuthenticationError(
        "CDSE S3 credentials are required to read eodata assets but none were "
        "found. Generate S3 keys at "
        f"{CDSE_DASHBOARD_URL} and set CDSE_S3_ACCESS_KEY / CDSE_S3_SECRET_KEY "
        "(or pass access_key= / secret_key=)." + extra
    )