gitpoulpi_hosting/trust/
guard.rs1use std::sync::Arc;
10
11use crate::http::{HttpRequest, HttpResponse, HttpTransport, Progress};
12use crate::{Error, Result};
13
14use super::store::TlsRecord;
15use super::{origin, report, TrustProblem, TrustSubject};
16
17pub struct GuardedTransport {
18 inner: Arc<dyn HttpTransport>,
19 subject: TrustSubject,
20 recorded: String,
22 allowed: Vec<String>,
24 tls: Option<TlsRecord>,
26}
27
28impl GuardedTransport {
29 pub fn new(
30 inner: Arc<dyn HttpTransport>,
31 subject: TrustSubject,
32 recorded: String,
33 allowed: Vec<String>,
34 tls: Option<TlsRecord>,
35 ) -> Self {
36 Self {
37 inner,
38 subject,
39 recorded,
40 allowed,
41 tls,
42 }
43 }
44
45 fn check(&self, url: &str) -> Result<()> {
46 match origin::origin_of(url) {
47 Some(o) if self.allowed.contains(&o) => Ok(()),
48 other => {
49 let problem = TrustProblem::OriginChanged {
50 subject: self.subject.clone(),
51 old: self.recorded.clone(),
52 new: other.unwrap_or_else(|| url.to_string()),
53 };
54 report(&problem);
55 Err(Error::Trust(problem))
56 }
57 }
58 }
59
60 fn bind(&self, error: Error) -> Error {
63 match error {
64 Error::Trust(problem) if matches!(problem.subject(), TrustSubject::Host(_)) => {
65 let problem = match problem {
66 TrustProblem::CertificateChanged { new, old, subject } => {
67 let old = match &self.tls {
68 Some(t) if t.cert.spki_sha256 == old.spki_sha256 => {
69 Box::new(t.cert.clone())
70 }
71 _ => old,
72 };
73 TrustProblem::CertificateChanged { subject, old, new }
74 }
75 other => other,
76 }
77 .with_subject(self.subject.clone());
78 report(&problem);
79 Error::Trust(problem)
80 }
81 other => other,
82 }
83 }
84}
85
86#[async_trait::async_trait]
87impl HttpTransport for GuardedTransport {
88 async fn send(&self, request: HttpRequest) -> Result<HttpResponse> {
89 self.check(&request.url)?;
90 self.inner.send(request).await.map_err(|e| self.bind(e))
91 }
92
93 async fn download(&self, request: HttpRequest, progress: &Progress<'_>) -> Result<Vec<u8>> {
94 self.check(&request.url)?;
95 self.inner
96 .download(request, progress)
97 .await
98 .map_err(|e| self.bind(e))
99 }
100}