From 08e837bf5559e9680fc8cb99bd05b93f8eb2cac5 Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Thu, 12 Aug 2021 20:09:35 +0200 Subject: :sparkles: api --- api/src/middlewares/Authentication.ts | 48 ++++++++++ api/src/middlewares/BodyParser.ts | 17 ++++ api/src/middlewares/CORS.ts | 16 ++++ api/src/middlewares/ErrorHandler.ts | 34 +++++++ api/src/middlewares/RateLimit.ts | 162 ++++++++++++++++++++++++++++++++++ api/src/middlewares/TestClient.ts | 66 ++++++++++++++ api/src/middlewares/index.ts | 5 ++ 7 files changed, 348 insertions(+) create mode 100644 api/src/middlewares/Authentication.ts create mode 100644 api/src/middlewares/BodyParser.ts create mode 100644 api/src/middlewares/CORS.ts create mode 100644 api/src/middlewares/ErrorHandler.ts create mode 100644 api/src/middlewares/RateLimit.ts create mode 100644 api/src/middlewares/TestClient.ts create mode 100644 api/src/middlewares/index.ts (limited to 'api/src/middlewares') diff --git a/api/src/middlewares/Authentication.ts b/api/src/middlewares/Authentication.ts new file mode 100644 index 00000000..01b7ef57 --- /dev/null +++ b/api/src/middlewares/Authentication.ts @@ -0,0 +1,48 @@ +import { NextFunction, Request, Response } from "express"; +import { HTTPError } from "lambert-server"; +import { checkToken, Config } from "@fosscord/server-util"; + +export const NO_AUTHORIZATION_ROUTES = [ + /^\/api(\/v\d+)?\/auth\/login/, + /^\/api(\/v\d+)?\/auth\/register/, + /^\/api(\/v\d+)?\/webhooks\//, + /^\/api(\/v\d+)?\/ping/, + /^\/api(\/v\d+)?\/gateway/, + /^\/api(\/v\d+)?\/experiments/, + /^\/api(\/v\d+)?\/guilds\/\d+\/widget\.(json|png)/ +]; + +export const API_PREFIX = /^\/api(\/v\d+)?/; +export const API_PREFIX_TRAILING_SLASH = /^\/api(\/v\d+)?\//; + +declare global { + namespace Express { + interface Request { + user_id: any; + user_bot: boolean; + token: any; + } + } +} + +export async function Authentication(req: Request, res: Response, next: NextFunction) { + if (req.method === "OPTIONS") return res.sendStatus(204); + if (!req.url.startsWith("/api")) return next(); + const apiPath = req.url.replace(API_PREFIX, ""); + if (apiPath.startsWith("/invites") && req.method === "GET") return next(); + if (NO_AUTHORIZATION_ROUTES.some((x) => x.test(req.url))) return next(); + if (!req.headers.authorization) return next(new HTTPError("Missing Authorization Header", 401)); + + try { + const { jwtSecret } = Config.get().security; + + const { decoded, user }: any = await checkToken(req.headers.authorization, jwtSecret); + + req.token = decoded; + req.user_id = decoded.id; + req.user_bot = user.bot; + return next(); + } catch (error) { + return next(new HTTPError(error.toString(), 400)); + } +} diff --git a/api/src/middlewares/BodyParser.ts b/api/src/middlewares/BodyParser.ts new file mode 100644 index 00000000..b0ff699d --- /dev/null +++ b/api/src/middlewares/BodyParser.ts @@ -0,0 +1,17 @@ +import bodyParser, { OptionsJson } from "body-parser"; +import { NextFunction, Request, Response } from "express"; +import { HTTPError } from "lambert-server"; + +export function BodyParser(opts?: OptionsJson) { + const jsonParser = bodyParser.json(opts); + + return (req: Request, res: Response, next: NextFunction) => { + jsonParser(req, res, (err) => { + if (err) { + // TODO: different errors for body parser (request size limit, wrong body type, invalid body, ...) + return next(new HTTPError("Invalid Body", 400)); + } + next(); + }); + }; +} diff --git a/api/src/middlewares/CORS.ts b/api/src/middlewares/CORS.ts new file mode 100644 index 00000000..49470611 --- /dev/null +++ b/api/src/middlewares/CORS.ts @@ -0,0 +1,16 @@ +import { NextFunction, Request, Response } from "express"; + +// TODO: config settings + +export function CORS(req: Request, res: Response, next: NextFunction) { + res.set("Access-Control-Allow-Origin", "*"); + // TODO: use better CSP policy + res.set( + "Content-security-policy", + "default-src * data: blob: filesystem: about: ws: wss: 'unsafe-inline' 'unsafe-eval'; script-src * data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src * data: blob: 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src * data: blob: ; style-src * data: blob: 'unsafe-inline'; font-src * data: blob: 'unsafe-inline';" + ); + res.set("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers") || "*"); + res.set("Access-Control-Allow-Methods", req.header("Access-Control-Request-Methods") || "*"); + + next(); +} diff --git a/api/src/middlewares/ErrorHandler.ts b/api/src/middlewares/ErrorHandler.ts new file mode 100644 index 00000000..2e6b1d8b --- /dev/null +++ b/api/src/middlewares/ErrorHandler.ts @@ -0,0 +1,34 @@ +import { NextFunction, Request, Response } from "express"; +import { HTTPError } from "lambert-server"; +import { FieldError } from "../util/instanceOf"; + +export function ErrorHandler(error: Error, req: Request, res: Response, next: NextFunction) { + try { + let code = 400; + let httpcode = code; + let message = error?.toString(); + let errors = undefined; + + if (error instanceof HTTPError && error.code) code = httpcode = error.code; + else if (error instanceof FieldError) { + code = Number(error.code); + message = error.message; + errors = error.errors; + } else { + console.error(error); + if (req.server?.options?.production) { + message = "Internal Server Error"; + } + code = httpcode = 500; + } + + if (httpcode > 511) httpcode = 400; + + res.status(httpcode).json({ code: code, message, errors }); + + return; + } catch (error) { + console.error(error); + return res.status(500).json({ code: 500, message: "Internal Server Error" }); + } +} diff --git a/api/src/middlewares/RateLimit.ts b/api/src/middlewares/RateLimit.ts new file mode 100644 index 00000000..c8fdeba2 --- /dev/null +++ b/api/src/middlewares/RateLimit.ts @@ -0,0 +1,162 @@ +import { db, MongooseCache, Bucket, Config } from "@fosscord/server-util"; +import { NextFunction, Request, Response, Router } from "express"; +import { getIpAdress } from "../util/ipAddress"; +import { API_PREFIX_TRAILING_SLASH } from "./Authentication"; + +const Cache = new MongooseCache( + db.collection("ratelimits"), + [ + // TODO: uncomment $match and fix error: not receiving change events + // { $match: { blocked: true } } + ], + { onlyEvents: false, array: true } +); + +// Docs: https://discord.com/developers/docs/topics/rate-limits + +/* +? bucket limit? Max actions/sec per bucket? + +TODO: ip rate limit +TODO: user rate limit +TODO: different rate limit for bots/user/oauth/webhook +TODO: delay database requests to include multiple queries +TODO: different for methods (GET/POST) +TODO: bucket major parameters (channel_id, guild_id, webhook_id) +TODO: use config values + +> IP addresses that make too many invalid HTTP requests are automatically and temporarily restricted from accessing the Discord API. Currently, this limit is 10,000 per 10 minutes. An invalid request is one that results in 401, 403, or 429 statuses. + +> All bots can make up to 50 requests per second to our API. This is independent of any individual rate limit on a route. If your bot gets big enough, based on its functionality, it may be impossible to stay below 50 requests per second during normal operations. + +*/ + +export default function RateLimit(opts: { + bucket?: string; + window: number; + count: number; + bot?: number; + webhook?: number; + oauth?: number; + GET?: number; + MODIFY?: number; + error?: boolean; + success?: boolean; + onlyIp?: boolean; +}): any { + Cache.init(); // will only initalize it once + + return async (req: Request, res: Response, next: NextFunction): Promise => { + const bucket_id = opts.bucket || req.originalUrl.replace(API_PREFIX_TRAILING_SLASH, ""); + var user_id = getIpAdress(req); + if (!opts.onlyIp && req.user_id) user_id = req.user_id; + + var max_hits = opts.count; + if (opts.bot && req.user_bot) max_hits = opts.bot; + if (opts.GET && ["GET", "OPTIONS", "HEAD"].includes(req.method)) max_hits = opts.GET; + else if (opts.MODIFY && ["POST", "DELETE", "PATCH", "PUT"].includes(req.method)) max_hits = opts.MODIFY; + + const offender = Cache.data?.find((x: Bucket) => x.user_id == user_id && x.id === bucket_id) as Bucket | null; + + if (offender && offender.blocked) { + const reset = offender.expires_at.getTime(); + const resetAfterMs = reset - Date.now(); + const resetAfterSec = resetAfterMs / 1000; + const global = bucket_id === "global"; + + if (resetAfterMs > 0) { + console.log("blocked bucket: " + bucket_id, { resetAfterMs }); + return ( + res + .status(429) + .set("X-RateLimit-Limit", `${max_hits}`) + .set("X-RateLimit-Remaining", "0") + .set("X-RateLimit-Reset", `${reset}`) + .set("X-RateLimit-Reset-After", `${resetAfterSec}`) + .set("X-RateLimit-Global", `${global}`) + .set("Retry-After", `${Math.ceil(resetAfterSec)}`) + .set("X-RateLimit-Bucket", `${bucket_id}`) + // TODO: error rate limit message translation + .send({ message: "You are being rate limited.", retry_after: resetAfterSec, global }) + ); + } else { + offender.hits = 0; + offender.expires_at = new Date(Date.now() + opts.window * 1000); + offender.blocked = false; + // mongodb ttl didn't update yet -> manually update/delete + db.collection("ratelimits").updateOne({ id: bucket_id, user_id }, { $set: offender }); + } + } + next(); + const hitRouteOpts = { bucket_id, user_id, max_hits, window: opts.window }; + + if (opts.error || opts.success) { + res.once("finish", () => { + // check if error and increment error rate limit + if (res.statusCode >= 400 && opts.error) { + return hitRoute(hitRouteOpts); + } else if (res.statusCode >= 200 && res.statusCode < 300 && opts.success) { + return hitRoute(hitRouteOpts); + } + }); + } else { + return hitRoute(hitRouteOpts); + } + }; +} + +export function initRateLimits(app: Router) { + const { routes, global, ip, error } = Config.get().limits.rate; + + app.use( + RateLimit({ + bucket: "global", + onlyIp: true, + ...ip + }) + ); + app.use(RateLimit({ bucket: "global", ...global })); + app.use( + RateLimit({ + bucket: "error", + error: true, + onlyIp: true, + ...error + }) + ); + app.use("/guilds/:id", RateLimit(routes.guild)); + app.use("/webhooks/:id", RateLimit(routes.webhook)); + app.use("/channels/:id", RateLimit(routes.channel)); + app.use("/auth/login", RateLimit(routes.auth.login)); + app.use("/auth/register", RateLimit({ onlyIp: true, success: true, ...routes.auth.register })); +} + +function hitRoute(opts: { user_id: string; bucket_id: string; max_hits: number; window: number }) { + return db.collection("ratelimits").updateOne( + { id: opts.bucket_id, user_id: opts.user_id }, + [ + { + $replaceRoot: { + newRoot: { + // similar to $setOnInsert + $mergeObjects: [ + { + id: opts.bucket_id, + user_id: opts.user_id, + expires_at: new Date(Date.now() + opts.window * 1000) + }, + "$$ROOT" + ] + } + } + }, + { + $set: { + hits: { $sum: [{ $ifNull: ["$hits", 0] }, 1] }, + blocked: { $gte: ["$hits", opts.max_hits] } + } + } + ], + { upsert: true } + ); +} diff --git a/api/src/middlewares/TestClient.ts b/api/src/middlewares/TestClient.ts new file mode 100644 index 00000000..4e3c9de3 --- /dev/null +++ b/api/src/middlewares/TestClient.ts @@ -0,0 +1,66 @@ +import bodyParser, { OptionsJson } from "body-parser"; +import express, { NextFunction, Request, Response, Application } from "express"; +import { HTTPError } from "lambert-server"; +import fs from "fs"; +import path from "path"; +import fetch, { Response as FetchResponse } from "node-fetch"; +import { Config } from "@fosscord/server-util"; + +export default function TestClient(app: Application) { + const assetCache = new Map(); + const indexHTML = fs.readFileSync(path.join(__dirname, "..", "..", "client_test", "index.html"), { encoding: "utf8" }); + + app.use("/assets", express.static(path.join(__dirname, "..", "assets"))); + + app.get("/assets/:file", async (req: Request, res: Response) => { + delete req.headers.host; + var response: FetchResponse; + var buffer: Buffer; + const cache = assetCache.get(req.params.file); + if (!cache) { + response = await fetch(`https://discord.com/assets/${req.params.file}`, { + // @ts-ignore + headers: { + ...req.headers + } + }); + buffer = await response.buffer(); + } else { + response = cache.response; + buffer = cache.buffer; + } + + response.headers.forEach((value, name) => { + if ( + [ + "content-length", + "content-security-policy", + "strict-transport-security", + "set-cookie", + "transfer-encoding", + "expect-ct", + "access-control-allow-origin", + "content-encoding" + ].includes(name.toLowerCase()) + ) { + return; + } + res.set(name, value); + }); + assetCache.set(req.params.file, { buffer, response }); + + return res.send(buffer); + }); + app.get("*", (req: Request, res: Response) => { + res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24); + res.set("content-type", "text/html"); + var html = indexHTML; + const CDN_ENDPOINT = (Config.get()?.cdn.endpoint || process.env.CDN || "").replace(/(https?)?(:\/\/?)/g, ""); + const GATEWAY_ENDPOINT = Config.get()?.gateway.endpoint || process.env.GATEWAY || ""; + + if (CDN_ENDPOINT) html = html.replace(/CDN_HOST: .+/, `CDN_HOST: "${CDN_ENDPOINT}",`); + if (GATEWAY_ENDPOINT) html = html.replace(/GATEWAY_ENDPOINT: .+/, `GATEWAY_ENDPOINT: "${GATEWAY_ENDPOINT}",`); + + res.send(html); + }); +} diff --git a/api/src/middlewares/index.ts b/api/src/middlewares/index.ts new file mode 100644 index 00000000..f0c50dbe --- /dev/null +++ b/api/src/middlewares/index.ts @@ -0,0 +1,5 @@ +export * from "./Authentication"; +export * from "./BodyParser"; +export * from "./CORS"; +export * from "./ErrorHandler"; +export * from "./RateLimit"; -- cgit 1.4.1