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