CIDR allowlist middleware using netip (trust boundary explicit)

9438
0

For internal admin endpoints, I often add a network allowlist in addition to auth. The tricky part is deciding which IP to trust: if you’re behind a proxy, you might need X-Forwarded-For, but only if the proxy is controlled by you. The middleware below parses CIDRs into netip.Prefix and checks whether the client address falls inside. I keep the allowlist immutable and fail closed: if the IP can’t be parsed, access is denied. In production, I also log denials with a request ID so you can debug misconfigured proxies without printing sensitive headers. The key is to treat this as a defense-in-depth layer, not your only protection.