diff --git a/e2e/console/sign-in.spec.ts b/e2e/console/sign-in.spec.ts index ed8311850..0c8e978ab 100644 --- a/e2e/console/sign-in.spec.ts +++ b/e2e/console/sign-in.spec.ts @@ -1,8 +1,49 @@ -import { expect, NAV_LABELS, openFromNav, signIn, startProxiedDaemon, test } from "./fixtures.js"; +import { + expect, + NAV_LABELS, + openFromNav, + signIn, + startDaemon, + startProxiedDaemon, + test, +} from "./fixtures.js"; const OPERATOR_NEEDED = "That token is real, but the console needs an operator token."; test.describe("sign-in", () => { + test("the configured SSO link opens the proxy login in the same tab", async ({ + page, + }, testInfo) => { + const signInUrl = "https://login.example.test/start"; + const gateway = await startDaemon("gateway", { + config: { + http: { + proxyAuth: { + header: "x-proxy-jwt", + jwksUrl: "https://login.example.test/keys", + issuer: "https://login.example.test", + audience: "fleet-console", + signInUrl, + }, + }, + }, + }); + try { + await page.route(signInUrl, (route) => + route.fulfill({ contentType: "text/html", body: "

Proxy sign in

" }), + ); + await page.goto(gateway.url); + await expect(page.getByRole("link", { name: "Sign in with SSO" })).toBeVisible(); + await expect(page.getByLabel("Operator token")).toBeVisible(); + await page.screenshot({ path: testInfo.outputPath("sso-sign-in.png"), fullPage: true }); + await page.getByRole("link", { name: "Sign in with SSO" }).click(); + await expect(page).toHaveURL(signInUrl); + await expect(page.getByRole("heading", { name: "Proxy sign in" })).toBeVisible(); + } finally { + await gateway.dispose(); + } + }); + test("an operator token signs in with its label, a reload keeps it, a new tab asks for a token, signing out is final, and the page asks no host but the daemon", async ({ context, daemon, diff --git a/src/auth/index.ts b/src/auth/index.ts index 3e74eee7f..6f69677df 100644 --- a/src/auth/index.ts +++ b/src/auth/index.ts @@ -91,11 +91,22 @@ export function createAuthFrom( for (const strategy of strategies) { const answer = await strategy.authenticate({ headers }); if (answer.kind === "identified") return answer.identity; - if (answer.kind === "rejected") throw new AuthError(401, answer.message, answer.details); + if (answer.kind === "rejected") + throw new AuthError( + 401, + answer.message, + answer.details, + options.config.proxyAuth?.signInUrl, + ); if (answer.kind === "forbidden") throw new AuthError(403, answer.message); sawCredential ||= answer.sawCredential; } - throw new AuthError(401, sawCredential ? "Unknown bearer token" : "Missing bearer token"); + throw new AuthError( + 401, + sawCredential ? "Unknown bearer token" : "Missing bearer token", + undefined, + options.config.proxyAuth?.signInUrl, + ); }, resolveHelloRole: async (hello) => { if (hello.credential === undefined) return "agent"; diff --git a/src/auth/strategies/proxy-jwt/index.ts b/src/auth/strategies/proxy-jwt/index.ts index efaf7bbec..f7a5632e9 100644 --- a/src/auth/strategies/proxy-jwt/index.ts +++ b/src/auth/strategies/proxy-jwt/index.ts @@ -70,6 +70,11 @@ const proxyAuthSchema = z.object({ .string({ error: "an http:// or https:// URL" }) .refine(isWebUrl, "an http:// or https:// URL") .optional(), + signInUrl: z + .string({ error: "an http:// or https:// URL" }) + .max(2048, "an http:// or https:// URL of at most 2048 characters") + .refine(isWebUrl, "an http:// or https:// URL") + .optional(), }); function credentialIn(headers: Headers, header: string): string | undefined { diff --git a/src/auth/strategy.ts b/src/auth/strategy.ts index e22b695cb..e3b30ec73 100644 --- a/src/auth/strategy.ts +++ b/src/auth/strategy.ts @@ -45,6 +45,7 @@ export class AuthError extends Error { readonly status: 401 | 403, message: string, readonly details?: unknown, + readonly signInUrl?: string, ) { super(message); this.name = "AuthError"; diff --git a/src/contract/config-schemas.ts b/src/contract/config-schemas.ts index b97c08923..663d7bfa9 100644 --- a/src/contract/config-schemas.ts +++ b/src/contract/config-schemas.ts @@ -50,6 +50,7 @@ const proxyAuthSchema = z.object({ issuer: z.string(), audience: z.string(), signOutUrl: z.string().optional(), + signInUrl: z.string().max(2048).optional(), }); const memoryPressureRuleSchema = z.object({ diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 122f75e9e..c55b0857a 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 89, max: 91 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 89, max: 92 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/core/config-auth-and-proxy.test.ts b/src/core/config-auth-and-proxy.test.ts index a0395154b..cac71a551 100644 --- a/src/core/config-auth-and-proxy.test.ts +++ b/src/core/config-auth-and-proxy.test.ts @@ -128,6 +128,24 @@ describe("loadConfig over http.proxyAuth", () => { ); }); + it("accepts a proxy sign-in URL and refuses non-web URLs", async () => { + const signInUrl = "https://login.example.test/start"; + expect(proxyAuthOf(await load({ ...complete, signInUrl }))).toEqual({ ...complete, signInUrl }); + const longest = "https://login.example.test/".padEnd(2048, "a"); + expect(proxyAuthOf(await load({ ...complete, signInUrl: longest }))).toEqual({ + ...complete, + signInUrl: longest, + }); + await expect(load({ ...complete, signInUrl: longest + "a" })).rejects.toThrow( + 'Invalid config value for "http.proxyAuth.signInUrl": expected an http:// or https:// URL of at most 2048 characters', + ); + for (const signInUrl of ["javascript:alert(1)", "//login.example.test/start", "not a url"]) { + await expect(load({ ...complete, signInUrl })).rejects.toThrow( + 'Invalid config value for "http.proxyAuth.signInUrl"', + ); + } + }); + it("refuses a sign-out URL that is not an http or https URL", async () => { for (const signOutUrl of ["not a url", "ftp://team.dev/out"]) { await expect(load({ ...complete, signOutUrl }), signOutUrl).rejects.toThrow( diff --git a/src/core/config-types.ts b/src/core/config-types.ts index f650fd4a1..d4590cfdc 100644 --- a/src/core/config-types.ts +++ b/src/core/config-types.ts @@ -153,6 +153,7 @@ export interface Config { readonly issuer: string; readonly audience: string; readonly signOutUrl?: string; + readonly signInUrl?: string; }; }; readonly health: { diff --git a/src/http/app-proxy-auth.test.ts b/src/http/app-proxy-auth.test.ts index 7d2c53741..5bba4f4b8 100644 --- a/src/http/app-proxy-auth.test.ts +++ b/src/http/app-proxy-auth.test.ts @@ -83,13 +83,16 @@ describe("a person the sign-in proxy signed in", () => { }); }); - it("answers a refused JWT with 401 UNAUTHENTICATED, the refusal's message and its reason in the body", async () => { + it("advertises the configured proxy sign-in URL on missing credentials and refused JWTs, preserving the refusal reason", async () => { const key = await createTestKey("ES256", "k1"); const keySetFetcher = new FakeKeySetFetcher(); keySetFetcher.answer({ status: 200, body: keySetBody(key) }); const clock = new FakeClock(PROXY_NOW); const auth = createAuth({ - config: authConfigWith(), + config: { + ...authConfigWith(), + proxyAuth: { ...proxyAuthConfig, signInUrl: "https://login.example.test/start" }, + }, dataDirectory: "/home/agent/.simlock", database: (await openMemoryStateDatabase([tokensOwner])).database, filesystem: new MemoryFilesystem(), @@ -107,6 +110,12 @@ describe("a person the sign-in proxy signed in", () => { }); expect(good.status).toBe(200); + const missing = await app.request("/v1/identity"); + expect(missing.status).toBe(401); + expect(await missing.json()).toMatchObject({ + error: { signInUrl: "https://login.example.test/start" }, + }); + const expired = await key.sign(personClaims({ exp: Math.floor(PROXY_NOW / 1000) - 120 })); const response = await app.request("/v1/identity", { headers: { [header]: expired } }); @@ -116,6 +125,7 @@ describe("a person the sign-in proxy signed in", () => { code: "UNAUTHENTICATED", message: "Sign-in proxy identity refused: expired", reason: "expired", + signInUrl: "https://login.example.test/start", }, }); }); diff --git a/src/http/auth.ts b/src/http/auth.ts index 25e87f56c..80e226a51 100644 --- a/src/http/auth.ts +++ b/src/http/auth.ts @@ -19,9 +19,14 @@ export function requireAuth(auth: Pick): Middleware error.status, error.status === 401 ? "UNAUTHENTICATED" : "FORBIDDEN", error.message, - error.details === undefined + error.details === undefined && error.signInUrl === undefined ? undefined - : { details: error.details, ...reasonOf(error.details) }, + : { + ...(error.details === undefined + ? {} + : { details: error.details, ...reasonOf(error.details) }), + ...(error.signInUrl === undefined ? {} : { signInUrl: error.signInUrl }), + }, ); } refuseCrossSiteChange(c); diff --git a/ui/src/app/sign-in.dom.test.tsx b/ui/src/app/sign-in.dom.test.tsx index 198769604..0f4cf2f29 100644 --- a/ui/src/app/sign-in.dom.test.tsx +++ b/ui/src/app/sign-in.dom.test.tsx @@ -55,6 +55,32 @@ function consoleNav(): HTMLElement { } describe("signing in with a token", () => { + it("offers the proxy sign-in link beside the operator token form when configured", async () => { + renderConsole({ + routes: { + ...DAEMON, + "/v1/identity": { + status: 401, + body: { + error: { + code: "UNAUTHENTICATED", + message: "Sign in", + signInUrl: "https://login.example.test/start", + }, + }, + }, + }, + token: null, + }); + + await screen.findByLabelText("Operator token"); + expect(screen.getByRole("link", { name: "Sign in with SSO" })).toHaveAttribute( + "href", + "https://login.example.test/start", + ); + expect(screen.getByRole("link", { name: "Sign in with SSO" })).not.toHaveAttribute("target"); + }); + it("an operator token signs in and shows the shell", async () => { const view = renderConsole({ routes: DAEMON, token: null }); diff --git a/ui/src/data/identity-check.test.ts b/ui/src/data/identity-check.test.ts index 44af48ef7..b6b8245fe 100644 --- a/ui/src/data/identity-check.test.ts +++ b/ui/src/data/identity-check.test.ts @@ -47,6 +47,20 @@ describe("checkIdentity", () => { { kind: "none" }, ], [json(401, simlock("UNAUTHENTICATED")), { kind: "none" }], + ...["javascript:alert(1)", "//login.example.test/start", "not a url", 42].map( + (signInUrl) => + [json(401, { error: { code: "UNAUTHENTICATED", signInUrl } }), { kind: "none" }] as const, + ), + [ + json(401, { + error: { + code: "UNAUTHENTICATED", + reason: "expired", + signInUrl: "https://login.example.test/start", + }, + }), + { kind: "refused", reason: "expired", signInUrl: "https://login.example.test/start" }, + ], [json(403, simlock("FORBIDDEN")), { kind: "none" }], [json(503, simlock("UNAVAILABLE")), { kind: "none" }], ]; diff --git a/ui/src/data/identity-check.ts b/ui/src/data/identity-check.ts index cd78dc891..8ab2956d6 100644 --- a/ui/src/data/identity-check.ts +++ b/ui/src/data/identity-check.ts @@ -2,8 +2,8 @@ import { type Fetch, hasSimlockErrorCode, RequestTimeoutError, send } from "./ap export type IdentityOutcome = | { readonly kind: "proxy"; readonly name: string; readonly signOutUrl?: string } - | { readonly kind: "refused"; readonly reason: string } - | { readonly kind: "none" } + | { readonly kind: "refused"; readonly reason: string; readonly signInUrl?: string } + | { readonly kind: "none"; readonly signInUrl?: string } | { readonly kind: "ended" } | { readonly kind: "unreachable" }; @@ -35,13 +35,29 @@ export async function checkIdentity(fetch: Fetch, afterLoss = false): Promise= 500) return unanswered; if (status === 200) return proxyIdentity(body) ?? { kind: "none" }; - if (status === 401) { - const reason = (body as { error?: { reason?: unknown } }).error?.reason; - if (typeof reason === "string") return { kind: "refused", reason }; - } + if (status === 401) return signInRefusal(body); return { kind: "none" }; } +function signInRefusal(body: unknown): IdentityOutcome { + const { reason, signInUrl } = + (body as { error?: { reason?: unknown; signInUrl?: unknown } }).error ?? {}; + const loginUrl = webSignInUrl(signInUrl); + const login = loginUrl === undefined ? {} : { signInUrl: loginUrl }; + if (typeof reason === "string") return { kind: "refused", reason, ...login }; + return { kind: "none", ...login }; +} + +function webSignInUrl(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + try { + const { protocol } = new URL(value); + return protocol === "https:" || protocol === "http:" ? value : undefined; + } catch { + return undefined; + } +} + async function readJson(response: Response): Promise { try { return await response.json(); diff --git a/ui/src/data/session.ts b/ui/src/data/session.ts index 1ea5f3591..35dc4922b 100644 --- a/ui/src/data/session.ts +++ b/ui/src/data/session.ts @@ -7,7 +7,7 @@ const STORAGE_KEY = "simlock.operatorToken"; type Storage = Pick; export type SessionState = - | { readonly kind: "none"; readonly refusedReason?: string } + | { readonly kind: "none"; readonly refusedReason?: string; readonly signInUrl?: string } | { readonly kind: "checking" } | { readonly kind: "token"; readonly token: string } | { readonly kind: "proxy"; readonly name: string; readonly signOutUrl?: string } @@ -67,13 +67,17 @@ export function createSession(storage: () => Storage, deps?: SessionDeps): Sessi case "proxy": return set(proxyState(outcome)); case "refused": - return set({ kind: "none", refusedReason: outcome.reason }); + return set({ + kind: "none", + refusedReason: outcome.reason, + ...(outcome.signInUrl === undefined ? {} : { signInUrl: outcome.signInUrl }), + }); case "ended": return atLoad ? set({ kind: "none" }) : ended(); case "unreachable": return atLoad ? set({ kind: "none" }) : undefined; case "none": - return set({ kind: "none" }); + return set(outcome); } }; const opening = async (atLoad: boolean) => { diff --git a/ui/src/screens/sign-in.test.tsx b/ui/src/screens/sign-in.test.tsx index 7319b9306..e64769885 100644 --- a/ui/src/screens/sign-in.test.tsx +++ b/ui/src/screens/sign-in.test.tsx @@ -35,5 +35,6 @@ describe("the sign-in screen", () => { expect(html).toContain("simlock token create --role operator"); expect(html).toMatch(/]*type="submit"[^>]*>Sign in<\/button>/); expect(html).not.toContain('role="alert"'); + expect(html).not.toContain("Sign in with SSO"); }); }); diff --git a/ui/src/screens/sign-in.tsx b/ui/src/screens/sign-in.tsx index 864d99be6..5e9c874c1 100644 --- a/ui/src/screens/sign-in.tsx +++ b/ui/src/screens/sign-in.tsx @@ -7,7 +7,7 @@ import { useReloadPage, useSignIn } from "../state/sign-in"; export function SignInScreen() { const [token, setToken] = useState(""); - const { checking, refusal, submit } = useSignIn(); + const { checking, refusal, submit, signInUrl } = useSignIn(); const onSubmit = (event: FormEvent) => { event.preventDefault(); void submit(token.trim()); @@ -17,6 +17,13 @@ export function SignInScreen() { return ( + {signInUrl === undefined ? null : ( +

+ + Sign in with SSO + +

+ )}
void { diff --git a/website/src/content/docs/docs/gateway/access-control.mdx b/website/src/content/docs/docs/gateway/access-control.mdx index d87fcc290..d7a1f1335 100644 --- a/website/src/content/docs/docs/gateway/access-control.mdx +++ b/website/src/content/docs/docs/gateway/access-control.mdx @@ -114,6 +114,13 @@ Then restart the gateway. | `issuer` | The `iss` the JWT must carry. | | `audience` | The `aud` the JWT must carry. For Cloudflare Access, the application's audience tag. | | `signOutUrl` | Optional. Where the console's **Sign out** sends a person signed in through the proxy. Without it, such a person sees no **Sign out**. | +| `signInUrl` | Optional absolute HTTP or HTTPS URL, at most 2048 characters, for your proxy's login entry point. The console shows **Sign in with SSO** alongside its operator-token form. The link opens in the same tab. | + +Set `signInUrl` when the proxy lets the unsigned console page and `/v1/identity` reach Simlock, and starts login only when a person chooses it. For example, use `https://fleet.example.com/oauth2/start?rd=/` with a proxy that supports that login route. Configure the proxy to return the person to the console after login and to attach its signed JWT on subsequent API requests. Simlock does not run an OAuth flow itself. Proxies that already redirect every unsigned page to login need no sign-in link. + +The link grants no permissions. Limit who can sign in using your identity provider's application assignments or your proxy's access policy. Every accepted proxy identity still becomes an operator. + +When configured, `signInUrl` is also included as `error.signInUrl` in HTTP `401 UNAUTHENTICATED` responses, including those for missing or unknown bearer tokens. HTTP clients may use it to offer interactive login. It is public login metadata, not a credential; headless clients should continue using their Simlock tokens. Your proxy must also: diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index ad79a6fba..74d6ad3ab 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -242,6 +242,7 @@ to make devices from. | `http.proxyAuth.issuer` | string, 1–128 characters | — | The `iss` the token must carry. | Both | | `http.proxyAuth.audience` | string, 1–512 characters | — | The `aud` the token must carry. | Both | | `http.proxyAuth.signOutUrl` | `http://` or `https://` URL | not set | Where the console sends a person to sign out. | Both | +| `http.proxyAuth.signInUrl` | `http://` or `https://` URL, at most 2048 characters | not set | Proxy login entry point. Adds a **Sign in with SSO** link beside the operator-token form. | Both | ```sh simlock --gateway config set http.proxyAuth '{"header":"cf-access-jwt-assertion","jwksUrl":"https://acme.cloudflareaccess.com/cdn-cgi/access/certs","issuer":"https://acme.cloudflareaccess.com","audience":"4f1c9a7e2b"}' diff --git a/website/src/content/docs/docs/worker/console.mdx b/website/src/content/docs/docs/worker/console.mdx index 35fef49cc..e08beb369 100644 --- a/website/src/content/docs/docs/worker/console.mdx +++ b/website/src/content/docs/docs/worker/console.mdx @@ -44,6 +44,8 @@ Every page has its own address, such as `/leases`, so you can bookmark a page, r ## Sign in with an operator token +If your operator configured a sign-in proxy with a login URL, choose **Sign in with SSO** to sign in through that proxy in the same tab. The operator-token form remains available. See [Access control](/simlock/docs/gateway/access-control#sign-in-to-the-console-through-a-sign-in-proxy). + The console asks for an operator token. Make one on the worker: ```sh