Skip to content
Open
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
44 changes: 42 additions & 2 deletions docs/gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,45 @@ the profile. The proxy then asks for the code on the terminal at start and at ev
Without a terminal (a Claude Code session, a background job) it does not wait for input: it
fails at once with "requires MFA; start `ct gateway proxy` in your own terminal".

## Read as another person (`--simulate`)

The gateway also serves `GET /simulate/<personId>/api/...`: the same allowlisted reads, but as
that ChurchTools person, to see what they see. It is opt-in:

```bash
ct gateway proxy --env prod-ro --simulate # profile eqrm-ct-simulate
ct gateway proxy --env prod-ro --simulate --simulate-profile my-simulate
ct get raw /simulate/<personId>/api/persons/<personId> --env prod-ro
```

The simulate role is a different role from the reader and can invoke only `GET /simulate/*`; the
reader role gets 403 on `/simulate`, so the proxy holds two credential sets and picks per request.
`/simulate/...` is signed with the simulate role, everything else with the reader role. The profile
(`~/.aws/config`):

```ini
[profile eqrm-ct-simulate]
source_profile = default
role_arn = arn:aws:iam::<account>:role/<gateway-simulate-role>
mfa_serial = arn:aws:iam::<account>:mfa/<user>
```

- **MFA is enforced by the role's trust policy, not by the proxy.** The proxy only asks for the code
(on the terminal, at start, so a wrong profile or code fails before it listens). Without a
terminal it fails at once.
- Without `--simulate`, `/simulate/...` stays refused locally (403, the hint names the flag).
- With it, the proxy forwards only `GET /simulate/<personId>/api/...`: `personId` is digits, no
leading zero, not 0; anything else under `/simulate` and every non-GET is refused locally. Query
handling and `login_token` stripping are the same as for `/api`.
- The gateway refuses unknown persons and admins (`{"error":"ChurchTools refused the simulation"}`):
an admin cannot be simulated.
- A role session lasts at most an hour. When it is about to expire, the next `/simulate` request
asks for a new MFA code on the proxy's terminal (same caching as the reader credentials; that
request waits for the code). Requests on `/api` are not affected.
- ChurchTools keeps one simulation per session (measured 2026-11-09), so simulating person B
after person A on the same gateway session replaces A; do not run two simulations in parallel.
- The log line of a simulated request carries the person id: `GET /simulate/<id>/api/... 200 [simulate person <id>]`.

## Use

```bash
Expand All @@ -66,14 +105,15 @@ discards it and the gateway uses its own session.
- The proxy binds `127.0.0.1` only. It builds every upstream request from scratch:
`Cookie`, `Authorization`, CSRF headers and any `login_token` query parameter never leave
the machine.
- Locally refused with 403: everything except `GET /api/...` and the two legacy
- Locally refused with 403: everything except `GET /api/...` (plus `GET /simulate/<personId>/api/...`
with `--simulate`) and the two legacy
`POST /index.php?q=churchauth/ajax` and `?q=churchdb/ajax` calls whose body is exactly
`func=getMasterData`. The gateway applies its own, stricter allowlist as the second lock.
- `ct` itself refuses writes for a gateway env ("`prod-ro` is read-only; writes happen in
CI") before any request is made.
- One log line per request on stderr: method, path without query, status. Never bodies.
- Credentials are re-requested shortly before the assumed role expires (a new MFA prompt only
if the profile has `mfa_serial`).
if the profile has `mfa_serial`; with `--simulate`, the simulate profile always has one).
- A `403` with a `blocked` body is the gateway's allowlist deciding. The proxy passes it to the
client unchanged and logs that the path is not on the gateway allowlist; `ct` reports the same.
Widening the allowlist is a change to the gateway's handler allowlist, made by whoever runs
Expand Down
24 changes: 22 additions & 2 deletions src/commands/gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,19 @@ export function gatewayCommand(): Command {
cmd
.command("proxy")
.description(
"Run a local SigV4-signing proxy (127.0.0.1) for a gateway env (asks for an MFA code only if the AWS profile has mfa_serial)",
"Run a local SigV4-signing proxy (127.0.0.1) for a gateway env (asks for an MFA code only with --simulate, or if the AWS profile has mfa_serial)",
)
.requiredOption("-e, --env <name>", "environment with a `gateway` block in ct.envs.json")
.action(async (opts: { env: string }) => {
.option(
"--simulate",
"also forward GET /simulate/<personId>/api/... (read as another person); asks for an MFA code at start",
)
.option(
"--simulate-profile <name>",
"AWS profile for the simulate role (needs mfa_serial); only with --simulate",
"eqrm-ct-simulate",
)
.action(async (opts: { env: string; simulate?: boolean; simulateProfile: string }) => {
try {
const profile = await loadEnvProfile(opts.env, resolve(resolveEnvsPath()));
if (!profile.gateway) {
Expand All @@ -25,18 +34,29 @@ export function gatewayCommand(): Command {
const { gateway } = profile;
const port = gatewayPort(profile);
const credentials = cachingCredentials(profileCredentials(gateway.profile));
// Own cache, own MFA prompt: the simulate role is separate from the reader role by design.
const simulateCredentials = opts.simulate
? cachingCredentials(profileCredentials(opts.simulateProfile))
: undefined;
const server = createProxyServer({
gatewayUrl: gateway.url,
region: gateway.region,
credentials,
simulateCredentials,
log: (line) => process.stderr.write(`${new Date().toISOString()} ${line}\n`),
});
// Fail fast on bad AWS config/MFA instead of at the first request.
await credentials();
if (simulateCredentials) await simulateCredentials();
await listenLoopback(server, port);
info(
`Proxy for ${opts.env} listening on http://127.0.0.1:${port} -> ${gateway.url} (Ctrl-C to stop).`,
);
if (simulateCredentials) {
info(
`Reading as another person is on: /simulate/<personId>/api/... (profile ${opts.simulateProfile}).`,
);
}
await new Promise<void>((done) => {
const stop = (): void => {
server.close(() => done());
Expand Down
2 changes: 1 addition & 1 deletion src/env/envs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export interface GatewayConfig {
/** The gateway's https base URL (API Gateway, SigV4/AWS_IAM). */
url: string;
region: string;
/** AWS profile (in ~/.aws/config) that assumes the reader role, with MFA. */
/** AWS profile (in ~/.aws/config) that assumes the reader role (no MFA; only the simulate role needs one). */
profile: string;
}

Expand Down
2 changes: 1 addition & 1 deletion src/gateway/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export interface ProfileCredentialsDeps {
}

/**
* Credentials for the gateway reader role: the AWS profile assumes the role. The normal profile has no
* Credentials for one gateway role: the AWS profile assumes it. The reader profile has no
* `mfa_serial`, so there is never a prompt and every refresh is silent. A profile that does have one
* asks for the code on the terminal, and fails at once when there is no terminal to ask (a Claude Code
* session, a launchd job) instead of hanging on stdin. Each call runs a fresh assume-role;
Expand Down
31 changes: 29 additions & 2 deletions src/gateway/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,21 @@
*
* Allowed: any GET under `/api/`, and exactly two legacy POSTs — `index.php?q=churchauth/ajax` and
* `index.php?q=churchdb/ajax` with the body exactly `func=getMasterData`.
*
* With `simulate: true` (`ct gateway proxy --simulate`) additionally `GET /simulate/<personId>/api/...`, the
* gateway's "read as another person" route. The id is digits only, positive, no leading zero. Without the
* option every `/simulate` request is denied here, as before.
*/

export type FilterResult =
| { ok: true; method: "GET" | "POST"; path: string; query: [string, string][] }
| {
ok: true;
method: "GET" | "POST";
path: string;
query: [string, string][];
/** Set for `/simulate/<id>/api/...`: the request must be signed with the simulate credentials. */
simulatePersonId?: number;
}
| { ok: false; reason: string };

const LEGACY_QUERIES = new Set(["churchauth/ajax", "churchdb/ajax"]);
Expand All @@ -22,7 +33,12 @@ function deny(reason: string): FilterResult {
}

/** `rawUrl` is the request target as received (`/api/groups/1?x=y`). `body` is only consulted for POST. */
export function checkRequest(method: string, rawUrl: string, body: string): FilterResult {
export function checkRequest(
method: string,
rawUrl: string,
body: string,
options: { simulate?: boolean } = {},
): FilterResult {
let url: URL;
try {
url = new URL(rawUrl, "http://localhost");
Expand All @@ -34,6 +50,17 @@ export function checkRequest(method: string, rawUrl: string, body: string): Filt
const query = [...url.searchParams.entries()].filter(([k]) => !STRIPPED_PARAMS.has(k.toLowerCase()));

if (method === "GET") {
if (path === "/simulate" || path.startsWith("/simulate/")) {
if (!options.simulate) {
return deny("GET /simulate/... is only forwarded when the proxy runs with --simulate");
}
const m = /^\/simulate\/([1-9][0-9]*)(\/api\/.*)$/.exec(path);
if (!m)
return deny("only GET /simulate/<personId>/api/... is forwarded (personId: digits, no leading zero)");
const personId = Number(m[1]);
if (!Number.isSafeInteger(personId)) return deny("simulate personId is out of range");
return { ok: true, method: "GET", path, query, simulatePersonId: personId };
}
if (!path.startsWith("/api/")) return deny("only GET /api/... is forwarded");
return { ok: true, method: "GET", path, query };
}
Expand Down
21 changes: 17 additions & 4 deletions src/gateway/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ export interface ProxyOptions {
region: string;
/** Called for every request; implementations cache (see {@link cachingCredentials}). */
credentials: () => Promise<AwsCredentials>;
/**
* Credentials of the MFA-trusted simulate role. When set, `GET /simulate/<personId>/api/...` is forwarded
* and signed with these; the reader credentials are never used for it, and these never for anything else.
* Unset: `/simulate` is denied locally.
*/
simulateCredentials?: () => Promise<AwsCredentials>;
log?: (line: string) => void;
fetchImpl?: typeof fetch;
}
Expand Down Expand Up @@ -102,8 +108,11 @@ export function createProxyServer(options: ProxyOptions): Server {
const method = req.method ?? "";
const rawUrl = req.url ?? "/";
const logPath = rawUrl.split("?")[0] ?? "/";
// /simulate/<digits>/... : name the person in the log line (the path already carries the id).
const simulated = /^\/simulate\/([1-9][0-9]*)\//.exec(logPath)?.[1];
const tag = simulated ? ` [simulate person ${simulated}]` : "";
const finish = (status: number, body: unknown, extra = ""): void => {
log(`${method} ${logPath} ${status}${extra}`);
log(`${method} ${logPath} ${status}${tag}${extra}`);
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(body));
};
Expand All @@ -121,7 +130,9 @@ export function createProxyServer(options: ProxyOptions): Server {
}

const body = method === "POST" ? await readBody(req) : "";
const verdict = checkRequest(method, rawUrl, body);
const verdict = checkRequest(method, rawUrl, body, {
simulate: options.simulateCredentials !== undefined,
});
if (!verdict.ok) {
finish(
403,
Expand All @@ -138,7 +149,9 @@ export function createProxyServer(options: ProxyOptions): Server {
let credentials: AwsCredentials;
let signed: { headers: Record<string, string> };
try {
credentials = await options.credentials();
const provider =
verdict.simulatePersonId !== undefined ? options.simulateCredentials! : options.credentials;
credentials = await provider();
const [{ HttpRequest }, makeSigner] = await Promise.all([import("@smithy/protocol-http"), signer()]);
const query: Record<string, string | string[]> = {};
for (const [k, v] of verdict.query) {
Expand Down Expand Up @@ -180,7 +193,7 @@ export function createProxyServer(options: ProxyOptions): Server {
// to the client unchanged; no retry, no other tier.
const allowlisted = upstream.status === 403 && isBlockedBody(payload);
log(
`${method} ${logPath} ${upstream.status}${allowlisted ? ` (not on the gateway allowlist; widening it is a change to the gateway's handler allowlist)` : ""}`,
`${method} ${logPath} ${upstream.status}${tag}${allowlisted ? ` (not on the gateway allowlist; widening it is a change to the gateway's handler allowlist)` : ""}`,
);
const responseHeaders: Record<string, string> = {
"content-type": upstream.headers.get("content-type") ?? "application/json",
Expand Down
49 changes: 49 additions & 0 deletions tests/gateway-filter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,52 @@ describe("gateway request filter", () => {
expect(checkRequest("POST", "/index.php?login_token=x", "func=getMasterData").ok).toBe(false);
});
});

describe("gateway request filter: /simulate", () => {
const on = { simulate: true };

it("is denied without the option, and the reason names the flag", () => {
const r = checkRequest("GET", "/simulate/42/api/persons/42", "");
expect(r).toMatchObject({ ok: false });
expect(!r.ok && r.reason).toMatch(/--simulate/);
});

it("allows GET /simulate/<id>/api/... with the option, keeping the query and stripping login_token", () => {
expect(checkRequest("GET", "/simulate/42/api/persons/42?a=1&login_token=s", "", on)).toEqual({
ok: true,
method: "GET",
path: "/simulate/42/api/persons/42",
query: [["a", "1"]],
simulatePersonId: 42,
});
});

it.each([
"/simulate",
"/simulate/",
"/simulate/42",
"/simulate/42/",
"/simulate/0/api/x",
"/simulate/042/api/x",
"/simulate/-1/api/x",
"/simulate/4.2/api/x",
"/simulate/%34%32/api/x",
"/simulate/42/index.php",
"/simulate/42/api",
"/simulate/42/../api/x",
"/simulate//42/api/x",
"/simulate/42/api//x",
"/simulate/99999999999999999999/api/x",
])("denies %s", (path) => {
expect(checkRequest("GET", path, "", on).ok).toBe(false);
});

it.each(["POST", "PUT", "DELETE", "HEAD"])("denies %s on /simulate", (m) => {
expect(checkRequest(m, "/simulate/42/api/persons/42", "func=getMasterData", on).ok).toBe(false);
});

it("leaves /api and the legacy POSTs unchanged with the option on", () => {
expect(checkRequest("GET", "/api/groups/1", "", on)).toEqual(checkRequest("GET", "/api/groups/1", ""));
expect(checkRequest("POST", "/index.php?q=churchdb/ajax", "func=getMasterData", on).ok).toBe(true);
});
});
67 changes: 66 additions & 1 deletion tests/gateway-proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, it, expect, afterEach, vi } from "vitest";
import { createServer, request, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { profileCredentials } from "../src/gateway/credentials.js";
import type { AwsCredentials } from "../src/gateway/proxy.js";
import { cachingCredentials, createProxyServer, listenLoopback } from "../src/gateway/proxy.js";

const CREDS = { accessKeyId: "AKIATEST", secretAccessKey: "secret", sessionToken: "tok-session" };
Expand All @@ -21,7 +22,9 @@ afterEach(async () => {
}
});

async function start(): Promise<{ proxy: string; seen: Seen[]; logs: string[] }> {
async function start(
simulate?: () => Promise<AwsCredentials>,
): Promise<{ proxy: string; seen: Seen[]; logs: string[] }> {
const seen: Seen[] = [];
const upstream = createServer((req, res) => {
const chunks: Buffer[] = [];
Expand Down Expand Up @@ -57,6 +60,7 @@ async function start(): Promise<{ proxy: string; seen: Seen[]; logs: string[] }>
gatewayUrl: "https://gw.example.execute-api.eu-central-1.amazonaws.com",
region: "eu-central-1",
credentials: async () => CREDS,
simulateCredentials: simulate,
log: (l) => logs.push(l),
fetchImpl: (input, init) =>
fetch(String(input).replace(/^https:\/\/[^/]+/, `http://127.0.0.1:${upstreamPort}`), init),
Expand Down Expand Up @@ -240,3 +244,64 @@ describe("cachingCredentials", () => {
expect(calls).toBe(2);
});
});

describe("simulate route", () => {
const SIM = { accessKeyId: "AKIASIMULATE", secretAccessKey: "sim-secret", sessionToken: "tok-sim" };

it("signs /simulate with the simulate credentials and everything else with the reader's, logging the person", async () => {
const { proxy, seen, logs } = await start(async () => SIM);
expect((await fetch(`${proxy}/simulate/42/api/persons/42?login_token=x`)).status).toBe(200);
expect((await fetch(`${proxy}/api/groups/1`)).status).toBe(200);
expect(seen[0]!.url).toBe("/simulate/42/api/persons/42");
expect(seen[0]!.headers.authorization).toContain("Credential=AKIASIMULATE/");
expect(seen[0]!.headers["x-amz-security-token"]).toBe("tok-sim");
expect(seen[1]!.headers.authorization).toContain("Credential=AKIATEST/");
expect(logs).toEqual([
"GET /simulate/42/api/persons/42 200 [simulate person 42]",
"GET /api/groups/1 200",
]);
});

it("answers /simulate 403 locally without the flag, naming the flag", async () => {
const { proxy, seen } = await start();
const res = await fetch(`${proxy}/simulate/42/api/persons/42`);
expect(res.status).toBe(403);
expect(((await res.json()) as { hint: string }).hint).toMatch(/--simulate/);
expect(seen).toHaveLength(0);
});

it("still refuses malformed or non-GET simulate requests with the flag on", async () => {
const { proxy, seen } = await start(async () => SIM);
for (const [method, path] of [
["GET", "/simulate/0/api/persons"],
["GET", "/simulate/007/api/persons"],
["GET", "/simulate/abc/api/persons"],
["GET", "/simulate/42/other"],
["PUT", "/simulate/42/api/persons/42"],
] as const) {
expect(
(await fetch(`${proxy}${path}`, { method, body: method === "GET" ? undefined : "{}" })).status,
).toBe(403);
}
expect(seen).toHaveLength(0);
});

it("re-runs the simulate provider (and so its MFA prompt) after expiry, via cachingCredentials", async () => {
let now = 0;
let prompts = 0;
const get = cachingCredentials(
async () => {
prompts++;
return { ...SIM, expiration: new Date(now + 3600_000) };
},
() => now,
);
const { proxy } = await start(get);
await fetch(`${proxy}/simulate/42/api/persons/42`);
await fetch(`${proxy}/simulate/43/api/persons/43`);
expect(prompts).toBe(1);
now = 3600_000 - 30_000;
await fetch(`${proxy}/simulate/42/api/persons/42`);
expect(prompts).toBe(2);
});
});
Loading