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