OXYGENHUB
# 8a2dbcb56246 oxygenhub / crates / hub / src / protocol.rs
9.9 KiB · Rust · last changed Milestone 0.6: releases, Git mirror, code search, anchored API comments 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>),
33
}
34
d23464c0 Andy McCall ↶ 35
impl HubBackend {
19bb31ff Andy McCall ↶ 36
    pub fn new(repos: Arc<Repos>, pool: db::Pool, site_tokens: Vec<String>, runtime: tokio::runtime::Handle) -> HubBackend {
18e381ea Andy McCall ↶ 37
        HubBackend { repos, pool, site_tokens, runtime, app_hint: Arc::new(std::sync::Mutex::new(None)) }
38
    }
39
40
    /// The slot the application registers itself in after construction.
41
    pub fn app_slot(&self) -> Arc<std::sync::Mutex<Option<std::sync::Weak<crate::App>>>> {
42
        self.app_hint.clone()
19bb31ff Andy McCall ↶ 43
    }
44
45
    fn block<T>(&self, f: impl std::future::Future<Output = T>) -> T {
46
        tokio::task::block_in_place(|| self.runtime.block_on(f))
d23464c0 Andy McCall ↶ 47
    }
48
49
    fn row(&self, name: &RepoName) -> Result<db::repos::RepoRow, Failure> {
50
        let pool = self.pool.clone();
19bb31ff Andy McCall ↶ 51
        match self.block(db::repos::get(&pool, &name.owner, &name.name)) {
d23464c0 Andy McCall ↶ 52
            Ok(Some(r)) => Ok(r),
53
            Ok(None) => Err(not_found()),
54
            Err(e) => Err(Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
55
        }
56
    }
57
19bb31ff Andy McCall ↶ 58
    fn caller(&self, headers: &HeaderMap) -> Result<Caller, Failure> {
59
        let Some(presented) = oxy_server::bearer_token(headers) else { return Ok(Caller::Anonymous) };
60
        if self.site_tokens.iter().any(|t| auth::mac_equal(t, presented)) {
61
            return Ok(Caller::Site);
d23464c0 Andy McCall ↶ 62
        }
19bb31ff Andy McCall ↶ 63
        let hash = auth::token_hash(presented);
64
        let pool = self.pool.clone();
65
        let token = self.block(db::accounts::token_by_hash(&pool, &hash)).map_err(internal)?;
66
        let Some(token) = token else { return Err(Failure(StatusCode::UNAUTHORIZED, "unknown token".into())) };
67
        if token.expired(db::now_ms()) {
68
            return Err(Failure(StatusCode::UNAUTHORIZED, "this token has expired".into()));
69
        }
70
        let account = self.block(db::accounts::account_by_id(&pool, token.account_id)).map_err(internal)?;
71
        let Some(account) = account else { return Err(Failure(StatusCode::UNAUTHORIZED, "unknown token".into())) };
72
        if account.banned {
73
            return Err(Failure(StatusCode::UNAUTHORIZED, "this account is banned".into()));
74
        }
75
        let _ = self.block(db::accounts::touch_token(&pool, token.id));
76
        Ok(Caller::Token(Box::new(account), Box::new(token)))
d23464c0 Andy McCall ↶ 77
    }
78
}
79
19bb31ff Andy McCall ↶ 80
fn internal(e: sqlx::Error) -> Failure {
81
    Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
82
}
83
d23464c0 Andy McCall ↶ 84
fn not_found() -> Failure {
85
    Failure(StatusCode::NOT_FOUND, "no such repository".into())
86
}
87
88
impl Backend for HubBackend {
89
    fn open(&self, name: &str) -> Result<Repo, Failure> {
90
        let name = RepoName::parse(name).ok_or_else(not_found)?;
91
        self.repos.open(&name).map_err(|e| match e {
92
            crate::repos::RepoError::NotFound => not_found(),
93
            other => Failure(StatusCode::INTERNAL_SERVER_ERROR, other.to_string()),
94
        })
95
    }
96
19bb31ff Andy McCall ↶ 97
    fn authorize(&self, name: &str, access: oxy_server::Access, headers: &HeaderMap) -> Result<(), Failure> {
d23464c0 Andy McCall ↶ 98
        let parsed = RepoName::parse(name).ok_or_else(not_found)?;
99
        let row = self.row(&parsed)?;
19bb31ff Andy McCall ↶ 100
        let caller = self.caller(headers)?;
101
        let (role, scope_ok) = match &caller {
102
            Caller::Site => (Some(Role::Admin), true),
103
            Caller::Anonymous => (self.block(auth::roles::role_for(&self.pool, None, &row)).map_err(internal)?, true),
104
            Caller::Token(account, token) => {
105
                let role = self.block(auth::roles::role_for(&self.pool, Some(account), &row)).map_err(internal)?;
106
                let needed = match access {
107
                    oxy_server::Access::Read => {
108
                        token.has_scope("repo:read") || token.has_scope("repo:write") || token.has_scope("repo:admin")
109
                    }
110
                    oxy_server::Access::Push => token.has_scope("repo:write") || token.has_scope("repo:admin"),
111
                };
112
                (role, needed && token.covers(&parsed.to_string()))
113
            }
114
        };
115
        // An unreadable repository does not exist for the caller (hub spec §4.4).
116
        if !auth::roles::allows(role, Access::Read) {
d23464c0 Andy McCall ↶ 117
            return Err(not_found());
118
        }
119
        match access {
19bb31ff Andy McCall ↶ 120
            oxy_server::Access::Read if scope_ok => Ok(()),
121
            oxy_server::Access::Read => Err(Failure(StatusCode::FORBIDDEN, "this token cannot read repositories".into())),
122
            oxy_server::Access::Push => {
123
                if matches!(caller, Caller::Anonymous) {
124
                    return Err(Failure(StatusCode::UNAUTHORIZED, "a personal access token is required to push".into()));
125
                }
126
                if !auth::roles::allows(role, Access::Write) {
127
                    return Err(Failure(StatusCode::FORBIDDEN, "you do not have write access to this repository".into()));
128
                }
129
                if !scope_ok {
130
                    return Err(Failure(StatusCode::FORBIDDEN, "this token lacks the repo:write scope for this repository".into()));
131
                }
132
                Ok(())
133
            }
d23464c0 Andy McCall ↶ 134
        }
135
    }
136
19bb31ff Andy McCall ↶ 137
    fn after_push(&self, name: &str, report: &PushReport, headers: &HeaderMap) {
d23464c0 Andy McCall ↶ 138
        let Some(parsed) = RepoName::parse(name) else { return };
139
        let Ok(row) = self.row(&parsed) else { return };
19bb31ff Andy McCall ↶ 140
        let pusher = match self.caller(headers) {
141
            Ok(Caller::Token(account, _)) => Some((account.id, account.username)),
142
            Ok(Caller::Site) => Some((0, "site token".to_string())),
143
            _ => None,
144
        };
d23464c0 Andy McCall ↶ 145
        let pool = self.pool.clone();
62d6e969 Andy McCall ↶ 146
        let results: Vec<db::repos::PushOutcome> = report
147
            .results
148
            .iter()
149
            .map(|r| {
150
                let updated = report.updated.iter().find(|u| u.name == r.name);
151
                db::repos::PushOutcome {
152
                    reference: r.name.clone(),
153
                    ok: r.ok,
154
                    reason: r.reason.clone(),
155
                    old_state: updated.map(|u| u.old_state.to_hex()).unwrap_or_default(),
156
                    new_state: updated.map(|u| u.new_state.to_hex()).unwrap_or_default(),
157
                    heads: updated.map(|u| u.heads.len() as i64).unwrap_or(0),
158
                    changes: if r.ok { report.imported.len() as i64 } else { 0 },
159
                }
160
            })
161
            .collect();
18e381ea Andy McCall ↶ 162
        // Messages of the changes stored, for `closes #N` (hub spec §8), when
163
        // the default bookmark moved.
164
        let messages: Vec<(String, String)> = if report.updated.iter().any(|u| u.name == row.default_bookmark) {
165
            self.repos
166
                .open(&parsed)
167
                .map(|r| report.imported.iter().filter_map(|h| r.store().get_change(h).ok().map(|c| (h.to_hex(), c.message))).collect())
168
                .unwrap_or_default()
169
        } else {
170
            vec![]
171
        };
172
        let app_hint = self.app_hint.clone();
d23464c0 Andy McCall ↶ 173
        self.runtime.spawn(async move {
18e381ea Andy McCall ↶ 174
            let who = pusher.as_ref().map(|(id, name)| (*id, name.as_str()));
175
            if let Err(e) = db::repos::record_push(&pool, row.id, who, &results).await {
d23464c0 Andy McCall ↶ 176
                tracing::warn!("recording push to {}: {e}", parsed);
177
            }
18e381ea Andy McCall ↶ 178
            let app = app_hint.lock().unwrap().as_ref().and_then(|w| w.upgrade());
179
            if let Some(app) = app {
180
                crate::web::issues::close_from_messages(&app, &row, &messages).await;
3f4b0ea6 Andy McCall ↶ 181
                if results.iter().any(|r| r.ok && r.reference == row.default_bookmark) {
182
                    crate::mirror::refresh(&app, &row).await;
183
                }
b64e2537 Andy McCall ↶ 184
                let accepted: Vec<serde_json::Value> = results
185
                    .iter()
186
                    .filter(|r| r.ok)
187
                    .map(|r| serde_json::json!({ "reference": r.reference, "old_state": r.old_state, "new_state": r.new_state, "heads": r.heads, "changes": r.changes }))
188
                    .collect();
189
                if !accepted.is_empty() {
190
                    let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
191
                    crate::hooks::emit(&app, &row, "push", &actor, serde_json::json!({ "updates": accepted })).await;
192
                }
18e381ea Andy McCall ↶ 193
            }
d23464c0 Andy McCall ↶ 194
        });
195
    }
196
}
197
198
/// `/{owner}/{name}/oxy/v1/{endpoint}`.
199
pub async fn dispatch(
200
    State(app): State<Shared>,
201
    Path((owner, name, endpoint)): Path<(String, String, String)>,
202
    method: Method,
203
    headers: HeaderMap,
204
    body: Bytes,
205
) -> Response {
206
    let Some(endpoint) = Endpoint::parse(&endpoint) else {
207
        return Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response();
208
    };
209
    let Some(repo) = RepoName::new(&owner, &name) else {
210
        return not_found().into_response();
211
    };
212
    let _guard = match endpoint {
213
        Endpoint::Push | Endpoint::Checkpoint => Guard::Write(app.repos.write_guard(&repo).await),
214
        _ => Guard::Read(app.repos.read_guard(&repo).await),
215
    };
216
    app.server.handle(repo.to_string(), endpoint, &method, &headers, body).await
217
}
218
219
enum Guard {
220
    Read(#[allow(dead_code)] tokio::sync::OwnedRwLockReadGuard<()>),
221
    Write(#[allow(dead_code)] tokio::sync::OwnedRwLockWriteGuard<()>),
222
}