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:
SnapOtter
2026-06-13 22:54:06 +08:00
parent 1787be35fe
commit db6f7bf38a
5 changed files with 503 additions and 0 deletions
+2
View File
@@ -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 });
},
);
}