atomic_integration_proxy/
lib.rs1mod access;
41mod agent_id;
42mod api_error;
43mod capability;
44mod catalog;
45mod config;
46mod connect;
47mod connections;
48#[cfg(test)]
49mod identity_catalog_tests;
50mod oauth;
51mod providers;
52mod proxy;
53mod security;
54mod signature;
55mod templates;
56#[cfg(test)]
57mod test_support;
58
59use std::sync::Arc;
60
61use axum::{
62 extract::{FromRef, State},
63 response::Html,
64 routing::{delete, get, post},
65 Router,
66};
67use axum_extra::extract::cookie::Key;
68use sha2::{Digest, Sha512};
69use tower_http::trace::TraceLayer;
70use tracing_subscriber::EnvFilter;
71
72pub use access::{Access, AccessPolicy, AllowAll, EnvAccessPolicy};
73pub use agent_id::{parse as parse_agent_id, AgentId};
74pub use config::{Config, DEFAULT_CATALOG_PATH};
75
76#[derive(Clone)]
77struct AppState {
78 http_client: reqwest::Client,
79 key: Key,
80 base_url: String,
82 public_origin: String,
85 catalog: catalog::Catalog,
86 security: Option<security::Security>,
87 access: Arc<dyn AccessPolicy>,
88 #[cfg(test)]
89 test_upstream: Option<String>,
90}
91
92impl FromRef<AppState> for Key {
93 fn from_ref(state: &AppState) -> Self {
94 state.key.clone()
95 }
96}
97
98pub(crate) fn now_secs() -> u64 {
99 std::time::SystemTime::now()
100 .duration_since(std::time::UNIX_EPOCH)
101 .expect("clock before epoch")
102 .as_secs()
103}
104
105pub(crate) fn now_ms() -> u64 {
106 std::time::SystemTime::now()
107 .duration_since(std::time::UNIX_EPOCH)
108 .expect("clock before epoch")
109 .as_millis() as u64
110}
111
112pub(crate) async fn check_access(
114 state: &AppState,
115 owner: &AgentId,
116) -> Result<(), api_error::ApiError> {
117 match state.access.check(owner).await {
118 Access::Allowed => Ok(()),
119 Access::Denied(reason) => Err(api_error::ApiError::AccessDenied(reason)),
120 }
121}
122
123fn build_http_client() -> reqwest::Client {
124 reqwest::Client::builder()
130 .user_agent("LocalThought-integration-proxy")
131 .redirect(reqwest::redirect::Policy::none())
132 .connect_timeout(std::time::Duration::from_secs(10))
133 .timeout(std::time::Duration::from_secs(30))
134 .build()
135 .expect("failed to build HTTP client")
136}
137
138#[derive(Debug)]
141#[non_exhaustive]
142pub enum Error {
143 Config(String),
145 Catalog(String),
147 Security(String),
149 Bind {
151 addr: String,
153 source: std::io::Error,
155 },
156 Serve(std::io::Error),
158}
159
160impl std::fmt::Display for Error {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 match self {
163 Error::Config(err) => write!(f, "configuration error: {err}"),
164 Error::Catalog(err) => write!(f, "catalog configuration error: {err}"),
165 Error::Security(err) => write!(f, "security configuration error: {err}"),
166 Error::Bind { addr, source } => write!(f, "failed to bind {addr}: {source}"),
167 Error::Serve(err) => write!(f, "server error: {err}"),
168 }
169 }
170}
171
172impl std::error::Error for Error {
173 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
174 match self {
175 Error::Bind { source, .. } | Error::Serve(source) => Some(source),
176 _ => None,
177 }
178 }
179}
180
181pub async fn build_app(config: &Config) -> Result<Router, Error> {
184 let access = EnvAccessPolicy::new(
185 config.allowed_agents.clone(),
186 config.revoked_subjects.clone(),
187 );
188 build_app_with_access(config, Arc::new(access)).await
189}
190
191pub async fn build_app_with_access(
197 config: &Config,
198 access: Arc<dyn AccessPolicy>,
199) -> Result<Router, Error> {
200 let base_url = config::validate_base_url(&config.base_url).map_err(Error::Config)?;
201 let key = match &config.session_secret {
202 Some(secret) => Key::from(&Sha512::digest(secret.as_bytes())),
203 None => {
204 tracing::warn!(
205 "SESSION_SECRET is not set; using a random key. A consent screen open during a restart must be started again."
206 );
207 Key::generate()
208 }
209 };
210
211 let http_client = build_http_client();
212 let catalog = catalog::Catalog::load(&config.catalog_path, &http_client)
213 .await
214 .map_err(Error::Catalog)?;
215 let security = security::Security::connect(&config.database_url, &config.encryption_key)
216 .await
217 .map_err(Error::Security)?;
218
219 let state = AppState {
220 http_client,
221 key,
222 base_url,
223 public_origin: config.public_origin(),
224 catalog,
225 security: Some(security),
226 access,
227 #[cfg(test)]
228 test_upstream: None,
229 };
230
231 Ok(router(state))
232}
233
234pub async fn serve(config: Config) -> Result<(), Error> {
237 let app = build_app(&config).await?;
238
239 let addr = format!("0.0.0.0:{}", config.port);
240 tracing::info!("integration-proxy listening on http://{addr}");
241
242 let listener = tokio::net::TcpListener::bind(&addr)
243 .await
244 .map_err(|source| Error::Bind {
245 addr: addr.clone(),
246 source,
247 })?;
248 axum::serve(listener, app).await.map_err(Error::Serve)
249}
250
251pub async fn run() -> std::process::ExitCode {
256 let _ = tracing_subscriber::fmt()
257 .with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
258 .try_init();
259
260 let result = match Config::from_env() {
261 Ok(config) => serve(config).await,
262 Err(err) => Err(Error::Config(err)),
263 };
264 match result {
265 Ok(()) => std::process::ExitCode::SUCCESS,
266 Err(err) => {
267 eprintln!("{err}");
268 std::process::ExitCode::FAILURE
269 }
270 }
271}
272
273fn browser_cors() -> tower_http::cors::CorsLayer {
278 use axum::http::{header, HeaderName, Method};
279 use tower_http::cors::{Any, CorsLayer};
280 CorsLayer::new()
281 .allow_origin(Any)
282 .allow_methods([
283 Method::GET,
284 Method::POST,
285 Method::PUT,
286 Method::PATCH,
287 Method::DELETE,
288 Method::OPTIONS,
289 ])
290 .allow_headers([
291 header::AUTHORIZATION,
292 header::CONTENT_TYPE,
293 header::IF_MATCH,
294 HeaderName::from_static(signature::AGENT_HEADER),
295 HeaderName::from_static(signature::PUBLIC_KEY_HEADER),
296 HeaderName::from_static(signature::TIMESTAMP_HEADER),
297 HeaderName::from_static(signature::SIGNATURE_HEADER),
298 HeaderName::from_static(signature::VERSION_HEADER),
299 ])
300 .expose_headers([
301 header::CONTENT_TYPE,
302 header::LINK,
303 header::RETRY_AFTER,
304 header::ETAG,
305 HeaderName::from_static("x-total-count"),
306 HeaderName::from_static("x-next-page"),
307 ])
308}
309
310fn router(state: AppState) -> Router {
311 Router::new()
312 .route("/", get(home))
313 .route("/healthz", get(healthz))
314 .route("/logo.png", get(logo))
315 .route("/connect", get(connect::page))
316 .route("/connect/authorize", post(connect::authorize))
317 .route("/connect/redeem", post(connect::redeem))
318 .route("/connections", get(connections::list))
319 .route("/connections/:connection_id", delete(connections::delete))
320 .route(
321 "/connections/:connection_id/agents",
322 post(connections::add_agent),
323 )
324 .route(
325 "/connections/:connection_id/agents/:agent",
326 delete(connections::remove_agent),
327 )
328 .route("/runtimes", post(connections::add_runtime))
329 .route("/runtimes/:agent", delete(connections::remove_runtime))
330 .route(
331 "/proxy/:connection_id/:platform/*path",
332 axum::routing::any(proxy::forward),
333 )
334 .route("/oauth/:provider/callback", get(oauth::callback))
335 .route("/catalog", get(catalog::list))
336 .route("/catalog/:file", get(catalog::document))
337 .layer(browser_cors())
338 .layer(TraceLayer::new_for_http())
339 .with_state(state)
340}
341
342async fn healthz(State(state): State<AppState>) -> impl axum::response::IntoResponse {
346 match &state.security {
347 Some(security) if security.is_ready().await => (axum::http::StatusCode::OK, "ok"),
348 _ => (
349 axum::http::StatusCode::SERVICE_UNAVAILABLE,
350 "database unavailable",
351 ),
352 }
353}
354
355async fn logo() -> impl axum::response::IntoResponse {
356 (
357 [
358 (axum::http::header::CONTENT_TYPE, "image/png"),
359 (axum::http::header::CACHE_CONTROL, "public, max-age=3600"),
360 ],
361 include_bytes!("../static/logo.png").as_slice(),
362 )
363}
364
365async fn home() -> Html<String> {
366 Html(templates::render_home())
367}
368
369#[cfg(test)]
370mod browser_tests {
371 use super::*;
372 use axum::{
373 body::Body,
374 http::{Request, StatusCode},
375 };
376 use tower::ServiceExt;
377
378 #[tokio::test]
379 async fn a_null_origin_frame_may_preflight_signed_proxy_requests() {
380 let app = test_support::router_without_database();
381 let response = app
382 .clone()
383 .oneshot(
384 Request::builder()
385 .method("OPTIONS")
386 .uri("/proxy/conn/pets/pets")
387 .header("origin", "null")
388 .header("access-control-request-method", "PATCH")
389 .header(
390 "access-control-request-headers",
391 "authorization,content-type,if-match,x-atomic-agent,x-atomic-public-key,x-atomic-timestamp,x-atomic-signature,x-atomic-signature-version",
392 )
393 .body(Body::empty())
394 .unwrap(),
395 )
396 .await
397 .unwrap();
398 assert_eq!(response.status(), StatusCode::OK);
399 assert_eq!(response.headers()["access-control-allow-origin"], "*");
400 let allowed = response.headers()["access-control-allow-headers"]
401 .to_str()
402 .unwrap()
403 .to_owned();
404 for name in [
405 "authorization",
406 "content-type",
407 "if-match",
408 "x-atomic-agent",
409 "x-atomic-public-key",
410 "x-atomic-timestamp",
411 "x-atomic-signature",
412 "x-atomic-signature-version",
413 ] {
414 assert!(allowed.contains(name), "{name} not in {allowed}");
415 }
416 assert!(!response
417 .headers()
418 .contains_key("access-control-allow-credentials"));
419 let response = app
420 .oneshot(
421 Request::builder()
422 .uri("/catalog")
423 .header("origin", "null")
424 .body(Body::empty())
425 .unwrap(),
426 )
427 .await
428 .unwrap();
429 let exposed = response.headers()["access-control-expose-headers"]
430 .to_str()
431 .unwrap();
432 for name in ["link", "retry-after", "etag", "content-type"] {
433 assert!(exposed.contains(name), "{name} not in {exposed}");
434 }
435 assert!(!exposed.contains("x-connection-code"));
436 }
437}