Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
90 changes: 83 additions & 7 deletions docs/CONSOLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,21 @@ what a Simlock host, or a gateway and its workers, is doing. The daemon serves
it itself. There is nothing to install and nothing is fetched from the
internet.

The console is for people who operate Simlock. It needs an operator token.
The console is for people who operate Simlock. It needs an operator token, or
a sign-in proxy in front of Simlock that signs you in
(see [Behind a sign-in proxy](#behind-a-sign-in-proxy)).
Coding agents keep using the CLI, the MCP server, the client and the HTTP API.

## Finding your way

A sidebar on the left leads to every page: **Overview**, **Workers**,
**Leases**, **Waiting**, **Attention**, **Events** and **Usage**. **Attention** shows how
many items need you, on every page. At the bottom of the sidebar are the
connection (see [Live updates](#live-updates)), **Sign out**, and the button
that collapses the sidebar to its icons and widens it again. The console
connection (see [Live updates](#live-updates)), who you are signed in as
(**Signed in as** and the name, hidden while the sidebar is collapsed),
**Sign out** (absent when a sign-in proxy signed you in and has no sign-out
page set), and the button that collapses the sidebar to its icons and widens
it again. The console
remembers your choice in this browser, and changing pages never changes it.
A window narrower than 1280 pixels starts with the sidebar collapsed until you
choose. On a phone the sidebar is a bar along the top with a menu button.
Expand Down Expand Up @@ -119,16 +124,85 @@ If the console does not accept the token, it says why:
| The daemon cannot be reached. | Nothing answers at this address. |
| The daemon answered with an error (HTTP *n*). | Anything else; the daemon's log says more. |

## Behind a sign-in proxy

When a sign-in proxy stands in front of Simlock, the console opens with no
token form. It asks the daemon who you are (`GET /v1/identity`), and if the
proxy signed you in, it opens at once and the sidebar reads **Signed in as**
and your name. Until the answer comes the page says **Signing in…**.

What you configure is in `http.proxyAuth` (see CONFIGURATION.md): the header
that carries the proxy's JWT, where the proxy publishes its keys, the issuer
and the audience. Set `signOutUrl` to the proxy's sign-out page. The proxy
must let `/v1/uplink` and `/v1/healthz` through without signing in.

Cloudflare Access:

```json
{
"http": {
"proxyAuth": {
"header": "cf-access-jwt-assertion",
"jwksUrl": "https://TEAM.cloudflareaccess.com/cdn-cgi/access/certs",
"issuer": "https://TEAM.cloudflareaccess.com",
"audience": "APPLICATION-AUD-TAG",
"signOutUrl": "https://TEAM.cloudflareaccess.com/cdn-cgi/access/logout"
}
}
}
```

oauth2-proxy, with its alpha config injecting the session's ID token into a
header of your choosing (`claimSource: { claim: id_token }`), so that an
operator token pasted into the console still reaches Simlock in
`Authorization`:

```json
{
"http": {
"proxyAuth": {
"header": "x-id-token",
"jwksUrl": "https://ISSUER/.well-known/jwks.json",
"issuer": "https://ISSUER",
"audience": "OAUTH2-PROXY-CLIENT-ID",
"signOutUrl": "https://CONSOLE-HOST/oauth2/sign_out"
}
}
}
```

If the daemon refuses the proxy's identity, the token form says why: "Your
sign-in proxy's identity was refused: *reason*. You can still sign in with an
operator token." The reasons are that it has expired, is not valid yet (check
this machine's clock), comes from a different sign-in service or was made for
a different application than the daemon expects, has a signature that does
not check out, is signed in a way the daemon does not accept, is not a valid
sign-in token, or that the daemon cannot reach the sign-in service's keys.

Pasting an operator token behind the proxy works as without it, and the
sidebar then reads the token's label.

## Staying signed in

The console keeps the token in this browser tab only.
The console keeps a token in this browser tab only. A person signed in
through a proxy is not kept by the console at all: every page load asks the
daemon again.

- **Reload** the page and you stay signed in.
- **Open a new tab** and it asks for a token again.
- **Close the tab** and you are signed out.
- **Sign out** forgets the token at once.
- **Sign out** forgets the token at once. Behind a sign-in proxy, a token's
Sign out brings back the proxy's sign-in; a person the proxy signed in goes
to the proxy's sign-out page (`signOutUrl`), and with none set there is no
Sign out button.
- If the proxy's own session ends, the page reloads so the proxy can show its
login page. If that happens again within a minute, the console says **Your
sign-in has ended.** with a **Sign in again** button instead of reloading.
- If the proxy's identity is refused while you are signed in through it, the
console shows the token form with the reason.
- If the token is **revoked**, the console signs you out the next time it asks
the daemon for anything, and at the latest when you reload.
the daemon for anything, and at the latest when you reload. Behind a
sign-in proxy it then signs you in as the proxy's person, if there is one.

Some browsers copy a tab's storage into a duplicated or reopened tab, so such a
tab may still be signed in.
Expand Down Expand Up @@ -462,7 +536,9 @@ it):
| Daemon is starting | The daemon is back, and is still starting up. |

While reconnecting, the console keeps the last data on screen and tries the
daemon again after 1, 2, 4 and 8 seconds, then every 10 seconds. When the
daemon again after 1, 2, 4 and 8 seconds, then every 10 seconds. Behind a
sign-in proxy it first checks that your proxy session is still valid, and
reconnects at once if it is. When the
daemon answers, the console refreshes the page and it goes back to
Connected. You do not need to reload.

Expand Down
3 changes: 2 additions & 1 deletion docs/internal/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,8 @@ put together from them and draws nothing of its own that one of them already dra
- **Sidebar.** The console's navigation, on the left of every signed-in page: the "SIMLOCK"
wordmark (`--on-accent` on an `--accent` block), one link per page in a fixed order (Overview,
Workers, Leases, Waiting, Attention, Events, Usage), then at the bottom the connection as a status,
**Sign out** and the collapse button. A link is an icon and its label in `--text-muted`; the
"Signed in as <name>" (hidden when collapsed, where the Sign out tooltip reads "Sign out (<name>)"),
**Sign out** (absent for a proxy person with no sign-out address) and the collapse button. A link is an icon and its label in `--text-muted`; the
current one is `--text` on `--field` with a 2px `--accent` bar on its left and
`aria-current="page"`. Attention carries its count in a small bordered box, and none at zero.
Collapsed, the sidebar is 64px wide: the labels go, every icon sits on its centre line, each
Expand Down
167 changes: 164 additions & 3 deletions e2e/console/fixtures.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { existsSync } from "node:fs";
import {
createServer,
type IncomingMessage,
request as httpRequest,
type Server,
type ServerResponse,
} from "node:http";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { test as base, expect, type Page } from "@playwright/test";
import { exportJWK, generateKeyPair, SignJWT } from "jose";
import { type RawData, WebSocket } from "ws";

import type { FakeDriverScript } from "../fake-driver/types.js";
Expand Down Expand Up @@ -76,13 +84,14 @@ export async function startDaemon(
const home = await mkdtemp(join(tmpdir(), "simlock-console-"));
const port = await freeLoopbackPort();
const scriptPath = join(home, "fake-driver-script.json");
const { http: extraHttp, ...extraConfig } = options.config ?? {};
await writeFile(
join(home, "config.json"),
JSON.stringify({
...(mode === "worker" ? FAKE_CAPACITY : {}),
http: { enabled: true, host: "127.0.0.1", port },
http: { enabled: true, host: "127.0.0.1", port, ...(extraHttp as object | undefined) },
mode,
...options.config,
...extraConfig,
}),
);
if (options.driverScript !== undefined) {
Expand Down Expand Up @@ -288,11 +297,163 @@ function rawText(data: RawData): string {
return Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.from(data).toString("utf8");
}

const PROXY_ISSUER = "https://proxy.example.test";
const PROXY_AUDIENCE = "simlock-console";
const PROXY_HEADER = "cf-access-jwt-assertion";

export type ProxyMode = "signed-in" | "expired" | "redirect" | "html";

export interface ProxiedDaemon {
readonly url: string;
readonly loginUrl: string;
readonly signedOutUrl: string;
readonly daemon: RunningDaemon;
setMode(mode: ProxyMode): void;
holdIdentity(): () => void;
reset(): void;
dispose(): Promise<void>;
}

export async function startProxiedDaemon(
options: { readonly signOutUrl?: boolean } = {},
): Promise<ProxiedDaemon> {
const { privateKey, publicKey } = await generateKeyPair("ES256");
const jwk = { ...(await exportJWK(publicKey)), alg: "ES256", kid: "test-key", use: "sig" };
const sign = (expiresAt: number) =>
new SignJWT({ email: "alice@example.test", name: "Alice" })
.setProtectedHeader({ alg: "ES256", kid: "test-key" })
.setIssuer(PROXY_ISSUER)
.setAudience(PROXY_AUDIENCE)
.setSubject("u1")
.setIssuedAt()
.setExpirationTime(expiresAt)
.sign(privateKey);
let mode: ProxyMode = "signed-in";
let held: Promise<void> | undefined;
let daemonPort = 0;
const listen = (server: Server, port: number) =>
new Promise<void>((resolve) => server.listen(port, "127.0.0.1", resolve));
const close = (server: Server) =>
new Promise<void>((resolve) => {
server.closeAllConnections();
server.close(() => resolve());
});

const idpPort = await freeLoopbackPort();
const idp = createServer((req, res) => {
const signedOut = req.url === "/signed-out";
res.setHeader("content-type", "text/html");
res.end(`<h1>${signedOut ? "Signed out of the proxy" : "Proxy login"}</h1>`);
});
await listen(idp, idpPort);
const loginUrl = `http://127.0.0.1:${idpPort}/login`;
const signedOutUrl = `http://127.0.0.1:${idpPort}/signed-out`;

const forward = async (req: IncomingMessage, res: ServerResponse) => {
const exp = Math.floor(Date.now() / 1000) + (mode === "expired" ? -600 : 3600);
const headers = {
...req.headers,
[PROXY_HEADER]: await sign(exp),
host: `127.0.0.1:${daemonPort}`,
};
if (req.url === "/v1/identity" && held !== undefined) await held;
const upstream = httpRequest(
{ headers, host: "127.0.0.1", method: req.method, path: req.url, port: daemonPort },
(answer) => {
res.writeHead(answer.statusCode ?? 502, answer.headers);
answer.pipe(res);
},
);
upstream.on("error", () => res.destroy());
res.on("close", () => upstream.destroy());
req.pipe(upstream);
};
const proxy = createServer((req, res) => {
if (req.url === "/.test/jwks") {
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ keys: [jwk] }));
return;
}
if (req.url !== "/v1/healthz" && mode === "redirect") {
res.writeHead(302, { location: loginUrl });
res.end();
return;
}
if (req.url !== "/v1/healthz" && mode === "html") {
res.writeHead(403, { "content-type": "text/html" });
res.end("<h1>Proxy sign-in</h1>");
return;
}
void forward(req, res);
});
const proxyPort = await freeLoopbackPort();
await listen(proxy, proxyPort);
let daemon: RunningDaemon;
try {
daemon = await startDaemon("worker", {
config: {
http: {
proxyAuth: {
audience: PROXY_AUDIENCE,
header: PROXY_HEADER,
issuer: PROXY_ISSUER,
jwksUrl: `http://127.0.0.1:${proxyPort}/.test/jwks`,
...(options.signOutUrl === false ? {} : { signOutUrl: signedOutUrl }),
},
},
},
});
} catch (error: unknown) {
await Promise.all([close(proxy), close(idp)]);
throw error;
}
daemonPort = daemon.port;
return {
daemon,
dispose: async () => {
await Promise.all([close(proxy), close(idp)]);
await daemon.dispose();
},
holdIdentity() {
let release: () => void = () => {};
held = new Promise<void>((resolve) => (release = resolve));
return () => {
held = undefined;
release();
};
},
loginUrl,
reset() {
mode = "signed-in";
held = undefined;
},
setMode: (next) => void (mode = next),
signedOutUrl,
url: `http://127.0.0.1:${proxyPort}/`,
};
}

/**
* `daemon` is a single host, shared by every test in a Playwright worker, and the base URL every
* `page.goto` resolves against. `gateway` starts only for a test that asks for it.
*/
export const test = base.extend<object, { daemon: RunningDaemon; gateway: RunningDaemon }>({
export const test = base.extend<
{ proxied: ProxiedDaemon },
{ daemon: RunningDaemon; gateway: RunningDaemon; proxiedDaemon: ProxiedDaemon }
>({
proxiedDaemon: [
// oxlint-disable-next-line no-empty-pattern -- as below.
async ({}, use) => {
const proxied = await startProxiedDaemon();
await use(proxied);
await proxied.dispose();
},
{ scope: "worker", timeout: 60_000 },
],
proxied: async ({ proxiedDaemon }, use) => {
proxiedDaemon.reset();
await use(proxiedDaemon);
},
daemon: [
// oxlint-disable-next-line no-empty-pattern -- Playwright requires a destructuring pattern here, even an empty one.
async ({}, use) => {
Expand Down
Loading
Loading