atomic-integration-proxy 0.4.1

OAuth/catalog integration proxy (pinned OpenAPI catalog, connections owned by Atomic agents, Atomic v2 request signatures, delegations and frame capabilities) used by Atomic Server and LocalThought
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! OAuth/catalog integration proxy for Atomic Server and LocalThought
//! clients.
//!
//! Clients authenticate with their Atomic agent key (issue #54): every
//! request that matters carries an Atomic v2 request signature, a connection
//! is owned by the agent that redeemed it, and apps use it through
//! owner-signed delegations. Opt-in RFC 8628 device sessions provide scoped
//! bearer authentication to the same canonical owner; they do not create
//! another account identity or revive provider connection codes.
//!
//! This crate is the whole service; the `integration-proxy` binary in this
//! package, and any deployment wrapper (e.g. the Heroku app that serves
//! localthought.io), is a thin `main` around it. The public API is
//! deliberately small:
//!
//! - [`Config`] — all runtime configuration, loaded with
//!   [`Config::from_env`] from the environment variables documented in the
//!   README.
//! - [`build_app`] — loads the catalog, connects to PostgreSQL and returns the
//!   ready-to-serve [`axum::Router`], for callers that bind or wrap it
//!   themselves. [`build_app_with_access`] does the same with a custom
//!   [`AccessPolicy`] (e.g. a SaaS account and tier lookup).
//! - [`serve`] — [`build_app`] plus binding `0.0.0.0:{config.port}` and
//!   serving until the listener fails.
//! - [`run`] — what the bundled binary does: initialise `tracing` from
//!   `RUST_LOG`, load [`Config::from_env`], [`serve`], and turn any
//!   [`Error`] into a message on stderr and a failing exit code.
//!
//! A minimal wrapper binary is therefore:
//!
//! ```no_run
//! #[tokio::main]
//! async fn main() -> std::process::ExitCode {
//!     atomic_integration_proxy::run().await
//! }
//! ```
//!
//! Everything else (route handlers, catalog composition, the security
//! store) is private and may change in any release.

mod access;
mod agent_id;
mod api_error;
mod capability;
mod catalog;
mod client_addr;
mod config;
mod connect;
mod connections;
mod device;
#[cfg(test)]
mod identity_catalog_tests;
mod oauth;
mod pacing;
mod providers;
mod proxy;
mod security;
mod signature;
mod templates;
#[cfg(test)]
mod test_support;
mod transfer;
mod webhooks;

use std::sync::Arc;

use axum::{
    extract::{FromRef, State},
    response::Html,
    routing::{delete, get, post},
    Router,
};
use axum_extra::extract::cookie::Key;
use sha2::{Digest, Sha512};
use tower_http::trace::TraceLayer;
use tracing_subscriber::EnvFilter;

pub use access::{Access, AccessPolicy, AllowAll, EnvAccessPolicy};
pub use agent_id::{parse as parse_agent_id, AgentId};
pub use config::{
    Config, TrustForwardedFor, WebhookConfig, DEFAULT_CATALOG_PATH,
    DEFAULT_KEY_CHECK_LIMIT_PER_HOUR, DEFAULT_OPERATOR_NAME, DEFAULT_WEBHOOK_INBOX_MAX_BYTES,
};
pub use device::DeviceConfig;

#[derive(Clone)]
struct AppState {
    http_client: reqwest::Client,
    key: Key,
    /// `Config::base_url`, trailing `/` trimmed: the signed URL's prefix.
    base_url: String,
    /// `Config::public_origin`: a capability's `aud`, and the only `Origin`
    /// accepted on the consent form.
    public_origin: String,
    catalog: catalog::Catalog,
    device: DeviceConfig,
    security: Option<security::Security>,
    access: Arc<dyn AccessPolicy>,
    /// `OPERATOR_NAME`, `OPERATOR_URL` and the `BASE_URL` host, for the pages.
    operator: templates::Operator,
    /// `KEY_CHECK_LIMIT_PER_HOUR` (0: off) and the window it counts over
    /// (an hour; shorter only in tests).
    key_check_limit: u32,
    key_check_window: std::time::Duration,
    /// `TRUST_FORWARDED_FOR`: where that limit finds the client address.
    trust_forwarded_for: config::TrustForwardedFor,
    /// The webhook inbox and its routes, only with `WEBHOOKS_ENABLED=true`.
    webhooks: Option<Arc<webhooks::Webhooks>>,
    /// The sliding logs pacing this instance's requests under providers'
    /// `x-throttling` quotas on the proxy's own address (pieces.md P4).
    pacer: Arc<pacing::Pacer>,
    #[cfg(test)]
    test_upstream: Option<String>,
}

/// The window [`AppState::key_check_limit`] counts over.
const KEY_CHECK_WINDOW: std::time::Duration = std::time::Duration::from_secs(3600);

impl FromRef<AppState> for Key {
    fn from_ref(state: &AppState) -> Self {
        state.key.clone()
    }
}

pub(crate) fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock before epoch")
        .as_secs()
}

pub(crate) fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock before epoch")
        .as_millis() as u64
}

/// Asks whether `owner` may own and use connections: refused when a key
/// transfer retired it (#410), then the access policy. Every signed route
/// asks this about the connection owner (or the signer that will become
/// one), so a retired owner is refused everywhere: management, redeem,
/// transfers, proxied requests by any caller, and the webhook routes.
pub(crate) async fn check_access(
    state: &AppState,
    owner: &AgentId,
) -> Result<(), api_error::ApiError> {
    if let Some(security) = &state.security {
        match security.is_retired(owner.as_str()).await {
            Ok(false) => {}
            Ok(true) => return Err(api_error::ApiError::AgentRetired),
            Err(_) => return Err(api_error::ApiError::Unavailable),
        }
    }
    match state.access.check(owner).await {
        Access::Allowed => Ok(()),
        Access::Denied(reason) => Err(api_error::ApiError::AccessDenied(reason)),
    }
}

fn build_http_client() -> reqwest::Client {
    // GitHub's REST API requires a User-Agent on every request. Redirects are
    // disabled because only the initial target is validated against the
    // catalog allowlist; a followed redirect would escape that validation.
    // A bounded timeout keeps a stalled or slow upstream from holding the
    // connection (and the caller's request) open indefinitely.
    reqwest::Client::builder()
        .user_agent("LocalThought-integration-proxy")
        .redirect(reqwest::redirect::Policy::none())
        .connect_timeout(std::time::Duration::from_secs(10))
        .timeout(std::time::Duration::from_secs(30))
        .build()
        .expect("failed to build HTTP client")
}

/// A failure while starting or running the proxy. The [`std::fmt::Display`]
/// form is the one-line message the binary prints before exiting.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// Missing or invalid environment configuration.
    Config(String),
    /// The catalog at `CATALOG_PATH` could not be loaded or composed.
    Catalog(String),
    /// The PostgreSQL connection or `ENCRYPTION_KEY` was rejected.
    Security(String),
    /// Binding the listening socket failed.
    Bind {
        /// The address that could not be bound.
        addr: String,
        /// The underlying I/O error.
        source: std::io::Error,
    },
    /// The HTTP server stopped with an I/O error.
    Serve(std::io::Error),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Config(err) => write!(f, "configuration error: {err}"),
            Error::Catalog(err) => write!(f, "catalog configuration error: {err}"),
            Error::Security(err) => write!(f, "security configuration error: {err}"),
            Error::Bind { addr, source } => write!(f, "failed to bind {addr}: {source}"),
            Error::Serve(err) => write!(f, "server error: {err}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Bind { source, .. } | Error::Serve(source) => Some(source),
            _ => None,
        }
    }
}

/// Builds the complete application router from `config`, with the default
/// [`EnvAccessPolicy`] (`REVOKED_SUBJECTS`, `ALLOWED_AGENTS`).
pub async fn build_app(config: &Config) -> Result<Router, Error> {
    let access = EnvAccessPolicy::new(
        config.allowed_agents.clone(),
        config.revoked_subjects.clone(),
    );
    build_app_with_access(config, Arc::new(access)).await
}

/// Builds the complete application router from `config`: the cookie key, the
/// composed catalog (fetched from `config.catalog_path`, which may be an
/// HTTPS URL) and the PostgreSQL-backed store, admitting connection owners
/// through `access`. The returned router already carries CORS and request
/// tracing layers.
pub async fn build_app_with_access(
    config: &Config,
    access: Arc<dyn AccessPolicy>,
) -> Result<Router, Error> {
    let base_url = config::validate_base_url(&config.base_url).map_err(Error::Config)?;
    config.device.validate().map_err(Error::Config)?;
    let key = match &config.session_secret {
        Some(secret) => Key::from(&Sha512::digest(secret.as_bytes())),
        None => {
            tracing::warn!(
                "SESSION_SECRET is not set; using a random key. A consent screen open during a restart must be started again."
            );
            Key::generate()
        }
    };

    let http_client = build_http_client();
    let catalog = catalog::Catalog::load(&config.catalog_path, &http_client)
        .await
        .map_err(Error::Catalog)?;
    let security = security::Security::connect(&config.database_url, &config.encryption_key)
        .await
        .map_err(Error::Security)?;
    // Off by default: with WEBHOOKS_ENABLED unset there are no inbox tables,
    // no sweeper and no webhook route.
    let webhooks = webhooks::start(&config.webhooks, &config.database_url, &security, &catalog)
        .await
        .map_err(Error::Security)?;
    if config.key_check_limit_per_hour > 0
        && config.trust_forwarded_for == config::TrustForwardedFor::None
        && std::env::var_os("DYNO").is_some()
    {
        // Heroku sets `DYNO`. There every peer address is the router's, so
        // without `TRUST_FORWARDED_FOR=heroku` all clients share one limit.
        tracing::warn!(
            "running on Heroku without TRUST_FORWARDED_FOR=heroku: the key-check limit counts the router's address, so all clients share it"
        );
    }

    let state = AppState {
        http_client,
        key,
        base_url,
        public_origin: config.public_origin(),
        catalog,
        device: config.device.clone(),
        security: Some(security),
        access,
        operator: templates::Operator::from_config(config),
        key_check_limit: config.key_check_limit_per_hour,
        key_check_window: KEY_CHECK_WINDOW,
        trust_forwarded_for: config.trust_forwarded_for,
        webhooks,
        pacer: Arc::default(),
        #[cfg(test)]
        test_upstream: None,
    };
    if let Some(webhooks) = &state.webhooks {
        webhooks::sweeper::spawn(
            webhooks.store.clone(),
            webhooks::provider::ProviderHookDeleter {
                state: state.clone(),
            },
        );
    }

    Ok(router(state))
}

/// Runs [`build_app`] and serves it on `0.0.0.0:{config.port}` until the
/// server fails; under normal operation it does not return. Each request
/// carries its peer address (`ConnectInfo<SocketAddr>`), which the key-check
/// limit counts unless `TRUST_FORWARDED_FOR` says otherwise. A caller that
/// serves [`build_app`]'s router itself should do the same
/// (`into_make_service_with_connect_info::<SocketAddr>()`); without it, and
/// without a trusted `X-Forwarded-For`, every client shares one limit.
pub async fn serve(config: Config) -> Result<(), Error> {
    let app = build_app(&config).await?;

    let addr = format!("0.0.0.0:{}", config.port);
    tracing::info!("integration-proxy listening on http://{addr}");

    let listener = tokio::net::TcpListener::bind(&addr)
        .await
        .map_err(|source| Error::Bind {
            addr: addr.clone(),
            source,
        })?;
    axum::serve(
        listener,
        app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
    )
    .await
    .map_err(Error::Serve)
}

/// The bundled binary's entry point: installs a `tracing` subscriber
/// filtered by `RUST_LOG` (default `info`; skipped if the caller already
/// installed one), loads [`Config::from_env`] and runs [`serve`]. Any
/// [`Error`] is printed to stderr and reported as a failing exit code.
pub async fn run() -> std::process::ExitCode {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()))
        .try_init();

    let result = match Config::from_env() {
        Ok(config) => serve(config).await,
        Err(err) => Err(Error::Config(err)),
    };
    match result {
        Ok(()) => std::process::ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("{err}");
            std::process::ExitCode::FAILURE
        }
    }
}

// Signatures and capabilities are supplied explicitly by the caller, never
// as cookies, so any origin may call, including a plugin's null-origin
// frame. Never enable cookie credentials: consent remains a top-level
// navigation.
fn browser_cors() -> tower_http::cors::CorsLayer {
    use axum::http::{header, HeaderName, Method};
    use tower_http::cors::{Any, CorsLayer};
    CorsLayer::new()
        .allow_origin(Any)
        .allow_methods([
            Method::GET,
            Method::POST,
            Method::PUT,
            Method::PATCH,
            Method::DELETE,
            Method::OPTIONS,
        ])
        .allow_headers(
            [
                header::AUTHORIZATION,
                HeaderName::from_static(proxy::IDEMPOTENCY_KEY),
                HeaderName::from_static(signature::AGENT_HEADER),
                HeaderName::from_static(signature::PUBLIC_KEY_HEADER),
                HeaderName::from_static(signature::TIMESTAMP_HEADER),
                HeaderName::from_static(signature::SIGNATURE_HEADER),
                HeaderName::from_static(signature::VERSION_HEADER),
            ]
            .into_iter()
            .chain(proxy::CALLER_HEADERS)
            .collect::<Vec<_>>(),
        )
        // The same list the proxy forwards from, so they cannot drift.
        .expose_headers(proxy::forwarded_response_headers().collect::<Vec<_>>())
}

fn router(state: AppState) -> Router {
    // The webhook routes exist only while the inbox is on.
    let webhook_routes = match &state.webhooks {
        Some(_) => webhooks::routes::router(),
        None => Router::new(),
    };
    Router::new()
        .merge(webhook_routes)
        .merge(device::router())
        .route("/", get(home))
        .route("/healthz", get(healthz))
        .route("/logo.png", get(logo))
        .route("/connect", get(connect::page))
        .route("/connect/authorize", post(connect::authorize))
        .route("/connect/redeem", post(connect::redeem))
        .route("/connections", get(connections::list))
        .route("/connections/:connection_id", delete(connections::delete))
        .route(
            "/connections/:connection_id/agents",
            post(connections::add_agent),
        )
        .route(
            "/connections/:connection_id/agents/:agent",
            delete(connections::remove_agent),
        )
        .route("/runtimes", post(connections::add_runtime))
        .route("/agents/transfer", post(transfer::transfer))
        .route("/runtimes/:agent", delete(connections::remove_runtime))
        .route(
            "/proxy/:connection_id/:platform/*path",
            axum::routing::any(proxy::forward),
        )
        .route("/oauth/:provider/callback", get(oauth::callback))
        .route("/catalog", get(catalog::list))
        .route("/catalog/:file", get(catalog::document))
        .layer(browser_cors())
        .layer(TraceLayer::new_for_http().make_span_with(|request: &axum::http::Request<_>| {
            tracing::info_span!("http_request", method = %request.method(), path = request.uri().path())
        }))
        .with_state(state)
}

/// Reports whether the database is currently reachable, so an operator or
/// load balancer can detect a still-recovering connection instead of only
/// finding out from a failed request.
async fn healthz(State(state): State<AppState>) -> impl axum::response::IntoResponse {
    match &state.security {
        Some(security) if security.is_ready().await => (axum::http::StatusCode::OK, "ok"),
        _ => (
            axum::http::StatusCode::SERVICE_UNAVAILABLE,
            "database unavailable",
        ),
    }
}

async fn logo() -> impl axum::response::IntoResponse {
    (
        [
            (axum::http::header::CONTENT_TYPE, "image/png"),
            (axum::http::header::CACHE_CONTROL, "public, max-age=3600"),
        ],
        include_bytes!("../static/logo.png").as_slice(),
    )
}

async fn home(State(state): State<AppState>) -> Html<String> {
    Html(templates::render_home(&state.operator))
}

#[cfg(test)]
mod browser_tests {
    use super::*;
    use axum::{
        body::Body,
        http::{Request, StatusCode},
    };
    use tower::ServiceExt;

    #[tokio::test]
    async fn a_null_origin_frame_may_preflight_signed_proxy_requests() {
        let app = test_support::router_without_database();
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("OPTIONS")
                    .uri("/proxy/conn/pets/pets")
                    .header("origin", "null")
                    .header("access-control-request-method", "PATCH")
                    .header(
                        "access-control-request-headers",
                        "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",
                    )
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(response.headers()["access-control-allow-origin"], "*");
        let allowed = response.headers()["access-control-allow-headers"]
            .to_str()
            .unwrap()
            .to_owned();
        for name in [
            "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",
        ] {
            assert!(allowed.contains(name), "{name} not in {allowed}");
        }
        assert!(!response
            .headers()
            .contains_key("access-control-allow-credentials"));
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/catalog")
                    .header("origin", "null")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let exposed = response.headers()["access-control-expose-headers"]
            .to_str()
            .unwrap();
        let exposed: Vec<&str> = exposed.split(',').map(str::trim).collect();
        for name in [
            "link",
            "retry-after",
            "etag",
            "content-type",
            "last-modified",
            "x-total-count",
            "x-next-page",
        ]
        .into_iter()
        .chain(proxy::RATE_LIMIT_HEADERS)
        {
            assert!(exposed.contains(&name), "{name} not in {exposed:?}");
        }
        assert!(!exposed.contains(&"x-connection-code"));
        assert!(!exposed.contains(&"set-cookie"));
    }
}