OXYGENHUB
# d7ce41acf22c oxygenhub / crates / hub / src / protocol.rs
13.0 KiB · Rust · last changed Admins disable, enable and delete accounts 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
        }
6a178055 Andy McCall ↶ 88
        if account.disabled {
89
            return Err(Failure(StatusCode::UNAUTHORIZED, "this account is disabled; contact the hub's administrator".into()));
90
        }
19bb31ff Andy McCall ↶ 91
        let _ = self.block(db::accounts::touch_token(&pool, token.id));
92
        Ok(Caller::Token(Box::new(account), Box::new(token)))
d23464c0 Andy McCall ↶ 93
    }
94
}
95
19bb31ff Andy McCall ↶ 96
fn internal(e: sqlx::Error) -> Failure {
97
    Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
98
}
99
d23464c0 Andy McCall ↶ 100
fn not_found() -> Failure {
101
    Failure(StatusCode::NOT_FOUND, "no such repository".into())
102
}
103
104
impl Backend for HubBackend {
105
    fn open(&self, name: &str) -> Result<Repo, Failure> {
106
        let name = RepoName::parse(name).ok_or_else(not_found)?;
107
        self.repos.open(&name).map_err(|e| match e {
108
            crate::repos::RepoError::NotFound => not_found(),
109
            other => Failure(StatusCode::INTERNAL_SERVER_ERROR, other.to_string()),
110
        })
111
    }
112
19bb31ff Andy McCall ↶ 113
    fn authorize(&self, name: &str, access: oxy_server::Access, headers: &HeaderMap) -> Result<(), Failure> {
d23464c0 Andy McCall ↶ 114
        let parsed = RepoName::parse(name).ok_or_else(not_found)?;
115
        let row = self.row(&parsed)?;
19bb31ff Andy McCall ↶ 116
        let caller = self.caller(headers)?;
fd3db644 Andy McCall ↶ 117
        if let Caller::Job { repo_id, also } = &caller {
118
            // Only reads: of the job's own repository, and of the subrepos its
119
            // state pins that its pusher could read when the job was claimed.
42fa9554 Andy McCall ↶ 120
            return match access {
fd3db644 Andy McCall ↶ 121
                oxy_server::Access::Read if *repo_id == row.id || also.contains(&row.id) => Ok(()),
42fa9554 Andy McCall ↶ 122
                oxy_server::Access::Read => Err(not_found()),
123
                oxy_server::Access::Push => Err(Failure(StatusCode::FORBIDDEN, "a job token cannot push".into())),
124
            };
125
        }
19bb31ff Andy McCall ↶ 126
        let (role, scope_ok) = match &caller {
42fa9554 Andy McCall ↶ 127
            Caller::Job { .. } => unreachable!(),
19bb31ff Andy McCall ↶ 128
            Caller::Site => (Some(Role::Admin), true),
129
            Caller::Anonymous => (self.block(auth::roles::role_for(&self.pool, None, &row)).map_err(internal)?, true),
130
            Caller::Token(account, token) => {
131
                let role = self.block(auth::roles::role_for(&self.pool, Some(account), &row)).map_err(internal)?;
132
                let needed = match access {
133
                    oxy_server::Access::Read => {
134
                        token.has_scope("repo:read") || token.has_scope("repo:write") || token.has_scope("repo:admin")
135
                    }
136
                    oxy_server::Access::Push => token.has_scope("repo:write") || token.has_scope("repo:admin"),
137
                };
138
                (role, needed && token.covers(&parsed.to_string()))
139
            }
140
        };
141
        // An unreadable repository does not exist for the caller (hub spec §4.4).
142
        if !auth::roles::allows(role, Access::Read) {
d23464c0 Andy McCall ↶ 143
            return Err(not_found());
144
        }
145
        match access {
19bb31ff Andy McCall ↶ 146
            oxy_server::Access::Read if scope_ok => Ok(()),
147
            oxy_server::Access::Read => Err(Failure(StatusCode::FORBIDDEN, "this token cannot read repositories".into())),
148
            oxy_server::Access::Push => {
149
                if matches!(caller, Caller::Anonymous) {
150
                    return Err(Failure(StatusCode::UNAUTHORIZED, "a personal access token is required to push".into()));
151
                }
152
                if !auth::roles::allows(role, Access::Write) {
153
                    return Err(Failure(StatusCode::FORBIDDEN, "you do not have write access to this repository".into()));
154
                }
155
                if !scope_ok {
156
                    return Err(Failure(StatusCode::FORBIDDEN, "this token lacks the repo:write scope for this repository".into()));
157
                }
158
                Ok(())
159
            }
d23464c0 Andy McCall ↶ 160
        }
161
    }
162
e271a37b Andy McCall ↶ 163
    fn default_bookmark(&self, name: &str) -> Option<String> {
164
        let parsed = RepoName::parse(name)?;
165
        self.row(&parsed).ok().map(|r| r.default_bookmark)
166
    }
167
19bb31ff Andy McCall ↶ 168
    fn after_push(&self, name: &str, report: &PushReport, headers: &HeaderMap) {
d23464c0 Andy McCall ↶ 169
        let Some(parsed) = RepoName::parse(name) else { return };
170
        let Ok(row) = self.row(&parsed) else { return };
19bb31ff Andy McCall ↶ 171
        let pusher = match self.caller(headers) {
172
            Ok(Caller::Token(account, _)) => Some((account.id, account.username)),
173
            Ok(Caller::Site) => Some((0, "site token".to_string())),
174
            _ => None,
175
        };
d23464c0 Andy McCall ↶ 176
        let pool = self.pool.clone();
62d6e969 Andy McCall ↶ 177
        let results: Vec<db::repos::PushOutcome> = report
178
            .results
179
            .iter()
180
            .map(|r| {
181
                let updated = report.updated.iter().find(|u| u.name == r.name);
182
                db::repos::PushOutcome {
183
                    reference: r.name.clone(),
184
                    ok: r.ok,
185
                    reason: r.reason.clone(),
186
                    old_state: updated.map(|u| u.old_state.to_hex()).unwrap_or_default(),
187
                    new_state: updated.map(|u| u.new_state.to_hex()).unwrap_or_default(),
188
                    heads: updated.map(|u| u.heads.len() as i64).unwrap_or(0),
189
                    changes: if r.ok { report.imported.len() as i64 } else { 0 },
190
                }
191
            })
192
            .collect();
78001759 Andy McCall ↶ 193
        // Messages of the changes stored: `closes #N` when the default
194
        // bookmark moved, and `#N` references on any bookmark (hub spec §8).
195
        let bookmarks: Vec<String> = report
196
            .updated
197
            .iter()
198
            .filter(|u| !u.name.starts_with("tags/") && report.results.iter().any(|r| r.ok && r.name == u.name))
199
            .map(|u| u.name.clone())
200
            .collect();
201
        let imported: Vec<(String, String)> = if bookmarks.is_empty() {
202
            vec![]
203
        } else {
18e381ea Andy McCall ↶ 204
            self.repos
205
                .open(&parsed)
df15b747 Andy McCall ↶ 206
                .map(|r| {
207
                    report.imported.iter().filter_map(|h| r.store().get_change_meta(h).ok().map(|c| (h.to_hex(), c.message))).collect()
208
                })
18e381ea Andy McCall ↶ 209
                .unwrap_or_default()
78001759 Andy McCall ↶ 210
        };
211
        let messages: Vec<(String, String)> = if bookmarks.contains(&row.default_bookmark) { imported.clone() } else { vec![] };
212
        let on = if bookmarks.contains(&row.default_bookmark) {
213
            row.default_bookmark.clone()
18e381ea Andy McCall ↶ 214
        } else {
78001759 Andy McCall ↶ 215
            bookmarks.first().cloned().unwrap_or_default()
18e381ea Andy McCall ↶ 216
        };
42fa9554 Andy McCall ↶ 217
        // Bookmarks that moved, with their new heads, for OxygenFlow runs.
218
        let moved: Vec<(String, String, Vec<oxy_core::hash::ChangeHash>)> = report
219
            .updated
220
            .iter()
221
            .filter(|u| report.results.iter().any(|r| r.ok && r.name == u.name))
222
            .map(|u| (u.name.clone(), u.new_state.to_hex(), u.heads.clone()))
223
            .collect();
18e381ea Andy McCall ↶ 224
        let app_hint = self.app_hint.clone();
d23464c0 Andy McCall ↶ 225
        self.runtime.spawn(async move {
18e381ea Andy McCall ↶ 226
            let who = pusher.as_ref().map(|(id, name)| (*id, name.as_str()));
227
            if let Err(e) = db::repos::record_push(&pool, row.id, who, &results).await {
d23464c0 Andy McCall ↶ 228
                tracing::warn!("recording push to {}: {e}", parsed);
229
            }
18e381ea Andy McCall ↶ 230
            let app = app_hint.lock().unwrap().as_ref().and_then(|w| w.upgrade());
231
            if let Some(app) = app {
232
                crate::web::issues::close_from_messages(&app, &row, &messages).await;
78001759 Andy McCall ↶ 233
                let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
234
                crate::web::issues::references_from_messages(&app, &row, &imported, &on, &actor).await;
3f4b0ea6 Andy McCall ↶ 235
                if results.iter().any(|r| r.ok && r.reference == row.default_bookmark) {
236
                    crate::mirror::refresh(&app, &row).await;
237
                }
b64e2537 Andy McCall ↶ 238
                let accepted: Vec<serde_json::Value> = results
239
                    .iter()
240
                    .filter(|r| r.ok)
241
                    .map(|r| serde_json::json!({ "reference": r.reference, "old_state": r.old_state, "new_state": r.new_state, "heads": r.heads, "changes": r.changes }))
242
                    .collect();
243
                if !accepted.is_empty() {
244
                    let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
245
                    crate::hooks::emit(&app, &row, "push", &actor, serde_json::json!({ "updates": accepted })).await;
42fa9554 Andy McCall ↶ 246
                }
247
                let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
248
                for (bookmark, state, heads) in &moved {
249
                    crate::flow::on_push(&app, &row, bookmark, state, heads, &actor).await;
b64e2537 Andy McCall ↶ 250
                }
18e381ea Andy McCall ↶ 251
            }
d23464c0 Andy McCall ↶ 252
        });
253
    }
254
}
255
256
/// `/{owner}/{name}/oxy/v1/{endpoint}`.
257
pub async fn dispatch(
258
    State(app): State<Shared>,
259
    Path((owner, name, endpoint)): Path<(String, String, String)>,
260
    method: Method,
261
    headers: HeaderMap,
262
    body: Bytes,
263
) -> Response {
264
    let Some(endpoint) = Endpoint::parse(&endpoint) else {
265
        return Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response();
266
    };
267
    let Some(repo) = RepoName::new(&owner, &name) else {
268
        return not_found().into_response();
269
    };
270
    let _guard = match endpoint {
271
        Endpoint::Push | Endpoint::Checkpoint => Guard::Write(app.repos.write_guard(&repo).await),
272
        _ => Guard::Read(app.repos.read_guard(&repo).await),
273
    };
274
    app.server.handle(repo.to_string(), endpoint, &method, &headers, body).await
275
}
276
277
enum Guard {
278
    Read(#[allow(dead_code)] tokio::sync::OwnedRwLockReadGuard<()>),
279
    Write(#[allow(dead_code)] tokio::sync::OwnedRwLockWriteGuard<()>),
280
}