Skip to content
Draft
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
43 changes: 42 additions & 1 deletion e2e/console/sign-in.spec.ts
Original file line number Diff line number Diff line change
@@ -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: "<h1>Proxy sign in</h1>" }),
);
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,
Expand Down
15 changes: 13 additions & 2 deletions src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
5 changes: 5 additions & 0 deletions src/auth/strategies/proxy-jwt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions src/auth/strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions src/contract/config-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
18 changes: 18 additions & 0 deletions src/core/config-auth-and-proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
1 change: 1 addition & 0 deletions src/core/config-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export interface Config {
readonly issuer: string;
readonly audience: string;
readonly signOutUrl?: string;
readonly signInUrl?: string;
};
};
readonly health: {
Expand Down
14 changes: 12 additions & 2 deletions src/http/app-proxy-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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 } });

Expand All @@ -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",
},
});
});
Expand Down
9 changes: 7 additions & 2 deletions src/http/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,14 @@ export function requireAuth(auth: Pick<Auth, "authenticateRequest">): 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);
Expand Down
26 changes: 26 additions & 0 deletions ui/src/app/sign-in.dom.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down
14 changes: 14 additions & 0 deletions ui/src/data/identity-check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" }],
];
Expand Down
28 changes: 22 additions & 6 deletions ui/src/data/identity-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" };

Expand Down Expand Up @@ -35,13 +35,29 @@ export async function checkIdentity(fetch: Fetch, afterLoss = false): Promise<Id
if ((status === 401 || status === 403) && !hasSimlockErrorCode(body)) return askHealthz(fetch);
if (status >= 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<unknown> {
try {
return await response.json();
Expand Down
10 changes: 7 additions & 3 deletions ui/src/data/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const STORAGE_KEY = "simlock.operatorToken";
type Storage = Pick<globalThis.Storage, "getItem" | "removeItem" | "setItem">;

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 }
Expand Down Expand Up @@ -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) => {
Expand Down
1 change: 1 addition & 0 deletions ui/src/screens/sign-in.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,6 @@ describe("the sign-in screen", () => {
expect(html).toContain("simlock token create --role operator");
expect(html).toMatch(/<button[^>]*type="submit"[^>]*>Sign in<\/button>/);
expect(html).not.toContain('role="alert"');
expect(html).not.toContain("Sign in with SSO");
});
});
9 changes: 8 additions & 1 deletion ui/src/screens/sign-in.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLFormElement>) => {
event.preventDefault();
void submit(token.trim());
Expand All @@ -17,6 +17,13 @@ export function SignInScreen() {
return (
<SignInFrame>
<Panel title="Sign in" level={1}>
{signInUrl === undefined ? null : (
<p>
<a className="button" href={signInUrl}>
Sign in with SSO
</a>
</p>
)}
<form className="sign-in-form" onSubmit={onSubmit} noValidate>
<label htmlFor="token">Operator token</label>
<input
Expand Down
7 changes: 6 additions & 1 deletion ui/src/state/sign-in.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ export function useSignIn() {
state.kind === "none" && state.refusedReason !== undefined
? proxyRefusalLine(state.refusedReason)
: undefined;
return { checking, refusal: refusal ?? proxyRefusal, submit };
return {
checking,
refusal: refusal ?? proxyRefusal,
submit,
signInUrl: state.kind === "none" ? state.signInUrl : undefined,
};
}

export function useReloadPage(): () => void {
Expand Down
7 changes: 7 additions & 0 deletions website/src/content/docs/docs/gateway/access-control.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
1 change: 1 addition & 0 deletions website/src/content/docs/docs/reference/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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"}'
Expand Down
Loading