diff --git a/crates/forge-web/src/git_auth.rs b/crates/forge-web/src/git_auth.rs index ca31939..15e5bbd 100644 --- a/crates/forge-web/src/git_auth.rs +++ b/crates/forge-web/src/git_auth.rs @@ -66,6 +66,15 @@ pub async fn user_from_basic( if !username_ok { return Err(AccessError::Unauthorized); } + // The same rule as the REST API: git over HTTP needs the `repo` scope, so a token made only + // for another purpose (packages) cannot read or push code. + if !access + .scopes + .iter() + .any(|scope| scope == crate::api::REPO_SCOPE) + { + return Err(AccessError::Unauthorized); + } state .store diff --git a/crates/forge-web/src/importer/api.rs b/crates/forge-web/src/importer/api.rs index 410fe98..f9c8e83 100644 --- a/crates/forge-web/src/importer/api.rs +++ b/crates/forge-web/src/importer/api.rs @@ -12,6 +12,8 @@ use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER}; use serde::Deserialize; use serde::de::DeserializeOwned; +use crate::webhooks::client::{WebhookPolicy, validate_url}; + const PER_PAGE: usize = 100; /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever. /// Forgejo and Gitea cap `limit` at 50 by default. @@ -200,6 +202,7 @@ pub enum Auth { /// A client under the outbound policy, with the token kept private to the API host. pub struct Http { client: reqwest::Client, + policy: WebhookPolicy, token: Option, auth: Auth, auth_host: String, @@ -209,6 +212,7 @@ pub struct Http { impl Http { pub fn new( client: reqwest::Client, + policy: WebhookPolicy, token: Option, auth: Auth, auth_host: String, @@ -217,6 +221,7 @@ impl Http { let token = token.filter(|t| !t.trim().is_empty()); Http { client, + policy, token, auth, auth_host, @@ -257,6 +262,10 @@ impl Http { /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx. async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult { + // Every URL, including one taken from an API answer or a redirect: the client's resolver + // filters host names, but an address literal never reaches it. + validate_url(url, &self.policy) + .map_err(|e| ApiError::Http(format!("address refused: {e}")))?; let mut attempt = 0u32; loop { attempt += 1; diff --git a/crates/forge-web/src/importer/forgejo_tests.rs b/crates/forge-web/src/importer/forgejo_tests.rs index b76f6aa..cb2c313 100644 --- a/crates/forge-web/src/importer/forgejo_tests.rs +++ b/crates/forge-web/src/importer/forgejo_tests.rs @@ -101,8 +101,15 @@ fn page_of(target: &str) -> usize { fn client(base: &str, token: Option<&str>) -> Forgejo { let notice: super::super::api::Notice = Arc::new(|_| {}); + let open = + crate::webhooks::client::WebhookPolicy::from_config(&forge_core::config::WebhookConfig { + allow_http: true, + allowed_hosts: vec!["127.0.0.1".into()], + }) + .expect("policy"); let http = Http::new( reqwest::Client::new(), + open, token.map(str::to_owned), Auth::Forgejo, "127.0.0.1".into(), diff --git a/crates/forge-web/src/importer/remote.rs b/crates/forge-web/src/importer/remote.rs index fe47977..e6a9dc2 100644 --- a/crates/forge-web/src/importer/remote.rs +++ b/crates/forge-web/src/importer/remote.rs @@ -18,6 +18,7 @@ pub fn make_github( .map_err(|e| format!("could not build the HTTP client: {e}"))?; Ok(GitHub::new(Http::new( client, + policy(state), token, Auth::GitHub, "api.github.com".into(), @@ -41,7 +42,7 @@ pub fn make_gitlab( let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") .map_err(|e| format!("could not build the HTTP client: {e}"))?; Ok(GitLab::new( - Http::new(client, token, Auth::GitLab, host, notice), + Http::new(client, policy(state), token, Auth::GitLab, host, notice), instance, )) } @@ -62,7 +63,7 @@ pub fn make_forgejo( let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") .map_err(|e| format!("could not build the HTTP client: {e}"))?; Ok(Forgejo::new( - Http::new(client, token, Auth::Forgejo, host, notice), + Http::new(client, policy(state), token, Auth::Forgejo, host, notice), instance, )) } diff --git a/crates/forge-web/src/lfs/route_tests.rs b/crates/forge-web/src/lfs/route_tests.rs index d3879cd..3fe575e 100644 --- a/crates/forge-web/src/lfs/route_tests.rs +++ b/crates/forge-web/src/lfs/route_tests.rs @@ -39,7 +39,13 @@ async fn fixture(visibility: Visibility) -> Fixture { .unwrap(); let token = generate_token(); store - .create_token(&tahinli.id, "test", &hash_token(&token), &[], None) + .create_token( + &tahinli.id, + "test", + &hash_token(&token), + &["repo".to_owned()], + None, + ) .await .unwrap(); let repo = store diff --git a/crates/forge-web/src/pages/push.rs b/crates/forge-web/src/pages/push.rs index fad8db1..003ff19 100644 --- a/crates/forge-web/src/pages/push.rs +++ b/crates/forge-web/src/pages/push.rs @@ -30,6 +30,7 @@ use crate::auth::{current_user, require_csrf, require_user}; use crate::pages::ci_runs::events_response; use crate::state::AppState; use crate::web_push::{self, Alert, crypto}; +use crate::webhooks::client::{WebhookPolicy, validate_url}; /// Longest push endpoint accepted, in bytes. const MAX_ENDPOINT: usize = 2048; @@ -70,7 +71,7 @@ struct CsrfForm { /// A push endpoint must be an https URL of sane length. The service worker never opens it, but /// the server posts to it, so only the push service's own kind of URL is accepted. -fn check_endpoint(endpoint: &str) -> forge_core::Result<()> { +fn check_endpoint(endpoint: &str, policy: &WebhookPolicy) -> forge_core::Result<()> { if endpoint.len() > MAX_ENDPOINT { return Err(forge_core::Error::Invalid( "the push endpoint is too long".into(), @@ -85,6 +86,8 @@ fn check_endpoint(endpoint: &str) -> forge_core::Result<()> { "the push endpoint must be an https URL on the default port".into(), )); } + // The server posts to it, so it is held to the outbound policy webhooks use. + validate_url(endpoint, policy).map_err(|e| forge_core::Error::Invalid(e.to_string()))?; Ok(()) } @@ -126,12 +129,13 @@ async fn vapid_key(cx: &Cx) -> Result { #[route(POST "/push/subscribe")] async fn subscribe(cx: &Cx, Form(form): Form) -> Result { let (user, _) = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let policy = crate::mirrors::policy(state); if let Err(e) = - check_endpoint(&form.endpoint).and_then(|()| check_keys(&form.p256dh, &form.auth)) + check_endpoint(&form.endpoint, &policy).and_then(|()| check_keys(&form.p256dh, &form.auth)) { return Ok(api::error(StatusCode::BAD_REQUEST, &e.to_string())); } - let state = app_context::(cx); let agent = headers(cx) .get(USER_AGENT) .and_then(|value| value.to_str().ok()) diff --git a/crates/forge-web/src/ssh_backend.rs b/crates/forge-web/src/ssh_backend.rs index a48038c..f2465cd 100644 --- a/crates/forge-web/src/ssh_backend.rs +++ b/crates/forge-web/src/ssh_backend.rs @@ -39,6 +39,16 @@ impl SshBackend { return Err(MSG_INTERNAL.to_string()); } }; + // Checked on every command, not only at key authentication: a connection opened before the + // account was suspended stays up and can still ask for new channels. + match self.state.store.suspension(&user.id).await { + Ok(None) => {} + Ok(Some(_)) => return Err(MSG_DENIED.to_string()), + Err(e) => { + tracing::error!(error = %e, "ssh: suspension lookup failed"); + return Err(MSG_INTERNAL.to_string()); + } + } match access::resolve_repo(&self.state, Some(&user), owner, name, service).await { Ok((repo, path)) => Ok((user, repo, path)), diff --git a/crates/forge-web/src/web_push/mod.rs b/crates/forge-web/src/web_push/mod.rs index aa33a61..0ad1bf2 100644 --- a/crates/forge-web/src/web_push/mod.rs +++ b/crates/forge-web/src/web_push/mod.rs @@ -21,6 +21,7 @@ use forge_core::{Error, Result}; use crate::i18n::{self, Lang, misc, push as text}; use crate::state::AppState; +use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url}; /// How long one push request may take before it counts as failed. const SEND_TIMEOUT: Duration = Duration::from_secs(15); @@ -192,18 +193,22 @@ pub fn agent_label(user_agent: &str) -> String { format!("{browser} on {os}") } -/// The shared HTTP client for push requests. Built once; redirects are not followed, since a push -/// service answers on the endpoint itself. -fn client() -> &'static reqwest::Client { - static CLIENT: OnceLock = OnceLock::new(); - CLIENT.get_or_init(|| { - reqwest::Client::builder() - .timeout(SEND_TIMEOUT) - .redirect(reqwest::redirect::Policy::none()) - .user_agent("forge-web-push") - .build() - .expect("the push client builds with the default TLS settings") - }) +/// The HTTP client for push requests: the webhook outbound policy (no internal addresses, no +/// redirects, no proxy). An endpoint is any URL a signed-in browser sent, so it gets the same +/// treatment as a hook URL. Built once; the policy comes from the config, which does not change. +fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> { + static CLIENT: OnceLock> = OnceLock::new(); + CLIENT + .get_or_init( + || match policy_client(policy.clone(), SEND_TIMEOUT, "forge-web-push") { + Ok(client) => Some(client), + Err(e) => { + tracing::error!(error = %e, "web push: the client does not build"); + None + } + }, + ) + .as_ref() } /// The instance's VAPID key pair. The private key is stored sealed with the instance key; the @@ -253,11 +258,17 @@ pub enum Outcome { /// Encrypts `payload` for one device and posts it to the device's push service. pub async fn send_one( + client: &reqwest::Client, + policy: &WebhookPolicy, keys: &VapidKeys, subject: &str, sub: &PushSubscription, payload: &[u8], ) -> Outcome { + // Checked again on each send: an address literal never reaches the resolver's filter. + if let Err(e) = validate_url(&sub.endpoint, policy) { + return Outcome::Failed(e.to_string()); + } let built = (|| { let p256dh = crypto::decode_b64(&sub.p256dh)?; let auth = crypto::decode_b64(&sub.auth)?; @@ -279,7 +290,7 @@ pub async fn send_one( Ok(request) => request, Err(e) => return Outcome::Failed(e.to_string()), }; - match client().execute(request).await { + match client.execute(request).await { Ok(res) => match res.status().as_u16() { 200..=299 => Outcome::Delivered, 404 | 410 => Outcome::Gone, @@ -315,8 +326,12 @@ pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result { state.store.mark_push_delivered(&device.id).await?; state.push_live.publish(user_id); @@ -495,7 +510,14 @@ mod tests { #[tokio::test] async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() { let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; + let mut state = crate::test_support::test_state(dir.path()).await; + // The mock push service is on loopback over http, which the policy refuses by default. + let mut config = crate::test_support::test_config(dir.path()); + config.webhooks = forge_core::config::WebhookConfig { + allow_http: true, + allowed_hosts: vec!["127.0.0.1".into()], + }; + state.config = std::sync::Arc::new(config); let user = state .store .create_user("tahinli", None, "h", false) @@ -553,15 +575,40 @@ mod tests { private, }; let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json"); - let ok = device(format!("http://{addr}/ok")); + let open = WebhookPolicy::from_config(&forge_core::config::WebhookConfig { + allow_http: true, + allowed_hosts: vec!["127.0.0.1".into()], + }) + .expect("policy"); + let client = reqwest::Client::new(); + let send = |endpoint: String, policy: WebhookPolicy| { + let (client, keys, payload) = (&client, &keys, &payload); + async move { + send_one( + client, + &policy, + keys, + "https://localhost", + &device(endpoint), + payload, + ) + .await + } + }; assert_eq!( - send_one(&keys, "https://localhost", &ok, &payload).await, + send(format!("http://{addr}/ok"), open.clone()).await, Outcome::Delivered ); - let gone = device(format!("http://{addr}/gone")); assert_eq!( - send_one(&keys, "https://localhost", &gone, &payload).await, + send(format!("http://{addr}/gone"), open).await, Outcome::Gone ); + // The default policy refuses an internal address before anything is sent. + let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default()) + .expect("policy"); + assert!(matches!( + send(format!("http://{addr}/ok"), strict).await, + Outcome::Failed(_) + )); } }