OXYGENHUB
# b6b7e4cf6b24 oxygenhub / crates / hub / src / protocol.rs
12.8 KiB · Rust · last changed Delete bookmarks: a button for writers, pushed deletions checked 1 month ago source blame history raw
d23464c0 Andy McCall ↶ 1
//! The wire protocol, embedded (hub spec §3.3, §5.4): `oxy-server`'s
19bb31ff Andy McCall ↶ 2
//! `Server` over a backend that resolves `owner/name`, authorises reads
3
//! and pushes by account role and token scope, and records who pushed.
d23464c0 Andy McCall ↶ 4
19bb31ff Andy McCall ↶ 5
use crate::auth::{self, Access, Role};
6
use crate::db::{self, accounts::Account};
d23464c0 Andy McCall ↶ 7
use crate::repos::{RepoName, Repos};
19bb31ff Andy McCall ↶ 8
use crate::Shared;
d23464c0 Andy McCall ↶ 9
use axum::body::Bytes;
10
use axum::extract::{Path, State};
11
use axum::http::{HeaderMap, Method, StatusCode};
12
use axum::response::{IntoResponse, Response};
62d6e969 Andy McCall ↶ 13
use oxy_core::repo::{PushReport, Repo};
19bb31ff Andy McCall ↶ 14
use oxy_server::{Backend, Endpoint, Failure};
d23464c0 Andy McCall ↶ 15
use std::sync::Arc;
16
17
pub struct HubBackend {
18
    repos: Arc<Repos>,
19
    pool: db::Pool,
19bb31ff Andy McCall ↶ 20
    /// Site tokens from `hub.toml`: full access, for bootstrapping.
21
    site_tokens: Vec<String>,
d23464c0 Andy McCall ↶ 22
    runtime: tokio::runtime::Handle,
18e381ea Andy McCall ↶ 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>>>>,
d23464c0 Andy McCall ↶ 25
}
26
19bb31ff Andy McCall ↶ 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>),
fd3db644 Andy McCall ↶ 33
    /// A running OxygenFlow job: reads its own repository and the subrepos
34
    /// its state pins, nothing else (hub spec §13.2).
42fa9554 Andy McCall ↶ 35
    Job {
36
        repo_id: i64,
fd3db644 Andy McCall ↶ 37
        also: Vec<i64>,
42fa9554 Andy McCall ↶ 38
    },
19bb31ff Andy McCall ↶ 39
}
40
d23464c0 Andy McCall ↶ 41
impl HubBackend {
19bb31ff Andy McCall ↶ 42
    pub fn new(repos: Arc<Repos>, pool: db::Pool, site_tokens: Vec<String>, runtime: tokio::runtime::Handle) -> HubBackend {
18e381ea Andy McCall ↶ 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()
19bb31ff Andy McCall ↶ 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))
d23464c0 Andy McCall ↶ 53
    }
54
55
    fn row(&self, name: &RepoName) -> Result<db::repos::RepoRow, Failure> {
56
        let pool = self.pool.clone();
19bb31ff Andy McCall ↶ 57
        match self.block(db::repos::get(&pool, &name.owner, &name.name)) {
d23464c0 Andy McCall ↶ 58
            Ok(Some(r)) => Ok(r),
59
            Ok(None) => Err(not_found()),
60
            Err(e) => Err(Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
61
        }
62
    }
63
19bb31ff Andy McCall ↶ 64
    fn caller(&self, headers: &HeaderMap) -> Result<Caller, Failure> {
65
        let Some(presented) = oxy_server::bearer_token(headers) else { return Ok(Caller::Anonymous) };
66
        if self.site_tokens.iter().any(|t| auth::mac_equal(t, presented)) {
67
            return Ok(Caller::Site);
d23464c0 Andy McCall ↶ 68
        }
19bb31ff Andy McCall ↶ 69
        let hash = auth::token_hash(presented);
70
        let pool = self.pool.clone();
42fa9554 Andy McCall ↶ 71
        if presented.starts_with(crate::flow::JOB_TOKEN_PREFIX) {
72
            let job = self.block(db::flow::job_by_token(&pool, &hash, crate::flow::JOB_TOKEN_MAX_AGE_MS)).map_err(internal)?;
73
            let Some(job) = job else { return Err(Failure(StatusCode::UNAUTHORIZED, "this job token is not valid".into())) };
74
            let run = self.block(db::flow::run_by_id(&pool, job.run_id)).map_err(internal)?;
75
            let Some(run) = run else { return Err(Failure(StatusCode::UNAUTHORIZED, "this job token is not valid".into())) };
fd3db644 Andy McCall ↶ 76
            return Ok(Caller::Job { repo_id: run.repo_id, also: job.also_read_ids() });
42fa9554 Andy McCall ↶ 77
        }
19bb31ff Andy McCall ↶ 78
        let token = self.block(db::accounts::token_by_hash(&pool, &hash)).map_err(internal)?;
79
        let Some(token) = token else { return Err(Failure(StatusCode::UNAUTHORIZED, "unknown token".into())) };
80
        if token.expired(db::now_ms()) {
81
            return Err(Failure(StatusCode::UNAUTHORIZED, "this token has expired".into()));
82
        }
83
        let account = self.block(db::accounts::account_by_id(&pool, token.account_id)).map_err(internal)?;
84
        let Some(account) = account else { return Err(Failure(StatusCode::UNAUTHORIZED, "unknown token".into())) };
85
        if account.banned {
86
            return Err(Failure(StatusCode::UNAUTHORIZED, "this account is banned".into()));
87
        }
88
        let _ = self.block(db::accounts::touch_token(&pool, token.id));
89
        Ok(Caller::Token(Box::new(account), Box::new(token)))
d23464c0 Andy McCall ↶ 90
    }
91
}
92
19bb31ff Andy McCall ↶ 93
fn internal(e: sqlx::Error) -> Failure {
94
    Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
95
}
96
d23464c0 Andy McCall ↶ 97
fn not_found() -> Failure {
98
    Failure(StatusCode::NOT_FOUND, "no such repository".into())
99
}
100
101
impl Backend for HubBackend {
102
    fn open(&self, name: &str) -> Result<Repo, Failure> {
103
        let name = RepoName::parse(name).ok_or_else(not_found)?;
104
        self.repos.open(&name).map_err(|e| match e {
105
            crate::repos::RepoError::NotFound => not_found(),
106
            other => Failure(StatusCode::INTERNAL_SERVER_ERROR, other.to_string()),
107
        })
108
    }
109
19bb31ff Andy McCall ↶ 110
    fn authorize(&self, name: &str, access: oxy_server::Access, headers: &HeaderMap) -> Result<(), Failure> {
d23464c0 Andy McCall ↶ 111
        let parsed = RepoName::parse(name).ok_or_else(not_found)?;
112
        let row = self.row(&parsed)?;
19bb31ff Andy McCall ↶ 113
        let caller = self.caller(headers)?;
fd3db644 Andy McCall ↶ 114
        if let Caller::Job { repo_id, also } = &caller {
115
            // Only reads: of the job's own repository, and of the subrepos its
116
            // state pins that its pusher could read when the job was claimed.
42fa9554 Andy McCall ↶ 117
            return match access {
fd3db644 Andy McCall ↶ 118
                oxy_server::Access::Read if *repo_id == row.id || also.contains(&row.id) => Ok(()),
42fa9554 Andy McCall ↶ 119
                oxy_server::Access::Read => Err(not_found()),
120
                oxy_server::Access::Push => Err(Failure(StatusCode::FORBIDDEN, "a job token cannot push".into())),
121
            };
122
        }
19bb31ff Andy McCall ↶ 123
        let (role, scope_ok) = match &caller {
42fa9554 Andy McCall ↶ 124
            Caller::Job { .. } => unreachable!(),
19bb31ff Andy McCall ↶ 125
            Caller::Site => (Some(Role::Admin), true),
126
            Caller::Anonymous => (self.block(auth::roles::role_for(&self.pool, None, &row)).map_err(internal)?, true),
127
            Caller::Token(account, token) => {
128
                let role = self.block(auth::roles::role_for(&self.pool, Some(account), &row)).map_err(internal)?;
129
                let needed = match access {
130
                    oxy_server::Access::Read => {
131
                        token.has_scope("repo:read") || token.has_scope("repo:write") || token.has_scope("repo:admin")
132
                    }
133
                    oxy_server::Access::Push => token.has_scope("repo:write") || token.has_scope("repo:admin"),
134
                };
135
                (role, needed && token.covers(&parsed.to_string()))
136
            }
137
        };
138
        // An unreadable repository does not exist for the caller (hub spec §4.4).
139
        if !auth::roles::allows(role, Access::Read) {
d23464c0 Andy McCall ↶ 140
            return Err(not_found());
141
        }
142
        match access {
19bb31ff Andy McCall ↶ 143
            oxy_server::Access::Read if scope_ok => Ok(()),
144
            oxy_server::Access::Read => Err(Failure(StatusCode::FORBIDDEN, "this token cannot read repositories".into())),
145
            oxy_server::Access::Push => {
146
                if matches!(caller, Caller::Anonymous) {
147
                    return Err(Failure(StatusCode::UNAUTHORIZED, "a personal access token is required to push".into()));
148
                }
149
                if !auth::roles::allows(role, Access::Write) {
150
                    return Err(Failure(StatusCode::FORBIDDEN, "you do not have write access to this repository".into()));
151
                }
152
                if !scope_ok {
153
                    return Err(Failure(StatusCode::FORBIDDEN, "this token lacks the repo:write scope for this repository".into()));
154
                }
155
                Ok(())
156
            }
d23464c0 Andy McCall ↶ 157
        }
158
    }
159
e271a37b Andy McCall ↶ 160
    fn default_bookmark(&self, name: &str) -> Option<String> {
161
        let parsed = RepoName::parse(name)?;
162
        self.row(&parsed).ok().map(|r| r.default_bookmark)
163
    }
164
19bb31ff Andy McCall ↶ 165
    fn after_push(&self, name: &str, report: &PushReport, headers: &HeaderMap) {
d23464c0 Andy McCall ↶ 166
        let Some(parsed) = RepoName::parse(name) else { return };
167
        let Ok(row) = self.row(&parsed) else { return };
19bb31ff Andy McCall ↶ 168
        let pusher = match self.caller(headers) {
169
            Ok(Caller::Token(account, _)) => Some((account.id, account.username)),
170
            Ok(Caller::Site) => Some((0, "site token".to_string())),
171
            _ => None,
172
        };
d23464c0 Andy McCall ↶ 173
        let pool = self.pool.clone();
62d6e969 Andy McCall ↶ 174
        let results: Vec<db::repos::PushOutcome> = report
175
            .results
176
            .iter()
177
            .map(|r| {
178
                let updated = report.updated.iter().find(|u| u.name == r.name);
179
                db::repos::PushOutcome {
180
                    reference: r.name.clone(),
181
                    ok: r.ok,
182
                    reason: r.reason.clone(),
183
                    old_state: updated.map(|u| u.old_state.to_hex()).unwrap_or_default(),
184
                    new_state: updated.map(|u| u.new_state.to_hex()).unwrap_or_default(),
185
                    heads: updated.map(|u| u.heads.len() as i64).unwrap_or(0),
186
                    changes: if r.ok { report.imported.len() as i64 } else { 0 },
187
                }
188
            })
189
            .collect();
78001759 Andy McCall ↶ 190
        // Messages of the changes stored: `closes #N` when the default
191
        // bookmark moved, and `#N` references on any bookmark (hub spec §8).
192
        let bookmarks: Vec<String> = report
193
            .updated
194
            .iter()
195
            .filter(|u| !u.name.starts_with("tags/") && report.results.iter().any(|r| r.ok && r.name == u.name))
196
            .map(|u| u.name.clone())
197
            .collect();
198
        let imported: Vec<(String, String)> = if bookmarks.is_empty() {
199
            vec![]
200
        } else {
18e381ea Andy McCall ↶ 201
            self.repos
202
                .open(&parsed)
203
                .map(|r| report.imported.iter().filter_map(|h| r.store().get_change(h).ok().map(|c| (h.to_hex(), c.message))).collect())
204
                .unwrap_or_default()
78001759 Andy McCall ↶ 205
        };
206
        let messages: Vec<(String, String)> = if bookmarks.contains(&row.default_bookmark) { imported.clone() } else { vec![] };
207
        let on = if bookmarks.contains(&row.default_bookmark) {
208
            row.default_bookmark.clone()
18e381ea Andy McCall ↶ 209
        } else {
78001759 Andy McCall ↶ 210
            bookmarks.first().cloned().unwrap_or_default()
18e381ea Andy McCall ↶ 211
        };
42fa9554 Andy McCall ↶ 212
        // Bookmarks that moved, with their new heads, for OxygenFlow runs.
213
        let moved: Vec<(String, String, Vec<oxy_core::hash::ChangeHash>)> = report
214
            .updated
215
            .iter()
216
            .filter(|u| report.results.iter().any(|r| r.ok && r.name == u.name))
217
            .map(|u| (u.name.clone(), u.new_state.to_hex(), u.heads.clone()))
218
            .collect();
18e381ea Andy McCall ↶ 219
        let app_hint = self.app_hint.clone();
d23464c0 Andy McCall ↶ 220
        self.runtime.spawn(async move {
18e381ea Andy McCall ↶ 221
            let who = pusher.as_ref().map(|(id, name)| (*id, name.as_str()));
222
            if let Err(e) = db::repos::record_push(&pool, row.id, who, &results).await {
d23464c0 Andy McCall ↶ 223
                tracing::warn!("recording push to {}: {e}", parsed);
224
            }
18e381ea Andy McCall ↶ 225
            let app = app_hint.lock().unwrap().as_ref().and_then(|w| w.upgrade());
226
            if let Some(app) = app {
227
                crate::web::issues::close_from_messages(&app, &row, &messages).await;
78001759 Andy McCall ↶ 228
                let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
229
                crate::web::issues::references_from_messages(&app, &row, &imported, &on, &actor).await;
3f4b0ea6 Andy McCall ↶ 230
                if results.iter().any(|r| r.ok && r.reference == row.default_bookmark) {
231
                    crate::mirror::refresh(&app, &row).await;
232
                }
b64e2537 Andy McCall ↶ 233
                let accepted: Vec<serde_json::Value> = results
234
                    .iter()
235
                    .filter(|r| r.ok)
236
                    .map(|r| serde_json::json!({ "reference": r.reference, "old_state": r.old_state, "new_state": r.new_state, "heads": r.heads, "changes": r.changes }))
237
                    .collect();
238
                if !accepted.is_empty() {
239
                    let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
240
                    crate::hooks::emit(&app, &row, "push", &actor, serde_json::json!({ "updates": accepted })).await;
42fa9554 Andy McCall ↶ 241
                }
242
                let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
243
                for (bookmark, state, heads) in &moved {
244
                    crate::flow::on_push(&app, &row, bookmark, state, heads, &actor).await;
b64e2537 Andy McCall ↶ 245
                }
18e381ea Andy McCall ↶ 246
            }
d23464c0 Andy McCall ↶ 247
        });
248
    }
249
}
250
251
/// `/{owner}/{name}/oxy/v1/{endpoint}`.
252
pub async fn dispatch(
253
    State(app): State<Shared>,
254
    Path((owner, name, endpoint)): Path<(String, String, String)>,
255
    method: Method,
256
    headers: HeaderMap,
257
    body: Bytes,
258
) -> Response {
259
    let Some(endpoint) = Endpoint::parse(&endpoint) else {
260
        return Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response();
261
    };
262
    let Some(repo) = RepoName::new(&owner, &name) else {
263
        return not_found().into_response();
264
    };
265
    let _guard = match endpoint {
266
        Endpoint::Push | Endpoint::Checkpoint => Guard::Write(app.repos.write_guard(&repo).await),
267
        _ => Guard::Read(app.repos.read_guard(&repo).await),
268
    };
269
    app.server.handle(repo.to_string(), endpoint, &method, &headers, body).await
270
}
271
272
enum Guard {
273
    Read(#[allow(dead_code)] tokio::sync::OwnedRwLockReadGuard<()>),
274
    Write(#[allow(dead_code)] tokio::sync::OwnedRwLockWriteGuard<()>),
275
}