Skip to main content

atomic_integration_proxy/
lib.rs

1//! OAuth/catalog integration proxy for Atomic Server and LocalThought
2//! clients.
3//!
4//! Clients authenticate with their Atomic agent key (issue #54): every
5//! request that matters carries an Atomic v2 request signature, a connection
6//! is owned by the agent that redeemed it, and apps use it through
7//! owner-signed delegations. There are no accounts, logins, tenants or
8//! rotating codes.
9//!
10//! This crate is the whole service; the `integration-proxy` binary in this
11//! package, and any deployment wrapper (e.g. the Heroku app that serves
12//! localthought.io), is a thin `main` around it. The public API is
13//! deliberately small:
14//!
15//! - [`Config`] — all runtime configuration, loaded with
16//!   [`Config::from_env`] from the environment variables documented in the
17//!   README.
18//! - [`build_app`] — loads the catalog, connects to PostgreSQL and returns the
19//!   ready-to-serve [`axum::Router`], for callers that bind or wrap it
20//!   themselves. [`build_app_with_access`] does the same with a custom
21//!   [`AccessPolicy`] (e.g. a SaaS account and tier lookup).
22//! - [`serve`] — [`build_app`] plus binding `0.0.0.0:{config.port}` and
23//!   serving until the listener fails.
24//! - [`run`] — what the bundled binary does: initialise `tracing` from
25//!   `RUST_LOG`, load [`Config::from_env`], [`serve`], and turn any
26//!   [`Error`] into a message on stderr and a failing exit code.
27//!
28//! A minimal wrapper binary is therefore:
29//!
30//! ```no_run
31//! #[tokio::main]
32//! async fn main() -> std::process::ExitCode {
33//!     atomic_integration_proxy::run().await
34//! }
35//! ```
36//!
37//! Everything else (route handlers, catalog composition, the security
38//! store) is private and may change in any release.
39
40mod 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    /// `Config::base_url`, trailing `/` trimmed: the signed URL's prefix.
85    base_url: String,
86    /// `Config::public_origin`: a capability's `aud`, and the only `Origin`
87    /// accepted on the consent form.
88    public_origin: String,
89    catalog: catalog::Catalog,
90    security: Option<security::Security>,
91    access: Arc<dyn AccessPolicy>,
92    /// `OPERATOR_NAME`, `OPERATOR_URL` and the `BASE_URL` host, for the pages.
93    operator: templates::Operator,
94    /// `KEY_CHECK_LIMIT_PER_HOUR` (0: off) and the window it counts over
95    /// (an hour; shorter only in tests).
96    key_check_limit: u32,
97    key_check_window: std::time::Duration,
98    /// `TRUST_FORWARDED_FOR`: where that limit finds the client address.
99    trust_forwarded_for: config::TrustForwardedFor,
100    #[cfg(test)]
101    test_upstream: Option<String>,
102}
103
104/// The window [`AppState::key_check_limit`] counts over.
105const 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
127/// Asks the access policy about `owner`.
128pub(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    // GitHub's REST API requires a User-Agent on every request. Redirects are
140    // disabled because only the initial target is validated against the
141    // catalog allowlist; a followed redirect would escape that validation.
142    // A bounded timeout keeps a stalled or slow upstream from holding the
143    // connection (and the caller's request) open indefinitely.
144    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/// A failure while starting or running the proxy. The [`std::fmt::Display`]
154/// form is the one-line message the binary prints before exiting.
155#[derive(Debug)]
156#[non_exhaustive]
157pub enum Error {
158    /// Missing or invalid environment configuration.
159    Config(String),
160    /// The catalog at `CATALOG_PATH` could not be loaded or composed.
161    Catalog(String),
162    /// The PostgreSQL connection or `ENCRYPTION_KEY` was rejected.
163    Security(String),
164    /// Binding the listening socket failed.
165    Bind {
166        /// The address that could not be bound.
167        addr: String,
168        /// The underlying I/O error.
169        source: std::io::Error,
170    },
171    /// The HTTP server stopped with an I/O error.
172    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
196/// Builds the complete application router from `config`, with the default
197/// [`EnvAccessPolicy`] (`REVOKED_SUBJECTS`, `ALLOWED_AGENTS`).
198pub 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
206/// Builds the complete application router from `config`: the cookie key, the
207/// composed catalog (fetched from `config.catalog_path`, which may be an
208/// HTTPS URL) and the PostgreSQL-backed store, admitting connection owners
209/// through `access`. The returned router already carries CORS and request
210/// tracing layers.
211pub 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        // Heroku sets `DYNO`. There every peer address is the router's, so
238        // without `TRUST_FORWARDED_FOR=heroku` all clients share one limit.
239        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
263/// Runs [`build_app`] and serves it on `0.0.0.0:{config.port}` until the
264/// server fails; under normal operation it does not return. Each request
265/// carries its peer address (`ConnectInfo<SocketAddr>`), which the key-check
266/// limit counts unless `TRUST_FORWARDED_FOR` says otherwise. A caller that
267/// serves [`build_app`]'s router itself should do the same
268/// (`into_make_service_with_connect_info::<SocketAddr>()`); without it, and
269/// without a trusted `X-Forwarded-For`, every client shares one limit.
270pub 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
290/// The bundled binary's entry point: installs a `tracing` subscriber
291/// filtered by `RUST_LOG` (default `info`; skipped if the caller already
292/// installed one), loads [`Config::from_env`] and runs [`serve`]. Any
293/// [`Error`] is printed to stderr and reported as a failing exit code.
294pub 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
312// Signatures and capabilities are supplied explicitly by the caller, never
313// as cookies, so any origin may call, including a plugin's null-origin
314// frame. Never enable cookie credentials: consent remains a top-level
315// navigation.
316fn 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
381/// Reports whether the database is currently reachable, so an operator or
382/// load balancer can detect a still-recovering connection instead of only
383/// finding out from a failed request.
384async 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}