Metadata-Version: 2.4
Name: arraylake-apps-gateway
Version: 0.1.0
Summary: Arraylake Apps gateway: runs Arraylake apps locally (preview, dev) and deployed
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# Arraylake Apps gateway

One binary, three commands: `serve` (the deployed gateway), and `preview` / `dev` (an app on your
machine, same code). As a service, it's what runs behind `<app>--<org>.<apps domain>`. It serves each app's current deploy and gives
the app's JavaScript same-origin access to Arraylake as the viewer. Tokens and bucket
credentials never reach the browser. It's written in Rust because it is a long-lived streaming
proxy for chunk reads. It's a thin client of the Arraylake API with no database: users, apps,
deploys and repo credentials all come from the API, as the viewer.

| Path (on an app host)                             | What                                                      |
| ------------------------------------------------- | --------------------------------------------------------- |
| `GET /_arraylake/v1/me`                           | the viewer: `{kind, id, email, first_name, family_name}`  |
| `GET /_arraylake/v1/api/{path}`                   | the Arraylake API as the viewer: reads of the routes listed in `proxy.rs` only |
| `GET\|HEAD /_arraylake/v1/icechunk/{org}/{repo}/{key}` | a repo's Icechunk objects; Range for chunks; immutable caching for content-addressed objects, `no-store` for refs |
| `GET /_arraylake/v1/debug`                        | `--dev` only: app, org, API, viewer, session, grant       |
| `GET /_auth/{client.json,login,callback,logout}`   | signing in to this app (below)                            |
| anything else                                     | the app's current deploy, with SPA fallback; a page load with no session signs in first |

Genuine S3 buckets are read through S3's dualstack endpoint (`--s3-dualstack`, on by default), so
in the cluster those reads go out over IPv6 through the egress-only gateway rather than the NAT
gateway. That matches the server's bulk-IO paths. Buckets with their own endpoint (R2, Tigris,
RustFS) are untouched.

Any other host answers `GET /healthz` and a 404 `unknown_app` otherwise. Errors are JSON with a
stable `error` code.

## How an app request is served

1. The Host header names `<app>--<org>`.
2. The viewer's token comes from the app's session cookie (below), or from
   `Authorization: Bearer` (scripts and the local CLI). With neither, a page load goes to
   `/_auth/login` and a `fetch` gets a 401.
3. `GET /orgs/{org}/apps/{app}/authorize` as the viewer says whether they may open the app and
   which deploy is current. The answer is cached per viewer for 60 seconds.
4. The deploy's manifest (`.../deploys/{id}/manifest`) maps the URL path to a file, with SPA
   fallback for extensionless paths.
5. The file bytes come straight from the org's bucket, by the short-lived presigned URL (15
   minutes) the manifest carries for each file. The gateway refetches the manifest before the
   URLs expire and never holds bucket credentials for app files. Buckets that can't be signed
   per file cheaply (GCS, Azure) get no URLs, and those files come through
   `.../deploys/{id}/files/{path}` instead, as does any file whose URL the bucket refuses.

Manifests and files are cached by deploy id, since deploys are immutable. Every response
carries the file's sha256 as its ETag, so revalidating after a new deploy is a 304 unless the
file changed.

## Owned apps: no sign-in, the app's own account

An owned app (`kind: owned`) is a page an org publishes: anyone may open it without signing in,
and it has no `/_auth/` routes. The app's `/client` says whose credentials to read with
(`reads_as`), so the gateway needs no rules of its own; the API's grants decide what each reads.

- `app`: a read-only service account of the app's own. The API declares it as an `AppAccount`
  resource; the compute controller mints it, writes its token into the `app-tokens` Secret in
  the gateway's namespace (one key per app id), rotates it before it expires and revokes it when
  the app goes (`compute/controller/compute_controller/app_accounts.py`). The gateway mounts the
  Secret at `--app-tokens` and reads the app's file on each request that carries no token of its
  own, so a rotated token takes effect when the kubelet refreshes the mount. A new app answers
  503 `app_starting` until its key arrives (up to a minute or so). The token never reaches a
  browser.
- `nobody` (`reads: public`): no account. Every call goes out with no credential, so the app
  reads only fully public repos, where anonymous access is on.

The gateway can read every owned app's token, as the compute controller can read every org
token: a known trade-off for now.

## Sign-in: every app is its own Auth0 client

The gateway serves each app's Auth0 client as a client ID metadata document (CIMD) at
`https://<app>--<org>.<domain>/_auth/client.json`. That URL is the client ID: Auth0 fetches it
and registers the app on its first sign-in. So:

- the consent screen names the app (`<app> (<org>)`)
- the token's `azp` is the app, so the API can tell apps apart
- the token carries only the app's scopes (its `scopes` setting: `read:data`, optionally
  `write:data`), capped by what the viewer approves. The API's delegated-token rules apply,
  as for any third-party app, and the viewer's own permissions still apply on top.

The flow is authorization code with PKCE, a public client, on the app's own host. `/_auth/login`
seals {state, verifier, next} into a short-lived cookie and sends the viewer to Auth0. The
callback checks the state against that cookie, trades the code for an access token, and seals
it into `__Host-al_session`. Cookies are AES-256-GCM sealed with `--session-key` and bound to
the app's host, so a session for one app never opens on another. There are no refresh tokens.
When the session ends, a page load signs in again, which Auth0 completes without a prompt
while its own session lasts.

Two things to know:

- **Auth0 quota.** Self-registered clients count toward the tenant's application limit (500
  self-registered clients per tenant by default). Clients for deleted apps stay until removed.
- **Local hosts.** Auth0 rejects `http://<app>--<org>.localhost` callbacks, so browser sign-in
  needs the app on HTTPS. Locally the CLI adds your token instead. To try sign-in locally, put
  the gateway behind an HTTPS tunnel that rewrites Host to the app and sets X-Forwarded-Host,
  and pass `--trust-forwarded`.

| Flag (env)                                      | Default                                  |
| ----------------------------------------------- | ---------------------------------------- |
| `--auth0` (`APPS_GATEWAY_AUTH0`)                | `https://earthmover-dev.us.auth0.com`    |
| `--audience` (`APPS_GATEWAY_AUDIENCE`)          | `--api`                                  |
| `--session-key` (`APPS_GATEWAY_SESSION_KEY`)    | required outside `--dev`; 32 bytes, base64, the same on every replica |
| `--public-scheme` (`APPS_GATEWAY_PUBLIC_SCHEME`) | `https`                                  |
| `--trust-forwarded` (`APPS_GATEWAY_TRUST_FORWARDED`) | off; on behind the ingress, which sets X-Forwarded-Host/-Proto |
| `--app-tokens` (`APPS_GATEWAY_APP_TOKENS`)       | unset: owned apps answer 503; deployed, the mounted `app-tokens` Secret |

## Deployed

The gateway runs in the controller stack's home region (`infrastructure/controller/appsGateway.ts`),
behind the compute NLB and its ingress-nginx, like booth. Setting `controller:appsDomain`
(dev: `apps.dev.arraylake.app`) adds:

- a wildcard certificate, added to the NLB's 443 listener by SNI
- the `*.<appsDomain>` DNS record
- a `gai.conf` (as jobroni's) so the pods prefer IPv6 for dual-stack endpoints. The VPC CNI gives
  pods a ULA IPv6 source, which glibc otherwise ranks below IPv4, sending bucket reads through
  the NAT
- the `apps-gateway` namespace, Service, Ingress, and a generated session key

`_apps-gateway-deploy.yaml` builds the image (ECR `earthmover/apps-gateway`), writes
`controller:appsGatewayImageTag` and applies the stack, which adds the Deployment (2 replicas on
the services pool) and its disruption budget. `env-deploy` runs it after the controller and
doorman whenever `apps/gateway` changes; `deploy.yaml` has an `apps_gateway` input for manual
deploys.

Logs are JSON lines (`--log-json`, `APPS_GATEWAY_LOG_JSON`, set in the image): flat objects
with `timestamp`, `level` and `message`. Each request line carries Datadog's standard attributes:
`http.method`, `http.status_code`, `http.url_details.host` and `.path`, and `duration` in ns. A
failed request adds `error.kind` (the gateway's error code). Server errors log at WARN with
`error.message`, and health probes at DEBUG. `RUST_LOG` overrides the level.

First time in an environment: run `pulumi up` once in `infrastructure/ecr` (no workflow applies
it), then deploy. Until the image tag exists, apps hosts answer 503 from nginx.

## Locally: `preview` and `dev`

The same binary runs an app on your machine at `http://<app>--<org>.localhost:8787`, signed in
with your `al auth login` session (or `ARRAYLAKE_TOKEN`). `al apps preview` and `al apps dev`
(`client/arraylake/cli/apps.py`) run it, passing the API (`service.uri`) and token file from arraylake's config; it
refreshes that token file the same way the Python and Rust clients do. Everything under `/_arraylake/` is the
deployed code; only the app's own files come from your machine (`src/local.rs`):

| Command | App files from |
| --- | --- |
| `arraylake-apps-gateway preview ORG/APP DIR` | a built folder, with SPA fallback |
| `arraylake-apps-gateway dev ORG/APP [--upstream URL] -- CMD...` | your dev server: it runs `CMD`, takes the URL it prints, and proxies to it, HMR websockets included |

Options: `--api` (`al apps` passes `service.uri`), `--port` (8787; `0` picks a free one), `-v`
for a request log (on stderr), and `--output json` for one JSON event per line (`ready`,
`dev_output`, `dev_exited`) with a failure as a JSON `error` on stderr and exit status 1. The
dev command failing, or printing no URL within `--upstream-timeout` (120s), stops the gateway
with exit status 1. The one app is also served on the bare loopback host
(`http://127.0.0.1:<port>/`), for HTTP clients that don't resolve `*.localhost`.

Two things differ from deployed, on purpose: the app's access setting isn't checked, and there is
no browser sign-in (`/_auth/*` is a 404). Auth0 can't call back to `*.localhost`, so your login
signs every request instead.

The binary ships as the `arraylake-apps-gateway` Python package, one wheel per platform
(`pyproject.toml`, built with maturin by `apps-gateway-wheels.yaml`), so no Rust toolchain is
needed. `al apps` finds it in the Python environment's scripts folder, or on `PATH`.

## Run it

```sh
just run                                    # serve, against https://dev.api.earthmover.io
just api=http://127.0.0.1:8000 run          # serve, against a local API
cargo run -- preview earthmover/vanilla ../examples/vanilla --api https://dev.api.earthmover.io
just pre-commit                             # fmt, clippy, tests
just docker                                 # build the image
```

