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: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ BCRYPT_COST_FACTOR=12
# -----------------------------------------------------------------------------
UPSTREAM_URL=http://localhost:4000
PROXY_TIMEOUT_MS=30000
REST_RATE_LIMIT_WINDOW_MS=60000
REST_RATE_LIMIT_MAX_REQUESTS=100

# -----------------------------------------------------------------------------
# CORS — comma-separated list of allowed origins
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ API gateway, usage metering, and billing services for the Callora API marketplac
- `POST /api/apis` for authenticated developers to register an API with priced endpoints
- Usage route: `GET /api/usage`
- JSON body parsing plus gateway API key authentication for upstream proxy routes
- Per-user global REST rate limiting for authenticated `/api/billing`, `/api/usage`, `/api/developers`, `/api/vault`, and `/api/keys` traffic, with IP fallback for unauthenticated requests
- In-memory `VaultRepository` with:
- `create(userId, contractId, network)`
- `findByUserId(userId, network)`
Expand Down Expand Up @@ -164,6 +165,8 @@ The app validates all environment variables at startup using [Zod](https://zod.d
| `METRICS_API_KEY` | **Yes** | — | Key for `/api/metrics` in production |
| `UPSTREAM_URL` | No | `http://localhost:4000` | Gateway upstream URL |
| `PROXY_TIMEOUT_MS` | No | `30000` | Proxy request timeout (ms) |
| `REST_RATE_LIMIT_WINDOW_MS` | No | `60000` | Window length for REST API rate limiting (ms) |
| `REST_RATE_LIMIT_MAX_REQUESTS` | No | `100` | Max REST API requests allowed per user/IP per window |
| `CORS_ALLOWED_ORIGINS` | No | `http://localhost:5173` | Comma-separated allowed origins |
| `SOROBAN_RPC_ENABLED` | No | `false` | Enable Soroban RPC health check |
| `SOROBAN_RPC_URL` | If `SOROBAN_RPC_ENABLED=true` | — | Soroban RPC endpoint URL |
Expand Down
4 changes: 3 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { VaultController } from './controllers/vaultController.js';
import { TransactionBuilderService } from './services/transactionBuilder.js';
import { requestIdMiddleware } from './middleware/requestId.js';
import { requestLogger } from './middleware/logging.js';
import { createConfiguredRestRateLimitMiddleware } from './middleware/restRateLimit.js';
import { metricsMiddleware, metricsEndpoint } from './metrics.js';
import {
BadRequestError,
Expand Down Expand Up @@ -76,6 +77,7 @@ const parseDate = (value: unknown): Date | null => {

export const createApp = (dependencies?: Partial<AppDependencies>) => {
const app = express();
const restRateLimit = createConfiguredRestRateLimitMiddleware();

// Set database pool in locals for billing routes
app.locals.dbPool = pool;
Expand Down Expand Up @@ -253,7 +255,7 @@ export const createApp = (dependencies?: Partial<AppDependencies>) => {
);

// Mount all routes including billing
app.use('/api', routes);
app.use('/api', createApiRouter({ restRateLimit }));

app.get('/api/usage', requireAuth, async (req, res: express.Response<unknown, AuthenticatedLocals>, next) => {
const user = res.locals.authenticatedUser;
Expand Down
33 changes: 33 additions & 0 deletions src/config/env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,36 @@ describe("env schema — BCRYPT_COST_FACTOR", () => {
);
});
});

describe('env schema — REST rate limit config', () => {
it('defaults REST rate limiting values when omitted', () => {
const result = envSchema.safeParse({ ...baseEnv });
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.REST_RATE_LIMIT_WINDOW_MS).toBe(60_000);
expect(result.data.REST_RATE_LIMIT_MAX_REQUESTS).toBe(100);
}
});

it('accepts positive integer REST rate limit values', () => {
const result = envSchema.safeParse({
...baseEnv,
REST_RATE_LIMIT_WINDOW_MS: '15000',
REST_RATE_LIMIT_MAX_REQUESTS: '12',
});
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.REST_RATE_LIMIT_WINDOW_MS).toBe(15_000);
expect(result.data.REST_RATE_LIMIT_MAX_REQUESTS).toBe(12);
}
});

it('rejects non-positive REST rate limit values', () => {
const result = envSchema.safeParse({
...baseEnv,
REST_RATE_LIMIT_WINDOW_MS: '0',
REST_RATE_LIMIT_MAX_REQUESTS: '-1',
});
expect(result.success).toBe(false);
});
});
2 changes: 2 additions & 0 deletions src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export const envSchema = z
// Proxy / Gateway
UPSTREAM_URL: z.string().url().default("http://localhost:4000"),
PROXY_TIMEOUT_MS: z.coerce.number().default(30_000),
REST_RATE_LIMIT_WINDOW_MS: z.coerce.number().int().positive().default(60_000),
REST_RATE_LIMIT_MAX_REQUESTS: z.coerce.number().int().positive().default(100),

// CORS
CORS_ALLOWED_ORIGINS: z.string().default("http://localhost:5173"),
Expand Down
37 changes: 36 additions & 1 deletion src/config/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,48 @@ describe('config validation', () => {
process.env.ADMIN_API_KEY = 'test-admin-key';
process.env.METRICS_API_KEY = 'test-metrics-key';

let cfg: { config: { port: unknown; databaseUrl: string } } | undefined;
let cfg:
| {
config: {
port: unknown;
databaseUrl: string;
restRateLimit: { windowMs: number; maxRequests: number };
};
}
| undefined;
await jest.isolateModulesAsync(async () => {
cfg = await import('./index.js');
});

expect(cfg!.config.port).toBeDefined();
expect(cfg!.config.databaseUrl).toContain('postgresql://');
expect(cfg!.config.restRateLimit.windowMs).toBe(60_000);
expect(cfg!.config.restRateLimit.maxRequests).toBe(100);
});

it('should expose configured REST rate limit values', async () => {
process.env.NODE_ENV = 'test';
process.env.JWT_SECRET = 'test-secret';
process.env.ADMIN_API_KEY = 'test-admin-key';
process.env.METRICS_API_KEY = 'test-metrics-key';
process.env.REST_RATE_LIMIT_WINDOW_MS = '30000';
process.env.REST_RATE_LIMIT_MAX_REQUESTS = '25';

let cfg:
| {
config: {
restRateLimit: { windowMs: number; maxRequests: number };
};
}
| undefined;
await jest.isolateModulesAsync(async () => {
cfg = await import('./index.js');
});

expect(cfg!.config.restRateLimit).toEqual({
windowMs: 30_000,
maxRequests: 25,
});
});

it('should call process.exit(1) when required env vars are missing', async () => {
Expand Down
5 changes: 5 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ export const config = {
timeoutMs: env.PROXY_TIMEOUT_MS,
},

restRateLimit: {
windowMs: env.REST_RATE_LIMIT_WINDOW_MS,
maxRequests: env.REST_RATE_LIMIT_MAX_REQUESTS,
},

sorobanRpc:
env.SOROBAN_RPC_ENABLED && env.SOROBAN_RPC_URL
? {
Expand Down
143 changes: 77 additions & 66 deletions src/middleware/requireAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,82 +13,93 @@ export type AuthenticatedLocals = {
/** Restrict accepted signing algorithms to prevent algorithm-confusion attacks. */
const ALLOWED_ALGORITHMS: jwt.Algorithm[] = ["HS256"];

export const requireAuth = (
req: Request,
res: Response<unknown, AuthenticatedLocals>,
next: NextFunction,
): void => {
let userId: string | undefined;
export interface ResolvedRequestUserId {
userId?: string;
error?: UnauthorizedError;
}

export function resolveRequestUserId(req: Request): ResolvedRequestUserId {
const authHeader = req.header("authorization");
if (authHeader !== undefined) {
if (authHeader.startsWith("Bearer ")) {
const token = authHeader.slice("Bearer ".length).trim();
if (!authHeader.startsWith("Bearer ")) {
return {
error: new UnauthorizedError(
"Invalid authorization header",
"INVALID_AUTH_HEADER",
),
};
}

if (!token) {
next(new UnauthorizedError("Missing token", "MISSING_TOKEN"));
return;
}
const token = authHeader.slice("Bearer ".length).trim();
if (!token) {
return {
error: new UnauthorizedError("Missing token", "MISSING_TOKEN"),
};
}

const secret = process.env.JWT_SECRET;
if (!secret) {
logger.error("[requireAuth] JWT_SECRET is not configured");
return { error: new UnauthorizedError() };
}

try {
const decoded = jwt.verify(token, secret, {
algorithms: ALLOWED_ALGORITHMS,
});

const secret = process.env.JWT_SECRET;
if (!secret) {
logger.error("[requireAuth] JWT_SECRET is not configured");
next(new UnauthorizedError());
return;
if (typeof decoded === "string" || !decoded) {
logger.warn("[requireAuth] Token payload is not a valid object");
return {
error: new UnauthorizedError("Invalid token", "INVALID_TOKEN"),
};
}

try {
const decoded = jwt.verify(token, secret, {
algorithms: ALLOWED_ALGORITHMS,
});

// jwt.verify can return a plain string for unsigned payloads
if (typeof decoded === "string" || !decoded) {
logger.warn("[requireAuth] Token payload is not a valid object");
next(new UnauthorizedError("Invalid token", "INVALID_TOKEN"));
return;
}

const payload = decoded as Record<string, unknown>;
const uid = payload.userId || payload.sub;

if (typeof uid !== "string" || uid.trim() === "") {
logger.warn("[requireAuth] Token missing required userId or sub claim");
next(
new UnauthorizedError(
"Token missing required claims",
"MISSING_CLAIMS",
),
);
return;
}

userId = uid;
} catch (err) {
// Log the failure reason but never the token contents
const code =
err instanceof jwt.TokenExpiredError
? "TOKEN_EXPIRED"
: err instanceof jwt.NotBeforeError
? "TOKEN_NOT_ACTIVE"
: "INVALID_TOKEN";

logger.warn("[requireAuth] JWT verification failed", { code });
next(
new UnauthorizedError(
code === "TOKEN_EXPIRED" ? "Token expired" : "Invalid token",
code,
const payload = decoded as Record<string, unknown>;
const uid = payload.userId || payload.sub;

if (typeof uid !== "string" || uid.trim() === "") {
logger.warn("[requireAuth] Token missing required userId or sub claim");
return {
error: new UnauthorizedError(
"Token missing required claims",
"MISSING_CLAIMS",
),
);
return;
};
}
} else {
next(new UnauthorizedError("Invalid authorization header", "INVALID_AUTH_HEADER"));
return;

return { userId: uid };
} catch (err) {
const code =
err instanceof jwt.TokenExpiredError
? "TOKEN_EXPIRED"
: err instanceof jwt.NotBeforeError
? "TOKEN_NOT_ACTIVE"
: "INVALID_TOKEN";

logger.warn("[requireAuth] JWT verification failed", { code });
return {
error: new UnauthorizedError(
code === "TOKEN_EXPIRED" ? "Token expired" : "Invalid token",
code,
),
};
}
} else {
const forwardedUserId = req.header("x-user-id");
userId = forwardedUserId?.trim();
}

const forwardedUserId = req.header("x-user-id")?.trim();
return forwardedUserId ? { userId: forwardedUserId } : {};
}

export const requireAuth = (
req: Request,
res: Response<unknown, AuthenticatedLocals>,
next: NextFunction,
): void => {
const { userId, error } = resolveRequestUserId(req);
if (error) {
next(error);
return;
}

if (!userId) {
Expand Down
Loading
Loading