OXYGENHUB
# d2c1d6a7d12e oxygenhub / crates / hub / src / lib.rs
5.4 KiB · Rust · last changed Flow: SLSA provenance for artifacts, in DSSE, that cosign verifies 20 days ago source blame history raw
8d2caf12 Andy McCall ↶ 1
//! OxygenHub: a forge for Oxygen repositories (`docs/spec.md`).
d23464c0 Andy McCall ↶ 2
//!
3
//! One process: an axum router serving pages, the JSON API and the wire
4
//! protocol; SQLite for hub state; repositories as bare Oxygen stores.
5
6
pub mod api;
ea85398a Andy McCall ↶ 7
pub mod apt;
e71846aa Andy McCall ↶ 8
pub mod assistants;
19bb31ff Andy McCall ↶ 9
pub mod auth;
d23464c0 Andy McCall ↶ 10
pub mod config;
11
pub mod db;
b64e2537 Andy McCall ↶ 12
pub mod events;
42fa9554 Andy McCall ↶ 13
pub mod flow;
b64e2537 Andy McCall ↶ 14
pub mod hooks;
d23464c0 Andy McCall ↶ 15
pub mod keys;
2a83f530 Andy McCall ↶ 16
pub mod levels;
5e6d6484 Andy McCall ↶ 17
pub mod live;
34beb1a7 Andy McCall ↶ 18
pub mod mail;
8a3334b7 Andy McCall ↶ 19
pub mod maintenance;
3f4b0ea6 Andy McCall ↶ 20
pub mod mirror;
18e381ea Andy McCall ↶ 21
pub mod notify;
d1727c57 Andy McCall ↶ 22
pub mod oidc;
d23464c0 Andy McCall ↶ 23
pub mod protocol;
076c7a7c Andy McCall ↶ 24
pub mod provenance;
d23464c0 Andy McCall ↶ 25
pub mod render;
26
pub mod repos;
4ac01a73 Andy McCall ↶ 27
pub mod secrets;
2a83f530 Andy McCall ↶ 28
pub mod variables;
d23464c0 Andy McCall ↶ 29
pub mod web;
30
31
use crate::config::Config;
32
use crate::repos::Repos;
33
use std::sync::Arc;
34
35
/// Everything a request handler can reach.
36
pub struct App {
37
    pub config: Config,
38
    pub db: db::Pool,
39
    pub repos: Arc<Repos>,
40
    pub server: Arc<oxy_server::Server>,
41
    pub hub_key: keys::HubKey,
19bb31ff Andy McCall ↶ 42
    pub cookie_key: auth::CookieKey,
e71846aa Andy McCall ↶ 43
    /// Seals AI assistants' tokens at rest (hub spec §13.4).
44
    pub assistant_key: assistants::SecretKey,
4ac01a73 Andy McCall ↶ 45
    /// Seals Flow secrets at rest (hub spec §13.2, #107).
46
    pub secret_key: assistants::SecretKey,
d1727c57 Andy McCall ↶ 47
    /// The OIDC issuer for jobs (hub spec §13.5), made on first use.
48
    pub oidc: tokio::sync::OnceCell<oidc::Issuer>,
7d2eb590 Andy McCall ↶ 49
    /// Which assistants are answering which proposals, and recent calls
50
    /// per repository (hub spec §13.4).
51
    pub assistant_gate: std::sync::Mutex<assistants::Gate>,
b64e2537 Andy McCall ↶ 52
    pub events: events::Events,
5e6d6484 Andy McCall ↶ 53
    /// Who is resolving which conflict together (hub spec §6.10).
54
    pub rooms: Arc<live::Rooms>,
3556d08e Andy McCall ↶ 55
    /// Outgoing mail: hub.toml's `[email]`, overridden by what the admin
56
    /// page saved (#101).
57
    pub mail: std::sync::RwLock<config::Email>,
d23464c0 Andy McCall ↶ 58
    pub started: std::time::Instant,
59
}
60
d1727c57 Andy McCall ↶ 61
impl App {
62
    /// The OIDC issuer, its key loaded or made the first time it is asked for.
63
    pub async fn oidc(&self) -> anyhow::Result<&oidc::Issuer> {
64
        let keys = self.config.keys_dir();
65
        self.oidc.get_or_try_init(|| async move { tokio::task::spawn_blocking(move || oidc::Issuer::load_or_create(&keys)).await? }).await
66
    }
67
}
68
d23464c0 Andy McCall ↶ 69
pub type Shared = Arc<App>;
70
71
/// Open the data directory and build the application state. `init` must
72
/// have run once; `serve` and the tests call this.
73
pub async fn build(config: Config) -> anyhow::Result<Shared> {
74
    std::fs::create_dir_all(config.repos_dir())?;
75
    let db = db::open(&config.db_path()).await?;
76
    let repos = Arc::new(Repos::new(config.repos_dir()));
77
    let hub_key = keys::ensure_identity(&config.keys_dir(), &config.site.name, config.base_url())?;
19bb31ff Andy McCall ↶ 78
    let cookie_key = auth::CookieKey::load_or_create(&config.keys_dir())?;
e71846aa Andy McCall ↶ 79
    let assistant_key = assistants::SecretKey::load_or_create(&config.keys_dir())?;
4ac01a73 Andy McCall ↶ 80
    let secret_key = assistants::SecretKey::load_or_create_named(&config.keys_dir(), "secrets.key")?;
d23464c0 Andy McCall ↶ 81
    let backend = protocol::HubBackend::new(repos.clone(), db.clone(), config.auth.push_tokens.clone(), tokio::runtime::Handle::current());
18e381ea Andy McCall ↶ 82
    let slot = backend.app_slot();
d23464c0 Andy McCall ↶ 83
    let server = oxy_server::Server::new(backend);
3556d08e Andy McCall ↶ 84
    let mail = mail::load(&db, &config.email).await;
b64e2537 Andy McCall ↶ 85
    let app = Arc::new(App {
3556d08e Andy McCall ↶ 86
        mail: std::sync::RwLock::new(mail),
b64e2537 Andy McCall ↶ 87
        config,
88
        db,
89
        repos,
90
        server,
91
        hub_key,
92
        cookie_key,
e71846aa Andy McCall ↶ 93
        assistant_key,
4ac01a73 Andy McCall ↶ 94
        secret_key,
d1727c57 Andy McCall ↶ 95
        oidc: tokio::sync::OnceCell::new(),
7d2eb590 Andy McCall ↶ 96
        assistant_gate: std::sync::Mutex::new(assistants::Gate::default()),
b64e2537 Andy McCall ↶ 97
        events: events::Events::default(),
5e6d6484 Andy McCall ↶ 98
        rooms: Arc::new(live::Rooms::default()),
b64e2537 Andy McCall ↶ 99
        started: std::time::Instant::now(),
100
    });
18e381ea Andy McCall ↶ 101
    *slot.lock().unwrap() = Some(Arc::downgrade(&app));
b64e2537 Andy McCall ↶ 102
    tokio::spawn(hooks::worker(app.clone()));
070a7b64 Andy McCall ↶ 103
    tokio::spawn(flow::reaper(app.clone()));
348f8c4b Andy McCall ↶ 104
    tokio::spawn(flow::scheduler(app.clone()));
8a3334b7 Andy McCall ↶ 105
    tokio::spawn(maintenance::nightly(app.clone()));
18e381ea Andy McCall ↶ 106
    Ok(app)
d23464c0 Andy McCall ↶ 107
}
108
109
/// The full router: pages, API, protocol and static assets.
110
pub fn router(app: Shared) -> axum::Router {
111
    web::router(app)
112
}
113
114
/// Serve on the configured addresses until the process is told to stop.
115
pub async fn serve(app: Shared) -> anyhow::Result<()> {
116
    let router = router(app.clone());
117
    let http = app.config.bind_addr()?;
118
    let https = app.config.tls_bind_addr()?;
119
    if http.is_none() && https.is_none() {
120
        anyhow::bail!("nothing to bind: set server.bind or server.tls_bind");
121
    }
122
    let mut tasks = tokio::task::JoinSet::new();
123
    if let Some(addr) = http {
124
        let listener = tokio::net::TcpListener::bind(addr).await?;
125
        tracing::info!("http on {addr}");
126
        let r = router.clone();
60f11b71 Andy McCall ↶ 127
        tasks.spawn(async move {
128
            axum::serve(listener, r.into_make_service_with_connect_info::<std::net::SocketAddr>()).await.map_err(anyhow::Error::from)
129
        });
d23464c0 Andy McCall ↶ 130
    }
131
    if let Some(addr) = https {
132
        let _ = rustls::crypto::ring::default_provider().install_default();
133
        let tls = axum_server::tls_rustls::RustlsConfig::from_pem_file(app.config.tls_cert(), app.config.tls_key())
134
            .await
135
            .map_err(|e| anyhow::anyhow!("loading TLS files: {e}"))?;
136
        tracing::info!("https on {addr}");
137
        let r = router.clone();
60f11b71 Andy McCall ↶ 138
        tasks.spawn(async move {
139
            axum_server::bind_rustls(addr, tls)
140
                .serve(r.into_make_service_with_connect_info::<std::net::SocketAddr>())
141
                .await
142
                .map_err(anyhow::Error::from)
143
        });
d23464c0 Andy McCall ↶ 144
    }
145
    tokio::select! {
146
        r = tasks.join_next() => { r.transpose()?.transpose()?; Ok(()) }
147
        _ = tokio::signal::ctrl_c() => { tracing::info!("stopping"); Ok(()) }
148
    }
149
}