diff --git a/src/app.ts b/src/app.ts index c239698..388ea26 100644 --- a/src/app.ts +++ b/src/app.ts @@ -21,6 +21,10 @@ export function buildApp(config: Config, deps: AppDeps = {}) { const app = express(); + // Behind exactly one proxy hop (Cloud Run's frontend). Without this req.ip is the + // proxy address, so the /post rate limit would be one shared bucket for everyone. + app.set("trust proxy", 1); + app.use(cors({ origin: config.corsOrigins === "*" ? true : config.corsOrigins.split(",").map(s => s.trim()), })); diff --git a/src/controllers/PostController.ts b/src/controllers/PostController.ts index 7d26c55..7ab65ef 100644 --- a/src/controllers/PostController.ts +++ b/src/controllers/PostController.ts @@ -149,7 +149,11 @@ export class PostController { let build; try { - build = await this.sponsor.buildSpendingTo(script); + // Build, submit and advance under one lock so concurrent posts chain + // off each other's change output instead of double-spending one UTXO. + build = await this.sponsor.buildSubmitAndAdvance(script, async (b) => { + await this.overlay.submit(b.beefHex, [this.config.overlayTopic]); + }); } catch (e) { if (e instanceof InsufficientFundsError) { res.status(503).json({ error: "sponsor wallet out of funds" }); @@ -159,12 +163,6 @@ export class PostController { res.status(503).json({ error: "sponsor wallet has no UTXO state" }); return; } - throw e; - } - - try { - await this.overlay.submit(build.beefHex, [this.config.overlayTopic]); - } catch (e) { if (e instanceof OverlayError) { console.error("[PostController] overlay rejected:", e.message); res.status(502).json({ error: "overlay rejected broadcast", detail: e.message }); @@ -173,9 +171,6 @@ export class PostController { throw e; } - // Overlay accepted + admitted — commit the new UTXO chain. - this.sponsor.advance(build.changeUtxo); - res.json({ txid: build.txid, script_hex: script.toHex(), diff --git a/src/services/SponsorWallet.ts b/src/services/SponsorWallet.ts index 34e1117..fb5be26 100644 --- a/src/services/SponsorWallet.ts +++ b/src/services/SponsorWallet.ts @@ -97,6 +97,27 @@ export class SponsorWallet { return next; } + /** + * Build, submit and commit in one critical section. buildSpendingTo() alone + * releases the lock before the caller has submitted and advanced, so two + * concurrent posts would both spend the same UTXO. Here the next build + * starts only after `submit` resolved and the change output was committed, + * or after it rejected (state unchanged). + */ + async buildSubmitAndAdvance( + opReturnScript: Script, + submit: (build: BroadcastBuildResult) => Promise, + ): Promise { + const next = this.buildLock.then(async () => { + const build = await this._build(opReturnScript); + await submit(build); + this.advance(build.changeUtxo); + return build; + }); + this.buildLock = next.catch(() => undefined); + return next; + } + private async _build(opReturnScript: Script): Promise { const utxo = this.currentUtxo; if (!utxo) throw new NoSeededUtxoError(); diff --git a/test/post.test.ts b/test/post.test.ts index 71a8ead..77a42ab 100644 --- a/test/post.test.ts +++ b/test/post.test.ts @@ -100,9 +100,11 @@ class FakeWab extends WabClient { class FakeOverlay extends OverlayClient { public submitCalls: { beefHex: string; topics: string[] }[] = []; public mode: "ok" | "no-admit" | "http-500" = "ok"; + public delayMs = 0; constructor() { super("http://fake-overlay"); } public override async submit(beefHex: string, topics: string[] = ["peck-schema"]) { this.submitCalls.push({ beefHex, topics }); + if (this.delayMs) await new Promise(r => setTimeout(r, this.delayMs)); if (this.mode === "no-admit") { throw new OverlayError(200, "overlay admitted no outputs (test)"); } @@ -386,4 +388,28 @@ describe("POST /post — broadcast layer", () => { expect(res1.body.txid).not.toBe(res2.body.txid); expect(overlay.submitCalls.length).toBe(2); }); + + it("concurrent posts chain off each other instead of spending the same UTXO", async () => { + const { app, overlay } = await setup(); + overlay.delayMs = 50; + const send = (n: string) => request(app).post("/post").send({ + url: `https://example.com/${n}`, comment: n, id_token: "valid", + }); + const [r1, r2] = await Promise.all([send("a"), send("b")]); + expect(r1.status).toBe(200); + expect(r2.status).toBe(200); + expect(overlay.submitCalls.length).toBe(2); + const [first, second] = overlay.submitCalls.map(c => Transaction.fromHexBEEF(c.beefHex)); + expect(second.inputs[0].sourceTXID).toBe(first.id("hex")); + }); +}); + +describe("POST /post — rate limit key", () => { + it("limits per X-Forwarded-For client, not one bucket for every caller", async () => { + const { app } = await setup(); + const hit = (ip: string) => request(app).post("/post").set("X-Forwarded-For", ip).send({}); + for (let i = 0; i < 10; i++) expect((await hit("198.51.100.1")).status).toBe(400); + expect((await hit("198.51.100.1")).status).toBe(429); + expect((await hit("198.51.100.2")).status).toBe(400); + }); });