1#![doc = include_str!("../README.md")]
107#![deny(unsafe_code)]
108#![warn(rust_2018_idioms)]
109
110#[cfg(feature = "activitypub")]
111pub mod activitypub;
112pub mod cli;
114pub mod cross_identity;
115pub mod scheme;
116
117pub(crate) mod hardened_git;
118
119mod handlers;
124
125#[cfg(feature = "jev")]
126pub mod jev;
127mod mcp;
130
131pub mod mempool;
136
137pub mod trail_store;
143
144use std::collections::HashMap;
145use std::net::{IpAddr, Ipv4Addr};
146use std::path::{Path, PathBuf};
147use std::sync::{Arc, Mutex};
148use std::time::{Duration, Instant};
149
150use actix_web::body::{BoxBody, EitherBody};
151use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
152use actix_web::http::{header, StatusCode};
153use actix_web::middleware::{NormalizePath, TrailingSlash};
154use actix_web::{web, App, Error as ActixError, HttpRequest, HttpResponse};
155use bytes::Bytes;
156use futures_util::future::{ready, LocalBoxFuture, Ready};
157use futures_util::StreamExt;
158use percent_encoding::percent_decode_str;
159use serde::Deserialize;
160use solid_pod_rs::{
161 auth::{nip98, replay::ReplayStore},
165 config::sources::parse_size,
166 interop,
167 ldp::{
168 self, cache_control_for_response, LdpContainerOps, PatchCreateOutcome, ResponseAudience,
169 },
170 mashlib::{self, MashlibConfig},
171 provenance::{ProvenanceReceipt, ProvenanceSkip},
172 security::DotfileAllowlist,
173 storage::Storage,
174 wac::{
175 self, conditions::RequestContext, effective_acl_target, parse_jsonld_acl,
176 protected_resource_for_acl, AccessMode,
177 },
178 PodError,
179};
180
181const _: () = solid_pod_rs::auth::nip98::assert_schnorr_verification_enabled();
193
194static NIP98_REPLAY: std::sync::LazyLock<solid_pod_rs::auth::replay::Nip98ReplayCache> =
201 std::sync::LazyLock::new(solid_pod_rs::auth::replay::Nip98ReplayCache::from_env);
202
203pub(crate) static PAYMENT_STATE_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
209 std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
210
211const RESOURCE_WRITE_LOCK_STRIPES: usize = 256;
213
214static RESOURCE_WRITE_LOCKS: std::sync::LazyLock<Vec<tokio::sync::Mutex<()>>> =
222 std::sync::LazyLock::new(|| {
223 (0..RESOURCE_WRITE_LOCK_STRIPES)
224 .map(|_| tokio::sync::Mutex::new(()))
225 .collect()
226 });
227
228pub(crate) async fn lock_resource(path: &str) -> tokio::sync::MutexGuard<'static, ()> {
241 use std::hash::BuildHasher;
242 static STRIPE_KEY: std::sync::LazyLock<std::collections::hash_map::RandomState> =
245 std::sync::LazyLock::new(std::collections::hash_map::RandomState::new);
246 let stripe = (STRIPE_KEY.hash_one(path) as usize) % RESOURCE_WRITE_LOCK_STRIPES;
247 RESOURCE_WRITE_LOCKS[stripe].lock().await
248}
249
250const MINT_LOCK_ATTEMPTS: usize = 64;
252
253pub(crate) async fn mint_and_lock_target(
262 storage: &dyn Storage,
263 target: &str,
264) -> Result<(String, tokio::sync::MutexGuard<'static, ()>), PodError> {
265 let mut previous: Option<String> = None;
266 for _ in 0..MINT_LOCK_ATTEMPTS {
267 let candidate = mint_unique_target(storage, target).await;
268 if previous.as_deref() == Some(candidate.as_str()) {
271 break;
272 }
273 let guard = lock_resource(&candidate).await;
274 if !storage.exists(&candidate).await? {
277 return Ok((candidate, guard));
278 }
279 drop(guard);
280 previous = Some(candidate);
281 }
282 Err(PodError::Conflict(format!("no free name for {target}")))
283}
284
285async fn check_write_preconditions(
290 req: &HttpRequest,
291 state: &AppState,
292 path: &str,
293) -> Result<(), ActixError> {
294 let value = |name| req.headers().get(name).and_then(|v| v.to_str().ok());
295 let (if_match, if_none_match) = (value(header::IF_MATCH), value(header::IF_NONE_MATCH));
296 if if_match.is_none() && if_none_match.is_none() {
297 return Ok(());
298 }
299 let current = match state.storage.head(path).await {
300 Ok(meta) => Some(meta.etag),
301 Err(PodError::NotFound(_)) => None,
302 Err(e) => return Err(to_actix(e)),
303 };
304 match ldp::evaluate_preconditions(
305 req.method().as_str(),
306 current.as_deref(),
307 if_match,
308 if_none_match,
309 ) {
310 ldp::ConditionalOutcome::PreconditionFailed => Err(
311 actix_web::error::ErrorPreconditionFailed("precondition failed"),
312 ),
313 _ => Ok(()),
314 }
315}
316
317#[derive(Clone)]
323pub struct AppState {
324 pub storage: Arc<dyn Storage>,
325 pub dotfiles: Arc<DotfileAllowlist>,
326 pub body_cap: usize,
327 pub nodeinfo: NodeInfoMeta,
328 pub mashlib: MashlibConfig,
329 pub mashlib_cdn: Option<String>,
332 pub live_reload: bool,
334 pub pay_config: solid_pod_rs::payments::PayConfig,
337 pub data_root: Option<PathBuf>,
342 pub quota: Option<Arc<dyn solid_pod_rs::quota::QuotaPolicy>>,
344 pub pod_create_limiter: Arc<PodCreateLimiter>,
346 pub allowed_origins: Vec<String>,
353 pub admin_key: Option<String>,
358 pub mcp_enabled: bool,
363 pub mempool_url: Option<String>,
369 pub conneg_enabled: bool,
373 pub trust_proxy: bool,
377 pub public_base_url: Option<String>,
381 pub allowed_hosts: Vec<String>,
384 pub cross_identity: Option<Arc<dyn cross_identity::CrossIdentityResolver>>,
387 pub activitypub: Option<Arc<dyn ActorDocument>>,
390}
391
392pub trait ActorDocument: Send + Sync {
395 fn actor_json(&self, base_url: &str) -> serde_json::Value;
397}
398
399#[cfg(test)]
400mod nip98_request_binding_tests {
401 use super::*;
402 use actix_web::test::TestRequest;
403
404 const SECRET: &str = "3333333333333333333333333333333333333333333333333333333333333333";
405
406 fn now() -> u64 {
407 std::time::SystemTime::now()
408 .duration_since(std::time::UNIX_EPOCH)
409 .unwrap()
410 .as_secs()
411 }
412
413 #[actix_web::test]
414 async fn authentication_binds_the_complete_query_string() {
415 let signed_url = "http://localhost:8080/private?include=true";
416 let token = nip98::mint(signed_url, "GET", SECRET, now()).unwrap();
417 let request = TestRequest::get()
418 .uri("/private?include=true")
419 .insert_header((header::AUTHORIZATION, format!("Nostr {token}")))
420 .to_http_request();
421 assert!(extract_pubkey(&request).await.is_some());
422
423 let path_only = nip98::mint("http://localhost:8080/private", "GET", SECRET, now()).unwrap();
424 let request = TestRequest::get()
425 .uri("/private?include=true")
426 .insert_header((header::AUTHORIZATION, format!("Nostr {path_only}")))
427 .to_http_request();
428 assert!(extract_pubkey(&request).await.is_none());
429 }
430
431 #[actix_web::test]
432 async fn authentication_binds_the_exact_raw_body() {
433 let expected = br#"{"value":"authorised"}"#;
434 let token = nip98::mint_with_payload(
435 "http://localhost:8080/resource",
436 "PUT",
437 Some(expected),
438 SECRET,
439 now(),
440 )
441 .unwrap();
442 let request = TestRequest::put()
443 .uri("/resource")
444 .insert_header((header::AUTHORIZATION, format!("Nostr {token}")))
445 .to_http_request();
446
447 assert!(
448 extract_pubkey_with_body(&request, Some(br#"{"value":"tampered"}"#))
449 .await
450 .is_none()
451 );
452 assert!(extract_pubkey_with_body(&request, Some(expected))
453 .await
454 .is_some());
455 }
456}
457
458#[derive(Clone, Debug)]
460pub struct NodeInfoMeta {
461 pub software_name: String,
462 pub software_version: String,
463 pub open_registrations: bool,
464 pub total_users: u64,
465 pub base_url: String,
466}
467
468impl Default for NodeInfoMeta {
469 fn default() -> Self {
470 Self {
471 software_name: "solid-pod-rs-server".to_string(),
472 software_version: env!("CARGO_PKG_VERSION").to_string(),
473 open_registrations: false,
474 total_users: 0,
475 base_url: "http://localhost".to_string(),
476 }
477 }
478}
479
480pub const DEFAULT_BODY_CAP: usize = 50 * 1024 * 1024;
483
484pub fn body_cap_from_env() -> usize {
489 match std::env::var("JSS_MAX_REQUEST_BODY").or_else(|_| std::env::var("JSS_BODY_LIMIT")) {
490 Ok(v) => parse_size(&v)
491 .map(|u| u as usize)
492 .unwrap_or(DEFAULT_BODY_CAP),
493 Err(_) => DEFAULT_BODY_CAP,
494 }
495}
496
497impl AppState {
498 pub fn public_origin(&self) -> Option<String> {
500 self.public_base_url
501 .as_deref()
502 .and_then(scheme::normalise_origin)
503 }
504
505 pub fn new(storage: Arc<dyn Storage>) -> Self {
508 Self {
509 storage,
510 dotfiles: Arc::new(DotfileAllowlist::from_env()),
511 body_cap: body_cap_from_env(),
512 nodeinfo: NodeInfoMeta::default(),
513 mashlib: MashlibConfig::default(),
514 mashlib_cdn: None,
515 live_reload: false,
516 pay_config: solid_pod_rs::payments::PayConfig::default(),
517 data_root: None,
518 quota: None,
519 pod_create_limiter: Arc::new(PodCreateLimiter::default()),
520 allowed_origins: Vec::new(),
521 admin_key: None,
522 mcp_enabled: false,
523 mempool_url: None,
524 conneg_enabled: false,
525 trust_proxy: false,
526 public_base_url: None,
527 allowed_hosts: Vec::new(),
528 cross_identity: None,
529 activitypub: None,
530 }
531 }
532}
533
534const LIVE_RELOAD_SCRIPT: &str = "<script>(function(){var ws=new WebSocket((location.protocol==='https:'?'wss:':'ws:')+'//'+location.host+'/.notifications');ws.onopen=function(){ws.send('sub '+location.href)};ws.onmessage=function(e){if(e.data.startsWith('pub '))location.reload()};ws.onclose=function(){setTimeout(function(){location.reload()},1000)}})();</script>";
535
536fn inject_live_reload(html: impl AsRef<[u8]>, enabled: bool) -> Vec<u8> {
537 let bytes = html.as_ref();
538 if !enabled {
539 return bytes.to_vec();
540 }
541 let html = String::from_utf8_lossy(bytes);
542 if let Some(index) = html.find("</body>") {
543 let mut out = String::with_capacity(html.len() + LIVE_RELOAD_SCRIPT.len());
544 out.push_str(&html[..index]);
545 out.push_str(LIVE_RELOAD_SCRIPT);
546 out.push_str(&html[index..]);
547 out.into_bytes()
548 } else {
549 format!("{html}{LIVE_RELOAD_SCRIPT}").into_bytes()
550 }
551}
552
553#[cfg(test)]
554mod live_reload_tests {
555 use super::*;
556
557 #[test]
558 fn injects_before_body_close_and_is_disabled_by_default() {
559 let html = b"<html><body>ok</body></html>";
560 assert_eq!(inject_live_reload(html, false), html);
561 let injected = String::from_utf8(inject_live_reload(html, true)).unwrap();
562 assert!(injected.contains("/.notifications"));
563 assert!(injected.find("<script>").unwrap() < injected.find("</body>").unwrap());
564 }
565}
566
567#[cfg(all(test, feature = "dev-bearer"))]
568mod dev_bearer_tests {
569 use super::*;
570 use base64::Engine as _;
571 use hmac::{Hmac, Mac};
572 use sha2::Sha256;
573 use std::sync::Mutex;
574
575 static ENV: Mutex<()> = Mutex::new(());
576
577 fn now() -> u64 {
578 std::time::SystemTime::now()
579 .duration_since(std::time::UNIX_EPOCH)
580 .unwrap()
581 .as_secs()
582 }
583
584 fn token_with(iat: u64, exp: u64, aud: Option<&str>) -> String {
585 let mut claims = serde_json::json!({"webId":"https://alice.example/profile/card#me","iat":iat,"exp":exp});
586 if let Some(a) = aud {
587 claims["aud"] = serde_json::json!(a);
588 }
589 let data = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
590 let mut mac = Hmac::<Sha256>::new_from_slice(b"01234567890123456789012345678901").unwrap();
591 mac.update(data.as_bytes());
592 let sig =
593 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes());
594 format!("{data}.{sig}")
595 }
596
597 fn token(exp: u64) -> String {
598 token_with(now().saturating_sub(10), exp, Some(DEV_BEARER_AUDIENCE))
599 }
600
601 #[test]
602 fn simple_bearer_verifies_signature_and_expiry() {
603 let _guard = ENV.lock().unwrap();
604 std::env::set_var("TOKEN_SECRET", "01234567890123456789012345678901");
605 assert_eq!(
606 verify_dev_bearer(&token(now() + 3600)).as_deref(),
607 Some("https://alice.example/profile/card#me")
608 );
609 assert!(verify_dev_bearer(&(token(now() + 3600) + "x")).is_none());
610 assert!(verify_dev_bearer(&token(2)).is_none());
611 std::env::remove_var("TOKEN_SECRET");
612 }
613
614 #[test]
615 fn dev_bearer_enforces_audience_and_max_lifetime() {
616 let _guard = ENV.lock().unwrap();
617 std::env::set_var("TOKEN_SECRET", "01234567890123456789012345678901");
618 let n = now();
619 assert!(verify_dev_bearer(&token_with(n, n + 60, None)).is_none());
621 assert!(verify_dev_bearer(&token_with(n, n + 60, Some("solid"))).is_none());
622 assert!(verify_dev_bearer(&token_with(
624 n,
625 n + DEV_BEARER_MAX_LIFETIME_SECS,
626 Some(DEV_BEARER_AUDIENCE)
627 ))
628 .is_some());
629 assert!(verify_dev_bearer(&token_with(
630 n,
631 n + DEV_BEARER_MAX_LIFETIME_SECS + 1,
632 Some(DEV_BEARER_AUDIENCE)
633 ))
634 .is_none());
635 assert!(verify_dev_bearer(&token_with(1, n + 3600, Some(DEV_BEARER_AUDIENCE))).is_none());
637 assert!(
638 verify_dev_bearer(&token_with(1, u64::MAX / 2, Some(DEV_BEARER_AUDIENCE))).is_none()
639 );
640 std::env::remove_var("TOKEN_SECRET");
641 }
642}
643
644#[derive(Debug)]
646pub struct PodCreateLimiter {
647 hits: Mutex<HashMap<IpAddr, Instant>>,
648 window: Duration,
649}
650
651impl Default for PodCreateLimiter {
652 fn default() -> Self {
653 Self {
654 hits: Mutex::new(HashMap::new()),
655 window: Duration::from_secs(24 * 60 * 60),
656 }
657 }
658}
659
660impl PodCreateLimiter {
661 fn check(&self, ip: IpAddr) -> Result<(), u64> {
662 let now = Instant::now();
663 let mut hits = self.hits.lock().unwrap();
664 if let Some(last) = hits.get(&ip).copied() {
665 let elapsed = now.saturating_duration_since(last);
666 if elapsed < self.window {
667 return Err(self.window.saturating_sub(elapsed).as_secs().max(1));
668 }
669 }
670 hits.insert(ip, now);
671 Ok(())
672 }
673}
674
675pub(crate) fn to_actix(e: PodError) -> ActixError {
680 match e {
681 PodError::NotFound(_) => actix_web::error::ErrorNotFound(e.to_string()),
682 PodError::BadRequest(_) => actix_web::error::ErrorBadRequest(e.to_string()),
683 PodError::Unsupported(_) => actix_web::error::ErrorUnsupportedMediaType(e.to_string()),
684 PodError::Forbidden => actix_web::error::ErrorForbidden(e.to_string()),
685 PodError::Unauthenticated => actix_web::error::ErrorUnauthorized(e.to_string()),
686 PodError::PreconditionFailed(_) => actix_web::error::ErrorPreconditionFailed(e.to_string()),
687 PodError::Conflict(_) => actix_web::error::ErrorConflict(e.to_string()),
688 PodError::PayloadTooLarge(_) => actix_web::error::ErrorPayloadTooLarge(e.to_string()),
689 _ => actix_web::error::ErrorInternalServerError(e.to_string()),
690 }
691}
692
693pub(crate) async fn extract_pubkey(req: &HttpRequest) -> Option<String> {
705 extract_pubkey_with_body(req, None).await
706}
707
708pub(crate) async fn extract_pubkey_with_body(
712 req: &HttpRequest,
713 body: Option<&[u8]>,
714) -> Option<String> {
715 let header_val = req
716 .headers()
717 .get(header::AUTHORIZATION)
718 .and_then(|v| v.to_str().ok())?;
719 if let Some(_token) = header_val.strip_prefix("Bearer ") {
720 #[cfg(feature = "dev-bearer")]
723 return verify_dev_bearer(_token);
724 #[cfg(not(feature = "dev-bearer"))]
725 return None;
726 }
727 let url = scheme::request_url(req);
740 let now = std::time::SystemTime::now()
741 .duration_since(std::time::UNIX_EPOCH)
742 .map(|d| d.as_secs())
743 .unwrap_or(0);
744 let verified = nip98::verify_at(header_val, &url, req.method().as_str(), body, now).ok()?;
745
746 if NIP98_REPLAY
750 .check_and_record(&verified.event_id)
751 .await
752 .is_err()
753 {
754 tracing::warn!(
755 pubkey = %verified.pubkey,
756 method = %req.method(),
757 "NIP-98 replay rejected: token id already used within window"
758 );
759 return None;
760 }
761
762 Some(verified.pubkey)
763}
764
765pub(crate) fn agent_uri(pubkey: Option<&String>) -> Option<String> {
766 pubkey.map(|pk| {
767 if pk.starts_with("https://") || pk.starts_with("http://") {
768 pk.clone()
769 } else {
770 format!("did:nostr:{pk}")
771 }
772 })
773}
774
775#[cfg(feature = "dev-bearer")]
777pub const DEV_BEARER_AUDIENCE: &str = "solid-pod-rs-dev-bearer";
778
779#[cfg(feature = "dev-bearer")]
782pub const DEV_BEARER_MAX_LIFETIME_SECS: u64 = 24 * 60 * 60;
783
784#[cfg(feature = "dev-bearer")]
792fn verify_dev_bearer(token: &str) -> Option<String> {
793 use base64::Engine as _;
794 use hmac::{Hmac, Mac};
795 use sha2::Sha256;
796
797 let secret = std::env::var("TOKEN_SECRET").ok()?;
798 if secret.len() < 32 {
799 tracing::warn!("TOKEN_SECRET shorter than 32 bytes; refusing development bearer token");
800 return None;
801 }
802 let (data, signature) = token.split_once('.')?;
803 if signature.contains('.') {
804 return None;
805 }
806 let signature = base64::engine::general_purpose::URL_SAFE_NO_PAD
807 .decode(signature)
808 .ok()?;
809 let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).ok()?;
810 mac.update(data.as_bytes());
811 mac.verify_slice(&signature).ok()?;
812
813 #[derive(serde::Deserialize)]
814 #[serde(rename_all = "camelCase")]
815 struct Claims {
816 web_id: String,
817 iat: u64,
818 exp: u64,
819 #[serde(default)]
820 aud: Option<String>,
821 }
822 let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
823 .decode(data)
824 .ok()?;
825 let claims: Claims = serde_json::from_slice(&payload).ok()?;
826 let now = std::time::SystemTime::now()
827 .duration_since(std::time::UNIX_EPOCH)
828 .ok()?
829 .as_secs();
830 if claims.aud.as_deref() != Some(DEV_BEARER_AUDIENCE) {
831 return None;
832 }
833 if claims.exp < now || claims.iat > now.saturating_add(60) || claims.exp <= claims.iat {
834 return None;
835 }
836 if claims.exp - claims.iat > DEV_BEARER_MAX_LIFETIME_SECS
837 || claims.exp - now > DEV_BEARER_MAX_LIFETIME_SECS
838 {
839 return None;
840 }
841 let url = url::Url::parse(&claims.web_id).ok()?;
842 if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
843 return None;
844 }
845 Some(claims.web_id)
846}
847
848fn req_origin(req: &HttpRequest) -> Option<&str> {
857 req.headers()
858 .get(header::ORIGIN)
859 .and_then(|v| v.to_str().ok())
860}
861
862pub(crate) const WEBLEDGER_PATH: &str = "/.well-known/webledgers/webledgers.json";
866
867async fn resolve_balance_sats(storage: &dyn Storage, agent_uri: Option<&str>) -> Option<u64> {
884 let did = agent_uri?;
885 use solid_pod_rs::payments::PaymentStore;
886 let ledger = handlers::pay::StoragePaymentStore::new(storage)
887 .read_ledger()
888 .await
889 .ok()?;
890 Some(ledger.get_balance(did))
891}
892
893fn accept_includes_html(accept: &str) -> bool {
901 accept.split(',').any(|entry| {
902 let mime = entry.split(';').next().unwrap_or("").trim();
903 mime.eq_ignore_ascii_case("text/html")
904 })
905}
906
907pub(crate) fn guarded_acl_target(path: &str, mode: AccessMode) -> (String, AccessMode) {
926 let (resource, mode) = effective_acl_target(path, mode);
927 match canonical_pod_path(&resource) {
931 Some(canon)
932 if !trail_store::is_secret_trail_path(&canon)
933 && !trail_store::is_prov_state_path(&canon)
934 && !trail_store::is_server_state_path(&canon) =>
935 {
936 (resource, mode)
937 }
938 _ => (resource, AccessMode::Control),
939 }
940}
941
942pub(crate) fn canonical_pod_path(raw: &str) -> Option<String> {
950 let decoded = percent_decode_str(raw).decode_utf8().ok()?;
951 if decoded.contains(['\\', '\0']) {
952 return None;
953 }
954 let mut out = String::with_capacity(decoded.len() + 1);
955 for seg in decoded.split('/') {
956 match seg {
957 "" => {}
958 "." | ".." => return None,
959 _ => {
960 out.push('/');
961 out.push_str(seg);
962 }
963 }
964 }
965 if out.is_empty() || decoded.ends_with('/') {
966 out.push('/');
967 }
968 Some(out)
969}
970
971async fn proposed_acl_keeps_caller_control(
975 state: &AppState,
976 req: &HttpRequest,
977 path: &str,
978 body: &[u8],
979 content_type: &str,
980 caller: Option<&str>,
981) -> bool {
982 if !ldp::is_acl_path(path) {
983 return true;
984 }
985 let Some(resource) = protected_resource_for_acl(path) else {
986 return false;
987 };
988 let wac::PolicyStep::Settled(wac::PolicyOutcome::Found(doc)) =
989 wac::classify_policy_read(path, wac::PolicyRead::Present { body, content_type }, false)
990 else {
991 return false;
992 };
993 if wac::validate_acl_document(&doc).is_err() {
994 return false;
995 }
996 if parse_jsonld_acl(body).is_err() {
1001 use solid_pod_rs::rdf_input::{parse_rdf_body, RdfInputSyntax};
1002 let syntax =
1003 RdfInputSyntax::from_content_type(content_type).unwrap_or(RdfInputSyntax::Turtle);
1004 let base = format!("{}{}", scheme::request_origin(req), path);
1005 if parse_rdf_body(syntax, body, &base).is_err() {
1006 return false;
1007 }
1008 }
1009 let balance = resolve_balance_sats(&*state.storage, caller).await;
1010 let linked = cross_identity::linked_identities(state.cross_identity.as_ref(), caller).await;
1011 let registry = wac::conditions::ConditionRegistry::default_with_client_and_issuer();
1012 let groups = wac::StaticGroupMembership::default();
1013 grant_for_identities(
1016 Some(&doc),
1017 caller,
1018 &linked,
1019 balance,
1020 &resource,
1021 AccessMode::Control,
1022 None,
1023 &groups,
1024 ®istry,
1025 )
1026 .is_some()
1027}
1028
1029#[cfg_attr(not(test), allow(dead_code))]
1036async fn enforce_write(
1037 state: &AppState,
1038 path: &str,
1039 mode: AccessMode,
1040 agent_uri: Option<&str>,
1041) -> Result<(), ActixError> {
1042 enforce_write_ctx(state, path, mode, agent_uri, None).await
1043}
1044
1045async fn enforce_write_ctx(
1053 state: &AppState,
1054 path: &str,
1055 mode: AccessMode,
1056 agent_uri: Option<&str>,
1057 request_origin: Option<&str>,
1058) -> Result<(), ActixError> {
1059 let origin = request_origin.and_then(wac::Origin::parse);
1060 let (resource, eff_mode) = guarded_acl_target(path, mode);
1072
1073 let outcome = resolve_policy_dyn(&*state.storage, &resource).await;
1081 if outcome.is_failure() {
1082 return Err(policy_failure_to_actix(&outcome, &resource));
1083 }
1084 let acl_doc = outcome.document().cloned();
1085
1086 let payment_balance_sats = resolve_balance_sats(&*state.storage, agent_uri).await;
1091
1092 let registry = wac::conditions::ConditionRegistry::default_with_client_and_issuer();
1093 let groups: wac::StaticGroupMembership = wac::StaticGroupMembership::default();
1094 let linked = cross_identity::linked_identities(state.cross_identity.as_ref(), agent_uri).await;
1097 let Some(ctx) = grant_for_identities(
1098 acl_doc.as_ref(),
1099 agent_uri,
1100 &linked,
1101 payment_balance_sats,
1102 &resource,
1103 eff_mode,
1104 origin.as_ref(),
1105 &groups,
1106 ®istry,
1107 ) else {
1108 return Err(acl_denial(acl_doc.as_ref(), agent_uri, &resource));
1109 };
1110 if resource.as_str() == path {
1117 charge_granted_payment(
1123 state,
1124 acl_doc.as_ref(),
1125 &ctx,
1126 &resource,
1127 eff_mode,
1128 &groups,
1129 ®istry,
1130 agent_uri,
1131 )
1132 .await?;
1133 }
1134 Ok(())
1135}
1136
1137#[allow(clippy::too_many_arguments)]
1146async fn charge_granted_payment(
1147 state: &AppState,
1148 acl_doc: Option<&wac::AclDocument>,
1149 ctx: &RequestContext<'_>,
1150 path: &str,
1151 mode: AccessMode,
1152 groups: &wac::StaticGroupMembership,
1153 registry: &wac::conditions::ConditionRegistry,
1154 payer: Option<&str>,
1155) -> Result<(), ActixError> {
1156 let cost = wac::granted_payment_cost(acl_doc, ctx, path, mode, groups, registry);
1157 if cost == 0 {
1158 return Ok(());
1159 }
1160 if let Some(did) = payer {
1163 if debit_ledger(&*state.storage, did, cost).await.is_err() {
1164 return Err(acl_denial(acl_doc, payer, path));
1165 }
1166 }
1167 Ok(())
1168}
1169
1170#[allow(clippy::too_many_arguments)]
1177pub(crate) fn grant_for_identities<'a>(
1178 acl_doc: Option<&wac::AclDocument>,
1179 primary: Option<&'a str>,
1180 linked: &'a [String],
1181 payment_balance_sats: Option<u64>,
1182 resource: &str,
1183 mode: AccessMode,
1184 origin: Option<&wac::Origin>,
1185 groups: &wac::StaticGroupMembership,
1186 registry: &wac::conditions::ConditionRegistry,
1187) -> Option<RequestContext<'a>> {
1188 std::iter::once(primary)
1189 .chain(linked.iter().map(|s| Some(s.as_str())))
1190 .map(|web_id| RequestContext {
1191 web_id,
1192 client_id: None,
1193 issuer: None,
1194 payment_balance_sats,
1195 })
1196 .find(|ctx| {
1197 wac::evaluate_access_ctx_with_registry(
1198 acl_doc, ctx, resource, mode, origin, groups, registry,
1199 )
1200 })
1201}
1202
1203fn acl_denial(
1209 acl_doc: Option<&wac::AclDocument>,
1210 agent_uri: Option<&str>,
1211 path: &str,
1212) -> ActixError {
1213 let allow_header = wac::wac_allow_header(acl_doc, agent_uri, path);
1214 let (status, body, unauthenticated) = if agent_uri.is_none() {
1215 (StatusCode::UNAUTHORIZED, "authentication required", true)
1216 } else {
1217 (StatusCode::FORBIDDEN, "access forbidden", false)
1218 };
1219 let mut rsp = HttpResponse::new(status);
1220 rsp.headers_mut().insert(
1221 header::HeaderName::from_static("wac-allow"),
1222 header::HeaderValue::from_str(&allow_header)
1223 .unwrap_or(header::HeaderValue::from_static("")),
1224 );
1225 if unauthenticated {
1226 rsp.headers_mut().insert(
1233 header::WWW_AUTHENTICATE,
1234 header::HeaderValue::from_static(
1235 "Nostr realm=\"Solid\", DPoP realm=\"Solid\", Bearer realm=\"Solid\"",
1236 ),
1237 );
1238 }
1239 actix_web::error::InternalError::from_response(body, rsp).into()
1240}
1241
1242#[cfg_attr(not(test), allow(dead_code))]
1253async fn enforce_read(
1254 state: &AppState,
1255 path: &str,
1256 agent_uri: Option<&str>,
1257) -> Result<ResponseAudience, ActixError> {
1258 enforce_read_ctx(state, path, agent_uri, None).await
1259}
1260
1261async fn enforce_read_ctx(
1264 state: &AppState,
1265 path: &str,
1266 agent_uri: Option<&str>,
1267 request_origin: Option<&str>,
1268) -> Result<ResponseAudience, ActixError> {
1269 enforce_read_inner(state, path, agent_uri, request_origin, true).await
1270}
1271
1272async fn enforce_read_inner(
1277 state: &AppState,
1278 path: &str,
1279 agent_uri: Option<&str>,
1280 request_origin: Option<&str>,
1281 charge: bool,
1282) -> Result<ResponseAudience, ActixError> {
1283 let origin = request_origin.and_then(wac::Origin::parse);
1284 let (resource, eff_mode) = guarded_acl_target(path, AccessMode::Read);
1296 let outcome = resolve_policy_dyn(&*state.storage, &resource).await;
1299 if outcome.is_failure() {
1300 return Err(policy_failure_to_actix(&outcome, &resource));
1301 }
1302 let acl_doc = outcome.document().cloned();
1303 let payment_balance_sats = resolve_balance_sats(&*state.storage, agent_uri).await;
1304 let registry = wac::conditions::ConditionRegistry::default_with_client_and_issuer();
1305 let groups: wac::StaticGroupMembership = wac::StaticGroupMembership::default();
1306 let linked = cross_identity::linked_identities(state.cross_identity.as_ref(), agent_uri).await;
1307 let Some(ctx) = grant_for_identities(
1308 acl_doc.as_ref(),
1309 agent_uri,
1310 &linked,
1311 payment_balance_sats,
1312 &resource,
1313 eff_mode,
1314 origin.as_ref(),
1315 &groups,
1316 ®istry,
1317 ) else {
1318 return Err(acl_denial(acl_doc.as_ref(), agent_uri, &resource));
1319 };
1320 if resource.as_str() == path && !charge {
1324 if wac::granted_payment_cost(
1325 acl_doc.as_ref(),
1326 &ctx,
1327 &resource,
1328 eff_mode,
1329 &groups,
1330 ®istry,
1331 ) > 0
1332 {
1333 return Err(acl_denial(acl_doc.as_ref(), agent_uri, &resource));
1334 }
1335 } else if resource.as_str() == path {
1336 charge_granted_payment(
1341 state,
1342 acl_doc.as_ref(),
1343 &ctx,
1344 &resource,
1345 eff_mode,
1346 &groups,
1347 ®istry,
1348 agent_uri,
1349 )
1350 .await?;
1351 }
1352 let anon_ctx = RequestContext {
1361 web_id: None,
1362 client_id: None,
1363 issuer: None,
1364 payment_balance_sats: None,
1365 };
1366 let anonymous_would_be_granted = wac::evaluate_access_ctx_with_registry(
1367 acl_doc.as_ref(),
1368 &anon_ctx,
1369 &resource,
1370 eff_mode,
1371 origin.as_ref(),
1372 &groups,
1373 ®istry,
1374 );
1375 Ok(if anonymous_would_be_granted && resource.as_str() == path {
1376 ResponseAudience::Public
1377 } else {
1378 ResponseAudience::Private
1379 })
1380}
1381
1382async fn debit_ledger(
1389 storage: &dyn Storage,
1390 did: &str,
1391 cost: u64,
1392) -> Result<(), solid_pod_rs::payments::PaymentError> {
1393 handlers::pay::StoragePaymentStore::new(storage)
1394 .charge_access(did, cost)
1395 .await
1396}
1397
1398fn set_link_headers(rsp: &mut HttpResponse, path: &str) {
1403 let links = ldp::link_headers(path).join(", ");
1404 if let Ok(value) = header::HeaderValue::from_str(&links) {
1405 rsp.headers_mut()
1406 .insert(header::HeaderName::from_static("link"), value);
1407 }
1408}
1409
1410fn set_wac_allow(rsp: &mut HttpResponse, header_value: &str) {
1411 if let Ok(v) = header::HeaderValue::from_str(header_value) {
1412 rsp.headers_mut()
1413 .insert(header::HeaderName::from_static("wac-allow"), v);
1414 }
1415}
1416
1417fn set_updates_via(rsp: &mut HttpResponse, base_url: &str) {
1418 let ws_base = base_url
1419 .replacen("https://", "wss://", 1)
1420 .replacen("http://", "ws://", 1);
1421 let ws_url = format!("{}/.notifications", ws_base.trim_end_matches('/'));
1422 if let Ok(v) = header::HeaderValue::from_str(&ws_url) {
1423 rsp.headers_mut()
1424 .insert(header::HeaderName::from_static("updates-via"), v);
1425 }
1426}
1427
1428fn set_provenance_headers(rsp: &mut HttpResponse, receipt: &ProvenanceReceipt) {
1439 if let Ok(v) = header::HeaderValue::from_str(&receipt.summary()) {
1440 rsp.headers_mut()
1441 .insert(header::HeaderName::from_static("x-provenance"), v);
1442 }
1443 if let Some(sha) = receipt.commit_sha() {
1444 if let Ok(v) = header::HeaderValue::from_str(sha) {
1445 rsp.headers_mut()
1446 .insert(header::HeaderName::from_static("x-provenance-commit"), v);
1447 }
1448 }
1449}
1450
1451fn set_cache_policy(rsp: &mut HttpResponse, content_type: &str, audience: ResponseAudience) {
1463 if audience == ResponseAudience::Private {
1464 append_vary(rsp, "Authorization");
1468 }
1469 if rsp.headers().contains_key(header::CACHE_CONTROL) {
1470 return;
1471 }
1472 if let Some(value) = cache_control_for_response(content_type, audience) {
1473 rsp.headers_mut().insert(
1474 header::CACHE_CONTROL,
1475 header::HeaderValue::from_static(value),
1476 );
1477 }
1478}
1479
1480fn append_vary(rsp: &mut HttpResponse, field: &str) {
1482 let existing = rsp
1483 .headers()
1484 .get(header::VARY)
1485 .and_then(|v| v.to_str().ok())
1486 .unwrap_or("")
1487 .to_string();
1488 if existing
1489 .split(',')
1490 .any(|f| f.trim().eq_ignore_ascii_case(field))
1491 {
1492 return;
1493 }
1494 let merged = if existing.trim().is_empty() {
1495 field.to_string()
1496 } else {
1497 format!("{existing}, {field}")
1498 };
1499 if let Ok(v) = header::HeaderValue::from_str(&merged) {
1500 rsp.headers_mut().insert(header::VARY, v);
1501 }
1502}
1503
1504async fn handle_get(
1505 req: HttpRequest,
1506 state: web::Data<AppState>,
1507) -> Result<HttpResponse, ActixError> {
1508 let path = req.uri().path().to_string();
1509
1510 #[cfg(feature = "activitypub")]
1515 if let (Some(ap), "/profile/card.jsonld") = (state.activitypub.as_ref(), path.as_str()) {
1516 let accept = req
1517 .headers()
1518 .get(header::ACCEPT)
1519 .and_then(|v| v.to_str().ok())
1520 .unwrap_or("");
1521 if solid_pod_rs_activitypub::negotiate_actor_format(accept)
1522 == solid_pod_rs_activitypub::ActorFormat::ActivityJson
1523 {
1524 let doc = ap.actor_json(&scheme::request_origin(&req));
1525 return Ok(HttpResponse::Ok()
1526 .content_type("application/activity+json")
1527 .insert_header((header::VARY, "Accept"))
1528 .json(doc));
1529 }
1530 }
1531
1532 if path.contains('*') {
1533 return handle_glob_get(req, state).await;
1534 }
1535
1536 let auth_pk = extract_pubkey(&req).await;
1537 let agent = agent_uri(auth_pk.as_ref());
1538
1539 let audience = enforce_read_ctx(&state, &path, agent.as_deref(), req_origin(&req)).await?;
1544
1545 let wac_allow = wac::wac_allow_header(None, agent.as_deref(), &path);
1546
1547 if ldp::is_container(&path) {
1548 let accept = req
1549 .headers()
1550 .get(header::ACCEPT)
1551 .and_then(|v| v.to_str().ok())
1552 .unwrap_or("");
1553
1554 if accept_includes_html(accept) {
1560 let index_path = format!("{path}index.html");
1561 let index_audience =
1564 enforce_read_ctx(&state, &index_path, agent.as_deref(), req_origin(&req))
1565 .await
1566 .ok();
1567 if let (Some(index_audience), Ok((body, _meta))) =
1568 (index_audience, state.storage.get(&index_path).await)
1569 {
1570 let mut rsp = HttpResponse::Ok()
1571 .content_type("text/html; charset=utf-8")
1572 .body(inject_live_reload(&body, state.live_reload));
1573 set_cache_policy(&mut rsp, "text/html", index_audience);
1574 set_wac_allow(&mut rsp, &wac_allow);
1575 set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1576 set_link_headers(&mut rsp, &path);
1577 return Ok(rsp);
1578 }
1579 }
1580
1581 let v = state
1582 .storage
1583 .container_representation(&path)
1584 .await
1585 .map_err(to_actix)?;
1586
1587 let sec_fetch_dest = req
1589 .headers()
1590 .get("sec-fetch-dest")
1591 .and_then(|v| v.to_str().ok());
1592 if mashlib::should_serve(
1593 accept,
1594 sec_fetch_dest,
1595 "application/ld+json",
1596 state.mashlib.enabled,
1597 ) {
1598 let json_ld = serde_json::to_string(&v).ok();
1599 let html = mashlib::generate_html(&path, &state.mashlib, json_ld.as_deref());
1600 let mut rsp = HttpResponse::Ok()
1601 .content_type("text/html; charset=utf-8")
1602 .insert_header(("X-Frame-Options", "DENY"))
1603 .insert_header(("Content-Security-Policy", "frame-ancestors 'none'"))
1604 .insert_header(("Cache-Control", "no-store"))
1605 .body(inject_live_reload(html, state.live_reload));
1606 set_cache_policy(&mut rsp, "text/html", audience);
1607 set_wac_allow(&mut rsp, &wac_allow);
1608 set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1609 set_link_headers(&mut rsp, &path);
1610 return Ok(rsp);
1611 }
1612
1613 let mut rsp = HttpResponse::Ok().json(v);
1614 rsp.headers_mut().insert(
1615 header::CONTENT_TYPE,
1616 header::HeaderValue::from_static("application/ld+json"),
1617 );
1618 set_cache_policy(&mut rsp, "application/ld+json", audience);
1619 set_wac_allow(&mut rsp, &wac_allow);
1620 set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1621 set_link_headers(&mut rsp, &path);
1622 return Ok(rsp);
1623 }
1624
1625 match state.storage.get(&path).await {
1626 Ok((body, meta)) => {
1627 let accept = req
1629 .headers()
1630 .get(header::ACCEPT)
1631 .and_then(|v| v.to_str().ok())
1632 .unwrap_or("");
1633 let sec_fetch_dest = req
1634 .headers()
1635 .get("sec-fetch-dest")
1636 .and_then(|v| v.to_str().ok());
1637 if mashlib::should_serve(
1638 accept,
1639 sec_fetch_dest,
1640 &meta.content_type,
1641 state.mashlib.enabled,
1642 ) {
1643 let embed = if body.len() <= state.mashlib.data_island_max_bytes {
1644 std::str::from_utf8(&body).ok().map(|s| s.to_string())
1645 } else {
1646 None
1647 };
1648 let html = mashlib::generate_html(&path, &state.mashlib, embed.as_deref());
1649 let mut rsp = HttpResponse::Ok()
1650 .content_type("text/html; charset=utf-8")
1651 .insert_header(("X-Frame-Options", "DENY"))
1652 .insert_header(("Content-Security-Policy", "frame-ancestors 'none'"))
1653 .insert_header(("Cache-Control", "no-store"))
1654 .body(inject_live_reload(html, state.live_reload));
1655 set_cache_policy(&mut rsp, "text/html", audience);
1656 set_wac_allow(&mut rsp, &wac_allow);
1657 set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1658 set_link_headers(&mut rsp, &path);
1659 return Ok(rsp);
1660 }
1661
1662 if let Some((negotiated_body, negotiated_ct)) =
1670 rdf_content_negotiate(&body, &meta.content_type, accept)
1671 {
1672 let mut rsp = HttpResponse::Ok().body(negotiated_body);
1673 rsp.headers_mut().insert(
1674 header::CONTENT_TYPE,
1675 header::HeaderValue::from_str(negotiated_ct)
1676 .unwrap_or_else(|_| header::HeaderValue::from_static("text/turtle")),
1677 );
1678 rsp.headers_mut()
1679 .insert(header::VARY, header::HeaderValue::from_static("Accept"));
1680 if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1681 rsp.headers_mut().insert(header::ETAG, etag);
1682 }
1683 set_cache_policy(&mut rsp, negotiated_ct, audience);
1684 set_wac_allow(&mut rsp, &wac_allow);
1685 set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1686 set_link_headers(&mut rsp, &path);
1687 return Ok(rsp);
1688 }
1689
1690 let response_body = if meta.content_type.starts_with("text/html") {
1691 inject_live_reload(&body, state.live_reload)
1692 } else {
1693 body.to_vec()
1694 };
1695 let mut rsp = HttpResponse::Ok().body(response_body);
1696 rsp.headers_mut().insert(
1697 header::CONTENT_TYPE,
1698 header::HeaderValue::from_str(&meta.content_type).unwrap_or_else(|_| {
1699 header::HeaderValue::from_static("application/octet-stream")
1700 }),
1701 );
1702 if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1703 rsp.headers_mut().insert(header::ETAG, etag);
1704 }
1705 set_cache_policy(&mut rsp, &meta.content_type, audience);
1706 set_wac_allow(&mut rsp, &wac_allow);
1707 set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1708 set_link_headers(&mut rsp, &path);
1709 Ok(rsp)
1710 }
1711 Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
1712 Err(e) => Err(to_actix(e)),
1713 }
1714}
1715
1716fn has_basic_container_link(req: &HttpRequest) -> bool {
1717 req.headers()
1718 .get_all(header::LINK)
1719 .filter_map(|v| v.to_str().ok())
1720 .any(|v| {
1721 v.contains("http://www.w3.org/ns/ldp#BasicContainer") && v.contains("rel=\"type\"")
1722 })
1723}
1724
1725fn validate_rdf_body(
1734 req: &HttpRequest,
1735 state: &AppState,
1736 resource_path: &str,
1737 content_type: &str,
1738 body: &[u8],
1739) -> Result<(), ActixError> {
1740 use solid_pod_rs::rdf_input::{parse_rdf_body, RdfInputSyntax};
1741 let Some(syntax) = RdfInputSyntax::from_content_type(content_type) else {
1742 return Ok(());
1743 };
1744 if syntax == RdfInputSyntax::N3 && !state.conneg_enabled {
1745 return Err(actix_web::error::ErrorUnsupportedMediaType(
1746 "text/n3 request bodies require content negotiation (conneg) to be enabled",
1747 ));
1748 }
1749 let base = format!("{}{}", scheme::request_origin(req), resource_path);
1750 match parse_rdf_body(syntax, body, &base) {
1751 Ok(_) => Ok(()),
1752 Err(solid_pod_rs::PodError::PayloadTooLarge(m)) => {
1753 Err(actix_web::error::ErrorPayloadTooLarge(m))
1754 }
1755 Err(e) => Err(to_actix(e)),
1756 }
1757}
1758
1759async fn handle_put(
1760 req: HttpRequest,
1761 body: web::Bytes,
1762 state: web::Data<AppState>,
1763) -> Result<HttpResponse, ActixError> {
1764 let path = req.uri().path().to_string();
1765
1766 if ldp::is_container(&path) {
1767 if has_basic_container_link(&req) {
1768 let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
1769 let agent = agent_uri(auth_pk.as_ref());
1770 enforce_write_ctx(
1771 &state,
1772 &path,
1773 AccessMode::Write,
1774 agent.as_deref(),
1775 req_origin(&req),
1776 )
1777 .await?;
1778 let _write_guard = lock_resource(&path).await;
1779 let meta = state
1780 .storage
1781 .create_container(&path)
1782 .await
1783 .map_err(to_actix)?;
1784 let mut rsp = HttpResponse::Created().finish();
1785 if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1786 rsp.headers_mut().insert(header::ETAG, etag);
1787 }
1788 set_link_headers(&mut rsp, &path);
1789 return Ok(rsp);
1790 }
1791 return Ok(HttpResponse::MethodNotAllowed().body("cannot PUT to a container"));
1792 }
1793
1794 let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
1795 let agent = agent_uri(auth_pk.as_ref());
1796 enforce_write_ctx(
1797 &state,
1798 &path,
1799 AccessMode::Write,
1800 agent.as_deref(),
1801 req_origin(&req),
1802 )
1803 .await?;
1804
1805 let ct = req
1806 .headers()
1807 .get(header::CONTENT_TYPE)
1808 .and_then(|v| v.to_str().ok())
1809 .unwrap_or("application/octet-stream");
1810
1811 if protected_resource_for_acl(&path).is_some()
1816 && !proposed_acl_keeps_caller_control(&state, &req, &path, &body, ct, agent.as_deref())
1817 .await
1818 {
1819 return Ok(HttpResponse::Conflict().body(
1820 "refused: the proposed ACL would not grant Control to the caller \
1821 (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
1822 ));
1823 }
1824
1825 validate_rdf_body(&req, &state, &path, ct, &body)?;
1826
1827 let _write_guard = lock_resource(&path).await;
1828 check_write_preconditions(&req, &state, &path).await?;
1829 let quota = reserve_quota_for_size(&state, &path, body.len() as u64).await?;
1830 let write = state
1831 .storage
1832 .put(&path, Bytes::from(body.to_vec()), ct)
1833 .await;
1834 finish_quota_reservation(&state, quota, write.is_ok()).await;
1835 let meta = write.map_err(to_actix)?;
1836 let provenance = git_mark_write(&state, &path, agent.as_deref(), "PUT").await;
1840 let mut rsp = HttpResponse::Created().finish();
1841 if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1842 rsp.headers_mut().insert(header::ETAG, etag);
1843 }
1844 set_provenance_headers(&mut rsp, &provenance);
1845 set_link_headers(&mut rsp, &path);
1846 Ok(rsp)
1847}
1848
1849async fn mint_unique_target(storage: &dyn Storage, target: &str) -> String {
1856 if !storage.exists(target).await.unwrap_or(false) {
1857 return target.to_string();
1858 }
1859 let (name, slash) = match target.strip_suffix('/') {
1861 Some(name) => (name, "/"),
1862 None => (target, ""),
1863 };
1864 let seg_start = name.rfind('/').map(|s| s + 1).unwrap_or(0);
1867 let (stem, ext) = match name.rfind('.') {
1868 Some(dot) if dot > seg_start => (&name[..dot], &name[dot..]),
1869 _ => (name, ""),
1870 };
1871 for n in 1..10_000u32 {
1872 let candidate = format!("{stem}-{n}{ext}{slash}");
1873 if !storage.exists(&candidate).await.unwrap_or(false) {
1874 return candidate;
1875 }
1876 }
1877 use std::hash::{Hash, Hasher};
1878 let mut h = std::collections::hash_map::DefaultHasher::new();
1879 target.hash(&mut h);
1880 format!("{stem}-{:x}{ext}{slash}", h.finish())
1881}
1882
1883async fn handle_post(
1884 req: HttpRequest,
1885 body: web::Bytes,
1886 state: web::Data<AppState>,
1887) -> Result<HttpResponse, ActixError> {
1888 let path = req.uri().path().to_string();
1889 let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
1892 let agent = agent_uri(auth_pk.as_ref());
1893 enforce_write_ctx(
1894 &state,
1895 &path,
1896 AccessMode::Append,
1897 agent.as_deref(),
1898 req_origin(&req),
1899 )
1900 .await?;
1901
1902 let slug = req
1903 .headers()
1904 .get(header::HeaderName::from_static("slug"))
1905 .and_then(|v| v.to_str().ok());
1906 let mut target = match ldp::resolve_slug(&path, slug) {
1907 Ok(p) => p,
1908 Err(e) => return Err(to_actix(e)),
1909 };
1910 let ct = req
1911 .headers()
1912 .get(header::CONTENT_TYPE)
1913 .and_then(|v| v.to_str().ok())
1914 .unwrap_or("application/octet-stream");
1915
1916 let _write_guard = if protected_resource_for_acl(&target).is_some() {
1925 enforce_write_ctx(
1926 &state,
1927 &target,
1928 AccessMode::Write,
1929 agent.as_deref(),
1930 req_origin(&req),
1931 )
1932 .await?;
1933 if !proposed_acl_keeps_caller_control(&state, &req, &target, &body, ct, agent.as_deref())
1934 .await
1935 {
1936 return Ok(HttpResponse::Conflict().body(
1937 "refused: the proposed ACL would not grant Control to the caller \
1938 (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
1939 ));
1940 }
1941 lock_resource(&target).await
1942 } else {
1943 let (minted, guard) = mint_and_lock_target(&*state.storage, &target)
1950 .await
1951 .map_err(to_actix)?;
1952 target = minted;
1953 guard
1954 };
1955
1956 validate_rdf_body(&req, &state, &target, ct, &body)?;
1957
1958 let quota = reserve_quota_for_size(&state, &target, body.len() as u64).await?;
1959 let write = state
1960 .storage
1961 .put(&target, Bytes::from(body.to_vec()), ct)
1962 .await;
1963 finish_quota_reservation(&state, quota, write.is_ok()).await;
1964 let meta = write.map_err(to_actix)?;
1965 let provenance = git_mark_write(&state, &target, agent.as_deref(), "POST").await;
1968 let mut rsp = HttpResponse::Created().finish();
1969 if let Ok(loc) = header::HeaderValue::from_str(&target) {
1970 rsp.headers_mut().insert(header::LOCATION, loc);
1971 }
1972 if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1973 rsp.headers_mut().insert(header::ETAG, etag);
1974 }
1975 set_provenance_headers(&mut rsp, &provenance);
1976 set_link_headers(&mut rsp, &target);
1977 Ok(rsp)
1978}
1979
1980const CONDITIONAL_ACL_PATCH_REFUSED: &str =
1982 "refused: the patched ACL carries acl:condition, which an RDF PATCH cannot \
1983 preserve (the N-Triples write-back turns an inline condition into a blank \
1984 node the WAC reader does not resolve); PUT the whole ACL document instead";
1985
1986fn graph_has_acl_condition(graph: &ldp::Graph) -> bool {
1990 const CONDITION: &str = "http://www.w3.org/ns/auth/acl#condition";
1991 graph
1992 .triples()
1993 .any(|t| matches!(&t.predicate, ldp::Term::Iri(p) if p == CONDITION))
1994}
1995
1996const PATCHED_RDF_CONTENT_TYPE: &str = "text/turtle";
2001
2002async fn handle_patch(
2003 req: HttpRequest,
2004 body: web::Bytes,
2005 state: web::Data<AppState>,
2006) -> Result<HttpResponse, ActixError> {
2007 let path = req.uri().path().to_string();
2008 if ldp::is_container(&path) {
2009 return Ok(HttpResponse::MethodNotAllowed().body("cannot PATCH a container"));
2010 }
2011 let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
2012 let agent = agent_uri(auth_pk.as_ref());
2013 let ct = req
2019 .headers()
2020 .get(header::CONTENT_TYPE)
2021 .and_then(|v| v.to_str().ok())
2022 .unwrap_or("")
2023 .to_string();
2024 let dialect = ldp::patch_dialect_from_mime(&ct);
2025 let body_str = std::str::from_utf8(&body).map(str::to_string);
2026 let base_iri = format!("{}{path}", scheme::request_origin(&req));
2029 let n3_parsed = match (dialect, &body_str) {
2030 (Some(ldp::PatchDialect::N3), Ok(text)) => Some(ldp::N3Patch::parse(text, Some(&base_iri))),
2031 _ => None,
2032 };
2033 let inspects = match dialect {
2041 Some(ldp::PatchDialect::N3) => {
2042 matches!(&n3_parsed, Some(Ok(p)) if !p.is_insert_only())
2043 }
2044 Some(ldp::PatchDialect::JsonPatch) => body_str.is_ok(),
2045 _ => false,
2046 };
2047 if inspects {
2048 enforce_read_inner(&state, &path, agent.as_deref(), req_origin(&req), false).await?;
2049 }
2050 enforce_write_ctx(
2056 &state,
2057 &path,
2058 AccessMode::Write,
2059 agent.as_deref(),
2060 req_origin(&req),
2061 )
2062 .await?;
2063
2064 let Some(dialect) = dialect else {
2065 return Ok(HttpResponse::UnsupportedMediaType()
2066 .body(format!("unsupported patch dialect for content-type {ct:?}")));
2067 };
2068 let Ok(body_str) = body_str else {
2069 return Ok(HttpResponse::BadRequest().body("patch body is not valid UTF-8"));
2070 };
2071 let n3_patch = match n3_parsed {
2072 Some(parsed) => Some(parsed.map_err(patch_parse_err)?),
2073 None => None,
2074 };
2075 let acl_origin = protected_resource_for_acl(&path)
2076 .is_some()
2077 .then(|| scheme::request_origin(&req));
2078
2079 let _write_guard = lock_resource(&path).await;
2082 check_write_preconditions(&req, &state, &path).await?;
2083
2084 let existing = state.storage.get(&path).await;
2086 match existing {
2087 Ok((current_body, meta)) => {
2088 let out = match dialect {
2098 ldp::PatchDialect::N3 => {
2099 let seed = seed_graph_from_patch_target(¤t_body, &base_iri)?;
2100 n3_patch
2101 .as_ref()
2102 .expect("parsed above for the N3 dialect")
2103 .apply(seed)
2104 .map_err(patch_parse_err)
2105 }
2106 ldp::PatchDialect::SparqlUpdate => {
2107 let seed = seed_graph_from_patch_target(¤t_body, &base_iri)?;
2108 ldp::apply_sparql_patch(seed, &body_str).map_err(patch_parse_err)
2109 }
2110 ldp::PatchDialect::JsonPatch => {
2111 let mut json: serde_json::Value = match serde_json::from_slice(¤t_body) {
2112 Ok(v) => v,
2113 Err(_) => serde_json::json!({}),
2114 };
2115 let patch: serde_json::Value = match serde_json::from_str(&body_str) {
2116 Ok(v) => v,
2117 Err(e) => return Err(to_actix(PodError::BadRequest(e.to_string()))),
2118 };
2119 ldp::apply_json_patch(&mut json, &patch).map_err(to_actix)?;
2120 let bytes = serde_json::to_vec(&json)
2121 .map_err(PodError::from)
2122 .map_err(to_actix)?;
2123 if !proposed_acl_keeps_caller_control(
2124 &state,
2125 &req,
2126 &path,
2127 &bytes,
2128 &meta.content_type,
2129 agent.as_deref(),
2130 )
2131 .await
2132 {
2133 return Ok(HttpResponse::Conflict().body(
2134 "refused: the patched ACL would not grant Control to the caller",
2135 ));
2136 }
2137 let quota = reserve_quota_for_size(&state, &path, bytes.len() as u64).await?;
2138 let write = state
2139 .storage
2140 .put(&path, Bytes::from(bytes), &meta.content_type)
2141 .await;
2142 finish_quota_reservation(&state, quota, write.is_ok()).await;
2143 let _ = write.map_err(to_actix)?;
2144 let provenance = git_mark_write(&state, &path, agent.as_deref(), "PATCH").await;
2145 let mut rsp = HttpResponse::NoContent().finish();
2146 set_provenance_headers(&mut rsp, &provenance);
2147 return Ok(rsp);
2148 }
2149 };
2150 let mut outcome = out?;
2151 if let Some(origin) = &acl_origin {
2152 outcome.graph = acl_targets_as_paths(outcome.graph, origin);
2153 }
2154 if acl_origin.is_some() && graph_has_acl_condition(&outcome.graph) {
2157 return Ok(HttpResponse::Conflict().body(CONDITIONAL_ACL_PATCH_REFUSED));
2158 }
2159 let serialised = graph_to_turtle(&outcome.graph);
2160 if protected_resource_for_acl(&path).is_some()
2166 && !proposed_acl_keeps_caller_control(
2167 &state,
2168 &req,
2169 &path,
2170 serialised.as_bytes(),
2171 PATCHED_RDF_CONTENT_TYPE,
2172 agent.as_deref(),
2173 )
2174 .await
2175 {
2176 return Ok(HttpResponse::Conflict().body(
2177 "refused: the patched ACL would not grant Control to the caller \
2178 (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
2179 ));
2180 }
2181 let quota = reserve_quota_for_size(&state, &path, serialised.len() as u64).await?;
2182 let write = state
2183 .storage
2184 .put(
2185 &path,
2186 Bytes::from(serialised.into_bytes()),
2187 PATCHED_RDF_CONTENT_TYPE,
2188 )
2189 .await;
2190 finish_quota_reservation(&state, quota, write.is_ok()).await;
2191 let _ = write.map_err(to_actix)?;
2192 let provenance = git_mark_write(&state, &path, agent.as_deref(), "PATCH").await;
2193 let mut rsp = HttpResponse::NoContent().finish();
2194 set_provenance_headers(&mut rsp, &provenance);
2195 Ok(rsp)
2196 }
2197 Err(PodError::NotFound(_)) => {
2198 let graph = match &n3_patch {
2200 Some(p) => p.apply(ldp::Graph::new()).map_err(patch_parse_err)?.graph,
2201 None => {
2202 let create =
2203 ldp::apply_patch_to_absent(dialect, &body_str).map_err(patch_parse_err)?;
2204 let PatchCreateOutcome::Created { graph, .. } = create else {
2205 return Err(to_actix(PodError::Unsupported(
2206 "unexpected patch outcome on absent resource".into(),
2207 )));
2208 };
2209 graph
2210 }
2211 };
2212 let graph = match &acl_origin {
2213 Some(origin) => acl_targets_as_paths(graph, origin),
2214 None => graph,
2215 };
2216 if acl_origin.is_some() && graph_has_acl_condition(&graph) {
2217 return Ok(HttpResponse::Conflict().body(CONDITIONAL_ACL_PATCH_REFUSED));
2218 }
2219 let serialised = graph_to_turtle(&graph);
2220 if protected_resource_for_acl(&path).is_some()
2222 && !proposed_acl_keeps_caller_control(
2223 &state,
2224 &req,
2225 &path,
2226 serialised.as_bytes(),
2227 PATCHED_RDF_CONTENT_TYPE,
2228 agent.as_deref(),
2229 )
2230 .await
2231 {
2232 return Ok(HttpResponse::Conflict().body(
2233 "refused: the patched ACL would not grant Control to the caller \
2234 (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
2235 ));
2236 }
2237 let quota = reserve_quota_for_size(&state, &path, serialised.len() as u64).await?;
2238 let write = state
2239 .storage
2240 .put(
2241 &path,
2242 Bytes::from(serialised.into_bytes()),
2243 PATCHED_RDF_CONTENT_TYPE,
2244 )
2245 .await;
2246 finish_quota_reservation(&state, quota, write.is_ok()).await;
2247 let _ = write.map_err(to_actix)?;
2248 let provenance = git_mark_write(&state, &path, agent.as_deref(), "PATCH").await;
2249 let mut rsp = HttpResponse::Created().finish();
2250 set_provenance_headers(&mut rsp, &provenance);
2251 Ok(rsp)
2252 }
2253 Err(e) => Err(to_actix(e)),
2254 }
2255}
2256
2257fn patch_parse_err(e: PodError) -> ActixError {
2261 match e {
2262 PodError::Unsupported(msg) | PodError::BadRequest(msg) => {
2263 actix_web::error::ErrorBadRequest(msg)
2264 }
2265 other => to_actix(other),
2266 }
2267}
2268
2269fn graph_to_turtle(g: &ldp::Graph) -> String {
2273 g.to_ntriples()
2274}
2275
2276fn best_explicit_rdf_format(accept: &str) -> Option<ldp::RdfFormat> {
2283 let mut best: Option<(f32, ldp::RdfFormat)> = None;
2284 for entry in accept.split(',') {
2285 let entry = entry.trim();
2286 if entry.is_empty() {
2287 continue;
2288 }
2289 let mut parts = entry.split(';').map(|s| s.trim());
2290 let mime = match parts.next() {
2291 Some(m) => m,
2292 None => continue,
2293 };
2294 let mut q: f32 = 1.0;
2295 for token in parts {
2296 if let Some(v) = token.strip_prefix("q=") {
2297 if let Ok(parsed) = v.parse::<f32>() {
2298 q = parsed;
2299 }
2300 }
2301 }
2302 if let Some(format) = ldp::RdfFormat::from_mime(mime) {
2305 match best {
2306 None => best = Some((q, format)),
2307 Some((bq, _)) if q > bq => best = Some((q, format)),
2308 _ => {}
2309 }
2310 }
2311 }
2312 best.map(|(_, f)| f)
2313}
2314
2315fn rdf_content_negotiate(
2331 body: &[u8],
2332 stored_ct: &str,
2333 accept: &str,
2334) -> Option<(Vec<u8>, &'static str)> {
2335 if accept.trim().is_empty() {
2336 return None;
2337 }
2338 let stored_format = ldp::RdfFormat::from_mime(stored_ct)?;
2339 let target = best_explicit_rdf_format(accept)?;
2340 if target == stored_format {
2341 return None;
2342 }
2343 let text = std::str::from_utf8(body).ok()?;
2344 let graph = ldp::Graph::parse_ntriples(text).ok()?;
2345 match target {
2346 ldp::RdfFormat::Turtle => Some((
2349 graph.to_ntriples().into_bytes(),
2350 ldp::RdfFormat::Turtle.mime(),
2351 )),
2352 ldp::RdfFormat::NTriples => Some((
2353 graph.to_ntriples().into_bytes(),
2354 ldp::RdfFormat::NTriples.mime(),
2355 )),
2356 ldp::RdfFormat::JsonLd => {
2357 let json = serde_json::to_vec(&graph.to_jsonld()).ok()?;
2358 Some((json, ldp::RdfFormat::JsonLd.mime()))
2359 }
2360 ldp::RdfFormat::RdfXml => None,
2362 }
2363}
2364
2365fn seed_graph_from_patch_target(
2375 current_body: &[u8],
2376 base_iri: &str,
2377) -> Result<ldp::Graph, ActixError> {
2378 let text = std::str::from_utf8(current_body).map_err(|_| {
2379 actix_web::error::ErrorConflict(
2380 "existing resource is not UTF-8 RDF; refusing destructive RDF PATCH",
2381 )
2382 })?;
2383 if text.trim().is_empty() {
2384 return Ok(ldp::Graph::new());
2385 }
2386 if let Ok(graph) = solid_pod_rs::rdf_input::parse_turtle(current_body, base_iri) {
2398 return Ok(graph);
2399 }
2400 ldp::Graph::parse_ntriples(text).map_err(|_| {
2401 actix_web::error::ErrorConflict(
2402 "existing resource is not Turtle or N-Triples RDF and cannot be \
2403 non-destructively patched; PUT an RDF representation or use a JSON Patch",
2404 )
2405 })
2406}
2407
2408fn acl_targets_as_paths(graph: ldp::Graph, origin: &str) -> ldp::Graph {
2418 const ACCESS_TO: &str = "http://www.w3.org/ns/auth/acl#accessTo";
2419 const DEFAULT: &str = "http://www.w3.org/ns/auth/acl#default";
2420 let origin = origin.trim_end_matches('/');
2421 let mut out = ldp::Graph::new();
2422 for t in graph.triples() {
2423 let object = match (&t.predicate, &t.object) {
2424 (ldp::Term::Iri(p), ldp::Term::Iri(o)) if p == ACCESS_TO || p == DEFAULT => o
2425 .strip_prefix(origin)
2426 .filter(|rest| rest.starts_with('/'))
2427 .map(|rest| ldp::Term::Iri(rest.to_string()))
2428 .unwrap_or_else(|| t.object.clone()),
2429 _ => t.object.clone(),
2430 };
2431 out.insert(ldp::Triple::new(
2432 t.subject.clone(),
2433 t.predicate.clone(),
2434 object,
2435 ));
2436 }
2437 out
2438}
2439
2440pub(crate) async fn find_effective_acl_dyn(
2456 storage: &dyn Storage,
2457 resource_path: &str,
2458) -> Result<Option<wac::AclDocument>, PodError> {
2459 resolve_policy_dyn(storage, resource_path)
2460 .await
2461 .into_result()
2462}
2463
2464pub(crate) async fn resolve_policy_dyn(
2469 storage: &dyn Storage,
2470 resource_path: &str,
2471) -> wac::PolicyOutcome {
2472 wac::resolve_policy_from_storage(storage, resource_path).await
2473}
2474
2475fn policy_failure_to_actix(outcome: &wac::PolicyOutcome, resource: &str) -> ActixError {
2485 match outcome {
2486 wac::PolicyOutcome::Invalid {
2487 policy_path,
2488 reason,
2489 } => {
2490 tracing::warn!(
2491 target: "solid_pod_rs_server::wac",
2492 resource = %resource,
2493 policy = %policy_path,
2494 "denying: effective ACL is invalid and MUST NOT inherit: {reason}"
2495 );
2496 actix_web::error::ErrorForbidden("access forbidden: governing ACL is invalid")
2497 }
2498 wac::PolicyOutcome::Unavailable {
2499 policy_path,
2500 detail,
2501 } => {
2502 tracing::error!(
2503 target: "solid_pod_rs_server::wac",
2504 resource = %resource,
2505 policy = %policy_path,
2506 "denying: effective ACL could not be read: {detail}"
2507 );
2508 actix_web::error::ErrorServiceUnavailable(
2509 "access control unavailable: governing ACL could not be read",
2510 )
2511 }
2512 _ => actix_web::error::ErrorInternalServerError("policy resolution error"),
2514 }
2515}
2516
2517async fn handle_delete(
2518 req: HttpRequest,
2519 state: web::Data<AppState>,
2520) -> Result<HttpResponse, ActixError> {
2521 let path = req.uri().path().to_string();
2522 let auth_pk = extract_pubkey(&req).await;
2523 let agent = agent_uri(auth_pk.as_ref());
2524 enforce_write_ctx(
2525 &state,
2526 &path,
2527 AccessMode::Write,
2528 agent.as_deref(),
2529 req_origin(&req),
2530 )
2531 .await?;
2532
2533 let _write_guard = lock_resource(&path).await;
2534 check_write_preconditions(&req, &state, &path).await?;
2535 let quota = reserve_quota_for_size(&state, &path, 0).await?;
2536 match state.storage.delete(&path).await {
2537 Ok(()) => {
2538 finish_quota_reservation(&state, quota, true).await;
2539 Ok(HttpResponse::NoContent().finish())
2540 }
2541 Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
2542 Err(e) => Err(to_actix(e)),
2543 }
2544}
2545
2546async fn handle_options(
2547 req: HttpRequest,
2548 state: web::Data<AppState>,
2549) -> Result<HttpResponse, ActixError> {
2550 let path = req.uri().path().to_string();
2551 let o = ldp::options_for_conneg(&path, state.conneg_enabled);
2552 let mut rsp = HttpResponse::NoContent().finish();
2553 if let Ok(v) = header::HeaderValue::from_str(&o.allow.join(", ")) {
2554 rsp.headers_mut()
2555 .insert(header::HeaderName::from_static("allow"), v);
2556 }
2557 if let Some(ap) = o.accept_post {
2558 if let Ok(v) = header::HeaderValue::from_str(ap) {
2559 rsp.headers_mut()
2560 .insert(header::HeaderName::from_static("accept-post"), v);
2561 }
2562 }
2563 if let Ok(v) = header::HeaderValue::from_str(o.accept_patch) {
2564 rsp.headers_mut()
2565 .insert(header::HeaderName::from_static("accept-patch"), v);
2566 }
2567 if let Ok(v) = header::HeaderValue::from_str(o.accept_ranges) {
2568 rsp.headers_mut()
2569 .insert(header::HeaderName::from_static("accept-ranges"), v);
2570 }
2571 set_updates_via(&mut rsp, &state.nodeinfo.base_url);
2572 Ok(rsp)
2573}
2574
2575async fn handle_well_known_solid(state: web::Data<AppState>) -> HttpResponse {
2580 let doc = interop::well_known_solid(&state.nodeinfo.base_url, &state.nodeinfo.base_url);
2581 HttpResponse::Ok()
2582 .content_type("application/ld+json")
2583 .json(doc)
2584}
2585
2586#[derive(Debug, Deserialize)]
2587struct WebFingerQuery {
2588 resource: Option<String>,
2589}
2590
2591async fn handle_well_known_webfinger(
2592 state: web::Data<AppState>,
2593 q: web::Query<WebFingerQuery>,
2594) -> HttpResponse {
2595 let resource = q.resource.clone().unwrap_or_else(|| {
2596 format!(
2597 "acct:anonymous@{}",
2598 state
2599 .nodeinfo
2600 .base_url
2601 .trim_start_matches("http://")
2602 .trim_start_matches("https://")
2603 )
2604 });
2605 let webid = format!(
2606 "{}/profile/card#me",
2607 state.nodeinfo.base_url.trim_end_matches('/')
2608 );
2609 match interop::webfinger_response(&resource, &state.nodeinfo.base_url, &webid) {
2610 Some(jrd) => HttpResponse::Ok()
2611 .content_type("application/jrd+json")
2612 .json(jrd),
2613 None => HttpResponse::NotFound().finish(),
2614 }
2615}
2616
2617async fn handle_well_known_nodeinfo(state: web::Data<AppState>) -> HttpResponse {
2618 let doc = interop::nodeinfo_discovery(&state.nodeinfo.base_url);
2619 HttpResponse::Ok()
2620 .content_type("application/json")
2621 .json(doc)
2622}
2623
2624async fn handle_well_known_nodeinfo_2_1(state: web::Data<AppState>) -> HttpResponse {
2625 let doc = interop::nodeinfo_2_1(
2626 &state.nodeinfo.software_name,
2627 &state.nodeinfo.software_version,
2628 state.nodeinfo.open_registrations,
2629 state.nodeinfo.total_users,
2630 );
2631 HttpResponse::Ok()
2632 .content_type("application/json")
2633 .json(doc)
2634}
2635
2636#[cfg(feature = "did-nostr")]
2637async fn handle_well_known_did_nostr(
2638 state: web::Data<AppState>,
2639 path: web::Path<String>,
2640) -> HttpResponse {
2641 let pubkey = path.into_inner();
2642 let pubkey_is_valid = pubkey.len() == 64
2647 && pubkey
2648 .bytes()
2649 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
2650 if !pubkey_is_valid {
2651 return HttpResponse::BadRequest()
2652 .insert_header(("Cache-Control", "no-store"))
2653 .json(serde_json::json!({
2654 "error": "invalid did:nostr pubkey (expected 64-char lowercase hex)"
2655 }));
2656 }
2657 let owner_pubkey = match state.storage.get("/profile/card").await {
2665 Ok((body, _)) => solid_pod_rs::webid::extract_nostr_pubkey(&body)
2666 .ok()
2667 .flatten(),
2668 Err(_) => None,
2669 };
2670 let owner_claims_key = owner_pubkey
2671 .as_deref()
2672 .is_some_and(|owner| owner.eq_ignore_ascii_case(&pubkey));
2673 if !owner_claims_key {
2674 return HttpResponse::NotFound()
2675 .insert_header(("Cache-Control", "no-store"))
2676 .json(serde_json::json!({
2677 "error": "no account on this pod claims this did:nostr pubkey"
2678 }));
2679 }
2680 let also = vec![format!(
2681 "{}/profile/card#me",
2682 state.nodeinfo.base_url.trim_end_matches('/')
2683 )];
2684 let doc = interop::did_nostr::did_nostr_document(&pubkey, &also);
2685 let body = serde_json::to_string(&doc).unwrap_or_else(|_| "{}".to_string());
2686 use std::hash::{Hash, Hasher};
2692 let mut hasher = std::collections::hash_map::DefaultHasher::new();
2693 body.hash(&mut hasher);
2694 let etag = format!("\"{:016x}\"", hasher.finish());
2695 HttpResponse::Ok()
2696 .content_type("application/did+json")
2697 .insert_header(("Cache-Control", "max-age=3600"))
2698 .insert_header(("ETag", etag))
2699 .body(body)
2700}
2701
2702#[cfg(feature = "nip05-endpoint")]
2710#[derive(Debug, Deserialize)]
2711struct Nip05Query {
2712 name: Option<String>,
2715}
2716
2717#[cfg(feature = "nip05-endpoint")]
2718fn nip05_name_is_valid(name: &str) -> bool {
2719 if name.is_empty() {
2722 return false;
2723 }
2724 name.bytes()
2725 .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
2726}
2727
2728#[cfg(feature = "nip05-endpoint")]
2729async fn handle_well_known_nip05(
2730 state: web::Data<AppState>,
2731 query: web::Query<Nip05Query>,
2732) -> HttpResponse {
2733 use solid_pod_rs::webid::extract_nostr_pubkey;
2734
2735 let name = query.name.clone().unwrap_or_else(|| "_".to_string());
2737 if !nip05_name_is_valid(&name) {
2738 return HttpResponse::BadRequest().json(serde_json::json!({
2739 "error": "invalid NIP-05 local part",
2740 }));
2741 }
2742
2743 let profile_path = if name == "_" {
2749 "/profile/card".to_string()
2750 } else {
2751 format!("/{name}/profile/card")
2752 };
2753
2754 let (body, _meta) = match state.storage.get(&profile_path).await {
2755 Ok(v) => v,
2756 Err(_) => {
2757 return nip05_empty_response();
2761 }
2762 };
2763
2764 let pubkey_hex = match extract_nostr_pubkey(&body) {
2765 Ok(Some(p)) => p,
2766 _ => return nip05_empty_response(),
2767 };
2768
2769 let doc = interop::nip05_document([(name, pubkey_hex)]);
2770 HttpResponse::Ok()
2771 .insert_header(("Access-Control-Allow-Origin", "*"))
2772 .content_type("application/json")
2773 .json(doc)
2774}
2775
2776#[cfg(feature = "nip05-endpoint")]
2777fn nip05_empty_response() -> HttpResponse {
2778 HttpResponse::Ok()
2779 .insert_header(("Access-Control-Allow-Origin", "*"))
2780 .content_type("application/json")
2781 .json(serde_json::json!({ "names": {} }))
2782}
2783
2784#[cfg(feature = "export-jsonld")]
2798async fn handle_export_all(
2799 req: HttpRequest,
2800 state: web::Data<AppState>,
2801) -> Result<HttpResponse, ActixError> {
2802 let auth_pk = extract_pubkey(&req).await;
2803 let agent = agent_uri(auth_pk.as_ref());
2804
2805 enforce_write_ctx(
2810 &state,
2811 "/",
2812 AccessMode::Control,
2813 agent.as_deref(),
2814 req_origin(&req),
2815 )
2816 .await?;
2817
2818 let include_private = web::Query::<HashMap<String, String>>::from_query(req.query_string())
2822 .ok()
2823 .and_then(|q| q.get("include_private").map(|v| v == "true"))
2824 .unwrap_or(false);
2825
2826 let pod_base = format!("{}/", scheme::request_origin(&req));
2830
2831 let options = solid_pod_rs::ExportOptions { include_private };
2832 let bundle = solid_pod_rs::export::export_pod_jsonld(&*state.storage, &pod_base, options)
2833 .await
2834 .map_err(to_actix)?;
2835
2836 let body = serde_json::to_vec(&bundle).map_err(|e| {
2837 actix_web::error::ErrorInternalServerError(format!("export serialise: {e}"))
2838 })?;
2839 Ok(HttpResponse::Ok()
2840 .content_type(solid_pod_rs::export::EXPORT_CONTENT_TYPE)
2841 .body(body))
2842}
2843
2844#[derive(Debug, Deserialize)]
2849struct CreateAccountRequest {
2850 username: String,
2851 #[serde(default)]
2852 name: Option<String>,
2853}
2854
2855#[derive(Debug, Deserialize)]
2856struct CreatePodRequest {
2857 name: String,
2858}
2859
2860async fn handle_pod_check(state: web::Data<AppState>, path: web::Path<String>) -> HttpResponse {
2861 let pod_name = path.into_inner();
2862 let pod_root = format!("/{pod_name}/");
2863 match state.storage.exists(&pod_root).await {
2864 Ok(true) => HttpResponse::Ok().json(serde_json::json!({"exists": true})),
2865 _ => HttpResponse::NotFound().json(serde_json::json!({"exists": false})),
2866 }
2867}
2868
2869fn valid_pod_name(name: &str) -> bool {
2870 !name.is_empty()
2871 && name
2872 .chars()
2873 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
2874}
2875
2876fn request_ip(req: &HttpRequest) -> IpAddr {
2877 req.peer_addr()
2878 .map(|addr| addr.ip())
2879 .unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST))
2880}
2881
2882#[derive(Debug)]
2883struct QuotaReservation {
2884 pod: String,
2885 delta: i64,
2886}
2887
2888fn pod_name_from_path(path: &str) -> Option<&str> {
2889 path.trim_start_matches('/')
2890 .split('/')
2891 .next()
2892 .filter(|p| !p.is_empty())
2893}
2894
2895async fn reserve_quota_for_size(
2896 state: &AppState,
2897 path: &str,
2898 new_size: u64,
2899) -> Result<Option<QuotaReservation>, ActixError> {
2900 let (Some(policy), Some(pod)) = (&state.quota, pod_name_from_path(path)) else {
2901 return Ok(None);
2902 };
2903 let old_size = state
2904 .storage
2905 .head(path)
2906 .await
2907 .map(|meta| meta.size)
2908 .unwrap_or(0);
2909 let delta = i128::from(new_size) - i128::from(old_size);
2910 let delta = delta.clamp(i64::MIN as i128, i64::MAX as i128) as i64;
2911 if delta > 0 {
2912 policy
2913 .reserve(pod, delta as u64)
2914 .await
2915 .map_err(|error| actix_web::error::ErrorInsufficientStorage(error.to_string()))?;
2916 }
2917 Ok(Some(QuotaReservation {
2918 pod: pod.to_string(),
2919 delta,
2920 }))
2921}
2922
2923async fn finish_quota_reservation(
2924 state: &AppState,
2925 reservation: Option<QuotaReservation>,
2926 write_succeeded: bool,
2927) {
2928 let (Some(policy), Some(reservation)) = (&state.quota, reservation) else {
2929 return;
2930 };
2931 if write_succeeded {
2932 if reservation.delta < 0 {
2933 policy.record(&reservation.pod, reservation.delta).await;
2934 }
2935 } else if reservation.delta > 0 {
2936 policy.record(&reservation.pod, -reservation.delta).await;
2937 }
2938}
2939
2940async fn handle_create_account(
2941 req: HttpRequest,
2942 state: web::Data<AppState>,
2943 body: web::Json<CreateAccountRequest>,
2944) -> Result<HttpResponse, ActixError> {
2945 if let Some(response) = provisioning_gate(&req, &state, &body.username).await {
2946 return Ok(response);
2947 }
2948 let pod_root = format!("/{}/", body.username);
2949 let _write_guard = lock_resource(&pod_root).await;
2954 if state.storage.exists(&pod_root).await.map_err(to_actix)? {
2955 return Ok(
2956 HttpResponse::Conflict().json(serde_json::json!({"error": "account already exists"}))
2957 );
2958 }
2959
2960 let base_uri = state.nodeinfo.base_url.trim_end_matches('/');
2961 let outcome =
2962 provision_named_pod(&state, &body.username, body.name.as_deref(), base_uri).await?;
2963 Ok(HttpResponse::Created().json(serde_json::json!({
2964 "webid": outcome.webid,
2965 "pod_root": outcome.pod_uri,
2966 "username": body.username,
2967 })))
2968}
2969
2970struct NamedPodOutcome {
2971 webid: String,
2972 pod_uri: String,
2973}
2974
2975async fn provisioning_gate(
2978 req: &HttpRequest,
2979 state: &AppState,
2980 name: &str,
2981) -> Option<HttpResponse> {
2982 if !valid_pod_name(name) {
2983 return Some(HttpResponse::BadRequest().json(serde_json::json!({
2984 "error": "Invalid pod name. Use alphanumeric, dash, or underscore only."
2985 })));
2986 }
2987
2988 let supplied_key = req
2989 .headers()
2990 .get("x-pod-admin-key")
2991 .and_then(|value| value.to_str().ok())
2992 .unwrap_or("");
2993 use subtle::ConstantTimeEq;
2994 let admin_override = state
2995 .admin_key
2996 .as_deref()
2997 .is_some_and(|expected| bool::from(supplied_key.as_bytes().ct_eq(expected.as_bytes())));
2998 let invite = req
2999 .headers()
3000 .get("x-invite-token")
3001 .and_then(|v| v.to_str().ok())
3002 .map(str::trim)
3003 .filter(|t| !t.is_empty());
3004 let closed = !state.nodeinfo.open_registrations && !admin_override;
3005 if closed && invite.is_none() {
3006 return Some(HttpResponse::Forbidden().json(serde_json::json!({
3007 "error": "pod registration is closed"
3008 })));
3009 }
3010
3011 if let Err(retry_after) = state.pod_create_limiter.check(request_ip(req)) {
3012 return Some(
3013 HttpResponse::TooManyRequests()
3014 .insert_header(("Retry-After", retry_after.to_string()))
3015 .json(serde_json::json!({
3016 "error": "Too Many Requests",
3017 "message": "Pod creation rate limit exceeded",
3018 "retryAfter": retry_after
3019 })),
3020 );
3021 }
3022 if closed {
3027 let (Some(token), Some(root)) = (invite, state.data_root.as_deref()) else {
3028 return Some(HttpResponse::Forbidden().json(serde_json::json!({
3029 "error": "pod registration is closed"
3030 })));
3031 };
3032 let refusal =
3033 |why: &str| HttpResponse::Forbidden().json(serde_json::json!({ "error": why }));
3034 match cli::FileInviteStore::new(root).consume(token).await {
3035 Ok(cli::Consume::Granted) => {}
3036 Ok(cli::Consume::Expired) => return Some(refusal("invite has expired")),
3037 Ok(cli::Consume::Exhausted) => return Some(refusal("invite has been used")),
3038 Ok(cli::Consume::Unknown) => return Some(refusal("invalid invite code")),
3039 Err(e) => {
3040 tracing::error!("invite store: {e}");
3041 return Some(
3042 HttpResponse::InternalServerError()
3043 .json(serde_json::json!({ "error": "invite store unavailable" })),
3044 );
3045 }
3046 }
3047 }
3048 None
3049}
3050
3051fn named_pod_acls(name: &str, webid: &str) -> Vec<(String, String)> {
3062 const PREFIXES: &str = "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
3063 @prefix foaf: <http://xmlns.com/foaf/0.1/> .\n";
3064 let owner = |target: &str| {
3065 format!(
3066 "<#owner> a acl:Authorization ;\n acl:agent <{webid}> ;\n \
3067 acl:accessTo <{target}> ;\n acl:default <{target}> ;\n \
3068 acl:mode acl:Read, acl:Write, acl:Control .\n"
3069 )
3070 };
3071 let public = |target: &str, mode: &str, inherited: bool| {
3072 let default = if inherited {
3073 format!(" acl:default <{target}> ;\n")
3074 } else {
3075 String::new()
3076 };
3077 format!(
3078 "<#public> a acl:Authorization ;\n acl:agentClass foaf:Agent ;\n \
3079 acl:accessTo <{target}> ;\n{default} acl:mode {mode} .\n"
3080 )
3081 };
3082
3083 let root = format!("/{name}/");
3084 let mut acls = vec![(
3085 solid_pod_rs::wac::resolver::acl_sidecar_key(&root),
3086 format!(
3087 "{PREFIXES}{}{}",
3088 owner(&root),
3089 public(&root, "acl:Read", false)
3090 ),
3091 )];
3092 for (container, mode) in [
3093 ("profile", "acl:Read"),
3094 ("public", "acl:Read"),
3095 ("inbox", "acl:Append"),
3096 ] {
3097 let target = format!("/{name}/{container}/");
3098 acls.push((
3099 solid_pod_rs::wac::resolver::acl_sidecar_key(&target),
3100 format!(
3101 "{PREFIXES}{}{}",
3102 owner(&target),
3103 public(&target, mode, true)
3104 ),
3105 ));
3106 }
3107 acls
3108}
3109
3110async fn provision_named_pod(
3114 state: &AppState,
3115 name: &str,
3116 display_name: Option<&str>,
3117 base_uri: &str,
3118) -> Result<NamedPodOutcome, ActixError> {
3119 let base_uri = base_uri.trim_end_matches('/');
3120 let pod_uri = format!("{base_uri}/{name}/");
3121 let canonical_prefix = format!("{base_uri}/pods/{name}/");
3122 let webid = format!("{pod_uri}profile/card#me");
3123
3124 for (key, body) in named_pod_acls(name, &webid) {
3129 state
3130 .storage
3131 .put(&key, Bytes::from(body), "text/turtle")
3132 .await
3133 .map_err(to_actix)?;
3134 }
3135
3136 for container in ["", "profile", "inbox", "public", "private", "settings"] {
3137 let path = if container.is_empty() {
3138 format!("/{name}")
3139 } else {
3140 format!("/{name}/{container}")
3141 };
3142 state
3143 .storage
3144 .put(
3145 &format!("{path}.meta"),
3146 Bytes::from_static(b"{}"),
3147 "application/ld+json",
3148 )
3149 .await
3150 .map_err(to_actix)?;
3151 }
3152 let profile = solid_pod_rs::webid::generate_webid_html(name, display_name, base_uri)
3153 .replace(&canonical_prefix, &pod_uri);
3154 state
3155 .storage
3156 .put(
3157 &format!("/{name}/profile/card"),
3158 Bytes::from(profile.into_bytes()),
3159 "text/html",
3160 )
3161 .await
3162 .map_err(to_actix)?;
3163
3164 #[cfg(feature = "git")]
3165 if let Some(root) = &state.data_root {
3166 let hook = solid_pod_rs_git::init::GitAutoInit::new();
3167 if let Err(error) = hook.init_repo_at(&root.join(name)).await {
3168 tracing::warn!(pod = name, %error, "git auto-init failed after pod creation");
3169 }
3170 }
3171
3172 Ok(NamedPodOutcome { webid, pod_uri })
3173}
3174
3175async fn handle_create_pod(
3176 req: HttpRequest,
3177 state: web::Data<AppState>,
3178 body: web::Json<CreatePodRequest>,
3179) -> Result<HttpResponse, ActixError> {
3180 if let Some(response) = provisioning_gate(&req, &state, &body.name).await {
3181 return Ok(response);
3182 }
3183
3184 let pod_root = format!("/{}/", body.name);
3185 let _write_guard = lock_resource(&pod_root).await;
3190 if state.storage.exists(&pod_root).await.map_err(to_actix)? {
3191 return Ok(
3192 HttpResponse::Conflict().json(serde_json::json!({"error": "Pod already exists"}))
3193 );
3194 }
3195
3196 let base_uri = scheme::request_origin(&req);
3197 let outcome = provision_named_pod(&state, &body.name, None, &base_uri).await?;
3198
3199 Ok(HttpResponse::Created()
3200 .insert_header(("Location", outcome.pod_uri.clone()))
3201 .json(serde_json::json!({
3202 "name": body.name,
3203 "webId": outcome.webid,
3204 "podUri": outcome.pod_uri,
3205 })))
3206}
3207
3208fn normalise_copy_source(raw: &str, host: &str) -> Option<String> {
3218 let path = if raw.starts_with("http://") || raw.starts_with("https://") {
3219 let url = url::Url::parse(raw).ok()?;
3220 let authority = match url.port() {
3221 Some(port) => format!("{}:{port}", url.host_str()?),
3222 None => url.host_str()?.to_string(),
3223 };
3224 if !authority.eq_ignore_ascii_case(host)
3225 || url.query().is_some()
3226 || url.fragment().is_some()
3227 {
3228 return None;
3229 }
3230 url.path().to_string()
3231 } else if raw.starts_with('/') && !raw.contains(['?', '#']) {
3232 raw.to_string()
3233 } else {
3234 return None;
3235 };
3236 canonical_pod_path(&path)
3237}
3238
3239async fn handle_copy(
3240 req: HttpRequest,
3241 state: web::Data<AppState>,
3242) -> Result<HttpResponse, ActixError> {
3243 let dest = req.uri().path().to_string();
3244 let auth_pk = extract_pubkey(&req).await;
3245 let agent = agent_uri(auth_pk.as_ref());
3246 enforce_write_ctx(
3247 &state,
3248 &dest,
3249 AccessMode::Write,
3250 agent.as_deref(),
3251 req_origin(&req),
3252 )
3253 .await?;
3254
3255 let source = req
3256 .headers()
3257 .get("source")
3258 .and_then(|v| v.to_str().ok())
3259 .map(|s| s.to_string());
3260 let source = match source {
3261 Some(s) => s,
3262 None => return Ok(HttpResponse::BadRequest().body("Source header required")),
3263 };
3264 let host = scheme::request_host(&req);
3265 let source = match normalise_copy_source(&source, &host) {
3266 Some(s) => s,
3267 None => return Ok(HttpResponse::BadRequest().body("invalid Source")),
3268 };
3269 if !state.dotfiles.is_allowed(Path::new(&source)) {
3270 return Ok(HttpResponse::Forbidden().body("dotfile path denied by allowlist"));
3271 }
3272 enforce_read_ctx(&state, &source, agent.as_deref(), req_origin(&req)).await?;
3275
3276 let (body, meta) = match state.storage.get(&source).await {
3277 Ok(v) => v,
3278 Err(PodError::NotFound(_)) => {
3279 return Ok(HttpResponse::NotFound().body("source resource not found"))
3280 }
3281 Err(e) => return Err(to_actix(e)),
3282 };
3283
3284 if protected_resource_for_acl(&dest).is_some()
3286 && !proposed_acl_keeps_caller_control(
3287 &state,
3288 &req,
3289 &dest,
3290 &body,
3291 &meta.content_type,
3292 agent.as_deref(),
3293 )
3294 .await
3295 {
3296 return Ok(HttpResponse::Conflict().body(
3297 "refused: the proposed ACL would not grant Control to the caller \
3298 (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
3299 ));
3300 }
3301
3302 {
3303 let _write_guard = lock_resource(&dest).await;
3306 let quota = reserve_quota_for_size(&state, &dest, body.len() as u64).await?;
3307 let write = state.storage.put(&dest, body, &meta.content_type).await;
3308 finish_quota_reservation(&state, quota, write.is_ok()).await;
3309 write.map_err(to_actix)?;
3310 }
3311
3312 let src_acl = format!("{}.acl", source.trim_end_matches('/'));
3317 let dst_acl = format!("{}.acl", dest.trim_end_matches('/'));
3318 if let Ok((acl_body, acl_meta)) = state.storage.get(&src_acl).await {
3319 let origin = req_origin(&req);
3320 let permitted = enforce_read_ctx(&state, &src_acl, agent.as_deref(), origin)
3321 .await
3322 .is_ok()
3323 && enforce_write_ctx(
3324 &state,
3325 &dst_acl,
3326 AccessMode::Write,
3327 agent.as_deref(),
3328 origin,
3329 )
3330 .await
3331 .is_ok()
3332 && proposed_acl_keeps_caller_control(
3333 &state,
3334 &req,
3335 &dst_acl,
3336 &acl_body,
3337 &acl_meta.content_type,
3338 agent.as_deref(),
3339 )
3340 .await;
3341 if permitted {
3342 let _write_guard = lock_resource(&dst_acl).await;
3343 let quota = reserve_quota_for_size(&state, &dst_acl, acl_body.len() as u64).await?;
3344 let write = state
3345 .storage
3346 .put(&dst_acl, acl_body, &acl_meta.content_type)
3347 .await;
3348 finish_quota_reservation(&state, quota, write.is_ok()).await;
3349 write.map_err(to_actix)?;
3350 }
3351 }
3352
3353 let mut rsp = HttpResponse::Created().finish();
3354 if let Ok(loc) = header::HeaderValue::from_str(&dest) {
3355 rsp.headers_mut().insert(header::LOCATION, loc);
3356 }
3357 Ok(rsp)
3358}
3359
3360async fn handle_glob_get(
3365 req: HttpRequest,
3366 state: web::Data<AppState>,
3367) -> Result<HttpResponse, ActixError> {
3368 let raw_path = req.uri().path().to_string();
3369 if !raw_path.ends_with("/*") {
3371 return Ok(HttpResponse::NotFound().body("unsupported glob pattern"));
3372 }
3373 let folder = &raw_path[..raw_path.len() - 1]; let folder = if folder.ends_with('/') {
3375 folder.to_string()
3376 } else {
3377 format!("{folder}/")
3378 };
3379
3380 let auth_pk = extract_pubkey(&req).await;
3384 let agent = agent_uri(auth_pk.as_ref());
3385 let origin = req_origin(&req);
3386 let audience = enforce_read_ctx(&state, &folder, agent.as_deref(), origin).await?;
3387
3388 let children = state.storage.list(&folder).await.map_err(to_actix)?;
3389 let mut merged = String::new();
3390 let mut audience = audience;
3391
3392 for child in &children {
3393 if child.ends_with('/')
3394 || child.ends_with(".acl")
3395 || child.ends_with(".meta")
3396 || child.ends_with(".prov.ttl")
3397 {
3398 continue;
3399 }
3400 let child_path = format!("{folder}{child}");
3401 match enforce_read_inner(&state, &child_path, agent.as_deref(), origin, false).await {
3404 Ok(ResponseAudience::Private) => audience = ResponseAudience::Private,
3405 Ok(ResponseAudience::Public) => {}
3406 Err(_) => continue,
3407 }
3408 if let Ok((body, meta)) = state.storage.get(&child_path).await {
3409 if meta.content_type.contains("turtle")
3410 || meta.content_type.contains("n-triples")
3411 || meta.content_type.contains("n3")
3412 {
3413 if let Ok(text) = std::str::from_utf8(&body) {
3414 merged.push_str(text);
3415 merged.push('\n');
3416 }
3417 }
3418 }
3419 }
3420
3421 if merged.is_empty() {
3422 return Ok(HttpResponse::NotFound().body("no matching RDF resources"));
3423 }
3424
3425 let mut rsp = HttpResponse::Ok().content_type("text/turtle").body(merged);
3426 set_cache_policy(&mut rsp, "text/turtle", audience);
3427 Ok(rsp)
3428}
3429
3430#[derive(Debug, Deserialize)]
3435struct LoginPasswordRequest {
3436 username: String,
3437 password: String,
3438}
3439
3440async fn handle_login_password(body: web::Json<LoginPasswordRequest>) -> HttpResponse {
3447 let _ = (&body.username, &body.password);
3448 HttpResponse::NotImplemented().json(serde_json::json!({
3449 "error": "password login is not implemented on this pod"
3450 }))
3451}
3452
3453#[derive(Debug, Deserialize)]
3454struct PasswordResetRequest {
3455 username: String,
3456}
3457
3458async fn handle_password_reset_request(body: web::Json<PasswordResetRequest>) -> HttpResponse {
3462 let _ = &body.username;
3463 HttpResponse::NotImplemented().json(serde_json::json!({
3464 "error": "password reset is not implemented on this pod"
3465 }))
3466}
3467
3468#[derive(Debug, Deserialize)]
3469struct PasswordChangeRequest {
3470 token: String,
3471 new_password: String,
3472}
3473
3474async fn handle_password_change(body: web::Json<PasswordChangeRequest>) -> HttpResponse {
3479 let _ = (&body.token, &body.new_password);
3480 HttpResponse::NotImplemented().json(serde_json::json!({
3481 "error": "password change is not implemented on this pod"
3482 }))
3483}
3484
3485async fn handle_pay_info(state: web::Data<AppState>) -> HttpResponse {
3490 let body = solid_pod_rs::payments::pay_info(&state.pay_config);
3491 HttpResponse::Ok()
3492 .content_type("application/json")
3493 .json(body)
3494}
3495
3496pub const DEFAULT_PROXY_BYTE_CAP: usize = 50 * 1024 * 1024;
3511
3512#[derive(Debug, Deserialize)]
3514struct ProxyQuery {
3515 url: String,
3516}
3517
3518const STRIPPED_RESPONSE_HEADERS: &[&str] = &[
3520 "set-cookie",
3521 "set-cookie2",
3522 "authorization",
3523 "www-authenticate",
3524 "proxy-authenticate",
3525 "proxy-authorization",
3526];
3527
3528async fn validate_proxy_target(target: &str) -> Result<(url::Url, IpAddr), HttpResponse> {
3544 let parsed = match url::Url::parse(target) {
3545 Ok(u) => u,
3546 Err(_) => {
3547 return Err(
3548 HttpResponse::BadRequest().json(serde_json::json!({"error": "invalid target URL"}))
3549 );
3550 }
3551 };
3552
3553 match parsed.scheme() {
3555 "http" | "https" => {}
3556 scheme => {
3557 return Err(HttpResponse::BadRequest()
3558 .json(serde_json::json!({"error": format!("unsupported scheme: {scheme}")})));
3559 }
3560 }
3561
3562 if solid_pod_rs::security::is_safe_url(target).is_err() {
3565 return Err(HttpResponse::Forbidden()
3566 .json(serde_json::json!({"error": "target URL blocked by SSRF policy"})));
3567 }
3568
3569 let host = match parsed.host_str() {
3571 Some(h) => h.to_string(),
3572 None => {
3573 return Err(HttpResponse::BadRequest()
3574 .json(serde_json::json!({"error": "target URL has no host"})))
3575 }
3576 };
3577 let host_lower = host.to_ascii_lowercase();
3578 if host_lower == "localhost"
3579 || host_lower.ends_with(".localhost")
3580 || host_lower == "0.0.0.0"
3581 || host_lower == "[::1]"
3582 || host_lower == "[::0]"
3583 {
3584 return Err(HttpResponse::Forbidden()
3585 .json(serde_json::json!({"error": "target URL blocked by SSRF policy"})));
3586 }
3587
3588 match solid_pod_rs::security::resolve_and_check(&host).await {
3591 Ok(ip) => Ok((parsed, ip)),
3592 Err(_) => Err(HttpResponse::Forbidden()
3593 .json(serde_json::json!({"error": "target URL blocked by SSRF policy"}))),
3594 }
3595}
3596
3597fn build_pinned_proxy_client(url: &url::Url, ip: IpAddr) -> Result<reqwest::Client, ActixError> {
3600 let mut builder = reqwest::Client::builder()
3601 .redirect(reqwest::redirect::Policy::none());
3604 if let Some(host) = url.host_str() {
3605 let port = url.port_or_known_default().unwrap_or(0);
3607 builder = builder.resolve(host, std::net::SocketAddr::new(ip, port));
3608 }
3609 builder
3610 .build()
3611 .map_err(|e| actix_web::error::ErrorInternalServerError(format!("proxy client: {e}")))
3612}
3613
3614async fn handle_proxy(
3615 req: HttpRequest,
3616 _state: web::Data<AppState>,
3617 query: web::Query<ProxyQuery>,
3618) -> Result<HttpResponse, ActixError> {
3619 let auth_pk = extract_pubkey(&req).await;
3621 let agent = agent_uri(auth_pk.as_ref());
3622 if agent.is_none() {
3623 return Ok(HttpResponse::Unauthorized()
3624 .json(serde_json::json!({"error": "authentication required"})));
3625 }
3626
3627 let mut current_url = query.url.clone();
3628 let mut redirect_count = 0u8;
3629 const MAX_REDIRECTS: u8 = 5;
3630 const TOTAL_TIMEOUT: Duration = Duration::from_secs(30);
3631 let started = Instant::now();
3632
3633 let byte_cap = std::env::var("PROXY_BYTE_CAP")
3634 .ok()
3635 .and_then(|v| {
3636 solid_pod_rs::config::sources::parse_size(&v)
3637 .map(|u| u as usize)
3638 .ok()
3639 })
3640 .unwrap_or(DEFAULT_PROXY_BYTE_CAP);
3641
3642 loop {
3643 let Some(remaining) = TOTAL_TIMEOUT.checked_sub(started.elapsed()) else {
3644 return Ok(HttpResponse::GatewayTimeout()
3645 .json(serde_json::json!({"error": "proxy operation timed out"})));
3646 };
3647 let (target_url, pinned_ip) = match validate_proxy_target(¤t_url).await {
3651 Ok(pair) => pair,
3652 Err(rsp) => return Ok(rsp),
3653 };
3654 let client = build_pinned_proxy_client(&target_url, pinned_ip)?;
3655
3656 let mut upstream_req = client.get(¤t_url).timeout(remaining);
3657
3658 if let Some(auth_val) = req
3660 .headers()
3661 .get("x-upstream-authorization")
3662 .and_then(|v| v.to_str().ok())
3663 {
3664 upstream_req = upstream_req.header("Authorization", auth_val);
3665 }
3666
3667 let response = upstream_req
3668 .send()
3669 .await
3670 .map_err(|e| actix_web::error::ErrorBadGateway(format!("upstream error: {e}")))?;
3671
3672 if response.status().is_redirection() {
3674 if redirect_count >= MAX_REDIRECTS {
3675 return Ok(HttpResponse::BadGateway()
3676 .json(serde_json::json!({"error": "too many redirects"})));
3677 }
3678 if let Some(location) = response.headers().get("location") {
3679 let loc_str = location
3680 .to_str()
3681 .map_err(|_| actix_web::error::ErrorBadGateway("invalid redirect location"))?;
3682 let base = url::Url::parse(¤t_url)
3684 .map_err(|_| actix_web::error::ErrorBadGateway("invalid current URL"))?;
3685 let resolved = base
3686 .join(loc_str)
3687 .map_err(|_| actix_web::error::ErrorBadGateway("invalid redirect URL"))?;
3688 current_url = resolved.to_string();
3689 redirect_count += 1;
3690 continue;
3691 }
3692 return Ok(HttpResponse::BadGateway()
3693 .json(serde_json::json!({"error": "redirect without location"})));
3694 }
3695
3696 let upstream_status = response.status().as_u16();
3698 let upstream_content_type = response
3699 .headers()
3700 .get("content-type")
3701 .and_then(|v| v.to_str().ok())
3702 .unwrap_or("application/octet-stream")
3703 .to_string();
3704 if response
3705 .content_length()
3706 .is_some_and(|length| length > byte_cap as u64)
3707 {
3708 return Ok(HttpResponse::PayloadTooLarge().json(serde_json::json!({
3709 "error": "proxied response exceeds byte cap",
3710 "limit": byte_cap
3711 })));
3712 }
3713
3714 let mut forwarded_headers: Vec<(String, String)> = Vec::new();
3716 for (name, value) in response.headers() {
3717 let name_lower = name.as_str().to_ascii_lowercase();
3718 if STRIPPED_RESPONSE_HEADERS.contains(&name_lower.as_str()) {
3719 continue;
3720 }
3721 if matches!(
3723 name_lower.as_str(),
3724 "transfer-encoding" | "connection" | "keep-alive" | "trailer" | "upgrade"
3725 ) {
3726 continue;
3727 }
3728 if let Ok(val_str) = value.to_str() {
3729 forwarded_headers.push((name_lower, val_str.to_string()));
3730 }
3731 }
3732
3733 let mut stream = response.bytes_stream();
3734 let mut body_bytes = Vec::with_capacity(byte_cap.min(64 * 1024));
3735 while let Some(chunk) = stream.next().await {
3736 let chunk =
3737 chunk.map_err(|e| actix_web::error::ErrorBadGateway(format!("body read: {e}")))?;
3738 if body_bytes.len().saturating_add(chunk.len()) > byte_cap {
3739 return Ok(HttpResponse::PayloadTooLarge().json(serde_json::json!({
3740 "error": "proxied response exceeds byte cap",
3741 "limit": byte_cap
3742 })));
3743 }
3744 body_bytes.extend_from_slice(&chunk);
3745 }
3746
3747 let mut rsp = HttpResponse::build(
3749 StatusCode::from_u16(upstream_status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
3750 );
3751 rsp.insert_header(("Content-Type", upstream_content_type.as_str()));
3752 rsp.insert_header(("X-Proxy-Status", upstream_status.to_string()));
3753
3754 for (name, value) in &forwarded_headers {
3756 if let Ok(hname) = header::HeaderName::from_bytes(name.as_bytes()) {
3757 if let Ok(hval) = header::HeaderValue::from_str(value) {
3758 rsp.insert_header((hname, hval));
3759 }
3760 }
3761 }
3762
3763 return Ok(rsp.body(body_bytes));
3764 }
3765}
3766
3767pub struct PathTraversalGuard;
3773
3774impl<S, B> Transform<S, ServiceRequest> for PathTraversalGuard
3775where
3776 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3777 B: 'static,
3778{
3779 type Response = ServiceResponse<EitherBody<B, BoxBody>>;
3780 type Error = ActixError;
3781 type InitError = ();
3782 type Transform = PathTraversalGuardMiddleware<S>;
3783 type Future = Ready<Result<Self::Transform, Self::InitError>>;
3784
3785 fn new_transform(&self, service: S) -> Self::Future {
3786 ready(Ok(PathTraversalGuardMiddleware { service }))
3787 }
3788}
3789
3790pub struct PathTraversalGuardMiddleware<S> {
3792 service: S,
3793}
3794
3795impl<S, B> Service<ServiceRequest> for PathTraversalGuardMiddleware<S>
3796where
3797 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3798 B: 'static,
3799{
3800 type Response = ServiceResponse<EitherBody<B, BoxBody>>;
3801 type Error = ActixError;
3802 type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
3803
3804 actix_web::dev::forward_ready!(service);
3805
3806 fn call(&self, req: ServiceRequest) -> Self::Future {
3807 let raw = req.path().to_string();
3810 if path_is_traversal(&raw) {
3811 let rsp = HttpResponse::BadRequest().body("invalid path: traversal rejected");
3812 let sr = req.into_response(rsp.map_into_boxed_body());
3813 return Box::pin(async move { Ok(sr.map_into_right_body()) });
3814 }
3815 let fut = self.service.call(req);
3816 Box::pin(async move {
3817 let resp = fut.await?;
3818 Ok(resp.map_into_left_body())
3819 })
3820 }
3821}
3822
3823fn path_is_traversal(path: &str) -> bool {
3824 let once: String = percent_decode_str(path).decode_utf8_lossy().into_owned();
3826 let twice: String = percent_decode_str(&once).decode_utf8_lossy().into_owned();
3827 for seg in once.split('/').chain(twice.split('/')) {
3828 if seg == ".." || seg == "." {
3829 return true;
3830 }
3831 }
3832 twice.contains("/../") || twice.starts_with("../") || twice.ends_with("/..")
3835}
3836
3837pub struct CorsHeaders {
3848 pub allowed_origins: Arc<Vec<String>>,
3849}
3850
3851impl<S, B> Transform<S, ServiceRequest> for CorsHeaders
3852where
3853 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3854 B: 'static,
3855{
3856 type Response = ServiceResponse<B>;
3857 type Error = ActixError;
3858 type InitError = ();
3859 type Transform = CorsHeadersMiddleware<S>;
3860 type Future = Ready<Result<Self::Transform, Self::InitError>>;
3861
3862 fn new_transform(&self, service: S) -> Self::Future {
3863 ready(Ok(CorsHeadersMiddleware {
3864 service,
3865 allowed_origins: self.allowed_origins.clone(),
3866 }))
3867 }
3868}
3869
3870pub struct CorsHeadersMiddleware<S> {
3872 service: S,
3873 allowed_origins: Arc<Vec<String>>,
3874}
3875
3876impl<S, B> Service<ServiceRequest> for CorsHeadersMiddleware<S>
3877where
3878 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3879 B: 'static,
3880{
3881 type Response = ServiceResponse<B>;
3882 type Error = ActixError;
3883 type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
3884
3885 actix_web::dev::forward_ready!(service);
3886
3887 fn call(&self, req: ServiceRequest) -> Self::Future {
3888 let origin = req
3889 .headers()
3890 .get(header::ORIGIN)
3891 .and_then(|v| v.to_str().ok())
3892 .map(str::to_string);
3893 let allowed = self.allowed_origins.clone();
3894 let fut = self.service.call(req);
3895 Box::pin(async move {
3896 let mut resp = fut.await?;
3897 add_cors_headers(resp.headers_mut(), origin.as_deref(), &allowed);
3898 Ok(resp)
3899 })
3900 }
3901}
3902
3903pub(crate) const CORS_EXPOSE_HEADERS: &str = "Accept-Patch, Accept-Post, Accept-Query, Accept-Ranges, Allow, Content-Length, Content-Range, Content-Type, ETag, Last-Modified, Link, Location, Updates-Via, WAC-Allow, WWW-Authenticate, X-Cost, X-Balance, X-Pay-Currency";
3911
3912fn add_cors_headers(headers: &mut header::HeaderMap, origin: Option<&str>, allowed: &[String]) {
3913 if headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) {
3923 return;
3924 }
3925 let (origin_value, allow_credentials): (String, bool) = if allowed.is_empty() {
3936 ("*".to_string(), false)
3937 } else {
3938 match origin.filter(|o| allowed.iter().any(|a| a == *o)) {
3939 Some(o) => (o.to_string(), true),
3940 None => return,
3943 }
3944 };
3945
3946 let mut pairs = vec![
3947 ("access-control-allow-origin", origin_value.as_str()),
3948 (
3949 "access-control-allow-methods",
3950 "GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS",
3951 ),
3952 (
3953 "access-control-allow-headers",
3954 "Accept, Authorization, Content-Type, DPoP, Git-Protocol, If-Match, If-None-Match, Link, Range, Slug, Origin",
3955 ),
3956 (
3957 "access-control-expose-headers",
3958 CORS_EXPOSE_HEADERS,
3959 ),
3960 ("access-control-max-age", "86400"),
3961 ];
3962 if allow_credentials {
3965 pairs.push(("access-control-allow-credentials", "true"));
3966 }
3967
3968 for (name, value) in pairs {
3969 if let (Ok(name), Ok(value)) = (
3970 header::HeaderName::from_lowercase(name.as_bytes()),
3971 header::HeaderValue::from_str(value),
3972 ) {
3973 headers.insert(name, value);
3974 }
3975 }
3976}
3977
3978pub struct ErrorLoggingMiddleware;
3994
3995impl<S, B> Transform<S, ServiceRequest> for ErrorLoggingMiddleware
3996where
3997 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3998 B: 'static,
3999{
4000 type Response = ServiceResponse<B>;
4001 type Error = ActixError;
4002 type InitError = ();
4003 type Transform = ErrorLoggingMiddlewareService<S>;
4004 type Future = Ready<Result<Self::Transform, Self::InitError>>;
4005
4006 fn new_transform(&self, service: S) -> Self::Future {
4007 ready(Ok(ErrorLoggingMiddlewareService { service }))
4008 }
4009}
4010
4011pub struct ErrorLoggingMiddlewareService<S> {
4013 service: S,
4014}
4015
4016impl<S, B> Service<ServiceRequest> for ErrorLoggingMiddlewareService<S>
4017where
4018 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
4019 B: 'static,
4020{
4021 type Response = ServiceResponse<B>;
4022 type Error = ActixError;
4023 type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
4024
4025 actix_web::dev::forward_ready!(service);
4026
4027 fn call(&self, req: ServiceRequest) -> Self::Future {
4028 let method = req.method().as_str().to_string();
4031 let path = req.path().to_string();
4032
4033 let fut = self.service.call(req);
4034 Box::pin(async move {
4035 let response = fut.await?;
4036 let status = response.status();
4037 if status.is_server_error() {
4038 log_5xx(&method, &path, status, response.response().error());
4039 }
4040 Ok(response)
4041 })
4042 }
4043}
4044
4045fn log_5xx(method: &str, path: &str, status: StatusCode, error: Option<&actix_web::Error>) {
4049 let chain = match error {
4053 Some(e) => format_error_chain(e),
4054 None => "<no error attached to response>".to_string(),
4055 };
4056
4057 let backtrace = if std::env::var("RUST_BACKTRACE").ok().as_deref() == Some("1") {
4058 Some(std::backtrace::Backtrace::force_capture().to_string())
4059 } else {
4060 None
4061 };
4062
4063 tracing::error!(
4064 target: "solid_pod_rs_server::http",
4065 method = %method,
4066 path = %path,
4067 status = %status.as_u16(),
4068 error.chain = %chain,
4069 backtrace = backtrace.as_deref().unwrap_or(""),
4070 "5xx response"
4071 );
4072}
4073
4074fn format_error_chain(e: &actix_web::Error) -> String {
4085 let summary = format!("{}", e.as_response_error());
4086 let debug = format!("{e:?}");
4087 if debug == summary || debug.is_empty() {
4088 summary
4089 } else {
4090 format!("{summary} -> {debug}")
4091 }
4092}
4093
4094pub struct DotfileGuard {
4100 allow: Arc<DotfileAllowlist>,
4101 hosts: Option<Arc<HostPolicy>>,
4102}
4103
4104pub struct HostPolicy {
4111 pub allowed: Vec<String>,
4113 pub trust_proxy: bool,
4115}
4116
4117impl DotfileGuard {
4118 pub fn new(allow: Arc<DotfileAllowlist>) -> Self {
4119 Self { allow, hosts: None }
4120 }
4121
4122 pub fn with_host_policy(mut self, policy: HostPolicy) -> Self {
4124 if !policy.allowed.is_empty() {
4125 self.hosts = Some(Arc::new(policy));
4126 }
4127 self
4128 }
4129}
4130
4131impl<S, B> Transform<S, ServiceRequest> for DotfileGuard
4132where
4133 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
4134 B: 'static,
4135{
4136 type Response = ServiceResponse<EitherBody<B, BoxBody>>;
4137 type Error = ActixError;
4138 type InitError = ();
4139 type Transform = DotfileGuardMiddleware<S>;
4140 type Future = Ready<Result<Self::Transform, Self::InitError>>;
4141
4142 fn new_transform(&self, service: S) -> Self::Future {
4143 ready(Ok(DotfileGuardMiddleware {
4144 service,
4145 allow: self.allow.clone(),
4146 hosts: self.hosts.clone(),
4147 }))
4148 }
4149}
4150
4151pub struct DotfileGuardMiddleware<S> {
4153 service: S,
4154 allow: Arc<DotfileAllowlist>,
4155 hosts: Option<Arc<HostPolicy>>,
4156}
4157
4158impl<S, B> Service<ServiceRequest> for DotfileGuardMiddleware<S>
4159where
4160 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
4161 B: 'static,
4162{
4163 type Response = ServiceResponse<EitherBody<B, BoxBody>>;
4164 type Error = ActixError;
4165 type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
4166
4167 actix_web::dev::forward_ready!(service);
4168
4169 fn call(&self, req: ServiceRequest) -> Self::Future {
4170 if let Some(p) = &self.hosts {
4171 let host = scheme::host_with(req.request(), None, p.trust_proxy);
4172 if !scheme::host_allowed(&host, &p.allowed) {
4173 let rsp = HttpResponse::build(actix_web::http::StatusCode::MISDIRECTED_REQUEST)
4174 .body("host not served here");
4175 let sr = req.into_response(rsp.map_into_boxed_body());
4176 return Box::pin(async move { Ok(sr.map_into_right_body()) });
4177 }
4178 }
4179 let path = req.path().to_string();
4180 let allow_system_route =
4187 path.starts_with("/.well-known/") || path == "/.pods" || path.starts_with("/pay/");
4188 if !allow_system_route {
4189 let pb = PathBuf::from(&path);
4190 if !self.allow.is_allowed(Path::new(&pb)) {
4191 let rsp = HttpResponse::Forbidden().body("dotfile path denied by allowlist");
4192 let sr = req.into_response(rsp.map_into_boxed_body());
4193 return Box::pin(async move { Ok(sr.map_into_right_body()) });
4194 }
4195 }
4196 let fut = self.service.call(req);
4197 Box::pin(async move {
4198 let resp = fut.await?;
4199 Ok(resp.map_into_left_body())
4200 })
4201 }
4202}
4203
4204#[cfg(feature = "git")]
4209pub(crate) fn pod_repo_path(state: &AppState, pubkey: &str) -> Option<PathBuf> {
4210 if pubkey.len() != 64 || !pubkey.bytes().all(|b| b.is_ascii_hexdigit()) {
4211 return None;
4212 }
4213 state.data_root.as_ref().map(|root| root.join(pubkey))
4214}
4215
4216#[cfg(feature = "git")]
4246async fn git_mark_write(
4247 state: &AppState,
4248 resource_path: &str,
4249 agent: Option<&str>,
4250 message: &str,
4251) -> ProvenanceReceipt {
4252 use solid_pod_rs::provenance::{prov_ttl, AnchorPolicy, ProvenanceLog};
4253 use solid_pod_rs_git::mark::ShellGitMarker;
4254
4255 if resource_path.ends_with(".acl")
4258 || resource_path.ends_with(".meta")
4259 || resource_path.ends_with(".prov.ttl")
4260 {
4261 return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::ExcludedPath);
4262 }
4263 if resource_path.ends_with('/') {
4265 return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::Container);
4266 }
4267
4268 let Some(data_root) = state.data_root.as_ref() else {
4270 return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::NotConfigured);
4271 };
4272
4273 let trimmed = resource_path.trim_start_matches('/');
4275 let mut segments = trimmed.splitn(2, '/');
4276 let pod = segments.next().unwrap_or("");
4277 let rel = segments.next().unwrap_or("");
4278 if pod.is_empty() || rel.is_empty() {
4279 return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::UnresolvablePath);
4280 }
4281 let repo = data_root.join(pod);
4282
4283 if !repo.join(".git").is_dir() {
4287 return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::NotGitBacked);
4288 }
4289
4290 let agent_did = agent.unwrap_or("urn:solid:anonymous");
4291 let created = std::time::SystemTime::now()
4292 .duration_since(std::time::UNIX_EPOCH)
4293 .map(|d| d.as_secs())
4294 .unwrap_or(0);
4295
4296 let (policy, ticker_override) =
4299 handlers::prov::resolve_anchor_policy(state, resource_path).await;
4300
4301 let marker = std::sync::Arc::new(ShellGitMarker::new());
4306 let anchorer_bundle = if matches!(policy, AnchorPolicy::Never) {
4307 None
4308 } else {
4309 handlers::prov::build_anchorer(state, ticker_override.as_deref()).await
4310 };
4311 let (log, ticker, network) = match &anchorer_bundle {
4312 Some((anchorer, ticker, network)) => (
4313 ProvenanceLog::with_anchorer(marker.clone(), anchorer.clone()),
4314 ticker.clone(),
4315 network.clone(),
4316 ),
4317 None => (
4319 ProvenanceLog::new(marker.clone()),
4320 String::new(),
4321 String::new(),
4322 ),
4323 };
4324
4325 let record_policy = match policy {
4329 AnchorPolicy::Epoch => AnchorPolicy::Never,
4330 other => other,
4331 };
4332 let high_value = matches!(policy, AnchorPolicy::HighValue) && anchorer_bundle.is_some();
4333
4334 let write_record = solid_pod_rs::provenance::WriteRecord {
4338 repo: &repo,
4339 path: rel,
4340 agent_did,
4341 message,
4342 policy: record_policy,
4343 high_value,
4344 ticker: &ticker,
4345 network: &network,
4346 created,
4347 };
4348 let mut receipt = log.record_receipt(write_record).await;
4353 receipt.resource = resource_path.to_string();
4356
4357 let Some(git) = receipt.mark.clone() else {
4358 tracing::warn!(
4362 target: "solid_pod_rs_server::git_mark",
4363 resource = %resource_path,
4364 "provenance record failed (write already succeeded): {}",
4365 receipt.mark_error.as_deref().unwrap_or("unspecified")
4366 );
4367 return receipt;
4368 };
4369 if let Some(err) = &receipt.anchor_error {
4370 tracing::warn!(
4373 target: "solid_pod_rs_server::git_mark",
4374 resource = %resource_path,
4375 commit = %git.commit_sha,
4376 "block-trail anchor failed (git-mark stands): {err}"
4377 );
4378 }
4379 let mark = solid_pod_rs::provenance::ProvenanceMark {
4380 resource: resource_path.to_string(),
4381 git: git.clone(),
4382 anchor: receipt.anchor.clone(),
4383 agent_did: agent_did.to_string(),
4384 created,
4385 };
4386
4387 if matches!(policy, AnchorPolicy::Epoch) {
4391 if let Some((anchorer, _, _)) = &anchorer_bundle {
4392 match handlers::prov::epoch_push_and_maybe_anchor(
4393 state,
4394 anchorer,
4395 &ticker,
4396 &network,
4397 &mark.git.commit_sha,
4398 )
4399 .await
4400 {
4401 Ok(Some(closed)) => tracing::debug!(
4402 target: "solid_pod_rs_server::git_mark",
4403 root = %closed.root,
4404 n = closed.commits.len(),
4405 "epoch anchored (one tx notarises {} commits)", closed.commits.len()
4406 ),
4407 Ok(None) => {}
4408 Err(e) => tracing::warn!(
4409 target: "solid_pod_rs_server::git_mark",
4410 "epoch batch/anchor failed (swallowed): {e}"
4411 ),
4412 }
4413 }
4414 }
4415
4416 let ttl = prov_ttl(&mark);
4421 let sidecar = format!("{resource_path}.prov.ttl");
4422 if let Err(e) = state
4423 .storage
4424 .put(&sidecar, Bytes::from(ttl.into_bytes()), "text/turtle")
4425 .await
4426 {
4427 tracing::warn!(
4428 target: "solid_pod_rs_server::git_mark",
4429 sidecar = %sidecar,
4430 "provenance sidecar write failed: {e}"
4431 );
4432 receipt.mark_error = Some(format!("PROV-O sidecar write failed: {e}"));
4435 return receipt;
4436 }
4437
4438 tracing::debug!(
4439 target: "solid_pod_rs_server::git_mark",
4440 resource = %resource_path,
4441 commit = %mark.git.commit_sha,
4442 stage = %receipt.stage(),
4443 "provenance recorded"
4444 );
4445 receipt
4446}
4447
4448#[cfg(not(feature = "git"))]
4451#[inline]
4452async fn git_mark_write(
4453 _state: &AppState,
4454 resource_path: &str,
4455 _agent: Option<&str>,
4456 _message: &str,
4457) -> ProvenanceReceipt {
4458 ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::NotConfigured)
4459}
4460
4461#[cfg(feature = "git")]
4462pub(crate) async fn require_pod_owner(req: &HttpRequest, pod_pubkey: &str) -> Option<String> {
4463 require_pod_owner_with_body(req, pod_pubkey, None).await
4464}
4465
4466#[cfg(feature = "git")]
4467pub(crate) async fn require_pod_owner_with_body(
4468 req: &HttpRequest,
4469 pod_pubkey: &str,
4470 body: Option<&[u8]>,
4471) -> Option<String> {
4472 let caller = extract_pubkey_with_body(req, body).await?;
4473 if caller != pod_pubkey {
4474 return None;
4475 }
4476 Some(caller)
4477}
4478
4479#[cfg(feature = "git")]
4480fn git_json_err(msg: &str, status: u16) -> HttpResponse {
4481 HttpResponse::build(StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR))
4482 .content_type("application/json")
4483 .body(format!(r#"{{"error":"{}"}}"#, msg.replace('"', "\\\"")))
4484}
4485
4486#[cfg(feature = "git")]
4488#[derive(serde::Deserialize)]
4489struct GitStageBody {
4490 paths: Option<Vec<String>>,
4491 all: Option<bool>,
4492}
4493
4494#[cfg(feature = "git")]
4495#[derive(serde::Deserialize)]
4496struct GitCommitBody {
4497 message: String,
4498 author_name: Option<String>,
4499 author_email: Option<String>,
4500}
4501
4502#[cfg(feature = "git")]
4503#[derive(serde::Deserialize)]
4504struct GitBranchBody {
4505 name: String,
4506}
4507
4508#[cfg(feature = "git")]
4511async fn handle_git_status(
4512 path: web::Path<String>,
4513 req: HttpRequest,
4514 state: web::Data<AppState>,
4515) -> HttpResponse {
4516 let pubkey = path.into_inner();
4517 if require_pod_owner(&req, &pubkey).await.is_none() {
4518 return git_json_err("Authentication required", 401);
4519 }
4520 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4521 return git_json_err("Git not available (no FS backend)", 501);
4522 };
4523 match solid_pod_rs_git::api::git_status(&repo).await {
4524 Ok(s) => HttpResponse::Ok()
4525 .content_type("application/json")
4526 .body(serde_json::to_string(&s).unwrap_or_default()),
4527 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4528 }
4529}
4530
4531#[cfg(feature = "git")]
4532async fn handle_git_log(
4533 path: web::Path<String>,
4534 req: HttpRequest,
4535 state: web::Data<AppState>,
4536 query: web::Query<std::collections::HashMap<String, String>>,
4537) -> HttpResponse {
4538 let pubkey = path.into_inner();
4539 if require_pod_owner(&req, &pubkey).await.is_none() {
4540 return git_json_err("Authentication required", 401);
4541 }
4542 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4543 return git_json_err("Git not available (no FS backend)", 501);
4544 };
4545 let limit: u32 = query
4546 .get("limit")
4547 .and_then(|v| v.parse().ok())
4548 .unwrap_or(20);
4549 match solid_pod_rs_git::api::git_log(&repo, limit).await {
4550 Ok(entries) => HttpResponse::Ok()
4551 .content_type("application/json")
4552 .body(serde_json::to_string(&entries).unwrap_or_default()),
4553 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4554 }
4555}
4556
4557#[cfg(feature = "git")]
4558async fn handle_git_diff(
4559 path: web::Path<String>,
4560 req: HttpRequest,
4561 state: web::Data<AppState>,
4562 query: web::Query<std::collections::HashMap<String, String>>,
4563) -> HttpResponse {
4564 let pubkey = path.into_inner();
4565 if require_pod_owner(&req, &pubkey).await.is_none() {
4566 return git_json_err("Authentication required", 401);
4567 }
4568 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4569 return git_json_err("Git not available (no FS backend)", 501);
4570 };
4571 let file_path = query.get("path").map(String::as_str);
4572 let staged = query
4573 .get("staged")
4574 .map(|v| v == "true" || v == "1")
4575 .unwrap_or(false);
4576 match solid_pod_rs_git::api::git_diff(&repo, file_path, staged).await {
4577 Ok(diff) => HttpResponse::Ok().content_type("text/plain").body(diff),
4578 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4579 }
4580}
4581
4582#[cfg(feature = "git")]
4583async fn handle_git_stage(
4584 path: web::Path<String>,
4585 req: HttpRequest,
4586 state: web::Data<AppState>,
4587 body: web::Bytes,
4588) -> HttpResponse {
4589 let pubkey = path.into_inner();
4590 if require_pod_owner(&req, &pubkey).await.is_none() {
4591 return git_json_err("Authentication required", 401);
4592 }
4593 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4594 return git_json_err("Git not available (no FS backend)", 501);
4595 };
4596 let parsed: GitStageBody = match serde_json::from_slice(&body) {
4597 Ok(v) => v,
4598 Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4599 };
4600 let paths = parsed.paths.unwrap_or_default();
4601 let all = parsed.all.unwrap_or(false);
4602 match solid_pod_rs_git::api::git_add(&repo, &paths, all).await {
4603 Ok(()) => HttpResponse::Ok()
4604 .content_type("application/json")
4605 .body(r#"{"ok":true}"#),
4606 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4607 }
4608}
4609
4610#[cfg(feature = "git")]
4611async fn handle_git_unstage(
4612 path: web::Path<String>,
4613 req: HttpRequest,
4614 state: web::Data<AppState>,
4615 body: web::Bytes,
4616) -> HttpResponse {
4617 let pubkey = path.into_inner();
4618 if require_pod_owner(&req, &pubkey).await.is_none() {
4619 return git_json_err("Authentication required", 401);
4620 }
4621 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4622 return git_json_err("Git not available (no FS backend)", 501);
4623 };
4624 let parsed: GitStageBody = match serde_json::from_slice(&body) {
4625 Ok(v) => v,
4626 Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4627 };
4628 let paths = parsed.paths.unwrap_or_default();
4629 let all = parsed.all.unwrap_or(false);
4630 match solid_pod_rs_git::api::git_unstage(&repo, &paths, all).await {
4631 Ok(()) => HttpResponse::Ok()
4632 .content_type("application/json")
4633 .body(r#"{"ok":true}"#),
4634 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4635 }
4636}
4637
4638#[cfg(feature = "git")]
4639async fn handle_git_commit(
4640 path: web::Path<String>,
4641 req: HttpRequest,
4642 state: web::Data<AppState>,
4643 body: web::Bytes,
4644) -> HttpResponse {
4645 let pubkey = path.into_inner();
4646 if require_pod_owner(&req, &pubkey).await.is_none() {
4647 return git_json_err("Authentication required", 401);
4648 }
4649 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4650 return git_json_err("Git not available (no FS backend)", 501);
4651 };
4652 let parsed: GitCommitBody = match serde_json::from_slice(&body) {
4653 Ok(v) => v,
4654 Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4655 };
4656 let author_name = parsed.author_name.as_deref().unwrap_or("Pod Owner");
4657 let author_email = parsed
4658 .author_email
4659 .as_deref()
4660 .unwrap_or("pod@dreamlab-ai.com");
4661 match solid_pod_rs_git::api::git_commit(&repo, &parsed.message, author_name, author_email).await
4662 {
4663 Ok(result) => HttpResponse::Ok()
4664 .content_type("application/json")
4665 .body(serde_json::to_string(&result).unwrap_or_default()),
4666 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4667 }
4668}
4669
4670#[cfg(feature = "git")]
4671async fn handle_git_branches(
4672 path: web::Path<String>,
4673 req: HttpRequest,
4674 state: web::Data<AppState>,
4675) -> HttpResponse {
4676 let pubkey = path.into_inner();
4677 if require_pod_owner(&req, &pubkey).await.is_none() {
4678 return git_json_err("Authentication required", 401);
4679 }
4680 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4681 return git_json_err("Git not available (no FS backend)", 501);
4682 };
4683 match solid_pod_rs_git::api::git_branches(&repo).await {
4684 Ok(info) => HttpResponse::Ok()
4685 .content_type("application/json")
4686 .body(serde_json::to_string(&info).unwrap_or_default()),
4687 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4688 }
4689}
4690
4691#[cfg(feature = "git")]
4692async fn handle_git_create_branch(
4693 path: web::Path<String>,
4694 req: HttpRequest,
4695 state: web::Data<AppState>,
4696 body: web::Bytes,
4697) -> HttpResponse {
4698 let pubkey = path.into_inner();
4699 if require_pod_owner(&req, &pubkey).await.is_none() {
4700 return git_json_err("Authentication required", 401);
4701 }
4702 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4703 return git_json_err("Git not available (no FS backend)", 501);
4704 };
4705 let parsed: GitBranchBody = match serde_json::from_slice(&body) {
4706 Ok(v) => v,
4707 Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4708 };
4709 match solid_pod_rs_git::api::git_create_branch(&repo, &parsed.name).await {
4710 Ok(()) => HttpResponse::Ok()
4711 .content_type("application/json")
4712 .body(r#"{"ok":true}"#),
4713 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4714 }
4715}
4716
4717#[cfg(feature = "git")]
4718async fn handle_git_discard(
4719 path: web::Path<String>,
4720 req: HttpRequest,
4721 state: web::Data<AppState>,
4722 body: web::Bytes,
4723) -> HttpResponse {
4724 let pubkey = path.into_inner();
4725 if require_pod_owner(&req, &pubkey).await.is_none() {
4726 return git_json_err("Authentication required", 401);
4727 }
4728 let Some(repo) = pod_repo_path(&state, &pubkey) else {
4729 return git_json_err("Git not available (no FS backend)", 501);
4730 };
4731 let parsed: GitStageBody = match serde_json::from_slice(&body) {
4732 Ok(v) => v,
4733 Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4734 };
4735 let paths = parsed.paths.unwrap_or_default();
4736 match solid_pod_rs_git::api::git_discard(&repo, &paths).await {
4737 Ok(()) => HttpResponse::Ok()
4738 .content_type("application/json")
4739 .body(r#"{"ok":true}"#),
4740 Err(e) => git_json_err(&e.to_string(), e.status_code()),
4741 }
4742}
4743
4744async fn handle_git_panel_options(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
4752 let origin = req
4753 .headers()
4754 .get(header::ORIGIN)
4755 .and_then(|v| v.to_str().ok())
4756 .map(str::to_string);
4757
4758 let mut rsp = HttpResponse::NoContent().finish();
4759 add_cors_headers(rsp.headers_mut(), origin.as_deref(), &state.allowed_origins);
4760 rsp
4761}
4762
4763async fn handle_admin_provision(
4780 req: HttpRequest,
4781 state: web::Data<AppState>,
4782 path: web::Path<String>,
4783) -> HttpResponse {
4784 let expected = match &state.admin_key {
4786 Some(k) => k.clone(),
4787 None => {
4788 return HttpResponse::Forbidden().json(serde_json::json!({
4789 "error": "admin key not configured on this server"
4790 }));
4791 }
4792 };
4793 let provided = req
4794 .headers()
4795 .get("x-pod-admin-key")
4796 .and_then(|v| v.to_str().ok())
4797 .unwrap_or("");
4798 use subtle::ConstantTimeEq;
4803 let key_match = provided.as_bytes().ct_eq(expected.as_bytes());
4804 if !bool::from(key_match) {
4805 return HttpResponse::Forbidden().json(serde_json::json!({"error": "invalid admin key"}));
4806 }
4807
4808 let pubkey = path.into_inner();
4810 if pubkey.len() != 64 || !pubkey.chars().all(|c| c.is_ascii_hexdigit()) {
4811 return HttpResponse::BadRequest()
4812 .json(serde_json::json!({"error": "pubkey must be 64 lowercase hex characters"}));
4813 }
4814
4815 let data_root = match &state.data_root {
4817 Some(r) => r.clone(),
4818 None => {
4819 return HttpResponse::InternalServerError().json(serde_json::json!({
4820 "error": "server has no fs-backend storage configured"
4821 }));
4822 }
4823 };
4824
4825 let pods_root = data_root.join("pods");
4838 let pod_dir = pods_root.join(&pubkey);
4839
4840 if let Err(e) = tokio::fs::create_dir_all(&pod_dir).await {
4842 tracing::error!(pubkey = %pubkey, error = %e, "/_admin/provision: create_dir_all failed");
4843 return HttpResponse::InternalServerError()
4844 .json(serde_json::json!({"error": format!("failed to create pod directory: {e}")}));
4845 }
4846
4847 let acl_content = format!(
4857 "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
4858 <#owner> a acl:Authorization ;\n\
4859 acl:agent <did:nostr:{pubkey}> ;\n\
4860 acl:accessTo </pods/{pubkey}/> ;\n\
4861 acl:default </pods/{pubkey}/> ;\n\
4862 acl:mode acl:Read, acl:Write, acl:Control .\n"
4863 );
4864
4865 let sibling_acl_path = pods_root.join(format!("{pubkey}.acl"));
4875 if !sibling_acl_path.exists() {
4876 if let Err(e) = tokio::fs::write(&sibling_acl_path, acl_content.as_bytes()).await {
4877 tracing::error!(pubkey = %pubkey, error = %e, "/_admin/provision: write sibling .acl failed");
4878 return HttpResponse::InternalServerError()
4879 .json(serde_json::json!({"error": format!("failed to write .acl: {e}")}));
4880 }
4881 }
4882
4883 let inner_acl_path = pod_dir.join(".acl");
4890 if !inner_acl_path.exists() {
4891 if let Err(e) = tokio::fs::write(&inner_acl_path, acl_content.as_bytes()).await {
4892 tracing::warn!(pubkey = %pubkey, error = %e, "/_admin/provision: write inner .acl failed (non-fatal; sibling ACL governs)");
4893 }
4894 }
4895
4896 #[cfg(feature = "git")]
4898 {
4899 if !pod_dir.join(".git").exists() {
4901 let init_out = crate::hardened_git::hardened_git_async()
4902 .args(["init", "-b", "main", pod_dir.to_str().unwrap_or(".")])
4903 .output()
4904 .await;
4905
4906 match init_out {
4907 Ok(out) if out.status.success() => {}
4908 Ok(out) => {
4909 let stderr = String::from_utf8_lossy(&out.stderr);
4910 tracing::warn!(pubkey = %pubkey, stderr = %stderr, "git init returned non-zero");
4911 }
4912 Err(e) => {
4913 tracing::warn!(pubkey = %pubkey, error = %e, "git init failed (git not in PATH?)");
4914 }
4915 }
4916
4917 let cfg_out = crate::hardened_git::hardened_git_async()
4920 .args([
4921 "-C",
4922 pod_dir.to_str().unwrap_or("."),
4923 "config",
4924 "receive.denyCurrentBranch",
4925 "updateInstead",
4926 ])
4927 .output()
4928 .await;
4929
4930 if let Err(e) = cfg_out {
4931 tracing::warn!(pubkey = %pubkey, error = %e, "git config receive.denyCurrentBranch failed");
4932 }
4933 }
4934 }
4935
4936 let base_url = state.nodeinfo.base_url.trim_end_matches('/');
4938 HttpResponse::Ok().json(serde_json::json!({
4939 "podUrl": format!("{base_url}/pods/{pubkey}/"),
4940 "ok": true,
4941 }))
4942}
4943
4944async fn handle_well_known_apps(state: web::Data<AppState>) -> HttpResponse {
4949 let Some(ref data_root) = state.data_root else {
4950 return HttpResponse::Ok()
4951 .content_type("application/json")
4952 .json(serde_json::json!({"apps": [], "count": 0}));
4953 };
4954
4955 let server_url = state.nodeinfo.base_url.clone();
4956
4957 let mut read_dir = match tokio::fs::read_dir(data_root).await {
4959 Ok(rd) => rd,
4960 Err(_) => {
4961 return HttpResponse::Ok()
4962 .content_type("application/json")
4963 .json(serde_json::json!({"apps": [], "serverUrl": server_url, "count": 0}));
4964 }
4965 };
4966
4967 let mut apps: Vec<serde_json::Value> = Vec::new();
4968 let mut scanned = 0usize;
4969
4970 while scanned < 1000 {
4971 let entry = match read_dir.next_entry().await {
4972 Ok(Some(e)) => e,
4973 Ok(None) => break,
4974 Err(_) => break,
4975 };
4976
4977 let file_type = match entry.file_type().await {
4978 Ok(ft) => ft,
4979 Err(_) => continue,
4980 };
4981 if !file_type.is_dir() {
4982 continue;
4983 }
4984
4985 scanned += 1;
4986
4987 let manifest_path = entry.path().join("apps").join("manifest.json");
4988 let contents = match tokio::fs::read(&manifest_path).await {
4989 Ok(c) => c,
4990 Err(_) => continue,
4991 };
4992
4993 let mut manifest: serde_json::Value = match serde_json::from_slice(&contents) {
4994 Ok(v) => v,
4995 Err(_) => continue,
4996 };
4997
4998 if let Some(pod_name) = entry.file_name().to_str() {
5000 if manifest.get("podOwner").is_none() {
5001 manifest["podOwner"] = serde_json::Value::String(pod_name.to_string());
5002 }
5003 }
5004
5005 apps.push(manifest);
5006 }
5007
5008 let count = apps.len();
5009 HttpResponse::Ok()
5010 .content_type("application/json")
5011 .json(serde_json::json!({
5012 "apps": apps,
5013 "serverUrl": server_url,
5014 "count": count,
5015 }))
5016}
5017
5018#[allow(dead_code)]
5031fn is_git_request(path: &str) -> bool {
5032 path.contains("/info/refs")
5033 || path.contains("/git-upload-pack")
5034 || path.contains("/git-receive-pack")
5035}
5036
5037#[allow(dead_code)]
5040fn is_dot_git_path(path: &str) -> bool {
5041 path.contains("/.git/") || path.ends_with("/.git")
5042}
5043
5044#[cfg(feature = "git")]
5045async fn handle_git(
5046 req: HttpRequest,
5047 body: web::Bytes,
5048 state: web::Data<AppState>,
5049) -> HttpResponse {
5050 use solid_pod_rs_git::auth::{BasicNostrExtractor, GitAuth};
5051 use solid_pod_rs_git::service::GitRequest;
5052
5053 let path = req.uri().path().to_string();
5054
5055 let pod_name = path
5058 .trim_start_matches('/')
5059 .split('/')
5060 .next()
5061 .unwrap_or("")
5062 .to_string();
5063 let Some(ref data_root) = state.data_root else {
5064 return HttpResponse::NotImplemented().json(serde_json::json!({
5065 "error": "git requires fs-backend storage",
5066 "reason": "data_root_not_configured"
5067 }));
5068 };
5069 let repo_root = data_root.join(&pod_name);
5070 if !repo_root.exists() {
5071 return HttpResponse::NotFound().json(serde_json::json!({"error": "pod not found"}));
5072 }
5073
5074 let query = req.uri().query().unwrap_or("").to_string();
5075 let host_url = Some(scheme::request_origin(&req));
5076 let headers: Vec<(String, String)> = req
5077 .headers()
5078 .iter()
5079 .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
5080 .collect();
5081
5082 let git_req = GitRequest {
5083 method: req.method().as_str().to_string(),
5084 path,
5085 query,
5086 headers,
5087 body,
5088 host_url,
5089 };
5090
5091 if git_req.is_write() {
5097 let mut builder = HttpResponse::Forbidden();
5098 for (k, v) in solid_pod_rs_git::service::GIT_CORS_HEADERS {
5099 builder.insert_header((k, v));
5100 }
5101 return builder.json(serde_json::json!({
5102 "error": "git push is not served by this server",
5103 "reason": "push_not_served"
5104 }));
5105 }
5106
5107 let agent = match BasicNostrExtractor::new().authorise(&git_req).await {
5118 Ok(pk) => Some(format!("did:nostr:{pk}")),
5119 Err(_) => None,
5120 };
5121 let wac_path = format!("/{pod_name}/");
5122 let origin = req_origin(&req);
5123 let wac = enforce_read_ctx(&state, &wac_path, agent.as_deref(), origin)
5127 .await
5128 .map(|_audience| ());
5129 if let Err(e) = wac {
5130 let mut resp = e.error_response();
5134 for (k, v) in solid_pod_rs_git::service::GIT_CORS_HEADERS {
5135 if let (Ok(name), Ok(value)) = (
5136 actix_web::http::header::HeaderName::from_bytes(k.as_bytes()),
5137 actix_web::http::header::HeaderValue::from_str(v),
5138 ) {
5139 resp.headers_mut().insert(name, value);
5140 }
5141 }
5142 return resp;
5143 }
5144
5145 if agent.as_deref() != Some(format!("did:nostr:{pod_name}").as_str()) {
5150 let mut response = HttpResponse::Forbidden();
5151 for (k, v) in solid_pod_rs_git::service::GIT_CORS_HEADERS {
5152 response.insert_header((k, v));
5153 }
5154 return response.json(serde_json::json!({
5155 "error": "whole-history export requires the pod owner",
5156 "reason": "history_export_owner_required"
5157 }));
5158 }
5159 let service = solid_pod_rs_git::service::GitHttpService::new(data_root.clone());
5161 match service.handle(git_req).await {
5162 Ok(git_resp) => {
5163 let mut builder = HttpResponse::build(
5164 actix_web::http::StatusCode::from_u16(git_resp.status)
5165 .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR),
5166 );
5167 for (k, v) in &git_resp.headers {
5168 builder.insert_header((k.as_str(), v.as_str()));
5169 }
5170 builder.body(git_resp.body)
5171 }
5172 Err(e) => {
5173 let status = e.status_code();
5174 let mut builder = HttpResponse::build(
5175 actix_web::http::StatusCode::from_u16(status)
5176 .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR),
5177 );
5178 for (k, v) in solid_pod_rs_git::service::GIT_CORS_HEADERS {
5179 builder.insert_header((k, v));
5180 }
5181 builder.json(serde_json::json!({"error": e.to_string()}))
5182 }
5183 }
5184}
5185
5186#[cfg(feature = "forge")]
5195fn forge_plugin_dir(state: &AppState) -> Option<PathBuf> {
5196 state.data_root.as_ref().map(|r| r.join(".forge"))
5197}
5198
5199#[cfg(feature = "forge")]
5205struct ServerLoopback {
5206 client: reqwest::Client,
5207}
5208
5209#[cfg(feature = "forge")]
5210#[async_trait::async_trait]
5211impl solid_pod_rs_forge::LoopbackFetch for ServerLoopback {
5212 async fn get(
5213 &self,
5214 url: &str,
5215 max_bytes: usize,
5216 timeout_secs: u64,
5217 ) -> solid_pod_rs_forge::bodies::FetchResult {
5218 use solid_pod_rs_forge::bodies::FetchResult;
5219 let resp = match self
5220 .client
5221 .get(url)
5222 .timeout(Duration::from_secs(timeout_secs.max(1)))
5223 .send()
5224 .await
5225 {
5226 Ok(r) => r,
5227 Err(e) => return FetchResult::Error(e.to_string()),
5228 };
5229 let code = resp.status().as_u16();
5230 if code == 404 || code == 410 {
5231 return FetchResult::Removed;
5232 }
5233 if !resp.status().is_success() {
5234 return FetchResult::Error(format!("status {code}"));
5235 }
5236 if resp
5237 .content_length()
5238 .is_some_and(|length| length > max_bytes as u64)
5239 {
5240 return FetchResult::TooLarge;
5241 }
5242 let mut stream = resp.bytes_stream();
5243 let mut body = Vec::with_capacity(max_bytes.min(16 * 1024));
5244 while let Some(chunk) = stream.next().await {
5245 match chunk {
5246 Ok(chunk) if body.len().saturating_add(chunk.len()) <= max_bytes => {
5247 body.extend_from_slice(&chunk);
5248 }
5249 Ok(_) => return FetchResult::TooLarge,
5250 Err(error) => return FetchResult::Error(error.to_string()),
5251 }
5252 }
5253 FetchResult::Body(body)
5254 }
5255}
5256
5257#[cfg(feature = "forge")]
5259fn env_list(name: &str) -> Vec<String> {
5260 std::env::var(name)
5261 .ok()
5262 .map(|v| {
5263 v.split(',')
5264 .map(str::trim)
5265 .filter(|s| !s.is_empty())
5266 .map(str::to_string)
5267 .collect()
5268 })
5269 .unwrap_or_default()
5270}
5271
5272#[cfg(feature = "forge")]
5277fn forge_config() -> solid_pod_rs_forge::ForgeConfig {
5278 use serde_json::{json, Map, Value};
5279 let mut o = Map::new();
5280 let flag = |n: &str| {
5281 std::env::var(n)
5282 .ok()
5283 .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
5284 };
5285 if let Some(b) = flag("FORGE_PRIVATE_REPOS") {
5286 o.insert("privateRepos".into(), json!(b));
5287 }
5288 if let Some(b) = flag("FORGE_ALLOW_MAINNET") {
5289 o.insert("allowMainnet".into(), json!(b));
5290 }
5291 if let Some(b) = flag("FORGE_OPEN_EDIT") {
5292 o.insert("openEdit".into(), json!(b));
5293 }
5294 if let Some(b) = flag("FORGE_ANCHORING_UI") {
5295 o.insert("anchoringUi".into(), json!(b));
5296 }
5297 if let Some(b) = flag("FORGE_SPARSE_MARKS") {
5298 o.insert("sparseMarks".into(), json!(b));
5299 }
5300 if let Ok(c) = std::env::var("FORGE_CHAIN") {
5301 if !c.trim().is_empty() {
5302 o.insert("chain".into(), Value::String(c.trim().to_string()));
5303 }
5304 }
5305 if let Ok(u) = std::env::var("FORGE_BASE_URL") {
5306 if !u.trim().is_empty() {
5307 o.insert("baseUrl".into(), Value::String(u.trim().to_string()));
5308 }
5309 }
5310 let relays = env_list("FORGE_ANNOUNCE_RELAYS");
5311 if !relays.is_empty() {
5312 o.insert("announceRelays".into(), json!(relays));
5313 }
5314 solid_pod_rs_forge::ForgeConfig::from_env(Value::Object(o))
5315}
5316
5317#[cfg(feature = "forge-mirror")]
5322fn mirror_config() -> Option<solid_pod_rs_forge::mirror::MirrorConfig> {
5323 use serde_json::json;
5324 let relays = env_list("FORGE_MIRROR_RELAYS");
5325 let follow: Vec<serde_json::Value> = env_list("FORGE_MIRROR_FOLLOW")
5326 .iter()
5327 .filter_map(|e| e.split_once('/'))
5328 .map(|(pk, name)| json!({"pubkey": pk.trim(), "name": name.trim()}))
5329 .collect();
5330 let mut cfg = json!({"relays": relays, "follow": follow});
5331 if let Some(ms) = std::env::var("FORGE_MIRROR_MIN_INTERVAL_MS")
5332 .ok()
5333 .and_then(|v| v.trim().parse::<u64>().ok())
5334 {
5335 cfg["minIntervalMs"] = json!(ms);
5336 }
5337 solid_pod_rs_forge::mirror::parse_mirror_config(&cfg)
5338}
5339
5340#[cfg(feature = "forge")]
5342struct ForgeRuntime {
5343 service: Arc<solid_pod_rs_forge::ForgeService>,
5344 #[cfg(feature = "forge-mirror")]
5345 _mirror: Option<solid_pod_rs_forge::mirror::MirrorHandle>,
5346}
5347
5348#[cfg(feature = "forge")]
5352fn forge_service(
5353 plugin_dir: PathBuf,
5354) -> Result<Arc<solid_pod_rs_forge::ForgeService>, solid_pod_rs_forge::ForgeError> {
5355 use std::collections::HashMap;
5356 use std::sync::{Mutex, OnceLock};
5357 static REGISTRY: OnceLock<Mutex<HashMap<PathBuf, Arc<ForgeRuntime>>>> = OnceLock::new();
5358 let reg = REGISTRY.get_or_init(|| Mutex::new(HashMap::new()));
5359 let mut reg = reg
5360 .lock()
5361 .unwrap_or_else(std::sync::PoisonError::into_inner);
5362 if let Some(rt) = reg.get(&plugin_dir) {
5363 return Ok(Arc::clone(&rt.service));
5364 }
5365 let cfg = forge_config();
5366 #[cfg(feature = "forge-announce")]
5367 let relay_policy: Arc<dyn solid_pod_rs_forge::publish::SsrfCheck> = Arc::new(
5368 solid_pod_rs_forge::publish::OperatorRelays::new(&cfg.announce_relays),
5369 );
5370 let loopback: Arc<dyn solid_pod_rs_forge::LoopbackFetch> = Arc::new(ServerLoopback {
5371 client: reqwest::Client::new(),
5372 });
5373 let svc =
5374 solid_pod_rs_forge::ForgeService::new(cfg, plugin_dir.clone())?.with_loopback(loopback);
5375 #[cfg(feature = "forge-announce")]
5376 let svc = svc.with_announce_ssrf(relay_policy);
5377 let service = Arc::new(svc);
5378 #[cfg(feature = "forge-mirror")]
5379 let mirror = mirror_config().map(|mcfg| {
5380 use solid_pod_rs_forge::mirror::{GitCli, Mirror, MirrorStore};
5381 let git = Arc::new(GitCli::new(plugin_dir.join("repos")));
5382 let engine = Arc::new(Mirror::new(mcfg, MirrorStore::new(&plugin_dir), git));
5383 tracing::info!("forge: mirror on kind-30618 started");
5384 engine.start()
5385 });
5386 reg.insert(
5387 plugin_dir,
5388 Arc::new(ForgeRuntime {
5389 service: Arc::clone(&service),
5390 #[cfg(feature = "forge-mirror")]
5391 _mirror: mirror,
5392 }),
5393 );
5394 Ok(service)
5395}
5396
5397#[cfg(feature = "forge")]
5401pub fn start_forge(state: &AppState) {
5402 if let Some(dir) = forge_plugin_dir(state) {
5403 match forge_service(dir) {
5404 Ok(_) => tracing::info!("forge: started"),
5405 Err(e) => tracing::error!("forge: could not start: {e}"),
5406 }
5407 }
5408}
5409
5410#[cfg(feature = "forge")]
5416async fn handle_forge(
5417 req: HttpRequest,
5418 body: web::Bytes,
5419 state: web::Data<AppState>,
5420) -> HttpResponse {
5421 use solid_pod_rs_forge::ForgeRequest;
5422
5423 let Some(plugin_dir) = forge_plugin_dir(&state) else {
5424 return HttpResponse::NotImplemented().json(serde_json::json!({
5425 "error": "forge requires fs-backend storage",
5426 "reason": "data_root_not_configured"
5427 }));
5428 };
5429
5430 let service = match web::block(move || forge_service(plugin_dir)).await {
5434 Ok(Ok(s)) => s,
5435 Ok(Err(e)) => {
5436 return HttpResponse::InternalServerError()
5437 .json(serde_json::json!({"error": e.to_string()}));
5438 }
5439 Err(e) => {
5440 return HttpResponse::InternalServerError()
5441 .json(serde_json::json!({"error": e.to_string()}));
5442 }
5443 };
5444
5445 let path = req.uri().path().to_string();
5446 let query = req.uri().query().unwrap_or("").to_string();
5447 let host_url = Some(scheme::request_origin(&req));
5448 let headers: Vec<(String, String)> = req
5449 .headers()
5450 .iter()
5451 .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
5452 .collect();
5453
5454 let forge_req = ForgeRequest {
5455 method: req.method().as_str().to_string(),
5456 path,
5457 query,
5458 headers,
5459 raw_body: body,
5460 host_url,
5461 };
5462
5463 let agent = service.resolve_agent(&forge_req).await;
5468
5469 #[cfg(feature = "jev")]
5471 let jev_ctx = (
5472 forge_req.method.clone(),
5473 forge_req.path.clone(),
5474 forge_req.query.clone(),
5475 );
5476
5477 match service.handle(forge_req, agent).await {
5478 Ok(resp) => {
5479 let mut builder = HttpResponse::build(
5480 StatusCode::from_u16(resp.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
5481 );
5482 for (k, v) in &resp.headers {
5483 #[cfg(feature = "jev")]
5485 if k.eq_ignore_ascii_case("content-length") {
5486 continue;
5487 }
5488 builder.insert_header((k.as_str(), v.as_str()));
5489 }
5490 #[cfg(feature = "jev")]
5494 if jev::enabled_in_process_env() {
5495 let rt = jev::JevRuntime::from_process_env();
5496 if let Some(body) = jev::rerank_forge_listing(
5497 &rt,
5498 &jev_ctx.0,
5499 &jev_ctx.1,
5500 &jev_ctx.2,
5501 resp.status,
5502 &resp.body,
5503 )
5504 .await
5505 {
5506 return builder.body(body);
5507 }
5508 }
5509 builder.body(resp.body)
5510 }
5511 Err(e) => {
5512 let status = e.status_code();
5513 HttpResponse::build(
5514 StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
5515 )
5516 .json(serde_json::json!({"error": e.to_string()}))
5517 }
5518 }
5519}
5520
5521pub fn build_app(
5533 state: AppState,
5534) -> App<
5535 impl actix_web::dev::ServiceFactory<
5536 ServiceRequest,
5537 Config = (),
5538 Response = ServiceResponse<EitherBody<EitherBody<BoxBody>>>,
5539 Error = ActixError,
5540 InitError = (),
5541 >,
5542> {
5543 let body_cap = state.body_cap;
5544 let dotfiles = state.dotfiles.clone();
5545 let allowed_origins = Arc::new(state.allowed_origins.clone());
5546 let allowed_hosts = state.allowed_hosts.clone();
5547
5548 let mut app = App::new()
5549 .app_data(web::Data::new(state.clone()))
5550 .app_data(web::PayloadConfig::new(body_cap))
5551 .wrap(ErrorLoggingMiddleware)
5556 .wrap(CorsHeaders { allowed_origins })
5557 .wrap(NormalizePath::new(TrailingSlash::MergeOnly))
5561 .wrap(PathTraversalGuard)
5562 .wrap(DotfileGuard::new(dotfiles).with_host_policy(HostPolicy {
5563 allowed: allowed_hosts,
5564 trust_proxy: state.trust_proxy,
5565 }));
5566
5567 app = app
5573 .route("/.well-known/solid", web::get().to(handle_well_known_solid))
5574 .route(
5575 "/.well-known/webfinger",
5576 web::get().to(handle_well_known_webfinger),
5577 )
5578 .route(
5579 "/.well-known/nodeinfo",
5580 web::get().to(handle_well_known_nodeinfo),
5581 )
5582 .route(
5583 "/.well-known/nodeinfo/2.1",
5584 web::get().to(handle_well_known_nodeinfo_2_1),
5585 );
5586
5587 #[cfg(feature = "did-nostr")]
5588 {
5589 app = app.route(
5590 "/.well-known/did/nostr/{pubkey}.json",
5591 web::get().to(handle_well_known_did_nostr),
5592 );
5593 }
5594
5595 #[cfg(feature = "nip05-endpoint")]
5600 {
5601 app = app.route(
5602 "/.well-known/nostr.json",
5603 web::get().to(handle_well_known_nip05),
5604 );
5605 }
5606
5607 #[cfg(feature = "export-jsonld")]
5612 {
5613 app = app.route("/api/exports/all", web::get().to(handle_export_all));
5614 }
5615
5616 app = app.route("/.well-known/apps", web::get().to(handle_well_known_apps));
5618
5619 app = app.route("/pay/.info", web::get().to(handle_pay_info));
5621
5622 app = app.configure(handlers::pay::register);
5627
5628 app = app.route("/proxy", web::get().to(handle_proxy));
5630
5631 if state.mcp_enabled {
5635 app = app.route("/mcp", web::post().to(mcp::handle_mcp)).route(
5636 "/mcp",
5637 web::method(actix_web::http::Method::OPTIONS).to(mcp::handle_mcp_options),
5638 );
5639 }
5640
5641 app = app.route(
5644 "/_admin/provision/{pubkey}",
5645 web::post().to(handle_admin_provision),
5646 );
5647
5648 app = app
5650 .route("/.pods", web::post().to(handle_create_pod))
5651 .route("/api/accounts/new", web::post().to(handle_create_account))
5652 .route("/pods/check/{name}", web::get().to(handle_pod_check))
5653 .route("/login/password", web::post().to(handle_login_password))
5654 .route(
5655 "/account/password/reset",
5656 web::post().to(handle_password_reset_request),
5657 )
5658 .route(
5659 "/account/password/change",
5660 web::post().to(handle_password_change),
5661 );
5662
5663 #[cfg(feature = "forge")]
5668 {
5669 app = app
5670 .route("/forge", web::route().to(handle_forge))
5671 .route("/forge/{tail:.*}", web::route().to(handle_forge));
5672 }
5673
5674 app = app
5679 .route(
5680 "/{tail:.*}/.git",
5682 web::route().to(|| async {
5683 HttpResponse::Forbidden()
5684 .json(serde_json::json!({"error": "direct .git access is forbidden"}))
5685 }),
5686 )
5687 .route(
5688 "/{tail:.*}/.git/{rest:.*}",
5689 web::route().to(|| async {
5690 HttpResponse::Forbidden()
5691 .json(serde_json::json!({"error": "direct .git access is forbidden"}))
5692 }),
5693 );
5694
5695 app = app.route(
5699 "/pods/{pk}/_git/{tail:.*}",
5700 web::method(actix_web::http::Method::OPTIONS).to(handle_git_panel_options),
5701 );
5702
5703 #[cfg(feature = "git")]
5704 {
5705 app = app
5712 .route("/{tail:.*}/info/refs", web::get().to(handle_git))
5713 .route("/{tail:.*}/git-upload-pack", web::post().to(handle_git))
5714 .route("/{tail:.*}/git-receive-pack", web::post().to(handle_git));
5715
5716 app = app
5719 .route(
5720 "/pods/{pubkey}/_git/status",
5721 web::get().to(handle_git_status),
5722 )
5723 .route("/pods/{pubkey}/_git/log", web::get().to(handle_git_log))
5724 .route("/pods/{pubkey}/_git/diff", web::get().to(handle_git_diff))
5725 .route(
5726 "/pods/{pubkey}/_git/stage",
5727 web::post().to(handle_git_stage),
5728 )
5729 .route(
5730 "/pods/{pubkey}/_git/unstage",
5731 web::post().to(handle_git_unstage),
5732 )
5733 .route(
5734 "/pods/{pubkey}/_git/commit",
5735 web::post().to(handle_git_commit),
5736 )
5737 .route(
5738 "/pods/{pubkey}/_git/branches",
5739 web::get().to(handle_git_branches),
5740 )
5741 .route(
5742 "/pods/{pubkey}/_git/branch",
5743 web::post().to(handle_git_create_branch),
5744 )
5745 .route(
5746 "/pods/{pubkey}/_git/discard",
5747 web::post().to(handle_git_discard),
5748 );
5749
5750 app = app.configure(handlers::prov::register);
5757 }
5758 #[cfg(not(feature = "git"))]
5759 {
5760 let git_501 = || async {
5764 HttpResponse::NotImplemented()
5765 .json(serde_json::json!({"error": "git feature not enabled in this build"}))
5766 };
5767 app = app
5768 .route("/{tail:.*}/info/refs", web::get().to(git_501))
5769 .route("/{tail:.*}/git-upload-pack", web::post().to(git_501))
5770 .route("/{tail:.*}/git-receive-pack", web::post().to(git_501));
5771 }
5772
5773 app.route("/{tail:.*}/", web::post().to(handle_post))
5776 .route("/{tail:.*}/", web::put().to(handle_put))
5777 .route("/{tail:.*}", web::get().to(handle_get))
5778 .route("/{tail:.*}", web::head().to(handle_get))
5779 .route("/{tail:.*}", web::put().to(handle_put))
5780 .route("/{tail:.*}", web::patch().to(handle_patch))
5781 .route("/{tail:.*}", web::delete().to(handle_delete))
5782 .route(
5783 "/{tail:.*}",
5784 web::method(actix_web::http::Method::from_bytes(b"COPY").unwrap()).to(handle_copy),
5785 )
5786 .route(
5787 "/{tail:.*}",
5788 web::method(actix_web::http::Method::OPTIONS).to(handle_options),
5789 )
5790}
5791
5792#[cfg(test)]
5797mod payment_gating_tests {
5798 use super::*;
5799 use solid_pod_rs::payments::WebLedger;
5800 use solid_pod_rs::storage::memory::MemoryBackend;
5801
5802 macro_rules! principal {
5806 () => {
5807 "did:nostr:4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa"
5808 };
5809 }
5810
5811 const PRINCIPAL: &str = principal!();
5812
5813 const OTHER_PRINCIPAL: &str =
5815 "did:nostr:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
5816
5817 const PAID_WRITE_ACL: &str = concat!(
5820 r#"
5821@prefix acl: <http://www.w3.org/ns/auth/acl#> .
5822
5823<#paid-write> a acl:Authorization ;
5824 acl:agent <"#,
5825 principal!(),
5826 r#"> ;
5827 acl:accessTo </premium/inbox> ;
5828 acl:mode acl:Write ;
5829 acl:condition [
5830 a acl:PaymentCondition ;
5831 acl:costSats 100
5832 ] .
5833"#
5834 );
5835
5836 async fn seed_ledger(storage: &dyn Storage, did: &str, sats: u64) {
5837 let mut ledger = WebLedger::new("Test Pod Credits");
5838 if sats > 0 {
5839 ledger
5840 .credit_by_outpoint(did, "satoshi", &"ab".repeat(32), 0, sats)
5841 .unwrap();
5842 }
5843 let body = serde_json::to_vec(&ledger).unwrap();
5844 storage
5845 .put(WEBLEDGER_PATH, Bytes::from(body), "application/json")
5846 .await
5847 .unwrap();
5848 }
5849
5850 async fn seed_acl(storage: &dyn Storage) {
5851 storage
5852 .put(
5853 "/premium/inbox.acl",
5854 Bytes::from(PAID_WRITE_ACL),
5855 "text/turtle",
5856 )
5857 .await
5858 .unwrap();
5859 }
5860
5861 #[actix_web::test]
5863 async fn resolve_balance_reads_ledger_entry() {
5864 let storage = MemoryBackend::new();
5865 seed_ledger(&storage, PRINCIPAL, 250).await;
5866 assert_eq!(
5867 resolve_balance_sats(&storage, Some(PRINCIPAL)).await,
5868 Some(250)
5869 );
5870 }
5871
5872 #[actix_web::test]
5873 async fn wac_balance_uses_authoritative_state_after_a_stale_mirror() {
5874 use solid_pod_rs::payments::PaymentStore;
5875 let storage = MemoryBackend::new();
5876 seed_ledger(&storage, PRINCIPAL, 250).await;
5877 let ledger = WebLedger::new("empty canonical balance");
5878 handlers::pay::StoragePaymentStore::new(&storage)
5879 .write_ledger(&ledger)
5880 .await
5881 .unwrap();
5882 seed_ledger(&storage, PRINCIPAL, 250).await;
5883 assert_eq!(
5884 resolve_balance_sats(&storage, Some(PRINCIPAL)).await,
5885 Some(0)
5886 );
5887 }
5888
5889 #[actix_web::test]
5891 async fn resolve_balance_zero_when_no_entry() {
5892 let storage = MemoryBackend::new();
5893 seed_ledger(&storage, OTHER_PRINCIPAL, 500).await;
5894 assert_eq!(
5895 resolve_balance_sats(&storage, Some(PRINCIPAL)).await,
5896 Some(0)
5897 );
5898 }
5899
5900 #[test]
5906 fn fixtures_use_teller_accounts_and_grant_the_principal() {
5907 use solid_pod_rs::payments::account_of;
5908 for did in [PRINCIPAL, OTHER_PRINCIPAL] {
5909 assert_eq!(account_of(did).unwrap(), did, "{did} must be canonical");
5910 }
5911 assert_ne!(PRINCIPAL, OTHER_PRINCIPAL);
5912 assert!(account_of("did:nostr:bob").is_err());
5913 let agent = format!("acl:agent <{PRINCIPAL}>");
5914 for (name, acl) in [
5915 ("PAID_WRITE_ACL", PAID_WRITE_ACL),
5916 ("WRITE_NOT_CONTROL_ACL", WRITE_NOT_CONTROL_ACL),
5917 ] {
5918 assert!(acl.contains(&agent), "{name} must grant PRINCIPAL");
5919 }
5920 assert!(!WRITE_NOT_CONTROL_ACL.contains("did:nostr:alice"));
5921 }
5922
5923 #[actix_web::test]
5926 async fn uncharged_read_skips_pay_per_read_resource() {
5927 let storage = Arc::new(MemoryBackend::new());
5928 let acl = format!(
5929 "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
5930 <#paid> a acl:Authorization ; acl:agent <{PRINCIPAL}> ;\n\
5931 acl:accessTo </premium/doc> ; acl:mode acl:Read ;\n\
5932 acl:condition [ a acl:PaymentCondition ; acl:costSats 100 ] .\n"
5933 );
5934 storage
5935 .put("/premium/doc.acl", Bytes::from(acl), "text/turtle")
5936 .await
5937 .unwrap();
5938 seed_ledger(storage.as_ref(), PRINCIPAL, 500).await;
5939 let state = AppState::new(storage.clone());
5940
5941 let skipped =
5942 enforce_read_inner(&state, "/premium/doc", Some(PRINCIPAL), None, false).await;
5943 assert!(skipped.is_err(), "glob must not serve a pay-per-read child");
5944 assert_eq!(
5945 resolve_balance_sats(&*storage, Some(PRINCIPAL)).await,
5946 Some(500)
5947 );
5948
5949 enforce_read_ctx(&state, "/premium/doc", Some(PRINCIPAL), None)
5950 .await
5951 .expect("a direct read pays and is served");
5952 assert_eq!(
5953 resolve_balance_sats(&*storage, Some(PRINCIPAL)).await,
5954 Some(400)
5955 );
5956 }
5957
5958 #[actix_web::test]
5960 async fn resolve_balance_none_when_anonymous() {
5961 let storage = MemoryBackend::new();
5962 seed_ledger(&storage, PRINCIPAL, 1_000).await;
5963 assert_eq!(resolve_balance_sats(&storage, None).await, None);
5964 }
5965
5966 #[actix_web::test]
5968 async fn paid_write_denied_below_balance() {
5969 let storage = Arc::new(MemoryBackend::new());
5970 seed_acl(storage.as_ref()).await;
5971 seed_ledger(storage.as_ref(), PRINCIPAL, 50).await; let state = AppState::new(storage);
5973
5974 let result =
5975 enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
5976 assert!(
5977 result.is_err(),
5978 "balance 50 < cost 100 must be denied — sat-gating loop closed"
5979 );
5980 }
5981
5982 #[actix_web::test]
5984 async fn paid_write_allowed_at_balance() {
5985 let storage = Arc::new(MemoryBackend::new());
5986 seed_acl(storage.as_ref()).await;
5987 seed_ledger(storage.as_ref(), PRINCIPAL, 100).await; let state = AppState::new(storage);
5989
5990 let result =
5991 enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
5992 assert!(
5993 result.is_ok(),
5994 "balance 100 >= cost 100 must be granted — sat-gating loop closed"
5995 );
5996 }
5997
5998 #[actix_web::test]
6000 async fn paid_write_allowed_above_balance() {
6001 let storage = Arc::new(MemoryBackend::new());
6002 seed_acl(storage.as_ref()).await;
6003 seed_ledger(storage.as_ref(), PRINCIPAL, 5_000).await;
6004 let state = AppState::new(storage);
6005
6006 let result =
6007 enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
6008 assert!(result.is_ok(), "balance 5000 >= cost 100 must be granted");
6009 }
6010
6011 #[actix_web::test]
6015 async fn paid_write_anonymous_denied() {
6016 let storage = Arc::new(MemoryBackend::new());
6017 seed_acl(storage.as_ref()).await;
6018 seed_ledger(storage.as_ref(), PRINCIPAL, 5_000).await;
6019 let state = AppState::new(storage);
6020
6021 let result = enforce_write(&state, "/premium/inbox", AccessMode::Write, None).await;
6022 assert!(
6023 result.is_err(),
6024 "anonymous caller has no ledger principal — PaymentCondition fails closed"
6025 );
6026 }
6027
6028 async fn read_balance(storage: &dyn Storage, did: &str) -> u64 {
6035 use solid_pod_rs::payments::PaymentStore;
6036 let ledger = handlers::pay::StoragePaymentStore::new(storage)
6037 .read_ledger()
6038 .await
6039 .unwrap();
6040 ledger.get_balance(did)
6041 }
6042
6043 #[actix_web::test]
6045 async fn paid_write_debits_ledger() {
6046 let storage = Arc::new(MemoryBackend::new());
6047 seed_acl(storage.as_ref()).await;
6048 seed_ledger(storage.as_ref(), PRINCIPAL, 250).await; let state = AppState::new(storage.clone());
6050
6051 let result =
6052 enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
6053 assert!(result.is_ok(), "balance 250 >= cost 100 must be granted");
6054 assert_eq!(
6055 read_balance(storage.as_ref(), PRINCIPAL).await,
6056 150,
6057 "250 - 100 cost: the grant must debit exactly the matched rule's cost"
6058 );
6059 }
6060
6061 #[actix_web::test]
6064 async fn paid_write_debits_each_grant() {
6065 let storage = Arc::new(MemoryBackend::new());
6066 seed_acl(storage.as_ref()).await;
6067 seed_ledger(storage.as_ref(), PRINCIPAL, 250).await;
6068 use solid_pod_rs::payments::PaymentStore;
6071 let store = handlers::pay::StoragePaymentStore::new(storage.as_ref());
6072 let ledger = store.read_ledger().await.unwrap();
6073 store.write_ledger(&ledger).await.unwrap();
6074 let state = AppState::new(storage.clone());
6075
6076 enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL))
6077 .await
6078 .unwrap();
6079 enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL))
6080 .await
6081 .unwrap();
6082 assert_eq!(
6083 read_balance(storage.as_ref(), PRINCIPAL).await,
6084 50,
6085 "250 - 2*100: each granted request debits, no unmetered re-use"
6086 );
6087
6088 let third =
6090 enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
6091 assert!(third.is_err(), "balance 50 < cost 100 must now be denied");
6092 assert_eq!(
6093 read_balance(storage.as_ref(), PRINCIPAL).await,
6094 50,
6095 "a denied request must not debit"
6096 );
6097 }
6098
6099 #[actix_web::test]
6101 async fn paid_read_debits_ledger() {
6102 const PAID_READ_ACL: &str = r#"
6103@prefix acl: <http://www.w3.org/ns/auth/acl#> .
6104
6105<#paid-read> a acl:Authorization ;
6106 acl:agent <did:nostr:4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa> ;
6107 acl:accessTo </premium/feed> ;
6108 acl:mode acl:Read ;
6109 acl:condition [
6110 a acl:PaymentCondition ;
6111 acl:costSats 30
6112 ] .
6113"#;
6114 let storage = Arc::new(MemoryBackend::new());
6115 storage
6116 .put(
6117 "/premium/feed.acl",
6118 Bytes::from(PAID_READ_ACL),
6119 "text/turtle",
6120 )
6121 .await
6122 .unwrap();
6123 seed_ledger(storage.as_ref(), PRINCIPAL, 100).await;
6124 let state = AppState::new(storage.clone());
6125
6126 let result = enforce_read(&state, "/premium/feed", Some(PRINCIPAL)).await;
6127 assert!(result.is_ok(), "balance 100 >= cost 30 must be granted");
6128 assert_eq!(
6129 read_balance(storage.as_ref(), PRINCIPAL).await,
6130 70,
6131 "100 - 30 cost: a granted paid read must debit"
6132 );
6133 }
6134
6135 #[actix_web::test]
6138 async fn free_read_does_not_debit() {
6139 let storage = Arc::new(MemoryBackend::new());
6140 seed_private_read_acl(storage.as_ref()).await; seed_ledger(storage.as_ref(), PRINCIPAL, 100).await;
6142 let state = AppState::new(storage.clone());
6143
6144 enforce_read(&state, "/private/secret", Some(PRINCIPAL))
6145 .await
6146 .unwrap();
6147 assert_eq!(
6148 read_balance(storage.as_ref(), PRINCIPAL).await,
6149 100,
6150 "a grant with no PaymentCondition must not debit"
6151 );
6152 }
6153
6154 const ALICE_ONLY_READ_ACL: &str = r#"
6160@prefix acl: <http://www.w3.org/ns/auth/acl#> .
6161
6162<#alice> a acl:Authorization ;
6163 acl:agent <did:nostr:4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa> ;
6164 acl:accessTo </private/secret> ;
6165 acl:default </private/> ;
6166 acl:mode acl:Read, acl:Write, acl:Control .
6167"#;
6168
6169 async fn seed_private_read_acl(storage: &dyn Storage) {
6170 storage
6175 .put(
6176 "/private.acl",
6177 Bytes::from(ALICE_ONLY_READ_ACL),
6178 "text/turtle",
6179 )
6180 .await
6181 .unwrap();
6182 }
6183
6184 #[actix_web::test]
6188 async fn enforce_read_grants_owner() {
6189 let storage = Arc::new(MemoryBackend::new());
6190 seed_private_read_acl(storage.as_ref()).await;
6191 let state = AppState::new(storage);
6192 let result = enforce_read(&state, "/private/secret", Some(PRINCIPAL)).await;
6193 assert!(result.is_ok(), "owner alice must be granted Read");
6194 }
6195
6196 #[actix_web::test]
6199 async fn enforce_read_denies_other_principal() {
6200 let storage = Arc::new(MemoryBackend::new());
6201 seed_private_read_acl(storage.as_ref()).await;
6202 let state = AppState::new(storage);
6203 let result = enforce_read(&state, "/private/secret", Some("did:nostr:bob")).await;
6204 assert!(
6205 result.is_err(),
6206 "bob has no Read grant — private resource must not be world-readable"
6207 );
6208 }
6209
6210 #[actix_web::test]
6213 async fn enforce_read_denies_anonymous() {
6214 let storage = Arc::new(MemoryBackend::new());
6215 seed_private_read_acl(storage.as_ref()).await;
6216 let state = AppState::new(storage);
6217 let result = enforce_read(&state, "/private/secret", None).await;
6218 assert!(result.is_err(), "anonymous Read must be denied");
6219 }
6220
6221 const WRITE_NOT_CONTROL_ACL: &str = concat!(
6229 r#"
6230@prefix acl: <http://www.w3.org/ns/auth/acl#> .
6231
6232<#owner> a acl:Authorization ;
6233 acl:agent <"#,
6234 principal!(),
6235 r#"> ;
6236 acl:accessTo </shared/doc> ;
6237 acl:default </shared/> ;
6238 acl:mode acl:Read, acl:Write, acl:Control .
6239
6240<#writer> a acl:Authorization ;
6241 acl:agent <did:nostr:writer> ;
6242 acl:accessTo </shared/doc> ;
6243 acl:default </shared/> ;
6244 acl:mode acl:Read, acl:Write .
6245"#
6246 );
6247
6248 async fn seed_shared_acl(storage: &dyn Storage) {
6249 storage
6254 .put(
6255 "/shared.acl",
6256 Bytes::from(WRITE_NOT_CONTROL_ACL),
6257 "text/turtle",
6258 )
6259 .await
6260 .unwrap();
6261 }
6262
6263 #[actix_web::test]
6267 async fn acl_put_denied_for_writer_without_control() {
6268 let storage = Arc::new(MemoryBackend::new());
6269 seed_shared_acl(storage.as_ref()).await;
6270 let state = AppState::new(storage);
6271 let result = enforce_write(
6275 &state,
6276 "/shared/.acl",
6277 AccessMode::Write,
6278 Some("did:nostr:writer"),
6279 )
6280 .await;
6281 assert!(
6282 result.is_err(),
6283 "writer lacks Control — must not be able to PUT /shared/.acl"
6284 );
6285 }
6286
6287 #[actix_web::test]
6289 async fn acl_put_allowed_for_control_holder() {
6290 let storage = Arc::new(MemoryBackend::new());
6291 seed_shared_acl(storage.as_ref()).await;
6292 let state = AppState::new(storage);
6293 let result =
6294 enforce_write(&state, "/shared/.acl", AccessMode::Write, Some(PRINCIPAL)).await;
6295 assert!(
6296 result.is_ok(),
6297 "the owner holds Control — must be allowed to PUT /shared/.acl"
6298 );
6299 }
6300
6301 #[actix_web::test]
6303 async fn meta_put_denied_for_writer_without_control() {
6304 let storage = Arc::new(MemoryBackend::new());
6305 seed_shared_acl(storage.as_ref()).await;
6306 let state = AppState::new(storage);
6307 let result = enforce_write(
6308 &state,
6309 "/shared/doc.meta",
6310 AccessMode::Write,
6311 Some("did:nostr:writer"),
6312 )
6313 .await;
6314 assert!(
6315 result.is_err(),
6316 "writer lacks Control — must not be able to PUT a .meta sidecar"
6317 );
6318 }
6319
6320 #[test]
6323 fn canonical_pod_path_vectors() {
6324 let ok = [
6325 ("a/b", "/a/b"),
6326 ("", "/"),
6327 ("/", "/"),
6328 ("//a//b/", "/a/b/"),
6329 ("/%2ewell-known/x", "/.well-known/x"),
6330 ("/a%2fb", "/a/b"),
6331 ("/a%2520b", "/a%20b"),
6332 ];
6333 for (raw, want) in ok {
6334 assert_eq!(canonical_pod_path(raw).as_deref(), Some(want), "{raw}");
6335 }
6336 for bad in [
6337 "/a/./b",
6338 "/a/..",
6339 "../a",
6340 "/a\\b",
6341 "/a%00b",
6342 "/a%ffb",
6343 "/%2e%2e/x",
6344 ] {
6345 assert_eq!(canonical_pod_path(bad), None, "{bad}");
6346 }
6347 }
6348
6349 #[test]
6350 fn guarded_acl_target_vectors() {
6351 use AccessMode::{Control, Read, Write};
6352 let c = |p: &str, m| guarded_acl_target(p, m);
6353 assert_eq!(
6354 c("/.well-known/token/x.json", Read),
6355 ("/.well-known/token/x.json".into(), Control)
6356 );
6357 assert_eq!(
6358 c("/.well-known/gitmark/p.json", Write),
6359 ("/.well-known/gitmark/p.json".into(), Control)
6360 );
6361 assert_eq!(c("/.well-known/%74oken/x.json", Read).1, Control);
6362 assert_eq!(
6363 c("/.well-known/token/x.json.acl", Read),
6364 ("/.well-known/token/x.json".into(), Control)
6365 );
6366 assert_eq!(
6367 c("/.well-known/gitmark/p/blocktrails.json", Read),
6368 ("/.well-known/gitmark/p/blocktrails.json".into(), Read)
6369 );
6370 assert_eq!(
6371 c("/.well-known/webledgers/webledgers.json", Write),
6372 ("/.well-known/webledgers/webledgers.json".into(), Control)
6373 );
6374 assert_eq!(c("/.well-known/%57ebledgers/state.json", Read).1, Control);
6375 assert_eq!(c("/.well-known/webledgersx/y", Read).1, Read);
6376 assert_eq!(c("/pub/x", Read), ("/pub/x".into(), Read));
6377 }
6378
6379 #[test]
6381 fn protected_resource_for_acl_strips_suffixes() {
6382 assert_eq!(
6383 protected_resource_for_acl("/victim/.acl").as_deref(),
6384 Some("/victim/")
6385 );
6386 assert_eq!(
6387 protected_resource_for_acl("/a/b.acl").as_deref(),
6388 Some("/a/b")
6389 );
6390 assert_eq!(protected_resource_for_acl("/.acl").as_deref(), Some("/"));
6391 assert_eq!(
6392 protected_resource_for_acl("/a/b.meta").as_deref(),
6393 Some("/a/b")
6394 );
6395 assert_eq!(protected_resource_for_acl("/a/b").as_deref(), None);
6396 }
6397}
6398
6399#[cfg(all(test, feature = "forge-mirror"))]
6400mod forge_env_tests {
6401 use super::*;
6402
6403 #[test]
6405 fn mirror_config_comes_from_the_environment() {
6406 let pk = "ab".repeat(32);
6407 std::env::remove_var("FORGE_MIRROR_RELAYS");
6408 std::env::remove_var("FORGE_MIRROR_FOLLOW");
6409 assert!(mirror_config().is_none(), "nothing configured: mirror off");
6410
6411 std::env::set_var(
6412 "FORGE_MIRROR_RELAYS",
6413 "ws://127.0.0.1:7777, wss://r.example , nope",
6414 );
6415 assert!(mirror_config().is_none(), "relays alone follow nothing");
6416
6417 std::env::set_var(
6418 "FORGE_MIRROR_FOLLOW",
6419 format!("{pk}/agent, bad/entry, {pk}/../x"),
6420 );
6421 std::env::set_var("FORGE_MIRROR_MIN_INTERVAL_MS", "1000");
6422 let cfg = mirror_config().expect("one relay and one valid entry");
6423 assert_eq!(cfg.relays, ["ws://127.0.0.1:7777", "wss://r.example"]);
6424 assert_eq!(cfg.follow.len(), 1);
6425 assert_eq!(cfg.follow[0].name, "agent");
6426 assert_eq!(cfg.min_interval_ms, 1000);
6427
6428 std::env::remove_var("FORGE_MIRROR_RELAYS");
6429 std::env::remove_var("FORGE_MIRROR_FOLLOW");
6430 std::env::remove_var("FORGE_MIRROR_MIN_INTERVAL_MS");
6431 }
6432
6433 #[test]
6434 fn the_forge_service_is_built_once_per_data_directory() {
6435 let td = tempfile::tempdir().unwrap();
6436 let a = forge_service(td.path().join(".forge")).unwrap();
6437 let b = forge_service(td.path().join(".forge")).unwrap();
6438 assert!(Arc::ptr_eq(&a, &b));
6439 let other = tempfile::tempdir().unwrap();
6440 let c = forge_service(other.path().join(".forge")).unwrap();
6441 assert!(!Arc::ptr_eq(&a, &c));
6442 }
6443}