Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ jobs:
USER_STAC_CATALOG_TRANSACTIONS_AUTH_MODE: ${{ vars.USER_STAC_CATALOG_TRANSACTIONS_AUTH_MODE }}
USER_STAC_CATALOG_TRANSACTIONS_AUTH_SECRET_ARN: ${{ vars.USER_STAC_CATALOG_TRANSACTIONS_AUTH_SECRET_ARN }}
USER_STAC_STAC_API_CUSTOM_DOMAIN_NAME: ${{ vars.USER_STAC_STAC_API_CUSTOM_DOMAIN_NAME }}
USER_STAC_OIDC_DISCOVERY_URL: ${{ vars.USER_STAC_OIDC_DISCOVERY_URL }}
USER_STAC_OIDC_ALLOWED_AUDIENCES: ${{ vars.USER_STAC_OIDC_ALLOWED_AUDIENCES }}
USER_STAC_OIDC_SWAGGER_CLIENT_ID: ${{ vars.USER_STAC_OIDC_SWAGGER_CLIENT_ID }}
USER_STAC_TITILER_PGSTAC_API_CUSTOM_DOMAIN_NAME: ${{ vars.USER_STAC_TITILER_PGSTAC_API_CUSTOM_DOMAIN_NAME }}
WEB_ACL_ARN: ${{ vars.WEB_ACL_ARN }}

Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ stac-browser/

dev-docs/plans/
issue-drafts/

# generated STAC Browser config
cdk/.generated/
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,34 @@ User STAC catalog configuration:
- `USER_STAC_CATALOG_TRANSACTIONS_AUTH_MODE=basic` enables catalog write routes and selects the supported auth mode. Catalog write routes require catalogs to stay enabled.
- `USER_STAC_CATALOG_TRANSACTIONS_AUTH_SECRET_ARN` can point at an existing auth secret.

### User-controlled access to DPS STAC API (Keycloak / OIDC)

By default the user STAC API is open for reads. Setting the variable `USER_STAC_OIDC_DISCOVERY_URL` will turn on
[stac-auth-proxy](https://developmentseed.org/stac-auth-proxy/) inside the STAC Lambda, which
requires a valid Keycloak bearer token on every route.

Relevant Variables for deployment:

- `USER_STAC_OIDC_DISCOVERY_URL` is the realm's `.well-known/openid-configuration` URL. Setting it turns user-controlled access on.
- `USER_STAC_OIDC_ALLOWED_AUDIENCES` is a comma-separated list of accepted token `aud` values, for example `maap-dps-stac`. This should be set because leaving it unset does not skip the check, and tokens that carry an `aud` are rejected. This audience value should match what is configured in the Keycloak client.
- `USER_STAC_OIDC_SWAGGER_CLIENT_ID` is the public Keycloak client used by the Swagger UI at `/api.html` and by the user STAC Browser login, for example `maap-stac-browser`. It is required when the discovery URL is set. The CDK stack writes this value and the discovery URL into the browser's `authConfig` at synth time
- `USER_STAC_COLLECTION_TRANSACTIONS_AUTH_MODE=oidc` and `USER_STAC_CATALOG_TRANSACTIONS_AUTH_MODE=oidc` enable the write routes with bearer scopes instead of Basic auth.

Relevant notes:

- The routes `/_mgmt/ping`, `/api`, `/api.html` and `/docs/oauth2-redirect` are public. Every other route, including the landing page, needs a token, since we want to protect them.
- Write routes also need scopes: `stac:collection:create|update|delete` and `stac:catalog:create|update|delete`.
- Basic and bearer auth both use the `Authorization` header, so they can't be combined. Synth should fail if OIDC is on and the transactions mode is set to `basic`, or if a transactions mode is `oidc` without a discovery URL.
- A custom API domain (`USER_STAC_STAC_API_CUSTOM_DOMAIN_NAME`) is not required for auth to work, but it is recommended. Whichever API address you use, make sure it is configured in Keycloak since the API's exact origin must be listed in the client's redirect URIs and web origins. With a custom domain, you can do this before deploying. Without one, AWS will generate it at the first deploy, so add it to Keycloak after that (and again if the stack is recreated).
- For issues with configuring auth for the STAC Browser, CloudFront seems to cache the browser files, so invalidate the cache if you still see the old behavior (no login prompt).

#### Keycloak configuration

The Keycloak clients and roles are defined in `veda-keycloak`, which is the source of truth: [dev](https://github.com/NASA-IMPACT/veda-keycloak/blob/main/keycloak-config-cli/config/dev/maap.yml) and [prod](https://github.com/NASA-IMPACT/veda-keycloak/blob/main/keycloak-config-cli/config/prod/maap.yml). When turning on user-controlled access, this API expects:

- a client matching `USER_STAC_OIDC_SWAGGER_CLIENT_ID`, with `https://<api-domain>/docs/oauth2-redirect` as a redirect URI and the API and browser origins as web origins
- the audience from `USER_STAC_OIDC_ALLOWED_AUDIENCES`, which Keycloak adds to the token for users with the `reader` role on that client

## DPS-generated STAC items

The DPS item generator assigns unregistered items to collections named
Expand Down Expand Up @@ -220,7 +248,7 @@ For a catalogs-enabled deployment, verify:

- OpenAPI includes read-only catalog routes such as `GET /catalogs`, `GET /catalogs/{catalog_id}`, and catalog-scoped collection/item reads.
- `GET /` includes `rel="child"` links for listed catalogs so STAC Browser can discover catalog roots.
- catalog write routes are absent unless `USER_STAC_CATALOG_TRANSACTIONS_AUTH_MODE=basic` is configured.
- catalog write routes are absent unless `USER_STAC_CATALOG_TRANSACTIONS_AUTH_MODE` is set to `basic` or `oidc`.

The deployment includes a public STAC Browser and, when
`USER_STAC_BROWSER_CUSTOM_DOMAIN_NAME` and `USER_STAC_BROWSER_CERTIFICATE_ARN` are
Expand Down
60 changes: 51 additions & 9 deletions cdk/config.py
Comment thread
jjfrench marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class TitilerPgstacConfig:
custom_domain_name: str | None = None


TransactionAuthMode = Literal["basic", "jwt"]
TransactionAuthMode = Literal["basic", "jwt", "oidc"]


@dataclass
Expand All @@ -39,10 +39,23 @@ class CollectionTransactionsConfig:
auth_secret_arn: str | None = None


@dataclass
class OidcAuthConfig:
"""
Require an OIDC (Keycloak) bearer token on every STAC API
route enforced in the STAC runtime by stac-auth-proxy
"""

discovery_url: str
allowed_audiences: str | None = None
swagger_client_id: str | None = None


@dataclass
class StacApiConfig:
custom_domain_name: str | None = None
integration_api_arn: str | None = None
oidc: OidcAuthConfig | None = None
transactions: CollectionTransactionsConfig | None = None
catalogs: StacCatalogsConfig | None = None

Expand Down Expand Up @@ -119,6 +132,14 @@ class Config(BaseSettings):
user_stac_inbound_topic_arns: list[str] | None = None
user_stac_collection_id_registry: dict[str, list[str]] | None = None

# --- For OIDC auth using Keycloak via stac-auth-proxy ---
# Set the discovery URL to require a token on all user STAC API routes
user_stac_oidc_discovery_url: str | None = None
# This is a comma-separated list of accepted JWT aud values
user_stac_oidc_allowed_audiences: str | None = None
# Public Keycloak client that is used by Swagger UI (/api.html) to log in
user_stac_oidc_swagger_client_id: str | None = None

# --- Collection transactions env fields ---
user_stac_collection_transactions_auth_mode: TransactionAuthMode | None = None
user_stac_collection_transactions_auth_secret_arn: str | None = None
Expand All @@ -140,10 +161,10 @@ def parse_auth_mode(cls, v: object) -> str | None:
return None
if isinstance(v, str):
normalized = v.strip().lower()
if normalized in {"basic", "jwt"}:
if normalized in {"basic", "jwt", "oidc"}:
return normalized
raise ValueError(
f"Unsupported auth mode: {v!r}. Expected one of: 'basic', 'jwt'."
f"Unsupported auth mode: {v!r}. Expected one of: 'basic', 'jwt', 'oidc'."
)

@field_validator("db_instance_type", mode="before")
Expand Down Expand Up @@ -222,10 +243,10 @@ def validate_catalogs_config(self) -> Config:
"USER_STAC_CATALOG_TRANSACTIONS_AUTH_SECRET_ARN is set."
)

if (auth_mode or auth_secret_arn) and auth_mode != "basic":
if (auth_mode or auth_secret_arn) and auth_mode not in ("basic", "oidc"):
raise ValueError(
f"Unsupported USER_STAC_CATALOG_TRANSACTIONS_AUTH_MODE: "
f'"{auth_mode}". Expected "basic".'
f'"{auth_mode}". Expected "basic" or "oidc".'
)

return self
Expand All @@ -235,10 +256,10 @@ def validate_collection_transactions(self) -> Config:
auth_mode = self.user_stac_collection_transactions_auth_mode
auth_secret_arn = self.user_stac_collection_transactions_auth_secret_arn

if (auth_mode or auth_secret_arn) and auth_mode != "basic":
if (auth_mode or auth_secret_arn) and auth_mode not in ("basic", "oidc"):
raise ValueError(
f"Unsupported USER_STAC_COLLECTION_TRANSACTIONS_AUTH_MODE: "
f'"{auth_mode}". Expected "basic".'
f'"{auth_mode}". Expected "basic" or "oidc".'
)

return self
Expand All @@ -252,7 +273,23 @@ def user_stac_collection_transactions(
return None
return CollectionTransactionsConfig(
auth_mode=self.user_stac_collection_transactions_auth_mode,
auth_secret_arn=self.user_stac_collection_transactions_auth_secret_arn,
# The secret holds Basic auth credentials, so have OIDC mode ignore it
auth_secret_arn=(
self.user_stac_collection_transactions_auth_secret_arn
if self.user_stac_collection_transactions_auth_mode == "basic"
else None
),
)

@computed_field # type: ignore[prop-decorator]
@property
def user_stac_oidc(self) -> OidcAuthConfig | None:
if not self.user_stac_oidc_discovery_url:
return None
return OidcAuthConfig(
discovery_url=self.user_stac_oidc_discovery_url,
allowed_audiences=self.user_stac_oidc_allowed_audiences,
swagger_client_id=self.user_stac_oidc_swagger_client_id,
)

@computed_field # type: ignore[prop-decorator]
Expand All @@ -262,7 +299,11 @@ def user_stac_catalogs(self) -> StacCatalogsConfig:
if self.user_stac_catalog_transactions_auth_mode is not None:
catalog_transactions = CollectionTransactionsConfig(
auth_mode=self.user_stac_catalog_transactions_auth_mode,
auth_secret_arn=self.user_stac_catalog_transactions_auth_secret_arn,
auth_secret_arn=(
self.user_stac_catalog_transactions_auth_secret_arn
if self.user_stac_catalog_transactions_auth_mode == "basic"
else None
),
)

return StacCatalogsConfig(
Expand Down Expand Up @@ -297,6 +338,7 @@ def public_stac_api(self) -> StacApiConfig:
def user_stac_api(self) -> StacApiConfig:
return StacApiConfig(
custom_domain_name=self.user_stac_stac_api_custom_domain_name,
oidc=self.user_stac_oidc,
transactions=self.user_stac_collection_transactions,
catalogs=self.user_stac_catalogs,
)
Expand Down
102 changes: 97 additions & 5 deletions cdk/pgstac_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from .config import (
DpsStacItemGenConfig,
IngestorConfig,
OidcAuthConfig,
PgStacDbConfig,
StacApiConfig,
StacBrowserConfig,
Expand All @@ -44,6 +45,44 @@
from constructs import Construct

_CDK_DIR = Path(__file__).parent
_USER_BROWSER_CONFIG = _CDK_DIR / "stac_browser_user_config.js"
_AUTH_CONFIG_PLACEHOLDER = "authConfig: null,"


def _user_stac_browser_config_path(oidc: OidcAuthConfig | None) -> str:
"""Path of the user STAC Browser config, with OIDC login added if enabled"""
if not oidc:
return str(_USER_BROWSER_CONFIG)
if not oidc.swagger_client_id:
raise ValueError(
"USER_STAC_OIDC_SWAGGER_CLIENT_ID is required when OIDC auth is "
"enabled, because the STAC Browser logs in with the same client"
)

source = _USER_BROWSER_CONFIG.read_text()
if source.count(_AUTH_CONFIG_PLACEHOLDER) != 1:
raise ValueError(
f"{_USER_BROWSER_CONFIG.name} must contain exactly one "
f"'{_AUTH_CONFIG_PLACEHOLDER}' line"
)
auth_config = json.dumps(
{
"type": "openIdConnect",
"openIdConnectUrl": oidc.discovery_url,
"oidcConfig": {
"client_id": oidc.swagger_client_id,
"scope": "openid profile email",
},
"description": "Log in with your MAAP account.",
},
indent=2,
)
generated = _CDK_DIR / ".generated" / _USER_BROWSER_CONFIG.name
generated.parent.mkdir(exist_ok=True)
generated.write_text(
source.replace(_AUTH_CONFIG_PLACEHOLDER, f"authConfig: {auth_config},")
)
return str(generated)


class PgStacInfra(Stack):
Expand Down Expand Up @@ -132,19 +171,30 @@ def __init__(
if catalog_transactions_config and not catalogs_enabled:
raise ValueError("STAC catalog transactions require catalogs to be enabled")

if transactions_config and transactions_config.auth_mode != "basic":
if transactions_config and transactions_config.auth_mode not in (
"basic",
"oidc",
):
raise ValueError(
f"Unsupported STAC collection transaction auth mode: "
f"{transactions_config.auth_mode}"
)
if (
catalog_transactions_config
and catalog_transactions_config.auth_mode != "basic"
and catalog_transactions_config.auth_mode not in ("basic", "oidc")
):
raise ValueError(
f"Unsupported STAC catalog transaction auth mode: "
f"{catalog_transactions_config.auth_mode}"
)
if (
transactions_config
and catalog_transactions_config
and transactions_config.auth_mode != catalog_transactions_config.auth_mode
):
raise ValueError(
"STAC collection and catalog transactions must use the same auth mode"
)
if (
transactions_config
and catalog_transactions_config
Expand All @@ -158,7 +208,24 @@ def __init__(

write_transactions_config = transactions_config or catalog_transactions_config

if write_transactions_config:
write_auth_mode = (
write_transactions_config.auth_mode if write_transactions_config else None
)
if stac_api_config.oidc:
if write_auth_mode not in (None, "oidc"):
raise ValueError(
"STAC transactions must use auth mode 'oidc' when OIDC auth is "
"enabled"
)
elif write_auth_mode == "oidc":
raise ValueError(
"STAC transactions with auth mode 'oidc' need OIDC auth to be "
"configured (set USER_STAC_OIDC_DISCOVERY_URL)"
)

uses_basic_auth = write_auth_mode == "basic"

if write_transactions_config and uses_basic_auth:
if write_transactions_config.auth_secret_arn:
transaction_auth_secret: secretsmanager.ISecret | None = (
secretsmanager.Secret.from_secret_complete_arn(
Expand Down Expand Up @@ -215,14 +282,39 @@ def __init__(
"HIDE_ALTERNATE_PARENTS": (
"true" if catalogs_config.hide_alternate_parents else "false"
),
**(
{
"MAAP_AUTH_OIDC_DISCOVERY_URL": stac_api_config.oidc.discovery_url,
**(
{
"MAAP_AUTH_ALLOWED_JWT_AUDIENCES": (
stac_api_config.oidc.allowed_audiences
)
}
if stac_api_config.oidc.allowed_audiences
else {}
),
**(
{
"MAAP_AUTH_SWAGGER_CLIENT_ID": (
stac_api_config.oidc.swagger_client_id
)
}
if stac_api_config.oidc.swagger_client_id
else {}
),
}
if stac_api_config.oidc
else {}
),
**(
{
"MAAP_TRANSACTION_AUTH_MODE": write_transactions_config.auth_mode,
"MAAP_TRANSACTION_AUTH_SECRET_ARN": (
transaction_auth_secret.secret_arn # type: ignore [union-attr]
),
}
if write_transactions_config
if write_transactions_config and uses_basic_auth
else {}
),
}
Expand Down Expand Up @@ -610,7 +702,7 @@ def __init__(
github_repo_tag=stac_browser_config.repo_tag,
clone_directory=f"./stac-browser-{type}",
config_file_path=(
str(_CDK_DIR / "stac_browser_user_config.js")
_user_stac_browser_config_path(stac_api_config.oidc)
if type == "internal"
else None
),
Expand Down
8 changes: 5 additions & 3 deletions cdk/runtimes/eoapi/stac/eoapi/stac/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
from starlette.middleware.cors import CORSMiddleware

from eoapi.stac.auth import build_transaction_route_dependencies
from eoapi.stac.oidc import configure_oidc_auth, oidc_auth_enabled
from eoapi.stac.transactions import CollectionTransactionExtension

if TYPE_CHECKING:
Expand Down Expand Up @@ -193,7 +194,8 @@ def parse_enabled_extensions(raw_value: str | None) -> set[str]:
def _build_middlewares() -> list[Middleware]:
"""Build the middleware stack used by the upstream pgSTAC app."""
return [
Middleware(BrotliMiddleware),
# When OIDC is on, stac-auth-proxy does the compression instead
*([] if oidc_auth_enabled() else [Middleware(BrotliMiddleware)]),
Middleware(ProxyHeaderMiddleware),
Middleware(
CORSMiddleware,
Expand Down Expand Up @@ -248,7 +250,7 @@ def create_app(
if with_catalog_transactions and not with_catalogs:
raise ValueError("catalog_transaction requires catalogs in ENABLED_EXTENSIONS")

if with_write_transactions:
if with_write_transactions and not oidc_auth_enabled():
transaction_route_dependencies = build_transaction_route_dependencies()

if with_collection_transactions:
Expand Down Expand Up @@ -354,7 +356,7 @@ def create_app(
middlewares=_build_middlewares(),
health_check=health_check, # type: ignore[arg-type]
)
return api.app
return configure_oidc_auth(api.app, settings)


def run() -> None:
Expand Down
Loading