adler_core/access.rs
1//! Per-site access policy and the egress (proxy) model.
2//!
3//! Access-engine phase 3: route the raw-HTTP probe path through a
4//! geo / IP-type-appropriate egress. A site declares what it needs via
5//! [`AccessPolicy`] (e.g. "only reachable from a Polish residential
6//! IP"); the client matches that against a configured pool of
7//! [`EgressSpec`]s. If the policy is unconstrained the request uses the
8//! client's default egress (direct, or the global `--proxy`); if it's
9//! constrained but nothing in the pool fits, the probe is reported as
10//! `Uncertain(GeoUnavailable)` — **never** a false `NotFound`, since
11//! "couldn't reach from the required location" is not "account absent".
12//!
13//! The browser transport keeps its backend's own egress; this phase
14//! routes the HTTP path only.
15
16use std::collections::{BTreeMap, HashMap};
17use std::fmt;
18use std::sync::Arc;
19
20use serde::{Deserialize, Serialize};
21
22use crate::transport::HttpFetcher;
23
24/// ISO-3166-1 alpha-2 country code, stored lowercased (e.g. `pl`, `de`).
25/// A newtype so a geo requirement can't be confused with an arbitrary
26/// string and is validated at the boundary.
27#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
28#[serde(try_from = "String", into = "String")]
29pub struct CountryCode([u8; 2]);
30
31impl CountryCode {
32 /// Parse a two-letter code, lowercasing ASCII. `None` for anything
33 /// that isn't exactly two ASCII letters.
34 #[must_use]
35 pub fn new(s: &str) -> Option<Self> {
36 let b = s.as_bytes();
37 if b.len() == 2 && b[0].is_ascii_alphabetic() && b[1].is_ascii_alphabetic() {
38 Some(Self([b[0].to_ascii_lowercase(), b[1].to_ascii_lowercase()]))
39 } else {
40 None
41 }
42 }
43
44 /// The lowercased two-letter code.
45 #[must_use]
46 pub fn as_str(&self) -> &str {
47 // Constructed only from ASCII letters, so this is always valid.
48 std::str::from_utf8(&self.0).unwrap_or("??")
49 }
50}
51
52impl TryFrom<String> for CountryCode {
53 type Error = String;
54 fn try_from(s: String) -> Result<Self, Self::Error> {
55 Self::new(&s).ok_or_else(|| format!("invalid country code: {s:?}"))
56 }
57}
58
59impl From<CountryCode> for String {
60 fn from(c: CountryCode) -> Self {
61 c.as_str().to_owned()
62 }
63}
64
65/// The kind of network an egress exits from.
66///
67/// A site's `ip_type` requirement is matched against this. (`Direct`
68/// isn't a kind here — the unproxied default egress is selected by an
69/// *unconstrained* policy, not by requesting a kind.)
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "kebab-case")]
72#[non_exhaustive]
73pub enum EgressKind {
74 /// A datacenter / hosting-provider IP (cheap, easily fingerprinted
75 /// and blocked). The default when a config entry omits `kind`.
76 #[default]
77 Datacenter,
78 /// A residential ISP IP (harder to block; what most "real users"
79 /// look like).
80 Residential,
81 /// A mobile-carrier IP (shared CGNAT ranges; highest trust on many
82 /// sites).
83 Mobile,
84 /// A Tor exit node.
85 Tor,
86}
87
88/// A configured egress (proxy) the client can route through.
89///
90/// Produced from CLI / config; the live client pairs each spec with its
91/// own HTTP client (reqwest bakes the proxy in at build time).
92/// Deserialises from the `[[egress]]` entries of a proxy-pool config
93/// file.
94#[derive(Debug, Clone, Deserialize)]
95pub struct EgressSpec {
96 /// Proxy URL — `http://`, `https://`, `socks5://`, or `socks5h://`.
97 pub url: String,
98 /// Country this egress exits from, if known.
99 #[serde(default)]
100 pub country: Option<CountryCode>,
101 /// Network kind this egress exits from (defaults to `datacenter`).
102 #[serde(default)]
103 pub kind: EgressKind,
104 /// Operator-supplied identifier for this egress — used by the web
105 /// UI's per-scan egress subset selection (and by any other call
106 /// site that needs to refer to a specific egress by stable name).
107 /// Optional: an unnamed egress still participates in policy-based
108 /// matching, it just can't be selected by name.
109 #[serde(default)]
110 pub name: Option<String>,
111}
112
113/// What a site needs from its egress. The default (empty) means "no
114/// special routing" — the request uses the client's default egress.
115///
116/// Two flavours of geo constraint co-exist:
117///
118/// - [`geo`](Self::geo) — **hard**. A site that won't answer from
119/// anywhere else (e.g. a country-locked profile). No matching egress
120/// in the pool → `Uncertain(GeoUnavailable)`, never a false `NotFound`.
121/// - [`prefer_geo`](Self::prefer_geo) — **soft**. A site that *prefers*
122/// a local egress (better recall, less aggressive bot filtering) but
123/// still works from anywhere. No matching egress → fall back to the
124/// default egress and probe normally. Auto-populated at registry-load
125/// time from `region:XX` tags when the site doesn't already declare
126/// a hard `geo` constraint.
127#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
128pub struct AccessPolicy {
129 /// Require an egress in one of these countries.
130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
131 pub geo: Vec<CountryCode>,
132 /// Prefer an egress in one of these countries — fall back to the
133 /// default if the pool has no match. Soft counterpart to [`geo`].
134 #[serde(default, skip_serializing_if = "Vec::is_empty")]
135 pub prefer_geo: Vec<CountryCode>,
136 /// Require an egress of this network kind.
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub ip_type: Option<EgressKind>,
139 /// Name of an operator-supplied session (see `--sessions`) whose
140 /// headers (cookies / auth tokens) this site's probes must carry.
141 /// The site is unreachable without it, so a missing session yields
142 /// `Uncertain(SessionRequired)` rather than a login-wall false
143 /// `NotFound`.
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub session: Option<String>,
146}
147
148impl AccessPolicy {
149 /// True when the policy imposes no constraint at all (the common
150 /// case). Drives `skip_serializing_if` so existing `sites.json`
151 /// entries serialise unchanged.
152 #[must_use]
153 pub fn is_default(&self) -> bool {
154 self.geo.is_empty()
155 && self.prefer_geo.is_empty()
156 && self.ip_type.is_none()
157 && self.session.is_none()
158 }
159}
160
161/// An operator-supplied authenticated session for a site: a bag of HTTP
162/// headers (typically `Cookie`, sometimes `Authorization` / CSRF
163/// tokens) applied to probes for sites whose `access.session` names it.
164///
165/// This is "use a real account", not evasion — the operator brings a
166/// session they're entitled to. Header *values* are secrets: they're
167/// redacted from `Debug` and are never logged or serialised.
168#[derive(Clone, Default)]
169pub struct Session {
170 headers: BTreeMap<String, String>,
171}
172
173impl Session {
174 /// Build a session from plain header name→value pairs (e.g. parsed
175 /// from a `--sessions` config file).
176 #[must_use]
177 pub fn from_headers(headers: BTreeMap<String, String>) -> Self {
178 Self { headers }
179 }
180
181 /// Merge this session's headers over `base` (the session wins on
182 /// conflict), producing the header set for the outgoing request.
183 pub(crate) fn apply(&self, base: &BTreeMap<String, String>) -> BTreeMap<String, String> {
184 let mut out = base.clone();
185 for (k, v) in &self.headers {
186 out.insert(k.clone(), v.clone());
187 }
188 out
189 }
190}
191
192impl fmt::Debug for Session {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 // Redact values — session headers carry cookies / tokens.
195 f.debug_struct("Session")
196 .field("headers", &self.headers.keys().collect::<Vec<_>>())
197 .finish_non_exhaustive()
198 }
199}
200
201/// Named-session store, indexed by the name a site references via
202/// `access.session`. Empty by default → a no-op.
203#[derive(Clone, Default, Debug)]
204pub struct SessionStore {
205 sessions: HashMap<String, Session>,
206}
207
208impl SessionStore {
209 /// An empty store.
210 #[must_use]
211 pub fn new() -> Self {
212 Self::default()
213 }
214
215 /// Insert (or replace) a named session.
216 pub fn insert(&mut self, name: impl Into<String>, session: Session) {
217 self.sessions.insert(name.into(), session);
218 }
219
220 /// True when no session is configured.
221 #[must_use]
222 pub fn is_empty(&self) -> bool {
223 self.sessions.is_empty()
224 }
225
226 /// Number of configured sessions.
227 #[must_use]
228 pub fn len(&self) -> usize {
229 self.sessions.len()
230 }
231
232 pub(crate) fn get(&self, name: &str) -> Option<&Session> {
233 self.sessions.get(name)
234 }
235
236 /// Names of the configured sessions, sorted lexicographically for a
237 /// stable display order. Values stay private — by design the public
238 /// surface only ever leaks the keys an operator referenced via
239 /// `access.session`, never the cookie/token bytes themselves.
240 #[must_use]
241 pub fn names(&self) -> Vec<String> {
242 let mut names: Vec<String> = self.sessions.keys().cloned().collect();
243 names.sort();
244 names
245 }
246}
247
248/// Read-only metadata for one configured egress, surfaced via
249/// [`Client::egress_summary`](crate::Client::egress_summary).
250///
251/// Carries only the match-relevant facets (name + country + kind); the
252/// proxy URL is *deliberately omitted* — those typically embed
253/// credentials (`socks5://user:pass@host:1080`) that have no business
254/// landing in a JSON response served to a browser.
255#[derive(Debug, Clone, Serialize)]
256pub struct EgressSummary {
257 /// Operator-supplied name, if any. Used by per-scan egress subset
258 /// selection (`POST /api/scan` with `egress_names`).
259 #[serde(skip_serializing_if = "Option::is_none")]
260 pub name: Option<String>,
261 /// Country this egress exits from, if declared.
262 #[serde(skip_serializing_if = "Option::is_none")]
263 pub country: Option<CountryCode>,
264 /// Network kind (`datacenter` / `residential` / `mobile` / `tor`).
265 pub kind: EgressKind,
266}
267
268/// One built egress: its match metadata plus the HTTP client that
269/// routes through it.
270struct EgressEntry {
271 name: Option<String>,
272 country: Option<CountryCode>,
273 kind: EgressKind,
274 fetcher: Arc<HttpFetcher>,
275}
276
277/// Runtime pool of built egresses. Empty by default → every site uses
278/// the client's default egress, so an empty pool is a no-op.
279pub(crate) struct EgressPool {
280 entries: Vec<EgressEntry>,
281}
282
283/// Result of matching a site's [`AccessPolicy`] against the pool.
284pub(crate) enum EgressChoice {
285 /// Unconstrained policy → use the client's default egress.
286 Default,
287 /// Route through this egress's HTTP client.
288 Use(Arc<HttpFetcher>),
289 /// Constrained policy with no matching egress → honest
290 /// `Uncertain(GeoUnavailable)` rather than a false `NotFound`.
291 Unavailable,
292}
293
294/// Constructor tuple for [`EgressPool`]: one row per configured proxy
295/// carries its operator-supplied `name` (if any), its country and
296/// kind, and the already-built `reqwest`-backed fetcher.
297pub(crate) type EgressEntryTuple = (
298 Option<String>,
299 Option<CountryCode>,
300 EgressKind,
301 Arc<HttpFetcher>,
302);
303
304impl EgressPool {
305 pub(crate) fn new(entries: Vec<EgressEntryTuple>) -> Self {
306 Self {
307 entries: entries
308 .into_iter()
309 .map(|(name, country, kind, fetcher)| EgressEntry {
310 name,
311 country,
312 kind,
313 fetcher,
314 })
315 .collect(),
316 }
317 }
318
319 /// Read-only view of the pool — `(name, country, kind)` for every
320 /// configured egress, in the order they were registered. Used by the
321 /// `GET /api/access` endpoint so the SPA can show what's configured
322 /// without ever touching proxy URLs.
323 pub(crate) fn summary(&self) -> Vec<EgressSummary> {
324 self.entries
325 .iter()
326 .map(|e| EgressSummary {
327 name: e.name.clone(),
328 country: e.country.clone(),
329 kind: e.kind,
330 })
331 .collect()
332 }
333
334 /// Return a new pool containing only entries whose `name` matches
335 /// one of `names`. Entries without a name are excluded (they can't
336 /// be referenced by name). `names` being empty is treated as "no
337 /// filter" and a clone of the full pool is returned — that
338 /// preserves the policy-driven default for callers who didn't ask
339 /// for an explicit subset.
340 pub(crate) fn subset(&self, names: &[String]) -> Self {
341 if names.is_empty() {
342 return Self {
343 entries: self
344 .entries
345 .iter()
346 .map(|e| EgressEntry {
347 name: e.name.clone(),
348 country: e.country.clone(),
349 kind: e.kind,
350 fetcher: Arc::clone(&e.fetcher),
351 })
352 .collect(),
353 };
354 }
355 let wanted: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
356 Self {
357 entries: self
358 .entries
359 .iter()
360 .filter(|e| e.name.as_deref().is_some_and(|n| wanted.contains(n)))
361 .map(|e| EgressEntry {
362 name: e.name.clone(),
363 country: e.country.clone(),
364 kind: e.kind,
365 fetcher: Arc::clone(&e.fetcher),
366 })
367 .collect(),
368 }
369 }
370
371 /// Names of egresses configured in this pool, in registration
372 /// order. Used by the server to validate `egress_names` on
373 /// `POST /api/scan`.
374 pub(crate) fn names(&self) -> Vec<String> {
375 self.entries.iter().filter_map(|e| e.name.clone()).collect()
376 }
377
378 /// Pick an egress for `policy`. Three outcomes:
379 ///
380 /// - Unconstrained policy (no hard `geo`, no `prefer_geo`, no
381 /// `ip_type`) → [`EgressChoice::Default`].
382 /// - Hard constraint with no match → [`EgressChoice::Unavailable`].
383 /// - Soft `prefer_geo` with no match → falls back to
384 /// [`EgressChoice::Default`] (the probe still happens, just via
385 /// the unproxied / default egress).
386 pub(crate) fn select(&self, policy: &AccessPolicy) -> EgressChoice {
387 // Session-only policy (no geo / no ip_type / no prefer_geo) →
388 // default egress.
389 if policy.geo.is_empty() && policy.prefer_geo.is_empty() && policy.ip_type.is_none() {
390 return EgressChoice::Default;
391 }
392
393 // Hard path: explicit `geo` (and optional `ip_type`) — when
394 // present, this is authoritative and prefer_geo is ignored.
395 if !policy.geo.is_empty() {
396 return self
397 .pick_matching(&policy.geo, policy.ip_type)
398 .map_or(EgressChoice::Unavailable, EgressChoice::Use);
399 }
400
401 // Soft path: only `prefer_geo` (and optional `ip_type`). Match
402 // → route through it; no match → fall back to the default
403 // egress rather than emit Unavailable. The site is *expected*
404 // to be reachable from anywhere; the egress preference is a
405 // recall optimisation, not a correctness constraint.
406 if !policy.prefer_geo.is_empty() {
407 return self
408 .pick_matching(&policy.prefer_geo, policy.ip_type)
409 .map_or(EgressChoice::Default, EgressChoice::Use);
410 }
411
412 // Only `ip_type` constrained — keep the hard semantics: a site
413 // that asks for a residential IP and the pool has none is
414 // Unavailable, not silently downgraded to datacenter.
415 self.pick_matching(&[], policy.ip_type)
416 .map_or(EgressChoice::Unavailable, EgressChoice::Use)
417 }
418
419 /// Internal: pick a random matching entry for the given geo and
420 /// optional `ip_type`. `geo` empty means "any country". Returns
421 /// `None` when nothing fits.
422 fn pick_matching(
423 &self,
424 geo: &[CountryCode],
425 ip_type: Option<EgressKind>,
426 ) -> Option<Arc<HttpFetcher>> {
427 let matches: Vec<&EgressEntry> = self
428 .entries
429 .iter()
430 .filter(|e| {
431 let geo_ok = geo.is_empty() || e.country.as_ref().is_some_and(|c| geo.contains(c));
432 let kind_ok = ip_type.is_none_or(|k| e.kind == k);
433 geo_ok && kind_ok
434 })
435 .collect();
436 match matches.len() {
437 0 => None,
438 n => Some(Arc::clone(&matches[fastrand::usize(0..n)].fetcher)),
439 }
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use crate::transport::HttpFetcher;
447
448 fn cc(s: &str) -> CountryCode {
449 CountryCode::new(s).expect("valid country code")
450 }
451
452 fn dummy_fetcher() -> Arc<HttpFetcher> {
453 Arc::new(HttpFetcher::new(reqwest::Client::new()))
454 }
455
456 fn pool() -> EgressPool {
457 EgressPool::new(vec![
458 (
459 None,
460 Some(cc("pl")),
461 EgressKind::Residential,
462 dummy_fetcher(),
463 ),
464 (
465 None,
466 Some(cc("de")),
467 EgressKind::Datacenter,
468 dummy_fetcher(),
469 ),
470 ])
471 }
472
473 #[test]
474 fn country_code_normalises_and_rejects() {
475 assert_eq!(CountryCode::new("PL").unwrap().as_str(), "pl");
476 assert!(CountryCode::new("p").is_none());
477 assert!(CountryCode::new("pol").is_none());
478 assert!(CountryCode::new("p1").is_none());
479 }
480
481 #[test]
482 fn unconstrained_policy_uses_default_egress() {
483 let choice = pool().select(&AccessPolicy::default());
484 assert!(matches!(choice, EgressChoice::Default));
485 }
486
487 #[test]
488 fn geo_match_picks_an_egress() {
489 let policy = AccessPolicy {
490 geo: vec![cc("pl")],
491 ..AccessPolicy::default()
492 };
493 assert!(matches!(pool().select(&policy), EgressChoice::Use(_)));
494 }
495
496 #[test]
497 fn ip_type_match_picks_an_egress() {
498 let policy = AccessPolicy {
499 ip_type: Some(EgressKind::Datacenter),
500 ..AccessPolicy::default()
501 };
502 assert!(matches!(pool().select(&policy), EgressChoice::Use(_)));
503 }
504
505 #[test]
506 fn geo_present_but_wrong_kind_is_unavailable() {
507 // PL exists in the pool, but only as Residential — asking for a
508 // PL *Mobile* egress must fail rather than fall back.
509 let policy = AccessPolicy {
510 geo: vec![cc("pl")],
511 ip_type: Some(EgressKind::Mobile),
512 ..AccessPolicy::default()
513 };
514 assert!(matches!(pool().select(&policy), EgressChoice::Unavailable));
515 }
516
517 #[test]
518 fn unknown_geo_is_unavailable() {
519 let policy = AccessPolicy {
520 geo: vec![cc("jp")],
521 ..AccessPolicy::default()
522 };
523 assert!(matches!(pool().select(&policy), EgressChoice::Unavailable));
524 }
525
526 #[test]
527 fn empty_pool_with_constraint_is_unavailable() {
528 let empty = EgressPool::new(Vec::new());
529 let policy = AccessPolicy {
530 geo: vec![cc("pl")],
531 ..AccessPolicy::default()
532 };
533 assert!(matches!(empty.select(&policy), EgressChoice::Unavailable));
534 }
535
536 #[test]
537 fn soft_prefer_match_routes_through_it() {
538 // prefer_geo = pl, pool has a PL residential → use it.
539 let policy = AccessPolicy {
540 prefer_geo: vec![cc("pl")],
541 ..AccessPolicy::default()
542 };
543 assert!(matches!(pool().select(&policy), EgressChoice::Use(_)));
544 }
545
546 #[test]
547 fn soft_prefer_no_match_falls_back_to_default() {
548 // prefer_geo = jp, pool has no JP egress → Default, NOT Unavailable.
549 // This is the whole point of soft routing: the probe still goes
550 // out, just via the unproxied default — the site is reachable
551 // from anywhere, the preference was a recall optimisation.
552 let policy = AccessPolicy {
553 prefer_geo: vec![cc("jp")],
554 ..AccessPolicy::default()
555 };
556 assert!(matches!(pool().select(&policy), EgressChoice::Default));
557 }
558
559 #[test]
560 fn hard_geo_wins_over_soft_prefer() {
561 // When both are set, hard `geo` is authoritative — prefer_geo
562 // is ignored. Asking for hard PL with no match in the JP-only
563 // prefer is still Unavailable.
564 let empty_pl = EgressPool::new(vec![(
565 None,
566 Some(cc("jp")),
567 EgressKind::Datacenter,
568 dummy_fetcher(),
569 )]);
570 let policy = AccessPolicy {
571 geo: vec![cc("pl")],
572 prefer_geo: vec![cc("jp")],
573 ..AccessPolicy::default()
574 };
575 assert!(matches!(
576 empty_pl.select(&policy),
577 EgressChoice::Unavailable
578 ));
579 }
580
581 #[test]
582 fn ip_type_only_is_still_hard() {
583 // Asking for residential when the pool has none must remain
584 // Unavailable. We only soften geo via prefer_geo — kind
585 // requirements are still load-bearing.
586 let dc_only = EgressPool::new(vec![(None, None, EgressKind::Datacenter, dummy_fetcher())]);
587 let policy = AccessPolicy {
588 ip_type: Some(EgressKind::Residential),
589 ..AccessPolicy::default()
590 };
591 assert!(matches!(dc_only.select(&policy), EgressChoice::Unavailable));
592 }
593
594 #[test]
595 fn session_apply_overrides_base_headers() {
596 let mut base = BTreeMap::new();
597 base.insert("X-IG-App-ID".to_string(), "936".to_string());
598 base.insert("Cookie".to_string(), "old".to_string());
599 let mut sh = BTreeMap::new();
600 sh.insert("Cookie".to_string(), "sessionid=real".to_string());
601 let merged = Session::from_headers(sh).apply(&base);
602 // Session wins on conflict; non-conflicting base header preserved.
603 assert_eq!(merged.get("Cookie").unwrap(), "sessionid=real");
604 assert_eq!(merged.get("X-IG-App-ID").unwrap(), "936");
605 }
606
607 #[test]
608 fn session_store_insert_and_lookup() {
609 let mut store = SessionStore::new();
610 assert!(store.is_empty());
611 store.insert("ig", Session::from_headers(BTreeMap::new()));
612 assert!(!store.is_empty());
613 assert!(store.get("ig").is_some());
614 assert!(store.get("missing").is_none());
615 }
616}