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 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    /// `Config::base_url`, trailing `/` trimmed: the signed URL's prefix.
81    base_url: String,
82    /// `Config::public_origin`: a capability's `aud`, and the only `Origin`
83    /// accepted on the consent form.
84    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
112/// Asks the access policy about `owner`.
113pub(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    // GitHub's REST API requires a User-Agent on every request. Redirects are
125    // disabled because only the initial target is validated against the
126    // catalog allowlist; a followed redirect would escape that validation.
127    // A bounded timeout keeps a stalled or slow upstream from holding the
128    // connection (and the caller's request) open indefinitely.
129    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/// A failure while starting or running the proxy. The [`std::fmt::Display`]
139/// form is the one-line message the binary prints before exiting.
140#[derive(Debug)]
141#[non_exhaustive]
142pub enum Error {
143    /// Missing or invalid environment configuration.
144    Config(String),
145    /// The catalog at `CATALOG_PATH` could not be loaded or composed.
146    Catalog(String),
147    /// The PostgreSQL connection or `ENCRYPTION_KEY` was rejected.
148    Security(String),
149    /// Binding the listening socket failed.
150    Bind {
151        /// The address that could not be bound.
152        addr: String,
153        /// The underlying I/O error.
154        source: std::io::Error,
155    },
156    /// The HTTP server stopped with an I/O error.
157    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
181/// Builds the complete application router from `config`, with the default
182/// [`EnvAccessPolicy`] (`REVOKED_SUBJECTS`, `ALLOWED_AGENTS`).
183pub 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
191/// Builds the complete application router from `config`: the cookie key, the
192/// composed catalog (fetched from `config.catalog_path`, which may be an
193/// HTTPS URL) and the PostgreSQL-backed store, admitting connection owners
194/// through `access`. The returned router already carries CORS and request
195/// tracing layers.
196pub 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
234/// Runs [`build_app`] and serves it on `0.0.0.0:{config.port}` until the
235/// server fails; under normal operation it does not return.
236pub 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
251/// The bundled binary's entry point: installs a `tracing` subscriber
252/// filtered by `RUST_LOG` (default `info`; skipped if the caller already
253/// installed one), loads [`Config::from_env`] and runs [`serve`]. Any
254/// [`Error`] is printed to stderr and reported as a failing exit code.
255pub 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
273// Signatures and capabilities are supplied explicitly by the caller, never
274// as cookies, so any origin may call, including a plugin's null-origin
275// frame. Never enable cookie credentials: consent remains a top-level
276// navigation.
277fn 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
342/// Reports whether the database is currently reachable, so an operator or
343/// load balancer can detect a still-recovering connection instead of only
344/// finding out from a failed request.
345async 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}