1mod access;
42mod agent_id;
43mod api_error;
44mod capability;
45mod catalog;
46mod client_addr;
47mod config;
48mod connect;
49mod connections;
50mod device;
51#[cfg(test)]
52mod identity_catalog_tests;
53mod oauth;
54mod pacing;
55mod providers;
56mod proxy;
57mod security;
58mod signature;
59mod templates;
60#[cfg(test)]
61mod test_support;
62mod transfer;
63mod webhooks;
64
65use std::sync::Arc;
66
67use axum::{
68 extract::{FromRef, State},
69 response::Html,
70 routing::{delete, get, post},
71 Router,
72};
73use axum_extra::extract::cookie::Key;
74use sha2::{Digest, Sha512};
75use tower_http::trace::TraceLayer;
76use tracing_subscriber::EnvFilter;
77
78pub use access::{Access, AccessPolicy, AllowAll, EnvAccessPolicy};
79pub use agent_id::{parse as parse_agent_id, AgentId};
80pub use config::{
81 Config, TrustForwardedFor, WebhookConfig, DEFAULT_CATALOG_PATH,
82 DEFAULT_KEY_CHECK_LIMIT_PER_HOUR, DEFAULT_OPERATOR_NAME, DEFAULT_WEBHOOK_INBOX_MAX_BYTES,
83};
84pub use device::DeviceConfig;
85
86#[derive(Clone)]
87struct AppState {
88 http_client: reqwest::Client,
89 key: Key,
90 base_url: String,
92 public_origin: String,
95 catalog: catalog::Catalog,
96 device: DeviceConfig,
97 security: Option<security::Security>,
98 access: Arc<dyn AccessPolicy>,
99 operator: templates::Operator,
101 key_check_limit: u32,
104 key_check_window: std::time::Duration,
105 trust_forwarded_for: config::TrustForwardedFor,
107 webhooks: Option<Arc<webhooks::Webhooks>>,
109 pacer: Arc<pacing::Pacer>,
112 #[cfg(test)]
113 test_upstream: Option<String>,
114}
115
116const KEY_CHECK_WINDOW: std::time::Duration = std::time::Duration::from_secs(3600);
118
119impl FromRef<AppState> for Key {
120 fn from_ref(state: &AppState) -> Self {
121 state.key.clone()
122 }
123}
124
125pub(crate) fn now_secs() -> u64 {
126 std::time::SystemTime::now()
127 .duration_since(std::time::UNIX_EPOCH)
128 .expect("clock before epoch")
129 .as_secs()
130}
131
132pub(crate) fn now_ms() -> u64 {
133 std::time::SystemTime::now()
134 .duration_since(std::time::UNIX_EPOCH)
135 .expect("clock before epoch")
136 .as_millis() as u64
137}
138
139pub(crate) async fn check_access(
145 state: &AppState,
146 owner: &AgentId,
147) -> Result<(), api_error::ApiError> {
148 if let Some(security) = &state.security {
149 match security.is_retired(owner.as_str()).await {
150 Ok(false) => {}
151 Ok(true) => return Err(api_error::ApiError::AgentRetired),
152 Err(_) => return Err(api_error::ApiError::Unavailable),
153 }
154 }
155 match state.access.check(owner).await {
156 Access::Allowed => Ok(()),
157 Access::Denied(reason) => Err(api_error::ApiError::AccessDenied(reason)),
158 }
159}
160
161fn build_http_client() -> reqwest::Client {
162 reqwest::Client::builder()
168 .user_agent("LocalThought-integration-proxy")
169 .redirect(reqwest::redirect::Policy::none())
170 .connect_timeout(std::time::Duration::from_secs(10))
171 .timeout(std::time::Duration::from_secs(30))
172 .build()
173 .expect("failed to build HTTP client")
174}
175
176#[derive(Debug)]
179#[non_exhaustive]
180pub enum Error {
181 Config(String),
183 Catalog(String),
185 Security(String),
187 Bind {
189 addr: String,
191 source: std::io::Error,
193 },
194 Serve(std::io::Error),
196}
197
198impl std::fmt::Display for Error {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 match self {
201 Error::Config(err) => write!(f, "configuration error: {err}"),
202 Error::Catalog(err) => write!(f, "catalog configuration error: {err}"),
203 Error::Security(err) => write!(f, "security configuration error: {err}"),
204 Error::Bind { addr, source } => write!(f, "failed to bind {addr}: {source}"),
205 Error::Serve(err) => write!(f, "server error: {err}"),
206 }
207 }
208}
209
210impl std::error::Error for Error {
211 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
212 match self {
213 Error::Bind { source, .. } | Error::Serve(source) => Some(source),
214 _ => None,
215 }
216 }
217}
218
219pub async fn build_app(config: &Config) -> Result<Router, Error> {
222 let access = EnvAccessPolicy::new(
223 config.allowed_agents.clone(),
224 config.revoked_subjects.clone(),
225 );
226 build_app_with_access(config, Arc::new(access)).await
227}
228
229pub async fn build_app_with_access(
235 config: &Config,
236 access: Arc<dyn AccessPolicy>,
237) -> Result<Router, Error> {
238 let base_url = config::validate_base_url(&config.base_url).map_err(Error::Config)?;
239 config.device.validate().map_err(Error::Config)?;
240 let key = match &config.session_secret {
241 Some(secret) => Key::from(&Sha512::digest(secret.as_bytes())),
242 None => {
243 tracing::warn!(
244 "SESSION_SECRET is not set; using a random key. A consent screen open during a restart must be started again."
245 );
246 Key::generate()
247 }
248 };
249
250 let http_client = build_http_client();
251 let catalog = catalog::Catalog::load(&config.catalog_path, &http_client)
252 .await
253 .map_err(Error::Catalog)?;
254 let security = security::Security::connect(&config.database_url, &config.encryption_key)
255 .await
256 .map_err(Error::Security)?;
257 let webhooks = webhooks::start(&config.webhooks, &config.database_url, &security, &catalog)
260 .await
261 .map_err(Error::Security)?;
262 if config.key_check_limit_per_hour > 0
263 && config.trust_forwarded_for == config::TrustForwardedFor::None
264 && std::env::var_os("DYNO").is_some()
265 {
266 tracing::warn!(
269 "running on Heroku without TRUST_FORWARDED_FOR=heroku: the key-check limit counts the router's address, so all clients share it"
270 );
271 }
272
273 let state = AppState {
274 http_client,
275 key,
276 base_url,
277 public_origin: config.public_origin(),
278 catalog,
279 device: config.device.clone(),
280 security: Some(security),
281 access,
282 operator: templates::Operator::from_config(config),
283 key_check_limit: config.key_check_limit_per_hour,
284 key_check_window: KEY_CHECK_WINDOW,
285 trust_forwarded_for: config.trust_forwarded_for,
286 webhooks,
287 pacer: Arc::default(),
288 #[cfg(test)]
289 test_upstream: None,
290 };
291 if let Some(webhooks) = &state.webhooks {
292 webhooks::sweeper::spawn(
293 webhooks.store.clone(),
294 webhooks::provider::ProviderHookDeleter {
295 state: state.clone(),
296 },
297 );
298 }
299
300 Ok(router(state))
301}
302
303pub async fn serve(config: Config) -> Result<(), Error> {
311 let app = build_app(&config).await?;
312
313 let addr = format!("0.0.0.0:{}", config.port);
314 tracing::info!("integration-proxy listening on http://{addr}");
315
316 let listener = tokio::net::TcpListener::bind(&addr)
317 .await
318 .map_err(|source| Error::Bind {
319 addr: addr.clone(),
320 source,
321 })?;
322 axum::serve(
323 listener,
324 app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
325 )
326 .await
327 .map_err(Error::Serve)
328}
329
330pub async fn run() -> std::process::ExitCode {
335 let _ = tracing_subscriber::fmt()
336 .with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
337 .try_init();
338
339 let result = match Config::from_env() {
340 Ok(config) => serve(config).await,
341 Err(err) => Err(Error::Config(err)),
342 };
343 match result {
344 Ok(()) => std::process::ExitCode::SUCCESS,
345 Err(err) => {
346 eprintln!("{err}");
347 std::process::ExitCode::FAILURE
348 }
349 }
350}
351
352fn browser_cors() -> tower_http::cors::CorsLayer {
357 use axum::http::{header, HeaderName, Method};
358 use tower_http::cors::{Any, CorsLayer};
359 CorsLayer::new()
360 .allow_origin(Any)
361 .allow_methods([
362 Method::GET,
363 Method::POST,
364 Method::PUT,
365 Method::PATCH,
366 Method::DELETE,
367 Method::OPTIONS,
368 ])
369 .allow_headers(
370 [
371 header::AUTHORIZATION,
372 HeaderName::from_static(proxy::IDEMPOTENCY_KEY),
373 HeaderName::from_static(signature::AGENT_HEADER),
374 HeaderName::from_static(signature::PUBLIC_KEY_HEADER),
375 HeaderName::from_static(signature::TIMESTAMP_HEADER),
376 HeaderName::from_static(signature::SIGNATURE_HEADER),
377 HeaderName::from_static(signature::VERSION_HEADER),
378 ]
379 .into_iter()
380 .chain(proxy::CALLER_HEADERS)
381 .collect::<Vec<_>>(),
382 )
383 .expose_headers(proxy::forwarded_response_headers().collect::<Vec<_>>())
385}
386
387fn router(state: AppState) -> Router {
388 let webhook_routes = match &state.webhooks {
390 Some(_) => webhooks::routes::router(),
391 None => Router::new(),
392 };
393 Router::new()
394 .merge(webhook_routes)
395 .merge(device::router())
396 .route("/", get(home))
397 .route("/healthz", get(healthz))
398 .route("/logo.png", get(logo))
399 .route("/connect", get(connect::page))
400 .route("/connect/authorize", post(connect::authorize))
401 .route("/connect/redeem", post(connect::redeem))
402 .route("/connections", get(connections::list))
403 .route("/connections/:connection_id", delete(connections::delete))
404 .route(
405 "/connections/:connection_id/agents",
406 post(connections::add_agent),
407 )
408 .route(
409 "/connections/:connection_id/agents/:agent",
410 delete(connections::remove_agent),
411 )
412 .route("/runtimes", post(connections::add_runtime))
413 .route("/agents/transfer", post(transfer::transfer))
414 .route("/runtimes/:agent", delete(connections::remove_runtime))
415 .route(
416 "/proxy/:connection_id/:platform/*path",
417 axum::routing::any(proxy::forward),
418 )
419 .route("/oauth/:provider/callback", get(oauth::callback))
420 .route("/catalog", get(catalog::list))
421 .route("/catalog/:file", get(catalog::document))
422 .layer(browser_cors())
423 .layer(TraceLayer::new_for_http().make_span_with(|request: &axum::http::Request<_>| {
424 tracing::info_span!("http_request", method = %request.method(), path = request.uri().path())
425 }))
426 .with_state(state)
427}
428
429async fn healthz(State(state): State<AppState>) -> impl axum::response::IntoResponse {
433 match &state.security {
434 Some(security) if security.is_ready().await => (axum::http::StatusCode::OK, "ok"),
435 _ => (
436 axum::http::StatusCode::SERVICE_UNAVAILABLE,
437 "database unavailable",
438 ),
439 }
440}
441
442async fn logo() -> impl axum::response::IntoResponse {
443 (
444 [
445 (axum::http::header::CONTENT_TYPE, "image/png"),
446 (axum::http::header::CACHE_CONTROL, "public, max-age=3600"),
447 ],
448 include_bytes!("../static/logo.png").as_slice(),
449 )
450}
451
452async fn home(State(state): State<AppState>) -> Html<String> {
453 Html(templates::render_home(&state.operator))
454}
455
456#[cfg(test)]
457mod browser_tests {
458 use super::*;
459 use axum::{
460 body::Body,
461 http::{Request, StatusCode},
462 };
463 use tower::ServiceExt;
464
465 #[tokio::test]
466 async fn a_null_origin_frame_may_preflight_signed_proxy_requests() {
467 let app = test_support::router_without_database();
468 let response = app
469 .clone()
470 .oneshot(
471 Request::builder()
472 .method("OPTIONS")
473 .uri("/proxy/conn/pets/pets")
474 .header("origin", "null")
475 .header("access-control-request-method", "PATCH")
476 .header(
477 "access-control-request-headers",
478 "authorization,content-type,if-match,if-none-match,if-modified-since,idempotency-key,x-atomic-agent,x-atomic-public-key,x-atomic-timestamp,x-atomic-signature,x-atomic-signature-version",
479 )
480 .body(Body::empty())
481 .unwrap(),
482 )
483 .await
484 .unwrap();
485 assert_eq!(response.status(), StatusCode::OK);
486 assert_eq!(response.headers()["access-control-allow-origin"], "*");
487 let allowed = response.headers()["access-control-allow-headers"]
488 .to_str()
489 .unwrap()
490 .to_owned();
491 for name in [
492 "authorization",
493 "content-type",
494 "if-match",
495 "if-none-match",
496 "if-modified-since",
497 "idempotency-key",
498 "x-atomic-agent",
499 "x-atomic-public-key",
500 "x-atomic-timestamp",
501 "x-atomic-signature",
502 "x-atomic-signature-version",
503 ] {
504 assert!(allowed.contains(name), "{name} not in {allowed}");
505 }
506 assert!(!response
507 .headers()
508 .contains_key("access-control-allow-credentials"));
509 let response = app
510 .oneshot(
511 Request::builder()
512 .uri("/catalog")
513 .header("origin", "null")
514 .body(Body::empty())
515 .unwrap(),
516 )
517 .await
518 .unwrap();
519 let exposed = response.headers()["access-control-expose-headers"]
520 .to_str()
521 .unwrap();
522 let exposed: Vec<&str> = exposed.split(',').map(str::trim).collect();
523 for name in [
524 "link",
525 "retry-after",
526 "etag",
527 "content-type",
528 "last-modified",
529 "x-total-count",
530 "x-next-page",
531 ]
532 .into_iter()
533 .chain(proxy::RATE_LIMIT_HEADERS)
534 {
535 assert!(exposed.contains(&name), "{name} not in {exposed:?}");
536 }
537 assert!(!exposed.contains(&"x-connection-code"));
538 assert!(!exposed.contains(&"set-cookie"));
539 }
540}