feat: add IP filter middleware (#3035)
Closes #3011 --------- Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Bartek Iwańczuk
Claude Opus 4.6
parent
e0ee53d458
commit
566a6ce5e4
@@ -0,0 +1,124 @@
|
||||
import type { Context } from "../context.ts";
|
||||
import type { Middleware } from "./mod.ts";
|
||||
import { isIPv4, matchSubnets } from "@std/net/unstable-ip";
|
||||
|
||||
/**
|
||||
* Configuration rules for IP restriction middleware.
|
||||
*/
|
||||
export interface IpFilterRules {
|
||||
/**
|
||||
* List of IP addresses or CIDR blocks to deny access.
|
||||
* If an IP matches any entry in this list, access will be blocked.
|
||||
*
|
||||
* @example ["192.168.1.10", "10.0.0.0/8", "2001:db8::1"]
|
||||
*/
|
||||
denyList?: string[];
|
||||
|
||||
/**
|
||||
* List of IP addresses or CIDR blocks to allow access.
|
||||
* If specified, only IPs matching entries in this list will be allowed.
|
||||
* If empty or undefined, all IPs are allowed (unless in denyList).
|
||||
*
|
||||
* @example ["192.168.1.0/24", "203.0.113.0/24", "2001:db8::/32"]
|
||||
*/
|
||||
allowList?: string[];
|
||||
}
|
||||
|
||||
export interface IpFilterOptions {
|
||||
/**
|
||||
* Called when a request is blocked by the IP filter.
|
||||
*
|
||||
* The function receives the remote information and the current request
|
||||
* context and should return a Response (or a Promise resolving to one)
|
||||
* which will be sent back to the client. If not provided, a default
|
||||
* 403 Forbidden response will be used.
|
||||
*
|
||||
* Parameters:
|
||||
* - `remote.addr` - the remote IP address as a string.
|
||||
* - `remote.type` - the network family: "IPv4" or "IPv6".
|
||||
* - `ctx` - the request `Context` which can be used to inspect the
|
||||
* request or produce a custom response.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const options: IpFilterOptions = {
|
||||
* onBlocked: (remote, ctx) => {
|
||||
* console.log(`Blocked ${remote.addr} (${remote.type})`, ctx.url);
|
||||
* return new Response("Access denied", { status: 401 });
|
||||
* },
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
onBlocked?: <State>(
|
||||
remote: {
|
||||
addr: string;
|
||||
type: Deno.NetworkInterfaceInfo["family"];
|
||||
},
|
||||
ctx: Context<State>,
|
||||
) => Response | Promise<Response>;
|
||||
}
|
||||
|
||||
/**
|
||||
* IP restriction Middleware for Fresh.
|
||||
*
|
||||
* @param rules Deny and allow rules object.
|
||||
* @param options Options for the IP Restriction middleware.
|
||||
* @returns The middleware handler function.
|
||||
*
|
||||
* Filters rule priority is denyList, then allowList.
|
||||
* If an IP is in the denyList, it will be blocked regardless of the allowList.
|
||||
*
|
||||
* @example Basic usage (with defaults)
|
||||
* ```ts
|
||||
* const app = new App<State>()
|
||||
*
|
||||
* app.use(ipFilter({
|
||||
* denyList: ["192.168.1.10", "2001:db8::1"]
|
||||
* }));
|
||||
* ```
|
||||
*
|
||||
* @example Custom blocked handler
|
||||
* ```ts
|
||||
* app.use(ipFilter({
|
||||
* denyList: ["192.168.1.10", "2001:db8::1"]
|
||||
* }, {
|
||||
* onBlocked: (remote, ctx) => {
|
||||
* console.log(
|
||||
* `Request URL: ${ctx.url}, Blocked IP: ${remote.addr} of type ${remote.type}`,
|
||||
* );
|
||||
* return new Response("Access denied", { status: 401 });
|
||||
* },
|
||||
* }));
|
||||
* ```
|
||||
*/
|
||||
export function ipFilter<State>(
|
||||
rules: IpFilterRules,
|
||||
options?: IpFilterOptions,
|
||||
): Middleware<State> {
|
||||
const onBlock = options?.onBlocked ??
|
||||
(() => new Response("Forbidden", { status: 403 }));
|
||||
return function ipFilter<State>(ctx: Context<State>) {
|
||||
if (
|
||||
ctx.info.remoteAddr.transport !== "udp" &&
|
||||
ctx.info.remoteAddr.transport !== "tcp"
|
||||
) {
|
||||
return ctx.next();
|
||||
}
|
||||
|
||||
const addr = ctx.info.remoteAddr.hostname;
|
||||
const type = isIPv4(addr) ? "IPv4" : "IPv6";
|
||||
|
||||
if (matchSubnets(addr, rules.denyList || [])) {
|
||||
return onBlock({ addr, type }, ctx);
|
||||
}
|
||||
|
||||
if (
|
||||
(rules.allowList || []).length === 0 ||
|
||||
matchSubnets(addr, rules.allowList || [])
|
||||
) {
|
||||
return ctx.next();
|
||||
}
|
||||
|
||||
return onBlock({ addr, type }, ctx);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { App } from "../app.ts";
|
||||
import type { Context } from "../context.ts";
|
||||
import {
|
||||
ipFilter,
|
||||
type IpFilterOptions,
|
||||
type IpFilterRules,
|
||||
} from "./ip_filter.ts";
|
||||
import { expect } from "@std/expect";
|
||||
|
||||
function testHandler<T>(
|
||||
remoteAddr: string,
|
||||
ipFilterRules: IpFilterRules,
|
||||
options?: IpFilterOptions,
|
||||
): (request: Request) => Promise<Response> {
|
||||
function remoteHostOverride(ctx: Context<T>) {
|
||||
(ctx.info.remoteAddr as { hostname: string }).hostname = remoteAddr;
|
||||
return ctx.next();
|
||||
}
|
||||
|
||||
return new App<T>()
|
||||
.use(remoteHostOverride)
|
||||
.use(ipFilter(ipFilterRules, options))
|
||||
.all("/", () => new Response("hello"))
|
||||
.handler();
|
||||
}
|
||||
|
||||
async function createTest(
|
||||
addr: string,
|
||||
ipFilterRules: IpFilterRules,
|
||||
options?: IpFilterOptions,
|
||||
): Promise<number> {
|
||||
const handler = testHandler(addr, ipFilterRules, options);
|
||||
|
||||
const res = await handler(new Request("https://localhost/"));
|
||||
|
||||
return res.status;
|
||||
}
|
||||
|
||||
Deno.test("ipFilter - no option", async () => {
|
||||
expect(await createTest("192.168.1.10", {})).toBe(200);
|
||||
});
|
||||
Deno.test("ipFilter - deny only", async () => {
|
||||
const ipFilterRules = {
|
||||
denyList: ["192.168.1.10", "2001:db8::1"],
|
||||
};
|
||||
|
||||
expect(await createTest("192.168.1.10", ipFilterRules)).toBe(403);
|
||||
expect(await createTest("192.168.1.11", ipFilterRules)).toBe(200);
|
||||
expect(await createTest("2001:db8::1", ipFilterRules)).toBe(403);
|
||||
expect(await createTest("2001:db8::2", ipFilterRules)).toBe(200);
|
||||
});
|
||||
|
||||
Deno.test("ipFilter - allow only", async () => {
|
||||
const ipFilterRules = {
|
||||
allowList: ["192.168.1.10", "2001:db8::1"],
|
||||
};
|
||||
expect(await createTest("192.168.1.10", ipFilterRules)).toBe(200);
|
||||
expect(await createTest("192.168.1.11", ipFilterRules)).toBe(403);
|
||||
expect(await createTest("2001:db8::1", ipFilterRules)).toBe(200);
|
||||
expect(await createTest("2001:db8::2", ipFilterRules)).toBe(403);
|
||||
});
|
||||
|
||||
// When both allow and deny are set, deny takes precedence
|
||||
Deno.test("ipFilter - allow and deny", async () => {
|
||||
const ipFilterRules = {
|
||||
denyList: ["192.168.1.10", "2001:db8::1"],
|
||||
allowList: ["192.168.1.10", "2001:db8::1"],
|
||||
};
|
||||
expect(await createTest("192.168.1.10", ipFilterRules)).toBe(403);
|
||||
expect(await createTest("2001:db8::1", ipFilterRules)).toBe(403);
|
||||
});
|
||||
|
||||
Deno.test("ipFilter - subnet mask", async () => {
|
||||
const ipFilterRules = {
|
||||
denyList: ["192.168.1.0/24"],
|
||||
};
|
||||
expect(await createTest("192.168.1.10", ipFilterRules)).toBe(403);
|
||||
});
|
||||
|
||||
Deno.test("ipFilter - custom onBlocked", async () => {
|
||||
const ipFilterRules = {
|
||||
denyList: ["192.168.1.0/24"],
|
||||
};
|
||||
|
||||
const options: IpFilterOptions = {
|
||||
onBlocked: () => {
|
||||
return new Response("custom blocked", { status: 401 });
|
||||
},
|
||||
};
|
||||
|
||||
expect(await createTest("192.168.1.10", ipFilterRules, options))
|
||||
.toBe(401);
|
||||
});
|
||||
@@ -13,6 +13,11 @@ export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
|
||||
export { staticFiles } from "./middlewares/static_files.ts";
|
||||
export { csrf, type CsrfOptions } from "./middlewares/csrf.ts";
|
||||
export { cors, type CORSOptions } from "./middlewares/cors.ts";
|
||||
export {
|
||||
ipFilter,
|
||||
type IpFilterOptions,
|
||||
type IpFilterRules,
|
||||
} from "./middlewares/ip_filter.ts";
|
||||
export { csp, type CSPOptions } from "./middlewares/csp.ts";
|
||||
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||
export type { Context, FreshContext, Island } from "./context.ts";
|
||||
|
||||
Reference in New Issue
Block a user