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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,8 @@ PAYMENT_ROUTER_CONTRACT_ID=CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
SIGNING_PROVIDER=null
# SIGNING_KMS_KEY_ID=
# SIGNING_ENV_SECRET_KEY=

# --- Operational guardrails ---
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW_MS=60000
BODY_LIMIT_BYTES=1048576
57 changes: 57 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
},
"dependencies": {
"@fastify/cors": "^10.0.2",
"@fastify/rate-limit": "^11.2.0",
"dotenv": "^16.4.7",
"fastify": "^5.2.1",
"zod": "^3.24.1"
Expand Down
3 changes: 3 additions & 0 deletions src/config/env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ const baseEnv = {
USAGE_METER_CONTRACT_ID: "CBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
PAYMENT_ROUTER_CONTRACT_ID: "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC",
SIGNING_PROVIDER: "null",
RATE_LIMIT_MAX: "100",
RATE_LIMIT_WINDOW_MS: "60000",
BODY_LIMIT_BYTES: "1048576",
};

Object.assign(process.env, baseEnv);
Expand Down
10 changes: 10 additions & 0 deletions src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ const baseEnvSchema = z.object({
SIGNING_PROVIDER: z.enum(["null", "kms", "env"]).default("null"),
SIGNING_KMS_KEY_ID: z.string().optional(),
SIGNING_ENV_SECRET_KEY: z.string().optional(),

// Operational guardrails — issue #43.
RATE_LIMIT_MAX: z.coerce.number().default(100),
RATE_LIMIT_WINDOW_MS: z.coerce.number().default(60000),
BODY_LIMIT_BYTES: z.coerce.number().default(1048576),
});

/** Exposed separately so callers that need `.shape` (e.g. tests) can get at
Expand Down Expand Up @@ -100,4 +105,9 @@ export const config = {
envSecret: raw.SIGNING_ENV_SECRET_KEY,
nodeEnv: raw.NODE_ENV,
},
rateLimit: {
max: raw.RATE_LIMIT_MAX,
windowMs: raw.RATE_LIMIT_WINDOW_MS,
},
bodyLimitBytes: raw.BODY_LIMIT_BYTES,
};
94 changes: 94 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import assert from "node:assert/strict";
import { test } from "node:test";

const validContractId = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

function setBaseEnv() {
process.env.NODE_ENV = "test";
process.env.PORT = "0";
process.env.API_PREFIX = "/api/v1";
process.env.CORS_ORIGIN = "http://localhost:3000";
process.env.STELLAR_NETWORK = "testnet";
process.env.SOROBAN_RPC_URL = "https://soroban-testnet.stellar.org";
process.env.AUDIT_REGISTRY_CONTRACT_ID = validContractId;
process.env.USAGE_METER_CONTRACT_ID = "CBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
process.env.PAYMENT_ROUTER_CONTRACT_ID = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
process.env.SIGNING_PROVIDER = "null";
}

async function buildApp(opts: { rateLimitMax?: number; bodyLimitBytes?: number } = {}) {
setBaseEnv();
process.env.RATE_LIMIT_MAX = "100";
process.env.RATE_LIMIT_WINDOW_MS = "60000";
process.env.BODY_LIMIT_BYTES = "1048576";

const { buildServer } = await import("./index.js");
const app = await buildServer({
rateLimit: opts.rateLimitMax !== undefined ? { max: opts.rateLimitMax } : undefined,
bodyLimitBytes: opts.bodyLimitBytes,
});
await app.ready();
return app;
}

test("rate limit rejects requests above the configured threshold", async () => {
const app = await buildApp({ rateLimitMax: 2 });

const first = await app.inject({ method: "GET", url: "/health" });
assert.equal(first.statusCode, 200);

const second = await app.inject({ method: "GET", url: "/health" });
assert.equal(second.statusCode, 200);

const blocked = await app.inject({ method: "GET", url: "/health" });
assert.equal(blocked.statusCode, 429);
const body = blocked.json();
assert.equal(body.error, "Too Many Requests");
assert.equal(body.message, "rate limit exceeded");

await app.close();
});

test("body limit rejects payloads larger than the configured size", async () => {
const app = await buildApp({ bodyLimitBytes: 64 });

const bigPayload = "x".repeat(128);
const res = await app.inject({
method: "POST",
url: "/api/v1/disputes",
headers: {
"x-role": "buyer",
"x-user-id": "buyer-1",
"content-type": "application/json",
},
payload: JSON.stringify({ content: bigPayload }),
});

assert.equal(res.statusCode, 413);

await app.close();
});

test("small payloads within the body limit are accepted", async () => {
const app = await buildApp({ bodyLimitBytes: 4096 });

const res = await app.inject({
method: "POST",
url: "/api/v1/disputes",
headers: {
"x-role": "buyer",
"x-user-id": "buyer-1",
"content-type": "application/json",
},
payload: JSON.stringify({
settlementId: "s1",
reason: "item not delivered",
buyerId: "buyer-1",
sellerId: "seller-1",
}),
});

assert.equal(res.statusCode, 201);

await app.close();
});
36 changes: 27 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Fastify, { type FastifyError, type FastifyRequest } from "fastify";
import cors from "@fastify/cors";
import rateLimit from "@fastify/rate-limit";
import { config } from "./config/env.js";
import { healthRoutes } from "./routes/health.js";
import { v1Routes } from "./routes/v1/index.js";
Expand All @@ -16,8 +17,14 @@ declare module "fastify" {
}
}

async function buildServer() {
export interface BuildServerOptions {
bodyLimitBytes?: number;
rateLimit?: { max?: number; windowMs?: number };
}

export async function buildServer(opts: BuildServerOptions = {}) {
const app = Fastify({
bodyLimit: opts.bodyLimitBytes ?? config.bodyLimitBytes,
logger: {
// Redaction runs at the serializer boundary rather than at call sites: a
// secret reaches the log by being nested in a request body or hanging off
Expand Down Expand Up @@ -65,17 +72,28 @@ async function buildServer() {
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
});

await app.register(rateLimit, {
max: opts.rateLimit?.max ?? config.rateLimit.max,
timeWindow: opts.rateLimit?.windowMs ?? config.rateLimit.windowMs,
keyGenerator: (req) => req.ip,
errorResponseBuilder: () => ({
statusCode: 429,
error: "Too Many Requests",
message: "rate limit exceeded",
}),
});

await app.register(healthRoutes);
await app.register(v1Routes, { prefix: config.apiPrefix });

return app;
}

buildServer()
.then((app) =>
app.listen({ port: config.port, host: "0.0.0.0" }),
)
.catch((err) => {
console.error(err);
process.exit(1);
});
if (import.meta.url === new URL(process.argv[1], import.meta.url).href) {
buildServer()
.then((app) => app.listen({ port: config.port, host: "0.0.0.0" }))
.catch((err) => {
console.error(err);
process.exit(1);
});
}
Loading