pub struct TrustedProxies { /* private fields */ }Available on crate feature
iputil only.Expand description
“可信代理网段 + 该边缘设置的客户端 IP 头“组合, 供鉴权、限流、封禁等安全决策取客户端 IP。
构造时必须显式声明部署边缘会强制覆盖的头 (Cloudflare 的 CF-Connecting-IP、
EdgeOne 的 EO-Client-IP、自建 nginx 明确 set 的 X-Real-IP, 或 X-Forwarded-For)。
不提供“来源可信就信任所有厂商头“的模式: 代理 / CDN 会透传客户端伪造的其它厂商头。
启动时构建一次, 之后可在多线程间共享 (Send + Sync)。
Implementations§
Source§impl TrustedProxies
impl TrustedProxies
Sourcepub fn new<I, S>(trusted_header: &str, cidrs: I) -> Result<Self, Error>
pub fn new<I, S>(trusted_header: &str, cidrs: I) -> Result<Self, Error>
构建可信代理集合。
trusted_header 为部署边缘强制覆盖的客户端 IP 头, 不能为空;
cidrs 支持 CIDR (如 10.0.0.0/8) 或单个 IP (按 /32、/128 处理),
空白条目忽略, 任一条目非法即返回错误, 不静默跳过; 至少要有一个网段。
Sourcepub fn contains_ip(&self, ip: IpAddr) -> bool
pub fn contains_ip(&self, ip: IpAddr) -> bool
判断 IP 是否落在可信网段内 (IPv4 映射地址按 IPv4 判断)
Sourcepub fn client_ip(&self, headers: &HeaderMap, remote: IpAddr) -> IpAddr
pub fn client_ip(&self, headers: &HeaderMap, remote: IpAddr) -> IpAddr
带信任边界校验地获取客户端 IP; 结果已规范化 (IPv4 映射地址转为 IPv4), 可直接作为限流 / 封禁的键:
- 直连来源不在可信网段: 忽略一切转发头, 返回直连 IP
- 可信头为
X-Forwarded-For: 从右往左跳过可信网段条目, 返回第一个不可信的合法 IP; 链上全部可信时返回最左侧合法 IP (内部设施互调), 无合法条目时返回直连 IP - 其它可信头: 返回该头的值 (自动去端口), 缺失或不是合法 IP 时返回直连 IP
Sourcepub fn client_ip_from_request<B>(&self, req: &Request<B>) -> Option<IpAddr>
pub fn client_ip_from_request<B>(&self, req: &Request<B>) -> Option<IpAddr>
TrustedProxies::client_ip 的请求版: 直连地址从请求扩展读取
(见 remote_ip); 读不到直连地址时返回 None
Trait Implementations§
Source§impl Clone for TrustedProxies
impl Clone for TrustedProxies
Auto Trait Implementations§
impl !Freeze for TrustedProxies
impl Forget for TrustedProxies
impl Move for TrustedProxies
impl RefUnwindSafe for TrustedProxies
impl Send for TrustedProxies
impl Sync for TrustedProxies
impl Unpin for TrustedProxies
impl UnsafeUnpin for TrustedProxieswhere
*const u8 is !null: UnsafeUnpin,
PhantomData<IpNet>: UnsafeUnpin,
*const u8: UnsafeUnpin,
Align8<*mut ()>: UnsafeUnpin,
&'static Vtable: UnsafeUnpin,
impl UnwindSafe for TrustedProxieswhere
RawVecInner: UnwindSafe,
*const u8: UnwindSafe,
Align8<*mut ()>: UnwindSafe,
&'static Vtable: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more