| d23464c0 Andy McCall ↶ |
1 |
|
| 19bb31ff Andy McCall ↶ |
2 |
|
| 3 |
|
| 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 |
|
| 21 |
site_tokens: Vec<String>, |
| d23464c0 Andy McCall ↶ |
22 |
runtime: tokio::runtime::Handle, |
| 18e381ea Andy McCall ↶ |
23 |
|
| 24 |
app_hint: Arc<std::sync::Mutex<Option<std::sync::Weak<crate::App>>>>, |
| d23464c0 Andy McCall ↶ |
25 |
} |
| 26 |
|
| 19bb31ff Andy McCall ↶ |
27 |
|
| 28 |
enum Caller { |
| 29 |
Anonymous, |
| 30 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 163 |
|
| 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; |
| b64e2537 Andy McCall ↶ |
181 |
let accepted: Vec<serde_json::Value> = results |
| 182 |
.iter() |
| 183 |
.filter(|r| r.ok) |
| 184 |
.map(|r| serde_json::json!({ "reference": r.reference, "old_state": r.old_state, "new_state": r.new_state, "heads": r.heads, "changes": r.changes })) |
| 185 |
.collect(); |
| 186 |
if !accepted.is_empty() { |
| 187 |
let actor = pusher.as_ref().map(|(_, n)| n.clone()).unwrap_or_default(); |
| 188 |
crate::hooks::emit(&app, &row, "push", &actor, serde_json::json!({ "updates": accepted })).await; |
| 189 |
} |
| 18e381ea Andy McCall ↶ |
190 |
} |
| d23464c0 Andy McCall ↶ |
191 |
}); |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
pub async fn dispatch( |
| 197 |
State(app): State<Shared>, |
| 198 |
Path((owner, name, endpoint)): Path<(String, String, String)>, |
| 199 |
method: Method, |
| 200 |
headers: HeaderMap, |
| 201 |
body: Bytes, |
| 202 |
) -> Response { |
| 203 |
let Some(endpoint) = Endpoint::parse(&endpoint) else { |
| 204 |
return Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(); |
| 205 |
}; |
| 206 |
let Some(repo) = RepoName::new(&owner, &name) else { |
| 207 |
return not_found().into_response(); |
| 208 |
}; |
| 209 |
let _guard = match endpoint { |
| 210 |
Endpoint::Push | Endpoint::Checkpoint => Guard::Write(app.repos.write_guard(&repo).await), |
| 211 |
_ => Guard::Read(app.repos.read_guard(&repo).await), |
| 212 |
}; |
| 213 |
app.server.handle(repo.to_string(), endpoint, &method, &headers, body).await |
| 214 |
} |
| 215 |
|
| 216 |
enum Guard { |
| 217 |
Read(#[allow(dead_code)] tokio::sync::OwnedRwLockReadGuard<()>), |
| 218 |
Write(#[allow(dead_code)] tokio::sync::OwnedRwLockWriteGuard<()>), |
| 219 |
} |