mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat(enterprise): add IP allowlisting with CIDR matching and Redis cache
Enterprise-gated onRequest hook that restricts API access to configured CIDR ranges using Node 22's native BlockList. - Plugin (ip-allowlist.ts): builds a BlockList from the ipAllowlist setting, caches in-process, syncs across instances via Redis pub/sub. Exempt paths for health probes, SCIM, SAML/OIDC callbacks. Handles IPv4-mapped IPv6 (::ffff:x.x.x.x) transparently. - Admin API (enterprise/ip-allowlist.ts): GET/PUT endpoints gated by security:manage permission and ip_allowlist feature flag. Validates CIDRs, prevents self-lockout, emits IP_ALLOWLIST_UPDATED audit event. - 32 unit tests covering CIDR matching, validation, exempt paths, IPv6, and edge cases (/0, /32, mapped addresses).
This commit is contained in:
@@ -293,6 +293,11 @@ await app.register(cookie, {
|
||||
hook: "onRequest",
|
||||
});
|
||||
|
||||
// IP allowlist (enterprise -- must run before auth to reject early)
|
||||
import { registerIpAllowlist } from "./plugins/ip-allowlist.js";
|
||||
|
||||
await registerIpAllowlist(app);
|
||||
|
||||
// Public config routes (no auth required)
|
||||
await configRoutes(app);
|
||||
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* Enterprise IP allowlist plugin.
|
||||
*
|
||||
* Registers an onRequest hook that checks whether the request IP falls
|
||||
* within any allowed CIDR range. Uses Node 22's built-in BlockList for
|
||||
* zero-dependency CIDR matching. The allowlist is cached in-process and
|
||||
* synchronized across instances via Redis pub/sub.
|
||||
*
|
||||
* Only active when the enterprise `ip_allowlist` feature is licensed.
|
||||
*/
|
||||
import { BlockList } from "node:net";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
|
||||
// Paths exempt from IP filtering -- infrastructure probes, IdP callbacks
|
||||
const EXEMPT_PATHS = [
|
||||
"/api/v1/health",
|
||||
"/api/v1/readyz",
|
||||
"/api/v1/metrics",
|
||||
"/api/v1/scim/", // SCIM from cloud IdPs
|
||||
"/api/auth/saml/callback", // SAML assertion POST
|
||||
"/api/auth/oidc/callback", // OIDC redirect
|
||||
];
|
||||
|
||||
function isExemptPath(url: string): boolean {
|
||||
return EXEMPT_PATHS.some((p) => url.startsWith(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an array of CIDR strings (or bare addresses) into a BlockList.
|
||||
* Returns null when the list is empty (meaning "allow all").
|
||||
*/
|
||||
export function buildBlockList(cidrs: string[]): BlockList | null {
|
||||
if (cidrs.length === 0) return null;
|
||||
const bl = new BlockList();
|
||||
for (const cidr of cidrs) {
|
||||
try {
|
||||
if (cidr.includes("/")) {
|
||||
const [addr, prefix] = cidr.split("/");
|
||||
bl.addSubnet(addr, Number(prefix), addr.includes(":") ? "ipv6" : "ipv4");
|
||||
} else {
|
||||
bl.addAddress(cidr, cidr.includes(":") ? "ipv6" : "ipv4");
|
||||
}
|
||||
} catch {
|
||||
// Invalid CIDR -- skip silently
|
||||
}
|
||||
}
|
||||
return bl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a single CIDR string (or bare IP).
|
||||
* Returns true when the string can be parsed without error.
|
||||
*/
|
||||
export function isValidCidr(cidr: string): boolean {
|
||||
try {
|
||||
const bl = new BlockList();
|
||||
if (cidr.includes("/")) {
|
||||
const [addr, prefix] = cidr.split("/");
|
||||
const prefixNum = Number(prefix);
|
||||
if (Number.isNaN(prefixNum) || prefixNum < 0) return false;
|
||||
const family = addr.includes(":") ? "ipv6" : "ipv4";
|
||||
if (family === "ipv4" && prefixNum > 32) return false;
|
||||
if (family === "ipv6" && prefixNum > 128) return false;
|
||||
bl.addSubnet(addr, prefixNum, family);
|
||||
} else {
|
||||
bl.addAddress(cidr, cidr.includes(":") ? "ipv6" : "ipv4");
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether an IP is covered by a BlockList (used as an allowlist).
|
||||
* Handles IPv4-mapped IPv6 addresses (::ffff:x.x.x.x) by extracting the
|
||||
* inner IPv4 address and checking both forms.
|
||||
*/
|
||||
export function isIpAllowed(ip: string, bl: BlockList): boolean {
|
||||
const family = ip.includes(":") ? "ipv6" : "ipv4";
|
||||
if (bl.check(ip, family)) return true;
|
||||
|
||||
// IPv4-mapped IPv6 -- also check the bare IPv4 portion
|
||||
if (ip.startsWith("::ffff:")) {
|
||||
const v4 = ip.slice(7);
|
||||
if (bl.check(v4, "ipv4")) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Re-export for tests
|
||||
export { EXEMPT_PATHS, isExemptPath };
|
||||
|
||||
const ALLOWLIST_KEY = "ip:allowlist";
|
||||
const ALLOWLIST_CHANNEL = "ip:allowlist:refresh";
|
||||
|
||||
export async function registerIpAllowlist(app: FastifyInstance): Promise<void> {
|
||||
// Only run if enterprise feature is enabled
|
||||
let isEnabled = false;
|
||||
try {
|
||||
const { isFeatureEnabled } = await import("@snapotter/enterprise");
|
||||
isEnabled = isFeatureEnabled("ip_allowlist");
|
||||
} catch {
|
||||
// Enterprise package not available
|
||||
}
|
||||
if (!isEnabled) return;
|
||||
|
||||
// Load allowlist from settings table
|
||||
async function loadAllowlist(): Promise<string[]> {
|
||||
const { getSettingString } = await import("../lib/settings-helpers.js");
|
||||
const raw = await getSettingString("ipAllowlist", "");
|
||||
if (!raw) return [];
|
||||
try {
|
||||
return JSON.parse(raw) as string[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Cache in-process
|
||||
const { sharedRedis } = await import("../jobs/connection.js");
|
||||
const redis = sharedRedis();
|
||||
|
||||
let cachedBlockList: BlockList | null = null;
|
||||
let cachedCidrs: string[] = [];
|
||||
|
||||
async function refreshAllowlist(): Promise<void> {
|
||||
const cidrs = await loadAllowlist();
|
||||
cachedCidrs = cidrs;
|
||||
cachedBlockList = buildBlockList(cidrs);
|
||||
// Mirror into Redis so other instances can bootstrap faster
|
||||
await redis.set(ALLOWLIST_KEY, JSON.stringify(cidrs));
|
||||
}
|
||||
|
||||
// Initial load
|
||||
await refreshAllowlist();
|
||||
|
||||
// Subscribe to refresh events from other instances
|
||||
const sub = redis.duplicate();
|
||||
await sub.subscribe(ALLOWLIST_CHANNEL);
|
||||
sub.on("message", async () => {
|
||||
await refreshAllowlist();
|
||||
});
|
||||
|
||||
// Hook -- runs before auth, before routes
|
||||
app.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
if (!cachedBlockList || cachedCidrs.length === 0) return; // No allowlist = allow all
|
||||
if (isExemptPath(request.url)) return;
|
||||
|
||||
const ip = request.ip;
|
||||
if (!isIpAllowed(ip, cachedBlockList)) {
|
||||
return reply.status(403).send({ error: "IP address not allowed" });
|
||||
}
|
||||
});
|
||||
|
||||
app.log.info(`IP allowlist active (${cachedCidrs.length} entries)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all instances to reload the IP allowlist from the DB.
|
||||
* Called by the admin API after updating the setting.
|
||||
*/
|
||||
export async function publishAllowlistRefresh(): Promise<void> {
|
||||
const { sharedRedis } = await import("../jobs/connection.js");
|
||||
const redis = sharedRedis();
|
||||
await redis.publish(ALLOWLIST_CHANNEL, "refresh");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { registerAuditExport } from "./audit-export.js";
|
||||
import { registerGdprRoutes } from "./gdpr.js";
|
||||
import { registerIpAllowlistRoutes } from "./ip-allowlist.js";
|
||||
import { registerLegalHoldRoutes } from "./legal-hold.js";
|
||||
import { registerScimRoutes } from "./scim.js";
|
||||
import { registerSiemRoutes } from "./siem.js";
|
||||
@@ -8,6 +9,7 @@ import { registerSiemRoutes } from "./siem.js";
|
||||
export async function registerEnterpriseRoutes(app: FastifyInstance) {
|
||||
await registerAuditExport(app);
|
||||
await registerGdprRoutes(app);
|
||||
await registerIpAllowlistRoutes(app);
|
||||
await registerLegalHoldRoutes(app);
|
||||
await registerScimRoutes(app);
|
||||
await registerSiemRoutes(app);
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Admin API for managing the enterprise IP allowlist.
|
||||
*
|
||||
* GET /api/v1/enterprise/ip-allowlist -- current list
|
||||
* PUT /api/v1/enterprise/ip-allowlist -- update (with self-lockout prevention)
|
||||
*/
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { db, schema } from "../../db/index.js";
|
||||
import { auditFromRequest } from "../../lib/audit.js";
|
||||
import { requirePermission } from "../../permissions.js";
|
||||
import { isValidCidr, publishAllowlistRefresh } from "../../plugins/ip-allowlist.js";
|
||||
|
||||
const SETTINGS_KEY = "ipAllowlist";
|
||||
|
||||
const updateSchema = z.object({
|
||||
cidrs: z.array(z.string().min(1).max(45)).max(1000),
|
||||
});
|
||||
|
||||
export async function registerIpAllowlistRoutes(app: FastifyInstance): Promise<void> {
|
||||
// GET /api/v1/enterprise/ip-allowlist
|
||||
app.get(
|
||||
"/api/v1/enterprise/ip-allowlist",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = await requirePermission("security:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
// Enterprise feature gate
|
||||
let featureEnabled = false;
|
||||
try {
|
||||
const { isFeatureEnabled } = await import("@snapotter/enterprise");
|
||||
featureEnabled = isFeatureEnabled("ip_allowlist");
|
||||
} catch {
|
||||
// Enterprise package not available
|
||||
}
|
||||
if (!featureEnabled) {
|
||||
return reply.status(403).send({
|
||||
error: "IP allowlisting requires an enterprise license with the ip_allowlist feature",
|
||||
});
|
||||
}
|
||||
|
||||
const [row] = await db
|
||||
.select({ value: schema.settings.value })
|
||||
.from(schema.settings)
|
||||
.where(eq(schema.settings.key, SETTINGS_KEY));
|
||||
|
||||
const cidrs = row ? (JSON.parse(row.value) as string[]) : [];
|
||||
return reply.send({ cidrs });
|
||||
},
|
||||
);
|
||||
|
||||
// PUT /api/v1/enterprise/ip-allowlist
|
||||
app.put(
|
||||
"/api/v1/enterprise/ip-allowlist",
|
||||
async (request: FastifyRequest<{ Body: unknown }>, reply: FastifyReply) => {
|
||||
const user = await requirePermission("security:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
// Enterprise feature gate
|
||||
let featureEnabled = false;
|
||||
try {
|
||||
const { isFeatureEnabled } = await import("@snapotter/enterprise");
|
||||
featureEnabled = isFeatureEnabled("ip_allowlist");
|
||||
} catch {
|
||||
// Enterprise package not available
|
||||
}
|
||||
if (!featureEnabled) {
|
||||
return reply.status(403).send({
|
||||
error: "IP allowlisting requires an enterprise license with the ip_allowlist feature",
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = updateSchema.safeParse(request.body);
|
||||
if (!parsed.success) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Invalid request body", details: parsed.error.issues });
|
||||
}
|
||||
|
||||
const { cidrs } = parsed.data;
|
||||
|
||||
// Validate each CIDR entry
|
||||
const invalid = cidrs.filter((c) => !isValidCidr(c));
|
||||
if (invalid.length > 0) {
|
||||
return reply.status(400).send({
|
||||
error: `Invalid CIDR entries: ${invalid.join(", ")}`,
|
||||
code: "INVALID_CIDR",
|
||||
});
|
||||
}
|
||||
|
||||
// Self-lockout prevention: if the new list is non-empty, ensure the
|
||||
// admin's current IP would still be allowed.
|
||||
if (cidrs.length > 0) {
|
||||
const { buildBlockList, isIpAllowed } = await import("../../plugins/ip-allowlist.js");
|
||||
const bl = buildBlockList(cidrs);
|
||||
if (bl && !isIpAllowed(request.ip, bl)) {
|
||||
return reply.status(400).send({
|
||||
error: `Your current IP (${request.ip}) would be blocked by this allowlist. Add it before saving.`,
|
||||
code: "SELF_LOCKOUT",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Persist
|
||||
const value = JSON.stringify(cidrs);
|
||||
const now = new Date();
|
||||
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(schema.settings)
|
||||
.where(eq(schema.settings.key, SETTINGS_KEY));
|
||||
|
||||
if (existing) {
|
||||
await db
|
||||
.update(schema.settings)
|
||||
.set({ value, updatedAt: now })
|
||||
.where(eq(schema.settings.key, SETTINGS_KEY));
|
||||
} else {
|
||||
await db.insert(schema.settings).values({ key: SETTINGS_KEY, value });
|
||||
}
|
||||
|
||||
// Notify all instances to reload
|
||||
await publishAllowlistRefresh();
|
||||
|
||||
await auditFromRequest(request)("IP_ALLOWLIST_UPDATED", {
|
||||
adminId: user.id,
|
||||
username: user.username,
|
||||
count: cidrs.length,
|
||||
});
|
||||
|
||||
return reply.send({ ok: true, count: cidrs.length });
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user