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
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ PANEL_AUTH_DISABLED=false
# non-browser client or another origin (a script); it turns that protection off.
PANEL_CSRF_DISABLED=false

# Failed panel sign-ins lock out the address they came from for 15 minutes. Behind
# a reverse proxy every request comes from the proxy, so one person's wrong
# guesses lock everyone out. Set to true ONLY when a proxy you run is the sole way
# in and appends the caller to X-Forwarded-For; the bridge then counts by the last
# entry. Anyone who can reach the bridge directly could otherwise pick that value.
PANEL_TRUST_PROXY=false

# Optional. When set, each directory's native + WorkOS bearer tokens are
# encrypted at rest (AES-256-GCM). Keep it stable — rotating or removing it
# leaves existing encrypted tokens unreadable. Leave blank to store plaintext.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ imported through the control panel.
| `DATABASE_PATH` | no | `/data/scim-bridge.db` | SQLite file path. Mount a volume here to persist. The default is a path *inside the image*; running outside a container, set it to somewhere that exists. |
| `PANEL_AUTH_USER` / `PANEL_AUTH_PASSWORD` | **yes** | — | HTTP Basic credentials guarding the control panel. The bridge refuses to start without them. |
| `PANEL_AUTH_DISABLED` | no | `false` | Set to `true` to run `/panel` unauthenticated on purpose, when something in front of the bridge already authenticates it. |
| `PANEL_TRUST_PROXY` | no | `false` | Set to `true` when the bridge is reachable only through your reverse proxy, which appends the caller to `X-Forwarded-For`. Failed panel sign-ins are then locked out per caller instead of per proxy. The Cloudflare adapter sets it. |
| `APP_ENCRYPTION_KEY` | no | — | When set, encrypts each directory's native + WorkOS bearer tokens at rest (AES-256-GCM). Keep it stable; leave unset to store them in plaintext. |
| `DEMO_MODE` | no | `false` | Mount the bundled IdP + native-app simulators under `/__demo` for a self-contained end-to-end demo. |

Expand Down
8 changes: 7 additions & 1 deletion deploy/cloudflare/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export class BridgeContainer extends Container<Env> {
WEBHOOK_SECRET: env.WEBHOOK_SECRET,
DIRECTORIES_JSON: env.DIRECTORIES_JSON,
BRIDGE_STATUS_URL: env.BRIDGE_STATUS_URL,
PANEL_TRUST_PROXY: "true",
});
}
}
Expand All @@ -98,6 +99,11 @@ export default {
// One instance, always the same one. SQLite has a single writer, and every
// request has to see the same database — including the panel, which reads what
// the SCIM data plane just wrote.
return getContainer(env.BRIDGE, "singleton").fetch(request);
//
// The container sees every request arrive from this Worker, so name the caller
// for its sign-in throttle. Overwritten, never appended, so a caller cannot pick it.
const forwarded = new Request(request);
forwarded.headers.set("X-Forwarded-For", request.headers.get("CF-Connecting-IP") ?? "");
return getContainer(env.BRIDGE, "singleton").fetch(forwarded);
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
},
};
3 changes: 3 additions & 0 deletions server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ export interface AppConfig {
* mutations — for scripting the panel from another origin. Off by default,
* and mirrors `panelAuthDisabled`: consent, logged loudly at boot. */
panelCsrfDisabled: boolean;
/** Count failed panel sign-ins by the last X-Forwarded-For entry, not the peer. */
panelTrustProxy: boolean;
/** `native-app` role: bearer token the bridge presents to this app's /scim/v2. */
nativeScimToken: string | null;
/** `native-app` role: HMAC secret of the WorkOS webhook endpoint feeding /webhooks/dsync. */
Expand Down Expand Up @@ -265,6 +267,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
panelAuthPassword,
panelAuthDisabled,
panelCsrfDisabled,
panelTrustProxy: bool(env.PANEL_TRUST_PROXY),
nativeScimToken: env.NATIVE_SCIM_TOKEN?.trim() || null,
webhookSecret,
bridgeStatusUrl: bridgeStatusUrl ? trimTrailingSlash(bridgeStatusUrl) : null,
Expand Down
15 changes: 11 additions & 4 deletions server/panel-boundary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,15 @@ export class PanelAuthThrottle {
}
}

/** The connecting peer. Forwarded-for headers are caller-controlled, so not them. */
function peerAddress(c: Context): string {
/**
* Who is guessing. Normally the connecting peer, since forwarded-for headers are
* caller-controlled. With PANEL_TRUST_PROXY the peer is a reverse proxy shared by
* everyone, so use the last X-Forwarded-For entry instead: the address that proxy
* appended itself, after anything the caller sent.
*/
function sourceAddress(c: Context, trustProxy: boolean): string {
const forwarded = trustProxy ? c.req.header("X-Forwarded-For")?.split(",").at(-1)?.trim() : null;
if (forwarded) return forwarded;
try {
return getConnInfo(c).remote.address ?? "unknown";
} catch {
Expand All @@ -86,9 +93,9 @@ function peerAddress(c: Context): string {
* only a wrong pair counts against the source.
*/
export function panelAuthGuard(
config: Pick<AppConfig, "panelAuthUser" | "panelAuthPassword" | "demoMode">,
config: Pick<AppConfig, "panelAuthUser" | "panelAuthPassword" | "demoMode" | "panelTrustProxy">,
throttle: PanelAuthThrottle = new PanelAuthThrottle(),
sourceOf: (c: Context) => string = peerAddress,
sourceOf: (c: Context) => string = (c) => sourceAddress(c, config.panelTrustProxy),
): MiddlewareHandler {
return async (c, next) => {
if (panelAuthExempt(new URL(c.req.url).pathname, config)) return next();
Expand Down
19 changes: 16 additions & 3 deletions tests/cloudflare-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { readFileSync } from "node:fs";
import { stripTypeScriptTypes } from "node:module";
import { describe, expect, it } from "vitest";

/** Execute the real constructor without starting a Cloudflare container. The
* deployment-only SDK is replaced at its import boundary, not the env builder. */
/** Execute the real adapter without starting a Cloudflare container. The
* deployment-only SDK is replaced at its import boundary; its container echoes
* back the request the Worker forwards. */
const sdkUrl = `data:text/javascript,${encodeURIComponent(
'export class Container {}\nexport function getContainer() { throw new Error("Container routing is outside this test"); }',
"export class Container {}\nexport function getContainer() { return { fetch: (request) => request }; }",
)}`;
const source = readFileSync(new URL("../deploy/cloudflare/src/bridge.ts", import.meta.url), "utf8");
const adapterUrl = `data:text/javascript,${encodeURIComponent(
Expand All @@ -17,6 +18,7 @@ const adapter = (await import(/* @vite-ignore */ adapterUrl)) as {
ctx: object,
env: Record<string, string | object | undefined>,
) => { envVars: Record<string, string> };
default: { fetch(request: Request, env: object): Request };
};

function container(vars: Record<string, string | undefined> = {}) {
Expand Down Expand Up @@ -48,3 +50,14 @@ describe("Cloudflare Worker container environment", () => {
expect(instance.envVars.PUBLIC_URL).toBe("https://bridge.example.test");
});
});

describe("Cloudflare Worker request forwarding", () => {
it("names the caller to the panel's sign-in throttle, replacing any forged address", () => {
expect(container().envVars.PANEL_TRUST_PROXY).toBe("true");
const request = new Request("https://bridge.example.test/panel", {
headers: { "CF-Connecting-IP": "198.51.100.7", "X-Forwarded-For": "10.0.0.1" },
});
const forwarded = adapter.default.fetch(request, { BRIDGE: {} });
expect(forwarded.headers.get("X-Forwarded-For")).toBe("198.51.100.7");
});
});
45 changes: 44 additions & 1 deletion tests/panel-boundary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { Hono } from "hono";
import { describe, expect, it } from "vitest";
import { antiFramingHeaders, PanelAuthThrottle, panelAuthGuard } from "../server/panel-boundary";

const config = { panelAuthUser: "ada", panelAuthPassword: "hunter2", demoMode: false };
const config = {
panelAuthUser: "ada",
panelAuthPassword: "hunter2",
demoMode: false,
panelTrustProxy: false,
};

function basic(user: string, pass: string): string {
return `Basic ${Buffer.from(`${user}:${pass}`).toString("base64")}`;
Expand Down Expand Up @@ -101,3 +106,41 @@ describe("failed panel sign-ins are throttled", () => {
expect(overlapping.map((r) => r.status)).toEqual(Array(11).fill(200));
});
});

describe("behind a reverse proxy", () => {
/** A panel behind the guard's real source lookup; every request shares one peer. */
function proxied(trustProxy: boolean) {
const app = new Hono();
app.use(
"*",
panelAuthGuard(
{ ...config, panelTrustProxy: trustProxy },
new PanelAuthThrottle({ perSource: 2 }),
),
);
app.get("/panel", (c) => c.text("tokens live here"));
return (authorization: string, forwardedFor: string) =>
app.request("/panel", {
headers: { Authorization: authorization, "X-Forwarded-For": forwardedFor },
});
}

it("with PANEL_TRUST_PROXY, one caller's wrong guesses do not lock out another", async () => {
const get = proxied(true);
for (let i = 0; i < 3; i++) await get(basic("ada", "x"), "198.51.100.7");
expect((await get(basic("ada", "hunter2"), "198.51.100.7")).status).toBe(429);
expect((await get(basic("ada", "hunter2"), "203.0.113.9")).status).toBe(200);
});

it("counts by the entry the proxy appended, not one the caller sent", async () => {
const get = proxied(true);
for (let i = 0; i < 3; i++) await get(basic("ada", "x"), `10.0.0.${i}, 198.51.100.7`);
expect((await get(basic("ada", "hunter2"), "198.51.100.7")).status).toBe(429);
});

it("ignores X-Forwarded-For unless told to trust it", async () => {
const get = proxied(false);
for (let i = 0; i < 3; i++) await get(basic("ada", "x"), `10.0.0.${i}`);
expect((await get(basic("ada", "hunter2"), "203.0.113.9")).status).toBe(429);
});
});
Loading