forge
Explore
Log in

Don't you dare go Hollow

Web push endpoints and every importer request (API answers, download redirects) are held to the webhook outbound policy, so neither can reach internal addresses

Browse files at this commit

8428320e4590c0fbbb6ae7f355272e31c92b038dAhmet Kaan Gümüş and ClaudeParent: e47fd94
Some checks failed
Show checks
  • harden
    • web push endpoints and every importer request (API answers, download redirects) are held to the webhook outbound policy, so neither can reach internal addresses
    • git over HTTP needs a token with the repo scope, like the API
    • an open SSH connection of a suspended user can no longer run git commands
Show full message
🔒 harden: web push endpoints and every importer request (API answers, download redirects) are held to the webhook outbound policy, so neither can reach internal addresses; git over HTTP needs a token with the repo scope, like the API; an open SSH connection of a suspended user can no longer run git commands
crates/forge-web/src/git_auth.rsmodified+9 -0
@@ -66,6 +66,15 @@ pub async fn user_from_basic(
66 if !username_ok {66 if !username_ok {
67 return Err(AccessError::Unauthorized);67 return Err(AccessError::Unauthorized);
68 }68 }
69+ // The same rule as the REST API: git over HTTP needs the `repo` scope, so a token made only
70+ // for another purpose (packages) cannot read or push code.
71+ if !access
72+ .scopes
73+ .iter()
74+ .any(|scope| scope == crate::api::REPO_SCOPE)
75+ {
76+ return Err(AccessError::Unauthorized);
77+ }
69 78
70 state79 state
71 .store80 .store
crates/forge-web/src/importer/api.rsmodified+9 -0
@@ -12,6 +12,8 @@ use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER};
12 use serde::Deserialize;12 use serde::Deserialize;
13 use serde::de::DeserializeOwned;13 use serde::de::DeserializeOwned;
14 14
15+use crate::webhooks::client::{WebhookPolicy, validate_url};
16+
15 const PER_PAGE: usize = 100;17 const PER_PAGE: usize = 100;
16 /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.18 /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.
17 /// Forgejo and Gitea cap `limit` at 50 by default.19 /// Forgejo and Gitea cap `limit` at 50 by default.
@@ -200,6 +202,7 @@ pub enum Auth {
200 /// A client under the outbound policy, with the token kept private to the API host.202 /// A client under the outbound policy, with the token kept private to the API host.
201 pub struct Http {203 pub struct Http {
202 client: reqwest::Client,204 client: reqwest::Client,
205+ policy: WebhookPolicy,
203 token: Option<String>,206 token: Option<String>,
204 auth: Auth,207 auth: Auth,
205 auth_host: String,208 auth_host: String,
@@ -209,6 +212,7 @@ pub struct Http {
209 impl Http {212 impl Http {
210 pub fn new(213 pub fn new(
211 client: reqwest::Client,214 client: reqwest::Client,
215+ policy: WebhookPolicy,
212 token: Option<String>,216 token: Option<String>,
213 auth: Auth,217 auth: Auth,
214 auth_host: String,218 auth_host: String,
@@ -217,6 +221,7 @@ impl Http {
217 let token = token.filter(|t| !t.trim().is_empty());221 let token = token.filter(|t| !t.trim().is_empty());
218 Http {222 Http {
219 client,223 client,
224+ policy,
220 token,225 token,
221 auth,226 auth,
222 auth_host,227 auth_host,
@@ -257,6 +262,10 @@ impl Http {
257 262
258 /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx.263 /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx.
259 async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult<reqwest::Response> {264 async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult<reqwest::Response> {
265+ // Every URL, including one taken from an API answer or a redirect: the client's resolver
266+ // filters host names, but an address literal never reaches it.
267+ validate_url(url, &self.policy)
268+ .map_err(|e| ApiError::Http(format!("address refused: {e}")))?;
260 let mut attempt = 0u32;269 let mut attempt = 0u32;
261 loop {270 loop {
262 attempt += 1;271 attempt += 1;
crates/forge-web/src/importer/forgejo_tests.rsmodified+7 -0
@@ -101,8 +101,15 @@ fn page_of(target: &str) -> usize {
101 101
102 fn client(base: &str, token: Option<&str>) -> Forgejo {102 fn client(base: &str, token: Option<&str>) -> Forgejo {
103 let notice: super::super::api::Notice = Arc::new(|_| {});103 let notice: super::super::api::Notice = Arc::new(|_| {});
104+ let open =
105+ crate::webhooks::client::WebhookPolicy::from_config(&forge_core::config::WebhookConfig {
106+ allow_http: true,
107+ allowed_hosts: vec!["127.0.0.1".into()],
108+ })
109+ .expect("policy");
104 let http = Http::new(110 let http = Http::new(
105 reqwest::Client::new(),111 reqwest::Client::new(),
112+ open,
106 token.map(str::to_owned),113 token.map(str::to_owned),
107 Auth::Forgejo,114 Auth::Forgejo,
108 "127.0.0.1".into(),115 "127.0.0.1".into(),
crates/forge-web/src/importer/remote.rsmodified+3 -2
@@ -18,6 +18,7 @@ pub fn make_github(
18 .map_err(|e| format!("could not build the HTTP client: {e}"))?;18 .map_err(|e| format!("could not build the HTTP client: {e}"))?;
19 Ok(GitHub::new(Http::new(19 Ok(GitHub::new(Http::new(
20 client,20 client,
21+ policy(state),
21 token,22 token,
22 Auth::GitHub,23 Auth::GitHub,
23 "api.github.com".into(),24 "api.github.com".into(),
@@ -41,7 +42,7 @@ pub fn make_gitlab(
41 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")42 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
42 .map_err(|e| format!("could not build the HTTP client: {e}"))?;43 .map_err(|e| format!("could not build the HTTP client: {e}"))?;
43 Ok(GitLab::new(44 Ok(GitLab::new(
44- Http::new(client, token, Auth::GitLab, host, notice),45+ Http::new(client, policy(state), token, Auth::GitLab, host, notice),
45 instance,46 instance,
46 ))47 ))
47 }48 }
@@ -62,7 +63,7 @@ pub fn make_forgejo(
62 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")63 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
63 .map_err(|e| format!("could not build the HTTP client: {e}"))?;64 .map_err(|e| format!("could not build the HTTP client: {e}"))?;
64 Ok(Forgejo::new(65 Ok(Forgejo::new(
65- Http::new(client, token, Auth::Forgejo, host, notice),66+ Http::new(client, policy(state), token, Auth::Forgejo, host, notice),
66 instance,67 instance,
67 ))68 ))
68 }69 }
crates/forge-web/src/lfs/route_tests.rsmodified+7 -1
@@ -39,7 +39,13 @@ async fn fixture(visibility: Visibility) -> Fixture {
39 .unwrap();39 .unwrap();
40 let token = generate_token();40 let token = generate_token();
41 store41 store
42- .create_token(&tahinli.id, "test", &hash_token(&token), &[], None)42+ .create_token(
43+ &tahinli.id,
44+ "test",
45+ &hash_token(&token),
46+ &["repo".to_owned()],
47+ None,
48+ )
43 .await49 .await
44 .unwrap();50 .unwrap();
45 let repo = store51 let repo = store
crates/forge-web/src/pages/push.rsmodified+7 -3
@@ -30,6 +30,7 @@ use crate::auth::{current_user, require_csrf, require_user};
30 use crate::pages::ci_runs::events_response;30 use crate::pages::ci_runs::events_response;
31 use crate::state::AppState;31 use crate::state::AppState;
32 use crate::web_push::{self, Alert, crypto};32 use crate::web_push::{self, Alert, crypto};
33+use crate::webhooks::client::{WebhookPolicy, validate_url};
33 34
34 /// Longest push endpoint accepted, in bytes.35 /// Longest push endpoint accepted, in bytes.
35 const MAX_ENDPOINT: usize = 2048;36 const MAX_ENDPOINT: usize = 2048;
@@ -70,7 +71,7 @@ struct CsrfForm {
70 71
71 /// A push endpoint must be an https URL of sane length. The service worker never opens it, but72 /// A push endpoint must be an https URL of sane length. The service worker never opens it, but
72 /// the server posts to it, so only the push service's own kind of URL is accepted.73 /// the server posts to it, so only the push service's own kind of URL is accepted.
73-fn check_endpoint(endpoint: &str) -> forge_core::Result<()> {74+fn check_endpoint(endpoint: &str, policy: &WebhookPolicy) -> forge_core::Result<()> {
74 if endpoint.len() > MAX_ENDPOINT {75 if endpoint.len() > MAX_ENDPOINT {
75 return Err(forge_core::Error::Invalid(76 return Err(forge_core::Error::Invalid(
76 "the push endpoint is too long".into(),77 "the push endpoint is too long".into(),
@@ -85,6 +86,8 @@ fn check_endpoint(endpoint: &str) -> forge_core::Result<()> {
85 "the push endpoint must be an https URL on the default port".into(),86 "the push endpoint must be an https URL on the default port".into(),
86 ));87 ));
87 }88 }
89+ // The server posts to it, so it is held to the outbound policy webhooks use.
90+ validate_url(endpoint, policy).map_err(|e| forge_core::Error::Invalid(e.to_string()))?;
88 Ok(())91 Ok(())
89 }92 }
90 93
@@ -126,12 +129,13 @@ async fn vapid_key(cx: &Cx) -> Result<Response> {
126 #[route(POST "/push/subscribe")]129 #[route(POST "/push/subscribe")]
127 async fn subscribe(cx: &Cx, Form(form): Form<SubscribeForm>) -> Result<Response> {130 async fn subscribe(cx: &Cx, Form(form): Form<SubscribeForm>) -> Result<Response> {
128 let (user, _) = require_csrf(cx, &form.csrf).await?;131 let (user, _) = require_csrf(cx, &form.csrf).await?;
132+ let state = app_context::<AppState>(cx);
133+ let policy = crate::mirrors::policy(state);
129 if let Err(e) =134 if let Err(e) =
130- check_endpoint(&form.endpoint).and_then(|()| check_keys(&form.p256dh, &form.auth))135+ check_endpoint(&form.endpoint, &policy).and_then(|()| check_keys(&form.p256dh, &form.auth))
131 {136 {
132 return Ok(api::error(StatusCode::BAD_REQUEST, &e.to_string()));137 return Ok(api::error(StatusCode::BAD_REQUEST, &e.to_string()));
133 }138 }
134- let state = app_context::<AppState>(cx);
135 let agent = headers(cx)139 let agent = headers(cx)
136 .get(USER_AGENT)140 .get(USER_AGENT)
137 .and_then(|value| value.to_str().ok())141 .and_then(|value| value.to_str().ok())
crates/forge-web/src/ssh_backend.rsmodified+10 -0
@@ -39,6 +39,16 @@ impl SshBackend {
39 return Err(MSG_INTERNAL.to_string());39 return Err(MSG_INTERNAL.to_string());
40 }40 }
41 };41 };
42+ // Checked on every command, not only at key authentication: a connection opened before the
43+ // account was suspended stays up and can still ask for new channels.
44+ match self.state.store.suspension(&user.id).await {
45+ Ok(None) => {}
46+ Ok(Some(_)) => return Err(MSG_DENIED.to_string()),
47+ Err(e) => {
48+ tracing::error!(error = %e, "ssh: suspension lookup failed");
49+ return Err(MSG_INTERNAL.to_string());
50+ }
51+ }
42 52
43 match access::resolve_repo(&self.state, Some(&user), owner, name, service).await {53 match access::resolve_repo(&self.state, Some(&user), owner, name, service).await {
44 Ok((repo, path)) => Ok((user, repo, path)),54 Ok((repo, path)) => Ok((user, repo, path)),
crates/forge-web/src/web_push/mod.rsmodified+66 -19
@@ -21,6 +21,7 @@ use forge_core::{Error, Result};
21 21
22 use crate::i18n::{self, Lang, misc, push as text};22 use crate::i18n::{self, Lang, misc, push as text};
23 use crate::state::AppState;23 use crate::state::AppState;
24+use crate::webhooks::client::{WebhookPolicy, policy_client, validate_url};
24 25
25 /// How long one push request may take before it counts as failed.26 /// How long one push request may take before it counts as failed.
26 const SEND_TIMEOUT: Duration = Duration::from_secs(15);27 const SEND_TIMEOUT: Duration = Duration::from_secs(15);
@@ -192,18 +193,22 @@ pub fn agent_label(user_agent: &str) -> String {
192 format!("{browser} on {os}")193 format!("{browser} on {os}")
193 }194 }
194 195
195-/// The shared HTTP client for push requests. Built once; redirects are not followed, since a push196+/// The HTTP client for push requests: the webhook outbound policy (no internal addresses, no
196-/// service answers on the endpoint itself.197+/// redirects, no proxy). An endpoint is any URL a signed-in browser sent, so it gets the same
197-fn client() -> &'static reqwest::Client {198+/// treatment as a hook URL. Built once; the policy comes from the config, which does not change.
198- static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();199+fn client(policy: &WebhookPolicy) -> Option<&'static reqwest::Client> {
199- CLIENT.get_or_init(|| {200+ static CLIENT: OnceLock<Option<reqwest::Client>> = OnceLock::new();
200- reqwest::Client::builder()201+ CLIENT
201- .timeout(SEND_TIMEOUT)202+ .get_or_init(
202- .redirect(reqwest::redirect::Policy::none())203+ || match policy_client(policy.clone(), SEND_TIMEOUT, "forge-web-push") {
203- .user_agent("forge-web-push")204+ Ok(client) => Some(client),
204- .build()205+ Err(e) => {
205- .expect("the push client builds with the default TLS settings")206+ tracing::error!(error = %e, "web push: the client does not build");
206- })207+ None
208+ }
209+ },
210+ )
211+ .as_ref()
207 }212 }
208 213
209 /// The instance's VAPID key pair. The private key is stored sealed with the instance key; the214 /// The instance's VAPID key pair. The private key is stored sealed with the instance key; the
@@ -253,11 +258,17 @@ pub enum Outcome {
253 258
254 /// Encrypts `payload` for one device and posts it to the device's push service.259 /// Encrypts `payload` for one device and posts it to the device's push service.
255 pub async fn send_one(260 pub async fn send_one(
261+ client: &reqwest::Client,
262+ policy: &WebhookPolicy,
256 keys: &VapidKeys,263 keys: &VapidKeys,
257 subject: &str,264 subject: &str,
258 sub: &PushSubscription,265 sub: &PushSubscription,
259 payload: &[u8],266 payload: &[u8],
260 ) -> Outcome {267 ) -> Outcome {
268+ // Checked again on each send: an address literal never reaches the resolver's filter.
269+ if let Err(e) = validate_url(&sub.endpoint, policy) {
270+ return Outcome::Failed(e.to_string());
271+ }
261 let built = (|| {272 let built = (|| {
262 let p256dh = crypto::decode_b64(&sub.p256dh)?;273 let p256dh = crypto::decode_b64(&sub.p256dh)?;
263 let auth = crypto::decode_b64(&sub.auth)?;274 let auth = crypto::decode_b64(&sub.auth)?;
@@ -279,7 +290,7 @@ pub async fn send_one(
279 Ok(request) => request,290 Ok(request) => request,
280 Err(e) => return Outcome::Failed(e.to_string()),291 Err(e) => return Outcome::Failed(e.to_string()),
281 };292 };
282- match client().execute(request).await {293+ match client.execute(request).await {
283 Ok(res) => match res.status().as_u16() {294 Ok(res) => match res.status().as_u16() {
284 200..=299 => Outcome::Delivered,295 200..=299 => Outcome::Delivered,
285 404 | 410 => Outcome::Gone,296 404 | 410 => Outcome::Gone,
@@ -315,8 +326,12 @@ pub async fn deliver(state: &AppState, user_id: &str, alert: &Alert) -> Result<u
315 .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?;326 .map_err(|e| Error::Invalid(format!("the push payload does not encode: {e}")))?;
316 let keys = vapid_keys(state).await?;327 let keys = vapid_keys(state).await?;
317 let subject = subject(&state.live().base_url);328 let subject = subject(&state.live().base_url);
329+ let policy = crate::mirrors::policy(state);
330+ let Some(client) = client(&policy) else {
331+ return Err(Error::Invalid("the web push client does not build".into()));
332+ };
318 for device in &devices {333 for device in &devices {
319- match send_one(&keys, &subject, device, &payload).await {334+ match send_one(client, &policy, &keys, &subject, device, &payload).await {
320 Outcome::Delivered => {335 Outcome::Delivered => {
321 state.store.mark_push_delivered(&device.id).await?;336 state.store.mark_push_delivered(&device.id).await?;
322 state.push_live.publish(user_id);337 state.push_live.publish(user_id);
@@ -495,7 +510,14 @@ mod tests {
495 #[tokio::test]510 #[tokio::test]
496 async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() {511 async fn a_device_the_service_reports_gone_is_removed_and_a_live_one_is_kept() {
497 let dir = tempfile::tempdir().expect("tempdir");512 let dir = tempfile::tempdir().expect("tempdir");
498- let state = crate::test_support::test_state(dir.path()).await;513+ let mut state = crate::test_support::test_state(dir.path()).await;
514+ // The mock push service is on loopback over http, which the policy refuses by default.
515+ let mut config = crate::test_support::test_config(dir.path());
516+ config.webhooks = forge_core::config::WebhookConfig {
517+ allow_http: true,
518+ allowed_hosts: vec!["127.0.0.1".into()],
519+ };
520+ state.config = std::sync::Arc::new(config);
499 let user = state521 let user = state
500 .store522 .store
501 .create_user("tahinli", None, "h", false)523 .create_user("tahinli", None, "h", false)
@@ -553,15 +575,40 @@ mod tests {
553 private,575 private,
554 };576 };
555 let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json");577 let payload = serde_json::to_vec(&Alert::Test.message(Lang::En)).expect("json");
556- let ok = device(format!("http://{addr}/ok"));578+ let open = WebhookPolicy::from_config(&forge_core::config::WebhookConfig {
579+ allow_http: true,
580+ allowed_hosts: vec!["127.0.0.1".into()],
581+ })
582+ .expect("policy");
583+ let client = reqwest::Client::new();
584+ let send = |endpoint: String, policy: WebhookPolicy| {
585+ let (client, keys, payload) = (&client, &keys, &payload);
586+ async move {
587+ send_one(
588+ client,
589+ &policy,
590+ keys,
591+ "https://localhost",
592+ &device(endpoint),
593+ payload,
594+ )
595+ .await
596+ }
597+ };
557 assert_eq!(598 assert_eq!(
558- send_one(&keys, "https://localhost", &ok, &payload).await,599+ send(format!("http://{addr}/ok"), open.clone()).await,
559 Outcome::Delivered600 Outcome::Delivered
560 );601 );
561- let gone = device(format!("http://{addr}/gone"));
562 assert_eq!(602 assert_eq!(
563- send_one(&keys, "https://localhost", &gone, &payload).await,603+ send(format!("http://{addr}/gone"), open).await,
564 Outcome::Gone604 Outcome::Gone
565 );605 );
606+ // The default policy refuses an internal address before anything is sent.
607+ let strict = WebhookPolicy::from_config(&forge_core::config::WebhookConfig::default())
608+ .expect("policy");
609+ assert!(matches!(
610+ send(format!("http://{addr}/ok"), strict).await,
611+ Outcome::Failed(_)
612+ ));
566 }613 }
567 }614 }