lean_ctx/core/ocla/
sidecar.rs1use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
9#[serde(default)]
10pub struct SidecarConfig {
11 pub bind_addr: String,
13 pub auth_token: Option<String>,
15 pub tls_cert_path: Option<PathBuf>,
17 pub tls_key_path: Option<PathBuf>,
19 pub enabled: bool,
21}
22
23impl Default for SidecarConfig {
24 fn default() -> Self {
25 Self {
26 bind_addr: "127.0.0.1:3334".to_string(),
27 auth_token: None,
28 tls_cert_path: None,
29 tls_key_path: None,
30 enabled: false,
31 }
32 }
33}
34
35#[cfg(feature = "http-server")]
36mod http {
37 use std::sync::Arc;
38
39 use anyhow::{Result, anyhow};
40 use axum::{
41 Router,
42 body::Body,
43 http::{Request, StatusCode, header},
44 middleware::{self, Next},
45 response::{IntoResponse, Response},
46 };
47 use subtle::ConstantTimeEq;
48 use tokio::net::TcpListener;
49
50 use super::SidecarConfig;
51
52 pub(super) async fn start(config: &SidecarConfig) -> Result<()> {
53 if !config.enabled {
54 return Ok(());
55 }
56
57 if config.tls_cert_path.is_some() != config.tls_key_path.is_some() {
58 return Err(anyhow!(
59 "tls_cert_path and tls_key_path must be configured together"
60 ));
61 }
62 if config.tls_cert_path.is_some() {
63 return Err(anyhow!(
64 "TLS sidecar transport requires a TLS listener dependency; \
65 configure the plain HTTP sidecar or add that runtime dependency"
66 ));
67 }
68
69 let listener = TcpListener::bind(&config.bind_addr).await?;
70 axum::serve(listener, router(config.auth_token.as_deref())).await?;
71 Ok(())
72 }
73
74 fn router(auth_token: Option<&str>) -> Router {
75 let router = crate::core::ocla::wire_api::ocla_router();
76 match auth_token.filter(|token| !token.is_empty()) {
77 Some(token) => {
78 let expected = Arc::new(token.as_bytes().to_vec());
79 router.layer(middleware::from_fn(move |req, next| {
80 let expected = Arc::clone(&expected);
81 async move { auth_middleware(req, next, expected).await }
82 }))
83 }
84 None => router,
85 }
86 }
87
88 async fn auth_middleware(
89 request: Request<Body>,
90 next: Next,
91 expected: Arc<Vec<u8>>,
92 ) -> Response {
93 let Some(value) = request.headers().get(header::AUTHORIZATION) else {
94 return unauthorized();
95 };
96 let Ok(value) = value.to_str() else {
97 return unauthorized();
98 };
99 let Some(token) = value
100 .strip_prefix("Bearer ")
101 .or_else(|| value.strip_prefix("bearer "))
102 else {
103 return unauthorized();
104 };
105 if !bool::from(token.as_bytes().ct_eq(expected.as_slice())) {
106 return unauthorized();
107 }
108 next.run(request).await
109 }
110
111 fn unauthorized() -> Response {
112 (StatusCode::UNAUTHORIZED, "unauthorized\n").into_response()
113 }
114
115 #[cfg(test)]
116 mod tests {
117 use axum::body::{Body, to_bytes};
118 use axum::http::{Request, StatusCode, header};
119 use tower::ServiceExt;
120
121 use super::router;
122
123 #[tokio::test]
124 async fn auth_rejects_missing_and_wrong_bearer_tokens() {
125 for authorization in [None, Some("Bearer wrong"), Some("Basic secret")] {
126 let mut request = Request::builder().method("GET").uri("/ocla/v1/health");
127 if let Some(value) = authorization {
128 request = request.header(header::AUTHORIZATION, value);
129 }
130 let response = router(Some("secret"))
131 .oneshot(request.body(Body::empty()).expect("request"))
132 .await
133 .expect("response");
134 assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
135 }
136 }
137
138 #[tokio::test]
139 async fn auth_accepts_matching_bearer_token() {
140 let response = router(Some("secret"))
141 .oneshot(
142 Request::builder()
143 .method("GET")
144 .uri("/ocla/v1/health")
145 .header(header::AUTHORIZATION, "Bearer secret")
146 .body(Body::empty())
147 .expect("request"),
148 )
149 .await
150 .expect("response");
151 assert_eq!(response.status(), StatusCode::OK);
152 let body = to_bytes(response.into_body(), 4096).await.expect("body");
153 assert!(body.windows(2).any(|window| window == b"ok"));
154 }
155 }
156}
157
158#[cfg(feature = "http-server")]
159pub async fn start_sidecar(config: &SidecarConfig) -> anyhow::Result<()> {
160 http::start(config).await
161}
162
163#[cfg(not(feature = "http-server"))]
164pub async fn start_sidecar(_config: &SidecarConfig) -> anyhow::Result<()> {
165 Err(anyhow::anyhow!(
166 "OCLA sidecar requires the `http-server` feature"
167 ))
168}