# Require sign-in

Put a login gate in front of every hostname of an app, with console accounts or your own OpenID Connect provider, and read who signed in from a signed header.

A login gate makes an app answer only people who have signed in. It covers every hostname the
app has: its default name, custom domains, the names of further compose services and preview
environments. Use it for an internal tool, an admin interface or a staging app that must not be
public, without writing sign-in code into the app.

| Sign in with                    | Who gets in                                                                                                                                                |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Console accounts (`console`)    | Members of the app's organization whose policies allow `deploy:AccessApp` on the app. Owners and administrators may already.                               |
| Your identity provider (`oidc`) | Everyone your OpenID Connect provider (Keycloak, Microsoft Entra ID, Okta, Google Workspace, …) signs in, narrowed by the email domains and webhook below. |
| Tokens you sign (`token`)       | Every request that carries a token your own service signed with a key you registered. See [Require a token you sign](#require-a-token-you-sign).           |

Two optional checks narrow who gets in, with console accounts or your provider:

- **Email domains**: only addresses in these domains, matched exactly (`example.com` does not
  admit `eu.example.com`). Only an address your provider marks as verified (`email_verified`) counts: a provider that does
  not say (Microsoft Entra ID) cannot be narrowed by domain; use a webhook there.
- **Access webhook**: your HTTPS endpoint is asked once per sign-in and answers
  `{"allow": true}` to admit the person. Any other answer, an error or no answer within 5 seconds
  refuses the sign-in.

The machines that serve the app check every request themselves, so a gated app keeps answering at
full speed and does not depend on Deutsche Cloud being reachable, except at the moment someone signs
in.

## Prerequisites

- `deploy:PutLoginGate` to require sign-in or change it, `deploy:DeleteLoginGate` to switch it
  off, `deploy:RevokeLoginGateSessions` to sign everyone out, `deploy:GetLoginGate` to see it,
  and in the console `deploy:DescribeApp` to open the app.
- For `oidc`: a client (application) at your provider with the authorization code flow, its client
  ID and client secret, and the redirect URI below registered on it.

## Require sign-in

**Console**
1. Open the app, then choose **More** › **Access**, then the **Login gate** section.
2. Choose **Require sign-in**.
3. For **Sign in with**, choose **Console accounts**, or **Your identity provider** (OpenID
   Connect). For your provider, register the **Redirect URI** the dialog shows
   at your provider, then enter the issuer URL, client ID and client secret.
4. Optionally enter **Email domains**, an **Access webhook**, the **Session length** and the
   **Open paths**.
5. Choose **Require sign-in**. The machines apply it within seconds.

**CLI**
```sh
dcloud deploy login-gate put app-id --provider console --exceptions /healthz
dcloud deploy login-gate put app-id --provider oidc \
  --oidc-issuer https://login.example.com/realms/staff --oidc-client-id dcloud-web \
  --oidc-client-secret "$OIDC_SECRET" --allowed-email-domains example.com --session-hours 12
dcloud deploy login-gate get app-id
```

**API**
```http
PUT /deploy/api/apps/app-id/login-gate
Content-Type: application/json

{
  "provider": "oidc",
  "oidcIssuer": "https://login.example.com/realms/staff",
  "oidcClientId": "dcloud-web",
  "oidcClientSecret": "…",
  "allowedEmailDomains": ["example.com"],
  "sessionHours": 12,
  "exceptions": ["/healthz", "/webhooks/"]
}
```

The answer is `201` with the gate when it is switched on, `200` when it is changed. Its
`redirectUri` is the one to register at your provider; it is the same for every app.

**Terraform**
```hcl
resource "dcloud_app_login_gate" "web" {
  app_id                = dcloud_app.web.id
  sign_in_with          = "oidc"
  oidc_issuer           = "https://login.example.com/realms/staff"
  oidc_client_id        = "dcloud-web"
  oidc_client_secret    = var.oidc_client_secret
  allowed_email_domains = ["example.com"]
  exceptions            = ["/healthz"]
}
```

Register `dcloud_app_login_gate.web.redirect_uri` at your provider.

A provider anyone can create an account at (Google accounts, the Microsoft `common`,
`consumers` and `organizations` endpoints) is refused without email domains or a webhook. Any
other provider without them needs `acknowledgeOpenAccess: true`: everyone it signs in gets in.

## Require a token you sign

When you already sign people in yourself, let the app's machines check your tokens instead.
Register the public keys your service signs with; a request passes when it carries a JSON Web
Token signed by one of them, either in a cookie (`dcloud_token` unless you name another) or in an
`Authorization: Bearer` header. A browser without a valid token is sent to your sign-in page with
`?return_to=` and the address it asked for; any other request gets `401`.

The machines check the signature (RS256 with an RSA key of 2048 bits or more, or ES256 with an EC
P-256 key), `exp` (required) and `nbf`, and `iss` and `aud` when you set them. They hold only your
public keys: a JWKS with a private key or a secret is refused. How long a token works is up to
your signer; to end tokens early, rotate the key.

**Console**
In **Require sign-in**, choose **Tokens you sign**, paste your public keys as a JWKS document,
enter your **Sign-in page** and, optionally, the cookie name, issuer and audience.

**CLI**
```sh
dcloud deploy login-gate put app-id --provider token \
  --token-jwks "$(cat jwks.json)" --redirect-url https://login.example.com/start \
  --token-cookie session --token-issuer https://auth.example.com --exceptions /healthz
```

**API**
```http
PUT /deploy/api/apps/app-id/login-gate
Content-Type: application/json

{
  "provider": "token",
  "tokenJwks": "{\"keys\":[{\"kty\":\"EC\",\"crv\":\"P-256\",\"kid\":\"k1\",\"x\":\"…\",\"y\":\"…\"}]}",
  "tokenCookie": "session",
  "tokenIssuer": "https://auth.example.com",
  "redirectUrl": "https://login.example.com/start"
}
```

**Terraform**
```hcl
resource "dcloud_app_login_gate" "web" {
  app_id       = dcloud_app.web.id
  sign_in_with = "token"
  token_jwks   = file("jwks.json")
  token_cookie = "session"
  redirect_url = "https://login.example.com/start"
}
```

Your sign-in page sets the cookie on the app's hostname (or a parent domain) and sends the
browser back to `return_to`, after checking that it is an address of your app (anyone can put
any address there). The app receives your token, unchanged, in `X-Dcloud-Identity`.
Email domains, the access webhook, the session length and **Sign everyone out** do not apply to a
token gate.

## What a visitor sees

A browser that opens the app without a session is sent to sign in, at your provider or at the
Deutsche Cloud sign-in page, and comes back to the page it asked for. Any other request without a
session (an API client, a `fetch` without HTML, a `POST`) gets `401` with the sign-in address in
the body. A sign-in lasts the session length (24 hours unless you set 1 to 168), then the person
signs in again; the provider and the webhook are asked again then.

To sign out, link to `/.dcloud/gate/logout` on the app's hostname. Paths under `/.dcloud/gate/`
belong to the gate on a gated app.

## Read who signed in

Every request that reaches the app carries two headers. Copies a client sends itself are removed
first, so neither can be forged by a visitor.

| Header                | Holds                                                                                                           |
| --------------------- | --------------------------------------------------------------------------------------------------------------- |
| `X-Dcloud-Identity`   | A JSON Web Token signed with RS256. Verify it and trust its claims.                                             |
| `X-Dcloud-User-Email` | The email address from the token, for convenience: read it only if the app is reachable through the gate alone. |

Verify the token against the keys at the `jwksUrl` the gate shows (the issuer's discovery
document is at `<issuer>/.well-known/openid-configuration`). Check `iss`, that `aud` is the app's
id, and `exp`. The claims:

| Claim              | Value                                                         |
| ------------------ | ------------------------------------------------------------- |
| `sub`              | The provider's stable id for the person (the console user id) |
| `email`, `name`    | As the provider said, when it said                            |
| `idp`              | `console`, or the issuer URL of your provider                 |
| `app_id`, `org_id` | The app and its organization                                  |

```js
import { createRemoteJWKSet, jwtVerify } from 'jose';

const keys = createRemoteJWKSet(new URL(process.env.GATE_JWKS_URL));
const { payload } = await jwtVerify(req.headers['x-dcloud-identity'], keys, {
  issuer: process.env.GATE_ISSUER,
  audience: process.env.APP_ID,
});
```

## The access webhook

Once per sign-in, after your provider (or the console) has said who the person is, the gate
sends a `POST` to the webhook URL:

```json
{
  "type": "login_gate.sign_in",
  "app": { "id": "…", "name": "intranet" },
  "host": "intranet.example.com",
  "user": { "subject": "…", "email": "ada@example.com", "name": "Ada", "idp": "https://login.example.com/realms/staff" },
  "time": "2026-11-30T09:00:00.000Z"
}
```

It carries `X-Dcloud-Timestamp` (Unix seconds) and `X-Dcloud-Signature: sha256=<hex>`, the
HMAC-SHA256 under your webhook secret of the timestamp, a dot and the body exactly as sent.
Check the signature and that the timestamp is recent, then answer `200` with `{"allow": true}`
to admit the person or `{"allow": false}` to refuse. The webhook is not called again until the
person's session ends.

## Open paths

**Open paths** are served without sign-in and without the identity headers: health checks, or
webhooks another service sends. `/healthz` matches `/healthz` and everything under `/healthz/`;
`/webhooks/` matches everything under it. A request whose path has `..` or `.` segments, an
encoded slash, dot or backslash, `;` or `//` never matches an open path: it is gated, so
`/healthz/../admin` cannot slip past.

## Sign everyone out, or switch it off

**Console**
In the **Login gate** section, choose **Sign everyone out** to end every session within seconds,
or **Stop requiring sign-in** to make every hostname public again.

**CLI**
```sh
dcloud deploy login-gate revoke-sessions app-id
dcloud deploy login-gate delete app-id
```

**API**
```http
POST /deploy/api/apps/app-id/login-gate/revoke-sessions
```

```http
DELETE /deploy/api/apps/app-id/login-gate
```

**Terraform**
Destroy the `dcloud_app_login_gate` resource to switch the gate off. Signing everyone out is an
action, not a resource: use the CLI or the API for it.

Changing the provider, issuer, client, email domains or webhook URL also signs everyone out. A
session from before the gate was switched off never works again after it is switched back on.

## Limits

- Removing someone from your provider or the organization does not end a session they already
  have; it ends at its session length. Sign everyone out to end it at once.
- Requests from programs (service tokens) cannot pass the gate yet; give such traffic an open
  path, or a separate app.
- A browser's CORS preflight (`OPTIONS`) to a gated path gets `401`.
- A preview environment is gated by the app it previews and has no settings of its own.
- Every change, every sign-in and every refusal is in the app's activity; the gate's settings
  changes and every console-account sign-in decision are in the audit log.

## Related

- [Pull a kill switch](pull-a-kill-switch.md)
- [Add a custom domain](add-a-custom-domain.md)
- `deploy.login-gate.put` · `dcloud deploy login-gate put`
