OXYGENHUB
# d0fbea2eb46e oxygenhub / crates / hub / src / protocol.rs
16.3 KiB · Rust · last changed Advanced settings: transfer, archive, delete, wiki placeholder 1 month ago source blame history raw
1
//! The wire protocol, embedded (hub spec §3.3, §5.4): `oxy-server`'s
2
//! `Server` over a backend that resolves `owner/name`, authorises reads
3
//! and pushes by account role and token scope, and records who pushed.
4
5
use crate::auth::{self, Access, Role};
6
use crate::db::{self, accounts::Account};
7
use crate::repos::{RepoName, Repos};
8
use crate::Shared;
9
use axum::body::Bytes;
10
use axum::extract::{Path, State};
11
use axum::http::{HeaderMap, Method, StatusCode};
12
use axum::response::{IntoResponse, Response};
13
use oxy_core::repo::{PushReport, Repo};
14
use oxy_server::{Backend, Endpoint, Failure};
15
use std::sync::Arc;
16
17
pub struct HubBackend {
18
    repos: Arc<Repos>,
19
    pool: db::Pool,
20
    /// Site tokens from `hub.toml`: full access, for bootstrapping.
21
    site_tokens: Vec<String>,
22
    runtime: tokio::runtime::Handle,
23
    /// The application, set once it exists (the backend is built first).
24
    app_hint: Arc<std::sync::Mutex<Option<std::sync::Weak<crate::App>>>>,
25
}
26
27
/// Who a request's credential resolved to.
28
enum Caller {
29
    Anonymous,
30
    /// A site token from the configuration.
31
    Site,
32
    Token(Box<Account>, Box<db::accounts::Token>),
33
    /// A running OxygenFlow job: reads its own repository and the subrepos
34
    /// its state pins, nothing else (hub spec §13.2).
35
    Job {
36
        repo_id: i64,
37
        also: Vec<i64>,
38
    },
39
}
40
41
impl HubBackend {
42
    pub fn new(repos: Arc<Repos>, pool: db::Pool, site_tokens: Vec<String>, runtime: tokio::runtime::Handle) -> HubBackend {
43
        HubBackend { repos, pool, site_tokens, runtime, app_hint: Arc::new(std::sync::Mutex::new(None)) }
44
    }
45
46
    /// The slot the application registers itself in after construction.
47
    pub fn app_slot(&self) -> Arc<std::sync::Mutex<Option<std::sync::Weak<crate::App>>>> {
48
        self.app_hint.clone()
49
    }
50
51
    fn block<T>(&self, f: impl std::future::Future<Output = T>) -> T {
52
        tokio::task::block_in_place(|| self.runtime.block_on(f))
53
    }
54
55
    fn row(&self, name: &RepoName) -> Result<db::repos::RepoRow, Failure> {
56
        let pool = self.pool.clone();
57
        match self.block(db::repos::get(&pool, &name.owner, &name.name)) {
58
            Ok(Some(r)) => Ok(r),
59
            // A transferred repository still answers to its old name (#108).
60
            Ok(None) => match self.block(db::repos::moved_to(&pool, &name.owner, &name.name)) {
61
                Ok(Some(r)) => Ok(r),
62
                Ok(None) => Err(not_found()),
63
                Err(e) => Err(Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
64
            },
65
            Err(e) => Err(Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
66
        }
67
    }
68
69
    fn caller(&self, headers: &HeaderMap) -> Result<Caller, Failure> {
70
        let Some(presented) = oxy_server::bearer_token(headers) else { return Ok(Caller::Anonymous) };
71
        if self.site_tokens.iter().any(|t| auth::mac_equal(t, presented)) {
72
            return Ok(Caller::Site);
73
        }
74
        let hash = auth::token_hash(presented);
75
        let pool = self.pool.clone();
76
        if presented.starts_with(crate::flow::JOB_TOKEN_PREFIX) {
77
            let job = self.block(db::flow::job_by_token(&pool, &hash, crate::flow::JOB_TOKEN_MAX_AGE_MS)).map_err(internal)?;
78
            let Some(job) = job else { return Err(Failure(StatusCode::UNAUTHORIZED, "this job token is not valid".into())) };
79
            let run = self.block(db::flow::run_by_id(&pool, job.run_id)).map_err(internal)?;
80
            let Some(run) = run else { return Err(Failure(StatusCode::UNAUTHORIZED, "this job token is not valid".into())) };
81
            return Ok(Caller::Job { repo_id: run.repo_id, also: job.also_read_ids() });
82
        }
83
        let token = self.block(db::accounts::token_by_hash(&pool, &hash)).map_err(internal)?;
84
        let Some(token) = token else { return Err(Failure(StatusCode::UNAUTHORIZED, "unknown token".into())) };
85
        if token.expired(db::now_ms()) {
86
            return Err(Failure(StatusCode::UNAUTHORIZED, "this token has expired".into()));
87
        }
88
        let account = self.block(db::accounts::account_by_id(&pool, token.account_id)).map_err(internal)?;
89
        let Some(account) = account else { return Err(Failure(StatusCode::UNAUTHORIZED, "unknown token".into())) };
90
        if account.banned {
91
            return Err(Failure(StatusCode::UNAUTHORIZED, "this account is banned".into()));
92
        }
93
        if account.disabled {
94
            return Err(Failure(StatusCode::UNAUTHORIZED, "this account is disabled; contact the hub's administrator".into()));
95
        }
96
        let _ = self.block(db::accounts::touch_token(&pool, token.id));
97
        Ok(Caller::Token(Box::new(account), Box::new(token)))
98
    }
99
}
100
101
fn internal(e: sqlx::Error) -> Failure {
102
    Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
103
}
104
105
fn not_found() -> Failure {
106
    Failure(StatusCode::NOT_FOUND, "no such repository".into())
107
}
108
109
impl Backend for HubBackend {
110
    fn open(&self, name: &str) -> Result<Repo, Failure> {
111
        let parsed = RepoName::parse(name).ok_or_else(not_found)?;
112
        // The row knows the current name: a transferred repository still
113
        // answers to its old one (#108).
114
        let row = self.row(&parsed)?;
115
        let name = RepoName::new(&row.owner, &row.name).ok_or_else(not_found)?;
116
        self.repos.open(&name).map_err(|e| match e {
117
            crate::repos::RepoError::NotFound => not_found(),
118
            other => Failure(StatusCode::INTERNAL_SERVER_ERROR, other.to_string()),
119
        })
120
    }
121
122
    fn authorize(&self, name: &str, access: oxy_server::Access, headers: &HeaderMap) -> Result<(), Failure> {
123
        let parsed = RepoName::parse(name).ok_or_else(not_found)?;
124
        let row = self.row(&parsed)?;
125
        let caller = self.caller(headers)?;
126
        if let Caller::Job { repo_id, also } = &caller {
127
            // Only reads: of the job's own repository, and of the subrepos its
128
            // state pins that its pusher could read when the job was claimed.
129
            return match access {
130
                oxy_server::Access::Read if *repo_id == row.id || also.contains(&row.id) => Ok(()),
131
                oxy_server::Access::Read => Err(not_found()),
132
                oxy_server::Access::Push => Err(Failure(StatusCode::FORBIDDEN, "a job token cannot push".into())),
133
            };
134
        }
135
        let (role, scope_ok) = match &caller {
136
            Caller::Job { .. } => unreachable!(),
137
            Caller::Site => (Some(Role::Admin), true),
138
            Caller::Anonymous => (self.block(auth::roles::role_for(&self.pool, None, &row)).map_err(internal)?, true),
139
            Caller::Token(account, token) => {
140
                let role = self.block(auth::roles::role_for(&self.pool, Some(account), &row)).map_err(internal)?;
141
                let needed = match access {
142
                    oxy_server::Access::Read => {
143
                        token.has_scope("repo:read") || token.has_scope("repo:write") || token.has_scope("repo:admin")
144
                    }
145
                    oxy_server::Access::Push => token.has_scope("repo:write") || token.has_scope("repo:admin"),
146
                };
147
                let current = format!("{}/{}", row.owner, row.name);
148
                (role, needed && (token.covers(&parsed.to_string()) || token.covers(&current)))
149
            }
150
        };
151
        // An unreadable repository does not exist for the caller (hub spec §4.4).
152
        if !auth::roles::allows(role, Access::Read) {
153
            return Err(not_found());
154
        }
155
        match access {
156
            oxy_server::Access::Read if scope_ok => Ok(()),
157
            oxy_server::Access::Read => Err(Failure(StatusCode::FORBIDDEN, "this token cannot read repositories".into())),
158
            oxy_server::Access::Push => {
159
                if matches!(caller, Caller::Anonymous) {
160
                    return Err(Failure(StatusCode::UNAUTHORIZED, "a personal access token is required to push".into()));
161
                }
162
                if !auth::roles::allows(role, Access::Write) {
163
                    return Err(Failure(StatusCode::FORBIDDEN, "you do not have write access to this repository".into()));
164
                }
165
                if row.archived {
166
                    return Err(Failure(StatusCode::FORBIDDEN, "this repository is archived and read-only".into()));
167
                }
168
                if !scope_ok {
169
                    return Err(Failure(StatusCode::FORBIDDEN, "this token lacks the repo:write scope for this repository".into()));
170
                }
171
                Ok(())
172
            }
173
        }
174
    }
175
176
    fn default_bookmark(&self, name: &str) -> Option<String> {
177
        let parsed = RepoName::parse(name)?;
178
        self.row(&parsed).ok().map(|r| r.default_bookmark)
179
    }
180
181
    fn after_push(&self, name: &str, report: &PushReport, headers: &HeaderMap) {
182
        let Some(parsed) = RepoName::parse(name) else { return };
183
        let Ok(row) = self.row(&parsed) else { return };
184
        let Some(parsed) = RepoName::new(&row.owner, &row.name) else { return };
185
        let pusher = match self.caller(headers) {
186
            Ok(Caller::Token(account, _)) => Some((account.id, account.username)),
187
            Ok(Caller::Site) => Some((0, "site token".to_string())),
188
            _ => None,
189
        };
190
        let pool = self.pool.clone();
191
        let results: Vec<db::repos::PushOutcome> = report
192
            .results
193
            .iter()
194
            .map(|r| {
195
                let updated = report.updated.iter().find(|u| u.name == r.name);
196
                db::repos::PushOutcome {
197
                    reference: r.name.clone(),
198
                    ok: r.ok,
199
                    reason: r.reason.clone(),
200
                    old_state: updated.map(|u| u.old_state.to_hex()).unwrap_or_default(),
201
                    new_state: updated.map(|u| u.new_state.to_hex()).unwrap_or_default(),
202
                    heads: updated.map(|u| u.heads.len() as i64).unwrap_or(0),
203
                    changes: if r.ok { report.imported.len() as i64 } else { 0 },
204
                }
205
            })
206
            .collect();
207
        // Messages of the changes stored: `closes #N` when the default
208
        // bookmark moved, and `#N` references on any bookmark (hub spec §8).
209
        let bookmarks: Vec<String> = report
210
            .updated
211
            .iter()
212
            .filter(|u| !u.name.starts_with("tags/") && report.results.iter().any(|r| r.ok && r.name == u.name))
213
            .map(|u| u.name.clone())
214
            .collect();
215
        let imported: Vec<(String, String)> = if bookmarks.is_empty() {
216
            vec![]
217
        } else {
218
            self.repos
219
                .open(&parsed)
220
                .map(|r| {
221
                    report.imported.iter().filter_map(|h| r.store().get_change_meta(h).ok().map(|c| (h.to_hex(), c.message))).collect()
222
                })
223
                .unwrap_or_default()
224
        };
225
        let messages: Vec<(String, String)> = if bookmarks.contains(&row.default_bookmark) { imported.clone() } else { vec![] };
226
        // Authors whose identity is a successor (a rotation, a renewal, a
227
        // delegation) of an earlier one: each step kept the key pair, so
228
        // if the chain reaches a linked key it is the same person, and the
229
        // successor is linked too, without re-uploading it (hub spec §5.3).
230
        let successors: Vec<(String, String, String, Vec<u8>, String)> = self
231
            .repos
232
            .open(&parsed)
233
            .map(|r| {
234
                let mut seen = std::collections::HashSet::new();
235
                let mut out = Vec::new();
236
                for h in &report.imported {
237
                    let Ok(meta) = r.store().get_change_meta(h) else { continue };
238
                    let mut key = meta.author;
239
                    while !key.is_zero() && seen.insert(key) {
240
                        let Ok(id) = r.store().get_identity(&key) else { break };
241
                        let Some(prev) = id.previous else { break };
242
                        let Ok(before) = r.store().get_identity(&prev) else { break };
243
                        if before.ed25519_pk != id.ed25519_pk || before.mldsa65_pk != id.mldsa65_pk {
244
                            break;
245
                        }
246
                        out.push((key.to_hex(), id.name.clone(), id.email.clone(), id.encode(), prev.to_hex()));
247
                        key = prev;
248
                    }
249
                }
250
                out
251
            })
252
            .unwrap_or_default();
253
        let on = if bookmarks.contains(&row.default_bookmark) {
254
            row.default_bookmark.clone()
255
        } else {
256
            bookmarks.first().cloned().unwrap_or_default()
257
        };
258
        // Bookmarks that moved, with their new heads, for OxygenFlow runs.
259
        let moved: Vec<(String, String, Vec<oxy_core::hash::ChangeHash>)> = report
260
            .updated
261
            .iter()
262
            // A bookmark sent again unchanged starts nothing.
263
            .filter(|u| u.old_state != u.new_state && report.results.iter().any(|r| r.ok && r.name == u.name))
264
            .map(|u| (u.name.clone(), u.new_state.to_hex(), u.heads.clone()))
265
            .collect();
266
        let app_hint = self.app_hint.clone();
267
        self.runtime.spawn(async move {
268
            let who = pusher.as_ref().map(|(id, name)| (*id, name.as_str()));
269
            if let Err(e) = db::repos::record_push(&pool, row.id, who, &results).await {
270
                tracing::warn!("recording push to {}: {e}", parsed);
271
            }
272
            // Oldest first: a link made for one step lets the next step link.
273
            for (key, name, email, object, prev) in successors.iter().rev() {
274
                let Ok(None) = db::accounts::identity_by_key(&pool, key).await else { continue };
275
                let Ok(Some(earlier)) = db::accounts::identity_by_key(&pool, prev).await else { continue };
276
                match db::accounts::link_identity(&pool, earlier.account_id, key, name, email, object).await {
277
                    Ok(()) => {
278
                        tracing::info!("linked identity {} to account {} as a successor of {}", &key[..12], earlier.account_id, &prev[..12]);
279
                        db::accounts::audit(&pool, None, "identity.rotated", key, &format!("successor of {}", &prev[..12])).await.ok();
280
                    }
281
                    Err(e) => tracing::warn!("linking successor identity {}: {e}", &key[..12]),
282
                }
283
            }
284
            let app = app_hint.lock().unwrap().as_ref().and_then(|w| w.upgrade());
285
            if let Some(app) = app {
286
                crate::web::issues::close_from_messages(&app, &row, &messages).await;
287
                let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
288
                crate::web::issues::references_from_messages(&app, &row, &imported, &on, &actor).await;
289
                if results.iter().any(|r| r.ok && r.reference == row.default_bookmark) {
290
                    crate::mirror::refresh(&app, &row).await;
291
                }
292
                let accepted: Vec<serde_json::Value> = results
293
                    .iter()
294
                    .filter(|r| r.ok)
295
                    .map(|r| serde_json::json!({ "reference": r.reference, "old_state": r.old_state, "new_state": r.new_state, "heads": r.heads, "changes": r.changes }))
296
                    .collect();
297
                if !accepted.is_empty() {
298
                    let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
299
                    crate::hooks::emit(&app, &row, "push", &actor, serde_json::json!({ "updates": accepted })).await;
300
                }
301
                let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
302
                for (bookmark, state, heads) in &moved {
303
                    crate::flow::on_push(&app, &row, bookmark, state, heads, &actor).await;
304
                }
305
            }
306
        });
307
    }
308
}
309
310
/// `/{owner}/{name}/oxy/v1/{endpoint}`.
311
pub async fn dispatch(
312
    State(app): State<Shared>,
313
    Path((owner, name, endpoint)): Path<(String, String, String)>,
314
    method: Method,
315
    headers: HeaderMap,
316
    body: Bytes,
317
) -> Response {
318
    let Some(endpoint) = Endpoint::parse(&endpoint) else {
319
        return Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response();
320
    };
321
    let Some(repo) = RepoName::new(&owner, &name) else {
322
        return not_found().into_response();
323
    };
324
    let _guard = match endpoint {
325
        Endpoint::Push | Endpoint::Checkpoint => Guard::Write(app.repos.write_guard(&repo).await),
326
        _ => Guard::Read(app.repos.read_guard(&repo).await),
327
    };
328
    app.server.handle(repo.to_string(), endpoint, &method, &headers, body).await
329
}
330
331
enum Guard {
332
    Read(#[allow(dead_code)] tokio::sync::OwnedRwLockReadGuard<()>),
333
    Write(#[allow(dead_code)] tokio::sync::OwnedRwLockWriteGuard<()>),
334
}