| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | | use super::{Error, Page, Shell}; |
| 9 | | use crate::auth::{self, phone, totp, Viewer}; |
| 10 | | use crate::db::{self, accounts}; |
| 11 | | use crate::throttle::{self, Key}; |
| 12 | | use crate::Shared; |
| 13 | | use askama::Template; |
| 14 | | use axum::extract::{Form, Path, Query, State}; |
| 15 | | use axum::http::{header, Method, StatusCode}; |
| 16 | | use axum::response::{IntoResponse, Redirect, Response}; |
| 17 | | use serde::Deserialize; |
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | 3954× | pub fn sensitive(method: &Method, path: &str) -> bool { |
| 22 | 3954× | if method == Method::GET || method == Method::HEAD { |
| 23 | 2049× | return false; |
| 24 | 1905× | } |
| 25 | 1905× | let p = path.trim_end_matches('/'); |
| 26 | 1905× | if p.starts_with("/admin") { |
| 27 | 103× | return true; |
| 28 | 1802× | } |
| 29 | 39× | if matches!( |
| 30 | 1802× | p, |
| 31 | 1802× | "/settings/password" |
| 32 | 1801× | | "/settings/security/totp/disable" |
| 33 | 1799× | | "/settings/keys/upload" |
| 34 | 1795× | | "/settings/keys/unlink" |
| 35 | 1795× | | "/settings/tokens" |
| 36 | 1769× | | "/settings/backups" |
| 37 | 1763× | ) || p.starts_with("/settings/security/phones/") |
| 38 | 1762× | || p.starts_with("/settings/security/disconnect/") |
| 39 | 1761× | || (p.starts_with("/settings/tokens/") && p.ends_with("/agent")) |
| 40 | | { |
| 41 | 42× | return true; |
| 42 | 1760× | } |
| 43 | 1760× | let parts: Vec<&str> = p.trim_start_matches('/').split('/').collect(); |
| 44 | 1760× | match parts.as_slice() { |
| 45 | 443× | ["orgs", _, "settings", what] => matches!(*what, "secrets" | "storage" | "hooks" | "backups"), |
| 46 | 430× | [owner, _, "settings", what] if !matches!(*owner, "settings" | "admin" | "orgs") => { |
| 47 | 70× | matches!(*what, "delete" | "transfer" | "secrets" | "hooks" | "push-protection" | "secret-bypass" | "backup" | "collaborators") |
| 48 | | } |
| 49 | 1677× | _ => false, |
| 50 | | } |
| 51 | 3954× | } |
| 52 | |
|
| 53 | |
|
| 54 | |
|
| 55 | |
|
| 56 | 3932× | pub async fn gate(State(app): State<Shared>, req: axum::extract::Request, next: axum::middleware::Next) -> Response { |
| 57 | 3932× | if !sensitive(req.method(), req.uri().path()) { |
| 58 | 3761× | return next.run(req).await; |
| 59 | 171× | } |
| 60 | 171× | let Some(value) = auth::viewer::cookie(req.headers(), auth::SESSION_COOKIE) else { return next.run(req).await }; |
| 61 | 170× | let Some((_, session)) = auth::viewer::resolve(&app, &value).await else { return next.run(req).await }; |
| 62 | 170× | if db::now_ms() - session.second_factor_ms < phone::FRESH_MS { |
| 63 | 169× | return next.run(req).await; |
| 64 | 1× | } |
| 65 | 1× | let base = app.config.base_url().trim_end_matches('/').to_string(); |
| 66 | 1× | let back = req |
| 67 | 1× | .headers() |
| 68 | 1× | .get(header::REFERER) |
| 69 | 1× | .and_then(|v| v.to_str().ok()) |
| 70 | 1× | .and_then(|r| r.strip_prefix(&base)) |
| 71 | 1× | .filter(|p| p.starts_with('/') && !p.starts_with("//")) |
| 72 | 1× | .unwrap_or("/settings/security") |
| 73 | 1× | .to_string(); |
| 74 | 1× | Redirect::to(&format!("/sudo?next={}", super::settings::urlencode(&back))).into_response() |
| 75 | 3932× | } |
| 76 | |
|
| 77 | | #[derive(Template)] |
| 78 | | #[template(path = "sudo.html")] |
| 79 | | pub struct SudoPage { |
| 80 | | shell: Shell, |
| 81 | | next: String, |
| 82 | | error: Option<String>, |
| 83 | | |
| 84 | | phones: bool, |
| 85 | | |
| 86 | | totp: bool, |
| 87 | | |
| 88 | | password: bool, |
| 89 | | |
| 90 | | approval: Option<(String, i64)>, |
| 91 | | } |
| 92 | |
|
| 93 | | #[derive(Deserialize)] |
| 94 | | pub struct NextQuery { |
| 95 | | #[serde(default)] |
| 96 | | next: String, |
| 97 | | } |
| 98 | |
|
| 99 | 5× | fn safe_next(next: &str) -> String { |
| 100 | 5× | if next.starts_with('/') && !next.starts_with("//") { |
| 101 | 5× | next.to_string() |
| 102 | | } else { |
| 103 | 0× | "/".into() |
| 104 | | } |
| 105 | 5× | } |
| 106 | |
|
| 107 | 4× | async fn page( |
| 108 | 4× | app: &Shared, |
| 109 | 4× | viewer: &Viewer, |
| 110 | 4× | next: &str, |
| 111 | 4× | error: Option<String>, |
| 112 | 4× | approval: Option<(String, i64)>, |
| 113 | 4× | ) -> Result<Response, Error> { |
| 114 | 4× | let shell = Shell::new(app, "/sudo", viewer); |
| 115 | 4× | let Some(me) = viewer.account() else { |
| 116 | 0× | return Ok(Redirect::to(&format!("/login?next={}", super::settings::urlencode(next))).into_response()); |
| 117 | | }; |
| 118 | 4× | let totp = me.totp_secret.is_some(); |
| 119 | 4× | let phones = totp && !db::approvals::authenticators(&app.db, me.id).await.map_err(|e| Error::from_db(shell.clone(), e))?.is_empty(); |
| 120 | 4× | let password = !totp && !me.password_hash.is_empty(); |
| 121 | 4× | Ok(Page(SudoPage { shell, next: safe_next(next), error, phones, totp, password, approval }).into_response()) |
| 122 | 4× | } |
| 123 | |
|
| 124 | |
|
| 125 | 2× | pub async fn show(State(app): State<Shared>, viewer: Viewer, Query(q): Query<NextQuery>) -> Result<Response, Error> { |
| 126 | 2× | page(&app, &viewer, &q.next, None, None).await |
| 127 | 2× | } |
| 128 | |
|
| 129 | | #[derive(Deserialize)] |
| 130 | | pub struct SudoForm { |
| 131 | | #[serde(rename = "_csrf")] |
| 132 | | csrf: String, |
| 133 | | #[serde(default)] |
| 134 | | next: String, |
| 135 | | #[serde(default)] |
| 136 | | code: String, |
| 137 | | #[serde(default)] |
| 138 | | password: String, |
| 139 | | } |
| 140 | |
|
| 141 | |
|
| 142 | |
|
| 143 | 2× | pub async fn confirm(State(app): State<Shared>, viewer: Viewer, Form(f): Form<SudoForm>) -> Result<Response, Error> { |
| 144 | 2× | let Some(me) = viewer.0.clone() else { return Ok(Redirect::to("/login").into_response()) }; |
| 145 | 2× | let shell = Shell::new(&app, "/sudo", &viewer); |
| 146 | 2× | if !viewer.csrf_ok(&f.csrf) { |
| 147 | 0× | return page(&app, &viewer, &f.next, Some("That form had expired: try again.".into()), None).await; |
| 148 | 2× | } |
| 149 | 2× | let now = db::now_ms(); |
| 150 | 2× | let keys = [Key::account("sudo", &me.account.username)]; |
| 151 | 2× | let wait = app.throttle.lock().unwrap().wait(&keys, now); |
| 152 | 2× | if let Some(wait) = wait { |
| 153 | 0× | return page(&app, &viewer, &f.next, Some(throttle::message(wait)), None).await; |
| 154 | 2× | } |
| 155 | 2× | let ok = match &me.account.totp_secret { |
| 156 | 2× | Some(secret) => { |
| 157 | 2× | totp::verify(secret, f.code.trim(), (now / 1000) as u64) |
| 158 | 1× | || match totp::use_recovery_code(&me.account.recovery_codes, f.code.trim()) { |
| 159 | 0× | Some(rest) => { |
| 160 | 0× | accounts::set_totp(&app.db, me.account.id, Some(secret), &rest) |
| 161 | 0× | .await |
| 162 | 0× | .map_err(|e| Error::from_db(shell.clone(), e))?; |
| 163 | 0× | true |
| 164 | | } |
| 165 | 1× | None => false, |
| 166 | | } |
| 167 | | } |
| 168 | 0× | None => !me.account.password_hash.is_empty() && auth::verify_password(&me.account.password_hash, &f.password), |
| 169 | | }; |
| 170 | 2× | if !ok { |
| 171 | 1× | app.throttle.lock().unwrap().failed(&keys, now); |
| 172 | 1× | accounts::audit(&app.db, Some(&me.account), "sudo.failed", &me.account.username, "").await.ok(); |
| 173 | 1× | let what = if me.account.totp_secret.is_some() { "That code is not right." } else { "That password is not right." }; |
| 174 | 1× | return page(&app, &viewer, &f.next, Some(what.into()), None).await; |
| 175 | 1× | } |
| 176 | 1× | app.throttle.lock().unwrap().cleared(&keys[0]); |
| 177 | 1× | db::sessions::mark_second_factor(&app.db, me.session_id, now).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 178 | 1× | accounts::audit( |
| 179 | 1× | &app.db, |
| 180 | 1× | Some(&me.account), |
| 181 | 1× | "sudo", |
| 182 | 1× | &me.account.username, |
| 183 | 1× | if me.account.totp_secret.is_some() { "code" } else { "password" }, |
| 184 | | ) |
| 185 | 1× | .await |
| 186 | 1× | .ok(); |
| 187 | 1× | Ok(Redirect::to(&safe_next(&f.next)).into_response()) |
| 188 | 2× | } |
| 189 | |
|
| 190 | | #[derive(Deserialize)] |
| 191 | | pub struct PhoneForm { |
| 192 | | #[serde(rename = "_csrf")] |
| 193 | | csrf: String, |
| 194 | | #[serde(default)] |
| 195 | | next: String, |
| 196 | | } |
| 197 | |
|
| 198 | |
|
| 199 | 1× | pub async fn ask_phone( |
| 200 | 1× | State(app): State<Shared>, |
| 201 | 1× | viewer: Viewer, |
| 202 | 1× | headers: axum::http::HeaderMap, |
| 203 | 1× | Form(f): Form<PhoneForm>, |
| 204 | 1× | ) -> Result<Response, Error> { |
| 205 | 1× | let Some(me) = viewer.0.clone() else { return Ok(Redirect::to("/login").into_response()) }; |
| 206 | 1× | let shell = Shell::new(&app, "/sudo", &viewer); |
| 207 | 1× | if !viewer.csrf_ok(&f.csrf) { |
| 208 | 0× | return page(&app, &viewer, &f.next, Some("That form had expired: try again.".into()), None).await; |
| 209 | 1× | } |
| 210 | 1× | let agent = headers.get(header::USER_AGENT).and_then(|v| v.to_str().ok()).unwrap_or(""); |
| 211 | 1× | let what = format!("Confirm a change from {}", super::settings::browser_of(agent)); |
| 212 | 1× | let a = phone::ask(&app, &me.account, "stepup", &what, Some(me.session_id)).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 213 | 1× | page(&app, &viewer, &f.next, None, Some((a.id, a.number))).await |
| 214 | 1× | } |
| 215 | |
|
| 216 | |
|
| 217 | 3× | pub async fn approval_state(State(app): State<Shared>, viewer: Viewer, Path(id): Path<String>) -> Response { |
| 218 | 3× | let found = match viewer.0.as_ref() { |
| 219 | 3× | Some(me) => { |
| 220 | 3× | db::approvals::get(&app.db, &id).await.ok().flatten().filter(|a| a.session_id == Some(me.session_id) && a.kind == "stepup") |
| 221 | | } |
| 222 | 0× | None => None, |
| 223 | | }; |
| 224 | 3× | match found { |
| 225 | 2× | Some(a) => { |
| 226 | 2× | let state = if a.state == "pending" && a.expires_ms <= db::now_ms() { "expired".to_string() } else { a.state }; |
| 227 | 2× | axum::Json(serde_json::json!({ "state": state })).into_response() |
| 228 | | } |
| 229 | 1× | None => (StatusCode::NOT_FOUND, axum::Json(serde_json::json!({ "state": "unknown" }))).into_response(), |
| 230 | | } |
| 231 | 3× | } |
| 232 | |
|
| 233 | | #[cfg(test)] |
| 234 | | mod tests { |
| 235 | | use super::*; |
| 236 | |
|
| 237 | | #[test] |
| 238 | 1× | fn only_changes_that_matter_are_guarded() { |
| 239 | 1× | let post = Method::POST; |
| 240 | 13× | for p in [ |
| 241 | 1× | "/settings/password", |
| 242 | 1× | "/settings/security/totp/disable", |
| 243 | 1× | "/settings/security/phones/3/remove", |
| 244 | 1× | "/settings/tokens", |
| 245 | 1× | "/settings/tokens/4/agent", |
| 246 | 1× | "/settings/keys/upload", |
| 247 | 1× | "/admin/mail", |
| 248 | 1× | "/admin/runners/7/state", |
| 249 | 1× | "/orgs/acme/settings/secrets", |
| 250 | 1× | "/andy/demo/settings/delete", |
| 251 | 1× | "/andy/demo/settings/transfer", |
| 252 | 1× | "/andy/demo/settings/secrets", |
| 253 | 1× | "/andy/demo/settings/collaborators", |
| 254 | 1× | ] { |
| 255 | 13× | assert!(sensitive(&post, p), "{p}"); |
| 256 | | } |
| 257 | 8× | for p in [ |
| 258 | 1× | "/settings", |
| 259 | 1× | "/settings/appearance", |
| 260 | 1× | "/settings/security/totp/begin", |
| 261 | 1× | "/settings/tokens/4/delete", |
| 262 | 1× | "/andy/demo/issues/new", |
| 263 | 1× | "/andy/demo/settings/topics", |
| 264 | 1× | "/login", |
| 265 | 1× | "/sudo", |
| 266 | 1× | ] { |
| 267 | 8× | assert!(!sensitive(&post, p), "{p}"); |
| 268 | | } |
| 269 | 1× | assert!(!sensitive(&Method::GET, "/admin/mail"), "reading never asks"); |
| 270 | 1× | } |
| 271 | | } |