guard-core-rs 4.2.0

Framework-agnostic security engine for the Guard ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! The cloud-provider blocking pipeline stage for tower stacks.
//!
//! One `tower::Layer` that answers the reference engine's `cloud_provider`
//! check (`guard_core/core/checks/implementations/cloud_provider.py`), over
//! the selector parser and range table
//! [`guard_core_engine::cloud_provider`]:
//!
//! ```text
//! whitelisted || exempt (the IpGateDecision extension): pass through
//! no client IP:                                         pass through
//! no block_cloud_providers selectors:                   pass through
//! address inside a selected provider's ranges
//!   (region carve-outs honored):                        403 "Cloud provider IP not allowed"
//! everything else:                                      pass through
//! ```
//!
//! ## Reference contract, point by point
//!
//! - **Skip state**: the check returns early for
//!   `is_whitelisted || is_exempt`, read the way the global IP gate leaves
//!   it: an [`IpGateDecision`] request extension. It runs after the
//!   reference pipeline's `ip_security` stage (which sets that state) and
//!   before `user_agent`.
//! - **No client IP passes**: `if not client_ip: return None`.
//! - **Selectors**: the config is the reference `block_cloud_providers`
//!   list - bare names and `":!region"` carve-outs, validated fail-closed
//!   at construction (an unknown provider is a config error, the reference
//!   pydantic `ValueError`). An empty list is the stage's inert default
//!   (the reference `get_cloud_providers_to_check` returning nothing).
//! - **The block shape**: `403 "Cloud provider IP not allowed"`; the
//!   [`CloudIpTable::provider_details`] pair rides the answer for adapters
//!   that log (the reference logs and emits `EVENT_CLOUD_BLOCKED`
//!   events there).
//! - **Not mirrored**: the reference route-level override
//!   (`RouteConfig.block_cloud_providers` plus the `clouds` bypass check;
//!   no route system exists yet, so the stage blocks on the global
//!   selector list only), and the range fetching/refreshing itself (the
//!   reference `cloud_handler` background fetchers, its Redis caching, and
//!   `cloud_ip_refresh_interval`): ranges are fed by the adapter through
//!   the shared [`CloudIpTable`].
//!
//! # Example
//!
//! ```
//! use std::net::IpAddr;
//! use std::str::FromStr;
//!
//! use guard_core_engine::cloud_provider::{parse_cloud_selectors, CloudIpTable};
//! use guard_core_rs::cloud_provider::{CloudProviderStage, CloudProviderStageConfig};
//!
//! let table = CloudIpTable::default();
//! table
//!     .set_provider_ranges("AWS", vec![("203.0.113.0/24".to_owned(), None)])
//!     .expect("valid ranges");
//! let stage = CloudProviderStage::new(CloudProviderStageConfig {
//!     block_cloud_providers: parse_cloud_selectors(["AWS"]).expect("valid selectors"),
//!     table,
//!     passive_mode: false,
//! });
//!
//! let decision = stage.decide(
//!     Some(IpAddr::from_str("203.0.113.9").unwrap()),
//!     None,
//! );
//! assert_eq!(
//!     decision.expect("blocked").answer.body,
//!     "Cloud provider IP not allowed"
//! );
//!
//! // No client IP, no decision: the reference passes it.
//! assert!(stage.decide(None, None).is_none());
//! ```

use std::fmt;
use std::future::Future;
use std::net::IpAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use ::tower::Layer;
use http::{Extensions, HeaderMap, Request, Response, StatusCode};

use crate::tower::{ExtractIp, IpGateDecision, StageResponse, default_extract_ip};
pub use guard_core_engine::cloud_provider::{
    CloudConfigError, CloudIpTable, CloudRangeError, CloudSelectors, VALID_CLOUD_PROVIDERS,
    parse_cloud_selectors,
};

/// The blocked answer body (`CloudProviderCheck`'s default message).
pub const CLOUD_PROVIDER_BLOCKED_BODY: &str = "Cloud provider IP not allowed";

/// The stage's block answer: the family shape plus the
/// `(provider, network)` details pair for adapters that log (the reference
/// logs and emits `EVENT_CLOUD_BLOCKED` events with them).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CloudDecision {
    /// The block answer (403, the default body).
    pub answer: StageResponse,
    /// The reference `get_cloud_provider_details` pair.
    pub details: Option<(String, String)>,
}

/// The stage's knobs: the parsed `block_cloud_providers` selectors and the
/// range table they consult.
#[derive(Debug, Clone, Default)]
pub struct CloudProviderStageConfig {
    /// The parsed `block_cloud_providers` selectors. The default (empty)
    /// never blocks - the reference `applies_to` registers the check only
    /// when the config or a route names providers.
    pub block_cloud_providers: CloudSelectors,
    /// The provider ranges the stage consults. Feed it with
    /// [`CloudIpTable::set_provider_ranges`] (at startup, and from a
    /// background refresher through a shared clone).
    pub table: CloudIpTable,
    /// The reference `SecurityConfig.passive_mode` (`false` by default):
    /// a cloud-provider match logs only - no `403` answer, the reference
    /// `CloudProviderCheck`'s passive path.
    pub passive_mode: bool,
}

/// The cloud-provider blocking stage over one table and one selector list.
///
/// Build it once at startup with [`CloudProviderStage::new`] (fail closed
/// on invalid selectors) and install it with [`CloudProviderStageLayer`].
/// The stage is cheaply clonable; clones share the table.
#[derive(Clone)]
pub struct CloudProviderStage {
    config: CloudProviderStageConfig,
    extract_ip: ExtractIp,
}

impl fmt::Debug for CloudProviderStage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CloudProviderStage")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl CloudProviderStage {
    /// Build the stage with the default IP extraction. Infallible by
    /// construction: [`CloudSelectors`] is parsed and validated by
    /// [`parse_cloud_selectors`], so an invalid provider name cannot reach
    /// the stage.
    #[must_use]
    pub fn new(config: CloudProviderStageConfig) -> Self {
        Self {
            config,
            extract_ip: Arc::new(default_extract_ip),
        }
    }

    /// Open the builder: the IP extraction is the optional seam over
    /// [`CloudProviderStage::new`]'s default.
    pub const fn builder(config: CloudProviderStageConfig) -> CloudProviderStageBuilder {
        CloudProviderStageBuilder {
            config,
            extract_ip: None,
        }
    }

    /// The validated config the stage decides under.
    #[must_use]
    pub const fn config(&self) -> &CloudProviderStageConfig {
        &self.config
    }

    /// One pass of the stage: `ip` is the extracted client identity
    /// (`None` passes, the reference `if not client_ip`), `gate` the
    /// global IP gate's skip state. `None` passes; `Some` carries the
    /// block answer and the `(provider, network)` details pair.
    #[must_use]
    pub fn decide(
        &self,
        ip: Option<IpAddr>,
        gate: Option<IpGateDecision>,
    ) -> Option<CloudDecision> {
        if gate.is_some_and(|gate| gate.is_whitelisted || gate.is_exempt) {
            return None;
        }
        let ip = ip?;
        if self.config.block_cloud_providers.blocked.is_empty() {
            return None;
        }
        if !self
            .config
            .table
            .is_cloud_ip(ip, &self.config.block_cloud_providers)
        {
            return None;
        }
        let details = self
            .config
            .table
            .provider_details(ip, &self.config.block_cloud_providers);
        if self.config.passive_mode {
            // Log-only: the reference's passive path emits the block events
            // and returns None.
            return None;
        }
        Some(CloudDecision {
            answer: StageResponse {
                status: StatusCode::FORBIDDEN,
                body: CLOUD_PROVIDER_BLOCKED_BODY,
                retry_after: None,
                custom_body: None,
            },
            details,
        })
    }
}

/// The builder for [`CloudProviderStage`].
#[must_use]
pub struct CloudProviderStageBuilder {
    config: CloudProviderStageConfig,
    extract_ip: Option<ExtractIp>,
}

impl CloudProviderStageBuilder {
    /// Replace the default client IP extraction ([`default_extract_ip`]).
    pub fn ip_extractor<F>(mut self, extractor: F) -> Self
    where
        F: Fn(&HeaderMap, &Extensions) -> Option<IpAddr> + Send + Sync + 'static,
    {
        self.extract_ip = Some(Arc::new(extractor));
        self
    }

    /// Build the stage.
    #[must_use]
    pub fn build(self) -> CloudProviderStage {
        let mut stage = CloudProviderStage::new(self.config);
        if let Some(extract_ip) = self.extract_ip {
            stage.extract_ip = extract_ip;
        }
        stage
    }
}

/// The `tower::Layer` carrying [`CloudProviderStage`].
///
/// Wrap any `Service<http::Request<B>>` whose responses are
/// `http::Response<ResBody>` with `ResBody: From<&'static str>` and the
/// stage answers the reference's 403 shape itself.
#[derive(Clone)]
pub struct CloudProviderStageLayer {
    stage: CloudProviderStage,
}

impl CloudProviderStageLayer {
    /// Carry `stage` into every service this layer wraps.
    #[must_use]
    pub const fn new(stage: CloudProviderStage) -> Self {
        Self { stage }
    }
}

impl fmt::Debug for CloudProviderStageLayer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CloudProviderStageLayer")
            .field("stage", &self.stage)
            .finish()
    }
}

impl<S> Layer<S> for CloudProviderStageLayer {
    type Service = CloudProviderStageService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        CloudProviderStageService {
            inner,
            stage: self.stage.clone(),
        }
    }
}

/// The stage as a `tower::Service` around the inner service it wrapped.
#[derive(Clone)]
pub struct CloudProviderStageService<S> {
    inner: S,
    stage: CloudProviderStage,
}

impl<S, B, ResBody> ::tower::Service<Request<B>> for CloudProviderStageService<S>
where
    S: ::tower::Service<Request<B>, Response = Response<ResBody>>,
    S::Future: Send + 'static,
    ResBody: From<&'static str> + Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<S::Response, S::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), S::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, request: Request<B>) -> Self::Future {
        let ip = (self.stage.extract_ip)(request.headers(), request.extensions());
        let gate = request.extensions().get::<IpGateDecision>().copied();
        if let Some(decision) = self.stage.decide(ip, gate) {
            let response = render(&decision.answer);
            return Box::pin(async move { Ok(response) });
        }
        let future = self.inner.call(request);
        Box::pin(future)
    }
}

/// Render the stage's block answer into the wrapped service's response body
/// type.
fn render<ResBody: From<&'static str>>(answer: &StageResponse) -> Response<ResBody> {
    let mut response = Response::new(ResBody::from(answer.body));
    *response.status_mut() = answer.status;
    response
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::convert::Infallible;
    use std::net::SocketAddr;
    use std::str::FromStr;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use ::tower::{Service, ServiceBuilder};

    fn aws_stage() -> CloudProviderStage {
        let table = CloudIpTable::default();
        table
            .set_provider_ranges("AWS", vec![("203.0.113.0/24".to_owned(), None)])
            .expect("valid ranges");
        CloudProviderStage::new(CloudProviderStageConfig {
            block_cloud_providers: parse_cloud_selectors(["AWS"]).expect("valid selectors"),
            table,
            passive_mode: false,
        })
    }

    fn passive_aws_stage() -> CloudProviderStage {
        let table = CloudIpTable::default();
        table
            .set_provider_ranges("AWS", vec![("203.0.113.0/24".to_owned(), None)])
            .expect("valid ranges");
        CloudProviderStage::new(CloudProviderStageConfig {
            block_cloud_providers: parse_cloud_selectors(["AWS"]).expect("valid selectors"),
            table,
            passive_mode: true,
        })
    }

    fn ip(text: &str) -> IpAddr {
        IpAddr::from_str(text).expect("test address")
    }

    #[test]
    fn default_stage_passes_everything_through() {
        let stage = CloudProviderStage::new(CloudProviderStageConfig::default());
        assert!(stage.config().block_cloud_providers.blocked.is_empty());
        for address in ["203.0.113.9", "192.0.2.1", "2001:db8::1"] {
            assert!(
                stage.decide(Some(ip(address)), None).is_none(),
                "an empty selector list must pass {address}"
            );
        }
    }

    #[test]
    fn blocked_provider_answers_the_reference_403_shape_with_details() {
        let stage = aws_stage();
        let decision = stage
            .decide(Some(ip("203.0.113.9")), None)
            .expect("blocked");
        assert_eq!(decision.answer.status, StatusCode::FORBIDDEN);
        assert_eq!(decision.answer.body, CLOUD_PROVIDER_BLOCKED_BODY);
        assert_eq!(decision.answer.retry_after, None);
        assert_eq!(
            decision.details,
            Some(("AWS".to_owned(), "203.0.113.0/24".to_owned()))
        );
        assert!(stage.decide(Some(ip("203.0.114.9")), None).is_none());
    }

    #[test]
    fn passive_mode_answers_nothing_for_a_cloud_match() {
        let stage = passive_aws_stage();
        assert!(stage.decide(Some(ip("203.0.113.9")), None).is_none());
    }

    #[test]
    fn missing_client_ip_passes() {
        let stage = aws_stage();
        assert!(stage.decide(None, None).is_none());
    }

    #[test]
    fn whitelisted_and_exempt_ips_skip_the_check() {
        let stage = aws_stage();
        for gate in [
            IpGateDecision {
                is_whitelisted: true,
                is_exempt: false,
            },
            IpGateDecision {
                is_whitelisted: false,
                is_exempt: true,
            },
        ] {
            assert!(
                stage.decide(Some(ip("203.0.113.9")), Some(gate)).is_none(),
                "the skip state must pass a cloud-provider address"
            );
        }
    }

    #[test]
    fn carve_outs_honor_the_region_data_through_the_stage() {
        let table = CloudIpTable::default();
        table
            .set_provider_ranges(
                "GCP",
                vec![
                    ("198.51.100.0/24".to_owned(), Some("us-central1".to_owned())),
                    (
                        "198.51.101.0/24".to_owned(),
                        Some("europe-west1".to_owned()),
                    ),
                ],
            )
            .expect("valid ranges");
        let stage = CloudProviderStage::new(CloudProviderStageConfig {
            block_cloud_providers: parse_cloud_selectors(["GCP:!us-central1"])
                .expect("valid selectors"),
            table,
            passive_mode: false,
        });
        assert!(stage.decide(Some(ip("198.51.100.9")), None).is_none());
        assert!(stage.decide(Some(ip("198.51.101.9")), None).is_some());
    }

    #[test]
    fn builder_swaps_the_ip_extractor() {
        let stage = CloudProviderStage::builder(CloudProviderStageConfig::default())
            .ip_extractor(|_headers, _extensions| Some(ip("192.0.2.99")))
            .build();
        let request = Request::builder().body(()).expect("request");
        assert_eq!(
            (stage.extract_ip)(request.headers(), request.extensions()),
            Some(ip("192.0.2.99"))
        );
    }

    /// The future the plumbing tests drive: the stub futures are always
    /// immediately ready, so a noop-waker spin never spins.
    fn block_on<F: Future>(future: F) -> F::Output {
        let mut future = std::pin::pin!(future);
        let waker = std::task::Waker::noop();
        let mut cx = Context::from_waker(waker);
        loop {
            match future.as_mut().poll(&mut cx) {
                Poll::Ready(output) => return output,
                Poll::Pending => std::hint::spin_loop(),
            }
        }
    }

    /// The inner service the plumbing tests wrap: counts its calls and
    /// answers `200 "inner"`.
    #[derive(Clone)]
    struct Inner {
        calls: Arc<AtomicUsize>,
    }

    impl Inner {
        fn new() -> Self {
            Self {
                calls: Arc::new(AtomicUsize::new(0)),
            }
        }

        fn call_count(&self) -> usize {
            self.calls.load(Ordering::Relaxed)
        }
    }

    impl ::tower::Service<Request<&'static str>> for Inner {
        type Response = Response<&'static str>;
        type Error = Infallible;
        type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Infallible>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, request: Request<&'static str>) -> Self::Future {
            self.calls.fetch_add(1, Ordering::Relaxed);
            drop(request);
            Box::pin(async move { Ok(Response::new("inner")) })
        }
    }

    fn request_from_client(ip_text: &str) -> Request<&'static str> {
        let socket = SocketAddr::from_str(&format!("{ip_text}:65535")).expect("socket");
        Request::builder()
            .extension(socket)
            .body("body")
            .expect("request")
    }

    #[test]
    fn layer_passes_through_and_the_inner_service_answers() {
        let layer = CloudProviderStageLayer::new(aws_stage());
        let inner = Inner::new();
        let mut service = ServiceBuilder::new().layer(layer).service(inner.clone());

        let response = block_on(service.call(request_from_client("192.0.2.20"))).expect("ready");
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.body(), &"inner");
        assert_eq!(inner.call_count(), 1);
    }

    #[test]
    fn layer_answers_the_blocked_shape_without_hitting_the_inner_service() {
        let layer = CloudProviderStageLayer::new(aws_stage());
        let inner = Inner::new();
        let mut service = ServiceBuilder::new().layer(layer).service(inner.clone());

        let response = block_on(service.call(request_from_client("203.0.113.9"))).expect("ready");
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        assert_eq!(response.body(), &CLOUD_PROVIDER_BLOCKED_BODY);
        assert_eq!(inner.call_count(), 0, "the blocked request never hits it");
    }

    #[test]
    fn layer_clone_shares_the_stage_table() {
        let stage = aws_stage();
        let mut first = CloudProviderStageService {
            inner: Inner::new(),
            stage: stage.clone(),
        };
        let mut second = CloudProviderStageService {
            inner: Inner::new(),
            stage,
        };

        let response = block_on(first.call(request_from_client("203.0.113.9"))).expect("ready");
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        let response = block_on(second.call(request_from_client("203.0.113.9"))).expect("ready");
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
    }
}