OXYGENHUB
# 941abdd6bb4c oxygenhub / crates / hub / src / protocol.rs
11.9 KiB · Rust · last changed OxygenFlow claims list the state's pinned Oxygen subrepos that the pusher can read, and the job token may read those repositories too 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
            Ok(None) => Err(not_found()),
60
            Err(e) => Err(Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
61
        }
62
    }
63
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);
68
        }
69
        let hash = auth::token_hash(presented);
70
        let pool = self.pool.clone();
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())) };
76
            return Ok(Caller::Job { repo_id: run.repo_id, also: job.also_read_ids() });
77
        }
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)))
90
    }
91
}
92
93
fn internal(e: sqlx::Error) -> Failure {
94
    Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
95
}
96
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
110
    fn authorize(&self, name: &str, access: oxy_server::Access, headers: &HeaderMap) -> Result<(), Failure> {
111
        let parsed = RepoName::parse(name).ok_or_else(not_found)?;
112
        let row = self.row(&parsed)?;
113
        let caller = self.caller(headers)?;
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.
117
            return match access {
118
                oxy_server::Access::Read if *repo_id == row.id || also.contains(&row.id) => Ok(()),
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
        }
123
        let (role, scope_ok) = match &caller {
124
            Caller::Job { .. } => unreachable!(),
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) {
140
            return Err(not_found());
141
        }
142
        match access {
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
            }
157
        }
158
    }
159
160
    fn after_push(&self, name: &str, report: &PushReport, headers: &HeaderMap) {
161
        let Some(parsed) = RepoName::parse(name) else { return };
162
        let Ok(row) = self.row(&parsed) else { return };
163
        let pusher = match self.caller(headers) {
164
            Ok(Caller::Token(account, _)) => Some((account.id, account.username)),
165
            Ok(Caller::Site) => Some((0, "site token".to_string())),
166
            _ => None,
167
        };
168
        let pool = self.pool.clone();
169
        let results: Vec<db::repos::PushOutcome> = report
170
            .results
171
            .iter()
172
            .map(|r| {
173
                let updated = report.updated.iter().find(|u| u.name == r.name);
174
                db::repos::PushOutcome {
175
                    reference: r.name.clone(),
176
                    ok: r.ok,
177
                    reason: r.reason.clone(),
178
                    old_state: updated.map(|u| u.old_state.to_hex()).unwrap_or_default(),
179
                    new_state: updated.map(|u| u.new_state.to_hex()).unwrap_or_default(),
180
                    heads: updated.map(|u| u.heads.len() as i64).unwrap_or(0),
181
                    changes: if r.ok { report.imported.len() as i64 } else { 0 },
182
                }
183
            })
184
            .collect();
185
        // Messages of the changes stored, for `closes #N` (hub spec §8), when
186
        // the default bookmark moved.
187
        let messages: Vec<(String, String)> = if report.updated.iter().any(|u| u.name == row.default_bookmark) {
188
            self.repos
189
                .open(&parsed)
190
                .map(|r| report.imported.iter().filter_map(|h| r.store().get_change(h).ok().map(|c| (h.to_hex(), c.message))).collect())
191
                .unwrap_or_default()
192
        } else {
193
            vec![]
194
        };
195
        // Bookmarks that moved, with their new heads, for OxygenFlow runs.
196
        let moved: Vec<(String, String, Vec<oxy_core::hash::ChangeHash>)> = report
197
            .updated
198
            .iter()
199
            .filter(|u| report.results.iter().any(|r| r.ok && r.name == u.name))
200
            .map(|u| (u.name.clone(), u.new_state.to_hex(), u.heads.clone()))
201
            .collect();
202
        let app_hint = self.app_hint.clone();
203
        self.runtime.spawn(async move {
204
            let who = pusher.as_ref().map(|(id, name)| (*id, name.as_str()));
205
            if let Err(e) = db::repos::record_push(&pool, row.id, who, &results).await {
206
                tracing::warn!("recording push to {}: {e}", parsed);
207
            }
208
            let app = app_hint.lock().unwrap().as_ref().and_then(|w| w.upgrade());
209
            if let Some(app) = app {
210
                crate::web::issues::close_from_messages(&app, &row, &messages).await;
211
                if results.iter().any(|r| r.ok && r.reference == row.default_bookmark) {
212
                    crate::mirror::refresh(&app, &row).await;
213
                }
214
                let accepted: Vec<serde_json::Value> = results
215
                    .iter()
216
                    .filter(|r| r.ok)
217
                    .map(|r| serde_json::json!({ "reference": r.reference, "old_state": r.old_state, "new_state": r.new_state, "heads": r.heads, "changes": r.changes }))
218
                    .collect();
219
                if !accepted.is_empty() {
220
                    let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
221
                    crate::hooks::emit(&app, &row, "push", &actor, serde_json::json!({ "updates": accepted })).await;
222
                }
223
                let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default();
224
                for (bookmark, state, heads) in &moved {
225
                    crate::flow::on_push(&app, &row, bookmark, state, heads, &actor).await;
226
                }
227
            }
228
        });
229
    }
230
}
231
232
/// `/{owner}/{name}/oxy/v1/{endpoint}`.
233
pub async fn dispatch(
234
    State(app): State<Shared>,
235
    Path((owner, name, endpoint)): Path<(String, String, String)>,
236
    method: Method,
237
    headers: HeaderMap,
238
    body: Bytes,
239
) -> Response {
240
    let Some(endpoint) = Endpoint::parse(&endpoint) else {
241
        return Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response();
242
    };
243
    let Some(repo) = RepoName::new(&owner, &name) else {
244
        return not_found().into_response();
245
    };
246
    let _guard = match endpoint {
247
        Endpoint::Push | Endpoint::Checkpoint => Guard::Write(app.repos.write_guard(&repo).await),
248
        _ => Guard::Read(app.repos.read_guard(&repo).await),
249
    };
250
    app.server.handle(repo.to_string(), endpoint, &method, &headers, body).await
251
}
252
253
enum Guard {
254
    Read(#[allow(dead_code)] tokio::sync::OwnedRwLockReadGuard<()>),
255
    Write(#[allow(dead_code)] tokio::sync::OwnedRwLockWriteGuard<()>),
256
}