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