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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1086,7 +1086,7 @@ x:

For a test the emulator cannot reach:

- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` (or seed `webhook_crc_delivery: control`) is an emulator mode: creation sends no challenge, and `GET /_emulate/x/webhooks/:id/challenge` returns the GET X would send for the test to deliver; report the answer with `POST /_emulate/x/webhooks/:id/challenge`. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port).
- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` (or seed `webhook_crc_delivery: control`) is an emulator mode: creation sends no challenge, and `GET /_emulate/x/webhooks/:id/challenge` returns the GET X would send for the test to deliver; report the answer with `POST /_emulate/x/webhooks/:id/challenge`. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port). The emulator never calls such an address: its deliveries are held and listed as held, and `POST /_emulate/x/dm/preview-delivery` gives the exact signed request. Deliveries go only to a webhook whose challenge was answered (X's CRC at creation or on `PUT /2/webhooks/:id`, or, in control mode, a correct answer at `POST /_emulate/x/webhooks/:id/challenge`); until then they are held, as are a seeded webhook's until `PUT`.
- `POST /_emulate/x/dm/arrive` with `{"to":"developer","from":"alice","text":"hi"}` makes a message arrive (stored, then delivered).
- `POST /_emulate/x/dm/preview-delivery` with `{"dm_event_id":"..."}` returns the exact URL, headers and body of each delivery without sending it.

Expand Down
2 changes: 1 addition & 1 deletion apps/web/app/docs/x/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Creating a webhook sends `GET <url>?crc_token=...`; the answer must be `sha256=`

### Tests the emulator cannot reach

- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` switches the instance to an emulator mode: webhook creation sends no challenge, `GET /_emulate/x/webhooks/:id/challenge` returns the request X would make, and `POST /_emulate/x/webhooks/:id/challenge` with the app's `response_token` checks it as X would. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port).
- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` switches the instance to an emulator mode: webhook creation sends no challenge, `GET /_emulate/x/webhooks/:id/challenge` returns the request X would make, and `POST /_emulate/x/webhooks/:id/challenge` with the app's `response_token` checks it as X would. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port). The emulator never calls such an address: its deliveries are held and listed as held, and `POST /_emulate/x/dm/preview-delivery` gives the exact signed request. Deliveries go only to a webhook whose challenge was answered (X's CRC at creation or on `PUT /2/webhooks/:id`, or, in control mode, a correct answer at `POST /_emulate/x/webhooks/:id/challenge`); until then they are held, as are a seeded webhook's until `PUT`.
- `POST /_emulate/x/dm/arrive` with `{"to":"developer","from":"alice","text":"hi"}` makes a message arrive: stored, readable, and delivered to subscribers.
- `POST /_emulate/x/dm/preview-delivery` with `{"dm_event_id":"..."}` returns each delivery's URL, headers and body without sending it; the bytes match a real delivery.

Expand Down
121 changes: 121 additions & 0 deletions packages/@emulators/x/src/__tests__/webhooks-media.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,127 @@ describe("webhook addresses in each CRC mode on an https instance", () => {
});
});

describe("deliveries go only to an address whose owner answered the challenge", () => {
const answer = async (control: (path: string, body?: unknown) => Promise<Response>, id: string) => {
const challenge = (await (await control(`/webhooks/${id}/challenge`)).json()) as Json;
return (await (
await control(`/webhooks/${id}/challenge`, { response_token: sign(SECRET, challenge.crc_token) })
).json()) as Json;
};

it("never calls an address accepted only through control mode's relaxation, even once answered", async () => {
const r = await receiver(SECRET); // http://127.0.0.1:<port>: http and a port
const host = "https://x.example.test";
const server = createServer(xPlugin, { baseUrl: host });
seedFromConfig(server.store, host, {
users: [
{ username: "developer", user_id: DEV },
{ username: "alice", user_id: ALICE },
],
oauth_clients: [{ client_id: "dm-app", client_secret: SECRET, client_type: "confidential" }],
webhook_crc_delivery: "control",
});
const xs = getXStore(server.store);
for (const [t, user] of [
["app", null],
["dev", DEV],
["alice", ALICE],
] as const) {
xs.accessTokens.insert({
token: t,
client_id: "dm-app",
user_id: user,
scopes: ["dm.read", "dm.write", "tweet.read", "users.read"],
app_only: !user,
expires: 0,
});
}
const req = (path: string, token: string | null, body?: unknown) =>
server.app.request(`${host}${path}`, {
method: body === undefined ? "GET" : "POST",
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const control = (path: string, body?: unknown) => req(`/_emulate/x${path}`, null, body);
const hook = ((await (await req("/2/webhooks", "app", { url: r.url })).json()) as Json).data;
await req("/2/activity/subscriptions", "dev", {
event_type: "dm.received",
filter: { user_id: DEV },
webhook_id: hook.id,
});
expect((await answer(control, hook.id)).valid).toBe(true);

const arrived = (await (
await control("/dm/arrive", { to: "developer", from: "alice", text: "hi" })
).json()) as Json;
expect(arrived.deliveries).toHaveLength(1);
expect(arrived.deliveries[0].held).toMatch(/never calls such an address/);
expect(arrived.deliveries[0].success).toBe(false);
expect(r.received).toHaveLength(0);
const preview = (await (
await control("/dm/preview-delivery", { dm_event_id: arrived.dm_event_id })
).json()) as Json;
expect(preview.deliveries[0].url).toBe(r.url);
expect(preview.deliveries[0].headers["x-twitter-webhooks-signature-oauth2"]).toBe(
sign(SECRET, preview.deliveries[0].body),
);
// A DM sent through X's own route is on the ledger, with the held delivery.
const sent = await req(`/2/dm_conversations/with/${DEV}/messages`, "alice", { text: "via the API" });
expect(sent.status).toBe(201);
expect(r.received).toHaveLength(0);
const entry = server.ledger.list().find((e) => e.method === "POST" && e.path.endsWith("/messages"))!;
expect(entry.summary).toBeDefined();
expect(entry.sideEffects.find((e) => e.collection === "x.dm_events")!.summary).toMatch(
/0 webhook deliveries sent, 1 held/,
);
expect(
entry.sideEffects.some((e) => e.collection === "x.webhook_deliveries" && /never calls/.test(e.summary ?? "")),
).toBe(true);
});

it("holds deliveries in control mode until the test answers the challenge, then sends them", async () => {
const r = await receiver(SECRET);
const { call, mint, control } = setup({ webhook_crc_delivery: "control" });
const hook = (
(await (
await call("/2/webhooks", mint(null), { method: "POST", body: JSON.stringify({ url: r.url }) })
).json()) as Json
).data;
await call("/2/activity/subscriptions", mint(DEV), {
method: "POST",
body: JSON.stringify({ event_type: "dm.received", filter: { user_id: DEV }, webhook_id: hook.id }),
});
const before = (await (
await control("/dm/arrive", { to: "developer", from: "alice", text: "one" })
).json()) as Json;
expect(before.deliveries[0].held).toMatch(/no challenge has been answered/);
expect(r.received).toHaveLength(0);

expect((await answer(control, hook.id)).valid).toBe(true);
const after = (await (await control("/dm/arrive", { to: "developer", from: "alice", text: "two" })).json()) as Json;
expect(after.deliveries[0]).toMatchObject({ success: true });
expect(after.deliveries[0].held).toBeUndefined();
expect(r.received.filter((x) => x.method === "POST")).toHaveLength(1);
});

it("holds deliveries to a seeded webhook until PUT passes X's CRC", async () => {
const r = await receiver(SECRET);
const { call, mint, control } = setup({
webhooks: [{ client_id: "dm-app", url: r.url }],
activity_subscriptions: [{ event_type: "dm.received", user: "developer", webhook: r.url }],
});
const before = (await (
await control("/dm/arrive", { to: "developer", from: "alice", text: "one" })
).json()) as Json;
expect(before.deliveries[0].held).toMatch(/no challenge has been answered/);
const hooks = (await (await call("/2/webhooks", mint(null))).json()) as Json;
expect((await call(`/2/webhooks/${hooks.data[0].id}`, mint(null), { method: "PUT" })).status).toBe(200);
const after = (await (await control("/dm/arrive", { to: "developer", from: "alice", text: "two" })).json()) as Json;
expect(after.deliveries[0].success).toBe(true);
expect(r.received.filter((x) => x.method === "POST")).toHaveLength(1);
});
});

describe("X Activity API DM deliveries", () => {
async function subscribed(extra: Partial<XSeedConfig> = {}) {
const r = await receiver(SECRET);
Expand Down
35 changes: 35 additions & 0 deletions packages/@emulators/x/src/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,24 @@ export interface PreparedDelivery {
method: "POST";
headers: Record<string, string>;
body: string;
/** Why the emulator holds this delivery instead of sending it (it is still previewable). */
held?: string;
}

/**
* Why a delivery to this webhook is held, or null when it may be sent. X delivers only
* to an address whose owner answered the challenge; and an address accepted only through
* control mode's relaxation (http, or a port, on an https instance) is never called at all,
* so a public instance cannot be pointed at an arbitrary host and port.
*/
export function deliveryHold(baseUrl: string, webhook: XWebhook): string | null {
if (baseUrl.startsWith("https://") && webhookUrlProblem(webhook.url, true)) {
return "held: the address was accepted only through control mode's relaxation (http or a port), and the emulator never calls such an address";
}
if (!webhook.crc_proven) {
return "held: no challenge has been answered for this webhook; answer it (the CRC on PUT /2/webhooks/:id, or POST /_emulate/x/webhooks/:id/challenge in control mode) before deliveries are sent";
}
return null;
}

function activeSubscription(sub: XActivitySubscription, now: number): boolean {
Expand Down Expand Up @@ -237,6 +255,7 @@ export function prepareDmDeliveries(
method: "POST",
headers: { "content-type": "application/json", ...signatureHeaders(client, body) },
body,
...(deliveryHold(baseUrl, webhook) ? { held: deliveryHold(baseUrl, webhook)! } : {}),
});
}
}
Expand All @@ -252,6 +271,8 @@ export interface DeliveryResult {
status_code: number | null;
success: boolean;
delivery_id: number;
/** Set when the delivery was held, not sent: the reason. */
held?: string;
}

export async function sendDeliveries(
Expand All @@ -260,6 +281,20 @@ export async function sendDeliveries(
): Promise<DeliveryResult[]> {
const results: DeliveryResult[] = [];
for (const d of deliveries) {
if (d.held) {
results.push({
subscription_id: d.subscription_id,
webhook_id: d.webhook_id,
event_type: d.event_type,
for_user_id: d.for_user_id,
url: d.url,
status_code: null,
success: false,
delivery_id: 0,
held: d.held,
});
continue;
}
const rec: WebhookDelivery = await dispatcher.deliver({
hookRef: d.webhook_id,
event: d.event_type,
Expand Down
6 changes: 6 additions & 0 deletions packages/@emulators/x/src/entities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,12 @@ export interface XWebhook extends Entity {
client_id: string;
url: string;
valid: boolean;
/**
* True once an answered challenge has proved the owner controls the address: X's
* CRC at creation or on PUT, or, in control mode, a correct answer reported at
* POST /_emulate/x/webhooks/:id/challenge. Deliveries go only to proven webhooks.
*/
crc_proven?: boolean;
created_at_x: string;
}

Expand Down
2 changes: 2 additions & 0 deletions packages/@emulators/x/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ export function seedFromConfig(store: Store, baseUrl: string, config: XSeedConfi
client_id: w.client_id,
url: w.url,
valid: w.valid ?? true,
// No challenge has been answered for a seeded webhook: PUT /2/webhooks/:id proves it.
crc_proven: false,
created_at_x: new Date().toISOString(),
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@emulators/x/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const manifest: ServiceManifest = {
status: "partial",
basePath: "/2/webhooks",
notes:
"Webhook configs with the CRC at creation and on PUT; X Activity API subscriptions for dm.sent and dm.received, delivered as the documented envelope and signed with X-Twitter-Webhooks-Signature-OAuth2 (client secret) plus X-Twitter-Webhooks-Signature when a consumer_secret is seeded. Other XAA event types, the persistent stream, replay, filter qualifiers and the hourly CRC are not emulated. CRC delivery mode `control` (POST /_emulate/x/webhooks/crc-delivery) is an emulator mode, not X behaviour. Emulator-only relaxation: in control mode POST /2/webhooks also accepts an http address and one with a port, which X refuses, so a test can register a local receiver and preview its deliveries; DM deliveries to that address are still attempted and recorded (from a hosted instance a local address is unreachable). Outbound mode keeps X's rule: https, no port, at most 200 characters.",
"Webhook configs with the CRC at creation and on PUT; X Activity API subscriptions for dm.sent and dm.received, delivered as the documented envelope and signed with X-Twitter-Webhooks-Signature-OAuth2 (client secret) plus X-Twitter-Webhooks-Signature when a consumer_secret is seeded. Other XAA event types, the persistent stream, replay, filter qualifiers and the hourly CRC are not emulated. CRC delivery mode `control` (POST /_emulate/x/webhooks/crc-delivery) is an emulator mode, not X behaviour. Emulator-only relaxation: in control mode POST /2/webhooks also accepts an http address and one with a port, which X refuses, so a test can register a local receiver and preview its deliveries; the emulator never calls such an address, and its deliveries are held (listed as held, previewable with POST /_emulate/x/dm/preview-delivery). Outbound mode keeps X's rule: https, no port, at most 200 characters. As on X, deliveries go only to a webhook whose challenge was answered: X's CRC at creation or on PUT in outbound mode, or a correct answer at POST /_emulate/x/webhooks/:id/challenge in control mode; until then, and for a seeded webhook until PUT, they are held.",
},
{
id: "account-activity",
Expand Down
5 changes: 3 additions & 2 deletions packages/@emulators/x/src/routes/control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
setCrcDeliveryMode,
} from "../activity.js";
import { clearRateWindows, getRateLimitConfig, rateLimitState, setRateLimitConfig } from "../rate-limits.js";
import { ensureOneToOne, storeAndDeliverMessage } from "./dm.js";
import { ensureOneToOne, recordHeldDeliveries, storeAndDeliverMessage } from "./dm.js";
import type { XSeedAttachment } from "../dm-seed.js";

/**
Expand Down Expand Up @@ -87,6 +87,7 @@ export function controlRoutes({ app, store, baseUrl, webhooks }: RouteContext):
text,
mediaKeys,
});
recordHeldDeliveries(c, deliveries);
return c.json({
dm_event_id: view.id,
dm_conversation_id: conv.conversation_id,
Expand Down Expand Up @@ -174,7 +175,7 @@ export function controlRoutes({ app, store, baseUrl, webhooks }: RouteContext):
body.response_token ?? (body.response as Record<string, unknown> | undefined)?.response_token ?? undefined;
const valid = !!client && crcAnswerValid(client, pending.crc_token, answer);
xs.pendingChallenges.update(pending.id, { answered: true, valid });
xs.webhooks.update(webhook.id, { valid });
xs.webhooks.update(webhook.id, { valid, crc_proven: valid });
return c.json({ webhook_id: webhook.webhook_id, valid });
});

Expand Down
17 changes: 16 additions & 1 deletion packages/@emulators/x/src/routes/dm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ export async function storeAndDeliverMessage(
return { view, deliveries };
}

/** Put each held delivery on the request's ledger entry, with the reason it was held. */
export function recordHeldDeliveries(c: Context, deliveries: DeliveryResult[]): void {
for (const d of deliveries) {
if (!d.held) continue;
recordSideEffect(c, {
type: "custom",
collection: "x.webhook_deliveries",
id: d.webhook_id,
summary: `${d.event_type} for ${d.for_user_id} to ${d.url} ${d.held}`,
});
}
}

/** Find or create the one-to-one conversation between two users. */
export function ensureOneToOne(store: Store, a: string, b: string): XDmConversation {
const xs = getXStore(store);
Expand Down Expand Up @@ -409,12 +422,14 @@ export function dmRoutes({ app, store, baseUrl, webhooks }: RouteContext): void
text: parsed.text,
mediaKeys: parsed.mediaKeys,
});
const held = deliveries.filter((d) => d.held).length;
recordSideEffect(c, {
type: "create",
collection: "x.dm_events",
id: view.id,
summary: `DM sent in ${conv.conversation_id}; ${deliveries.length} webhook deliveries`,
summary: `DM sent in ${conv.conversation_id}; ${deliveries.length - held} webhook deliveries sent, ${held} held`,
});
recordHeldDeliveries(c, deliveries);
return c.json({ data: { dm_conversation_id: conv.conversation_id, dm_event_id: view.id } }, 201);
}

Expand Down
3 changes: 2 additions & 1 deletion packages/@emulators/x/src/routes/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ export function webhookRoutes({ app, store, baseUrl }: RouteContext): void {
client_id: client.client_id,
url,
valid: true,
crc_proven: mode === "outbound",
created_at_x: new Date().toISOString(),
});
if (mode === "control") holdChallenge(store, webhook);
Expand Down Expand Up @@ -142,7 +143,7 @@ export function webhookRoutes({ app, store, baseUrl }: RouteContext): void {
}
const client = xs.oauthClients.findOneBy("client_id", webhook.client_id)!;
const crc = await runCrc(client, webhook.url);
xs.webhooks.update(webhook.id, { valid: crc.valid });
xs.webhooks.update(webhook.id, { valid: crc.valid, crc_proven: crc.valid });
if (!crc.valid) return webhookFailure(c, "CrcValidationFailed", crc.reason ?? "The CRC check failed.");
return c.json({ data: { valid: true } });
});
Expand Down
4 changes: 3 additions & 1 deletion skills/x/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ When the emulator cannot reach the app under test:

```bash
# Emulator mode: hold CRC challenges for the test to deliver itself. In this mode a webhook
# address may also be http or carry a port (an emulator-only relaxation of X's rule).
# address may also be http or carry a port (an emulator-only relaxation of X's rule); the emulator
# never calls such an address and holds its deliveries (preview them instead). Any webhook gets
# deliveries only after its challenge is answered.
curl -X POST "$X_EMULATOR_URL/_emulate/x/webhooks/crc-delivery" -H "Content-Type: application/json" -d '{"mode":"control"}'
curl "$X_EMULATOR_URL/_emulate/x/webhooks/$WEBHOOK_ID/challenge"

Expand Down
Loading