camel-core 0.35.0

Core engine for rust-camel
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
//! Tests for the ADR-0061 per-bind public-exposure gate (Task 1.9) and
//! the plan-only SecurityContext delivery to server-route consumers
//! (Task 1.2).

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use camel_api::CamelError;
use camel_api::RouteController;
use camel_api::security_policy::{
    AccessMode, AudienceBinding, AuthContext, AuthorizationDecision, Principal, RouteSecurityPlan,
    SecurityPolicy, SecurityPolicyConfig, TransportId,
};

use crate::lifecycle::adapters::route_controller_trait::{
    BindExposureAcks, enforce_bind_exposure_gate,
};

fn public_plan() -> RouteSecurityPlan {
    RouteSecurityPlan {
        access_mode: AccessMode::Public,
        provider_ref: None,
        transport: TransportId::Http,
        credential_sources: vec![],
        audience_binding: None,
    }
}

fn authenticated_plan(provider: &str) -> RouteSecurityPlan {
    RouteSecurityPlan {
        access_mode: AccessMode::Authenticated,
        provider_ref: Some(provider.to_string()),
        transport: TransportId::Http,
        credential_sources: vec![],
        audience_binding: Some(AudienceBinding {
            issuers: vec![],
            audiences: vec![],
        }),
    }
}

/// Runs `f` under a thread-local `fmt` subscriber capturing output into a
/// buffer; returns the captured text.
fn capture_logs(f: impl FnOnce()) -> String {
    struct CaptureWriter {
        buf: Arc<std::sync::Mutex<Vec<u8>>>,
    }
    impl std::io::Write for CaptureWriter {
        fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
            self.buf.lock().unwrap().extend_from_slice(data);
            Ok(data.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CaptureWriter {
        type Writer = CaptureWriter;
        fn make_writer(&'a self) -> Self::Writer {
            CaptureWriter {
                buf: Arc::clone(&self.buf),
            }
        }
    }
    let buf = Arc::new(std::sync::Mutex::new(Vec::new()));
    let subscriber = tracing_subscriber::fmt::Subscriber::builder()
        .with_writer(CaptureWriter {
            buf: Arc::clone(&buf),
        })
        .with_ansi(false)
        .finish();
    tracing::subscriber::with_default(subscriber, f);
    String::from_utf8(buf.lock().unwrap().clone()).expect("captured output must be UTF-8")
}

#[test]
fn gate_refuses_nonloopback_public_without_ack() {
    let err = enforce_bind_exposure_gate("0.0.0.0:8080", false, &[("r1", &public_plan())], false)
        .unwrap_err();
    let CamelError::RouteError(msg) = &err else {
        panic!("expected RouteError, got {err:?}");
    };
    assert!(msg.contains("0.0.0.0:8080"), "must name the bind: {msg}");
    assert!(msg.contains("r1"), "must name the public route: {msg}");
}

#[test]
fn gate_names_all_public_routes_on_the_bind() {
    let plans = [("r1", &public_plan()), ("r2", &public_plan())];
    let err = enforce_bind_exposure_gate("10.0.0.1:9000", false, &plans, false).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("r1") && msg.contains("r2"),
        "must name both: {msg}"
    );
}

#[test]
fn gate_acknowledged_warns_and_passes() {
    let captured = capture_logs(|| {
        enforce_bind_exposure_gate("0.0.0.0:8080", false, &[("r1", &public_plan())], true)
            .expect("acknowledged bind must pass");
    });
    assert!(
        captured.contains("0.0.0.0:8080"),
        "warn must name the bind: {captured}"
    );
    assert!(
        captured.contains("public_routes=1"),
        "warn must state the public-route count: {captured}"
    );
    assert!(
        captured.to_lowercase().contains("warn"),
        "must be a warning, not silent: {captured}"
    );
}

#[test]
fn gate_loopback_public_needs_no_ack() {
    for (key, loopback) in [
        ("127.0.0.1:0", true),
        ("[::1]:0", true),
        ("localhost:8080", true),
    ] {
        let captured = capture_logs(|| {
            enforce_bind_exposure_gate(key, loopback, &[("r1", &public_plan())], false)
                .unwrap_or_else(|e| panic!("loopback {key} must pass: {e}"));
        });
        assert!(captured.is_empty(), "loopback must not warn: {captured}");
    }
}

#[test]
fn gate_hostname_authority_is_nonloopback() {
    // Hostnames other than localhost fail closed to the gate check.
    let err = enforce_bind_exposure_gate(
        "myhost.example:8080",
        false,
        &[("r1", &public_plan())],
        false,
    )
    .unwrap_err();
    assert!(err.to_string().contains("myhost.example:8080"));
    // And the ack key is the authority string as written.
    enforce_bind_exposure_gate(
        "myhost.example:8080",
        false,
        &[("r1", &public_plan())],
        true,
    )
    .expect("hostname ack by authority string passes");
}

#[test]
fn gate_passes_when_no_public_routes() {
    enforce_bind_exposure_gate(
        "0.0.0.0:8080",
        false,
        &[("r1", &authenticated_plan("idp-a"))],
        false,
    )
    .expect("non-public routes never trip the gate");
}

#[test]
fn bind_acks_default_is_unacknowledged() {
    let acks = BindExposureAcks::new(HashMap::new());
    assert!(!acks.acknowledged("0.0.0.0:8080"));
    let acks = BindExposureAcks::new(HashMap::from([("0.0.0.0:8080".to_string(), true)]));
    assert!(acks.acknowledged("0.0.0.0:8080"));
    assert!(!acks.acknowledged("10.0.0.1:8080"));
}

// ── plan-only SecurityContext delivery (Task 1.2) ──

struct AllowPolicy;

#[async_trait::async_trait]
impl SecurityPolicy for AllowPolicy {
    async fn evaluate(
        &self,
        _exchange: &mut camel_api::Exchange,
        _auth: &AuthContext<'_>,
    ) -> Result<AuthorizationDecision, CamelError> {
        Ok(AuthorizationDecision::Granted {
            principal: Principal {
                subject: "tester".into(),
                issuer: "test".into(),
                audience: vec![],
                scopes: vec![],
                roles: vec![],
                claims: serde_json::Value::Null,
            },
        })
    }
}

struct StubAuth;

#[async_trait::async_trait]
impl camel_auth::TokenAuthenticator for StubAuth {
    async fn authenticate_bearer(&self, _token: &str) -> Result<Principal, CamelError> {
        Ok(Principal {
            subject: "tester".into(),
            issuer: "test".into(),
            audience: vec![],
            scopes: vec![],
            roles: vec![],
            claims: serde_json::Value::Null,
        })
    }
}

/// What `set_security_context` delivered, reduced to comparable facts
/// (`SecurityContext` holds trait objects without equality).
#[derive(Debug)]
struct CapturedSecurityContext {
    policy_present: bool,
    public_plan: bool,
    authorized_plan: bool,
    providers_present: bool,
}

fn capture_from(ctx: &camel_component_api::SecurityContext) -> CapturedSecurityContext {
    CapturedSecurityContext {
        policy_present: ctx.policy.is_some(),
        public_plan: matches!(
            ctx.plan.as_ref().map(|p| &p.access_mode),
            Some(AccessMode::Public)
        ),
        authorized_plan: matches!(
            ctx.plan.as_ref().map(|p| &p.access_mode),
            Some(AccessMode::Authorized(_))
        ),
        providers_present: ctx.providers.is_some(),
    }
}

struct ContextCaptureComponent {
    captured: Arc<Mutex<Option<CapturedSecurityContext>>>,
}

#[async_trait::async_trait]
impl camel_component_api::Component for ContextCaptureComponent {
    fn scheme(&self) -> &str {
        "http"
    }

    fn create_endpoint(
        &self,
        _uri: &str,
        _ctx: &dyn camel_component_api::ComponentContext,
    ) -> Result<Box<dyn camel_component_api::Endpoint>, CamelError> {
        Ok(Box::new(ContextCaptureEndpoint {
            captured: Arc::clone(&self.captured),
        }))
    }
}

struct ContextCaptureEndpoint {
    captured: Arc<Mutex<Option<CapturedSecurityContext>>>,
}

impl camel_component_api::Endpoint for ContextCaptureEndpoint {
    fn uri(&self) -> &str {
        "http"
    }

    fn create_consumer(
        &self,
        _rt: Arc<dyn camel_component_api::RuntimeObservability>,
    ) -> Result<Box<dyn camel_component_api::Consumer>, CamelError> {
        Ok(Box::new(ContextCaptureConsumer {
            captured: Arc::clone(&self.captured),
        }))
    }

    fn create_producer(
        &self,
        _rt: Arc<dyn camel_component_api::RuntimeObservability>,
        _ctx: &camel_component_api::ProducerContext,
    ) -> Result<camel_api::BoxProcessor, CamelError> {
        Ok(camel_api::BoxProcessor::new(camel_api::IdentityProcessor))
    }
}

struct ContextCaptureConsumer {
    captured: Arc<Mutex<Option<CapturedSecurityContext>>>,
}

#[async_trait::async_trait]
impl camel_component_api::Consumer for ContextCaptureConsumer {
    async fn start(&mut self, ctx: camel_component_api::ConsumerContext) -> Result<(), CamelError> {
        ctx.mark_ready();
        Ok(())
    }

    async fn stop(&mut self) -> Result<(), CamelError> {
        Ok(())
    }

    fn startup_mode(&self) -> camel_component_api::ConsumerStartupMode {
        camel_component_api::ConsumerStartupMode::Explicit
    }

    fn set_security_context(&mut self, ctx: camel_component_api::SecurityContext) {
        *self.captured.lock().expect("capture slot") = Some(capture_from(&ctx));
    }
}

async fn stage_and_start(
    uri: &str,
    route_id: &str,
    security: impl FnOnce(
        crate::lifecycle::application::route_definition::RouteDefinition,
    ) -> crate::lifecycle::application::route_definition::RouteDefinition,
) -> CapturedSecurityContext {
    use crate::lifecycle::adapters::route_controller::DefaultRouteController;
    use crate::shared::components::domain::Registry;

    let captured: Arc<Mutex<Option<CapturedSecurityContext>>> = Arc::new(Mutex::new(None));
    let component_registry = Arc::new(std::sync::Mutex::new(Registry::new()));
    component_registry
        .lock()
        .expect("registry lock")
        .register(Arc::new(ContextCaptureComponent {
            captured: Arc::clone(&captured),
        }));

    let mut controller = DefaultRouteController::new(
        component_registry,
        Arc::new(camel_api::NoopPlatformService::default()),
    );

    let def = security(
        crate::lifecycle::application::route_definition::RouteDefinition::new(uri, vec![])
            .with_route_id(route_id),
    );
    controller
        .add_route(def)
        .await
        .unwrap_or_else(|e| panic!("staging {route_id} must succeed: {e}"));
    controller
        .start_route(route_id)
        .await
        .unwrap_or_else(|e| panic!("start {route_id} must succeed: {e}"));

    let snapshot = captured
        .lock()
        .expect("capture slot")
        .take()
        .unwrap_or_else(|| panic!("set_security_context must have been invoked for {route_id}"));

    controller
        .stop_route(route_id)
        .await
        .unwrap_or_else(|e| panic!("stop {route_id} must succeed: {e}"));
    snapshot
}

#[tokio::test]
async fn undeclared_server_route_receives_plan_only_context() {
    let captured =
        stage_and_start("http://127.0.0.1:18061/api", "undeclared-route", |def| def).await;
    assert!(
        !captured.policy_present,
        "plan-only context carries no policy: {captured:?}"
    );
    assert!(
        captured.public_plan,
        "plan must be the compiled Public plan: {captured:?}"
    );
    assert!(
        !captured.providers_present,
        "no providers without a registry: {captured:?}"
    );
}

#[tokio::test]
async fn declared_route_context_unchanged() {
    let provider_registry = Arc::new(camel_auth::ProviderRegistry::new());
    provider_registry.register(
        "idp-a",
        camel_auth::ProviderEntry {
            authenticator: Arc::new(StubAuth),
            audience_binding: None,
        },
    );
    let captured = stage_and_start("http://127.0.0.1:18062/api", "declared-route", |def| {
        def.with_security_policy(SecurityPolicyConfig::new(AllowPolicy))
            .with_security_authenticator(Arc::new(StubAuth))
            .with_provider_registry(provider_registry)
    })
    .await;
    assert!(
        captured.policy_present,
        "declared route keeps its policy: {captured:?}"
    );
    assert!(
        captured.authorized_plan,
        "plan must carry the Authorized classification: {captured:?}"
    );
    assert!(
        captured.providers_present,
        "declared route keeps its providers: {captured:?}"
    );
}