1pub mod cert;
18mod forget;
19mod guard;
20pub mod origin;
21pub mod store;
22#[cfg(feature = "network")]
23pub mod tls;
24
25#[cfg(all(test, any(feature = "hosting", feature = "network")))]
26mod fixtures;
27#[cfg(feature = "hosting")]
28mod verify;
29
30use std::collections::HashMap;
31use std::path::PathBuf;
32use std::sync::Mutex;
33
34use gitpoulpi_config::{ConfigPaths, Integration};
35
36pub use self::forget::{forget, ForgetReport};
37pub use self::guard::GuardedTransport;
38pub use self::origin::{api_origins, integration_origin, is_public_saas_host, normalize};
39pub use self::store::{
40 AiRecord, CertInfo, IntegrationRecord, TlsMode, TlsRecord, TrustStore, TRUST_FILE,
41};
42#[cfg(feature = "hosting")]
43pub use self::verify::VerifyReason;
44
45use crate::{Error, Result};
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum TrustSubject {
50 Integration(String),
52 Ai(String),
54 Host(String),
57}
58
59impl TrustSubject {
60 pub fn name(&self) -> &str {
62 match self {
63 Self::Integration(s) | Self::Ai(s) | Self::Host(s) => s,
64 }
65 }
66}
67
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
70pub struct Account {
71 pub login: String,
72 pub id: String,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum TrustProblem {
79 OriginChanged {
81 subject: TrustSubject,
82 old: String,
83 new: String,
84 },
85 AccountChanged {
87 subject: TrustSubject,
88 old: Box<Account>,
89 new: Box<Account>,
90 },
91 UntrustedCertificate {
93 subject: TrustSubject,
94 new: Box<CertInfo>,
95 },
96 CertificateChanged {
98 subject: TrustSubject,
99 old: Box<CertInfo>,
100 new: Box<CertInfo>,
101 },
102 PlainHttp {
104 subject: TrustSubject,
105 origin: String,
106 },
107}
108
109impl TrustProblem {
110 pub fn subject(&self) -> &TrustSubject {
111 match self {
112 Self::OriginChanged { subject, .. }
113 | Self::AccountChanged { subject, .. }
114 | Self::UntrustedCertificate { subject, .. }
115 | Self::CertificateChanged { subject, .. }
116 | Self::PlainHttp { subject, .. } => subject,
117 }
118 }
119
120 #[must_use]
122 pub fn with_subject(mut self, new_subject: TrustSubject) -> Self {
123 match &mut self {
124 Self::OriginChanged { subject, .. }
125 | Self::AccountChanged { subject, .. }
126 | Self::UntrustedCertificate { subject, .. }
127 | Self::CertificateChanged { subject, .. }
128 | Self::PlainHttp { subject, .. } => *subject = new_subject,
129 }
130 self
131 }
132
133 pub fn change(&self) -> &'static str {
135 match self {
136 Self::OriginChanged { .. } => "origin",
137 Self::AccountChanged { .. } => "account",
138 Self::UntrustedCertificate { .. } => "untrusted_certificate",
139 Self::CertificateChanged { .. } => "certificate",
140 Self::PlainHttp { .. } => "plain_http",
141 }
142 }
143
144 pub fn old_text(&self) -> String {
146 match self {
147 Self::OriginChanged { old, .. } => old.clone(),
148 Self::AccountChanged { old, .. } => format!("{} ({})", old.login, old.id),
149 Self::CertificateChanged { old, .. } => old.spki_sha256.clone(),
150 Self::UntrustedCertificate { .. } | Self::PlainHttp { .. } => String::new(),
151 }
152 }
153
154 pub fn new_text(&self) -> String {
156 match self {
157 Self::OriginChanged { new, .. } => new.clone(),
158 Self::AccountChanged { new, .. } => new.id.clone(),
159 Self::UntrustedCertificate { new, .. } | Self::CertificateChanged { new, .. } => {
160 new.spki_sha256.clone()
161 }
162 Self::PlainHttp { origin, .. } => origin.clone(),
163 }
164 }
165
166 pub fn fix(&self) -> Vec<String> {
169 let (cmd, name) = match self.subject() {
170 TrustSubject::Ai(p) => ("gitpoulpi ai trust".to_string(), p.clone()),
171 other => (
172 "gitpoulpi hosting integrations trust".to_string(),
173 other.name().to_string(),
174 ),
175 };
176 let accept = match self {
177 Self::OriginChanged { new, .. } => format!("--accept-origin {new}"),
178 Self::AccountChanged { new, .. } => format!("--accept-account {}", new.id),
179 Self::UntrustedCertificate { new, .. } | Self::CertificateChanged { new, .. } => {
180 format!("--accept-certificate {}", new.spki_sha256)
181 }
182 Self::PlainHttp { .. } => "--allow-insecure-http on".to_string(),
183 };
184 vec![format!("{cmd} {name} {accept}")]
185 }
186}
187
188impl std::fmt::Display for TrustProblem {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190 let who = self.subject().name();
191 match self {
192 Self::OriginChanged { old, new, .. } => write!(
193 f,
194 "`{who}` now points to {new}, it was {old}: nothing was sent; \
195 review it with `gitpoulpi hosting integrations trust`"
196 ),
197 Self::AccountChanged { old, new, .. } => write!(
198 f,
199 "the token of `{who}` now belongs to {} (id {}), it was {} (id {})",
200 new.login, new.id, old.login, old.id
201 ),
202 Self::UntrustedCertificate { new, .. } => write!(
203 f,
204 "`{who}` presents a certificate that is not signed by a known authority \
205 (key {}, {})",
206 new.spki_sha256, new.subject
207 ),
208 Self::CertificateChanged { old, new, .. } => write!(
209 f,
210 "the certificate key of `{who}` changed: it was {}, it is {}",
211 old.spki_sha256, new.spki_sha256
212 ),
213 Self::PlainHttp { origin, .. } => write!(
214 f,
215 "`{who}` uses {origin}, which is not encrypted: allow it explicitly to continue"
216 ),
217 }
218 }
219}
220
221static PENDING: Mutex<Vec<TrustProblem>> = Mutex::new(Vec::new());
224
225fn pending() -> std::sync::MutexGuard<'static, Vec<TrustProblem>> {
226 PENDING.lock().unwrap_or_else(|p| p.into_inner())
227}
228
229pub fn report(problem: &TrustProblem) {
233 let mut queue = pending();
234 let same =
235 |p: &TrustProblem| p.subject() == problem.subject() && p.change() == problem.change();
236 queue.retain(|p| !same(p));
237 queue.push(problem.clone());
238}
239
240pub fn take_pending() -> Vec<TrustProblem> {
242 std::mem::take(&mut *pending())
243}
244
245pub fn peek_pending() -> Vec<TrustProblem> {
247 pending().clone()
248}
249
250pub fn clear_pending(subject: &TrustSubject) {
252 pending().retain(|p| p.subject() != subject);
253}
254
255fn unix_now() -> u64 {
256 std::time::SystemTime::now()
257 .duration_since(std::time::UNIX_EPOCH)
258 .map_or(0, |d| d.as_secs())
259}
260
261#[derive(Debug, Clone)]
266pub struct Admitted {
267 pub subject: TrustSubject,
268 pub record: IntegrationRecord,
269 pub origins: Vec<String>,
270}
271
272pub struct TrustGate {
277 file: Option<PathBuf>,
278 mem: Mutex<TrustStore>,
279 provisional: Mutex<HashMap<String, IntegrationRecord>>,
282 provisional_ai: Mutex<HashMap<String, AiRecord>>,
283 lenient: bool,
284}
285
286fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
287 m.lock().unwrap_or_else(|p| p.into_inner())
288}
289
290impl TrustGate {
291 fn new(file: Option<PathBuf>, lenient: bool) -> Self {
292 Self {
293 file,
294 mem: Mutex::new(TrustStore::default()),
295 provisional: Mutex::default(),
296 provisional_ai: Mutex::default(),
297 lenient,
298 }
299 }
300
301 pub fn load(paths: &ConfigPaths) -> Self {
303 Self::new(Some(TrustStore::file_in(paths)), false)
304 }
305
306 pub fn ambient() -> Self {
309 match ConfigPaths::discover() {
310 Some(paths) => Self::load(&paths),
311 None => Self::new(None, false),
312 }
313 }
314
315 #[cfg(any(test, feature = "test-support"))]
319 pub fn for_tests() -> Self {
320 Self::new(None, true)
321 }
322
323 #[cfg(any(test, feature = "test-support"))]
325 pub fn for_tests_in(paths: &ConfigPaths) -> Self {
326 Self::new(Some(TrustStore::file_in(paths)), true)
327 }
328
329 fn store(&self) -> Result<TrustStore> {
330 match &self.file {
331 Some(path) => TrustStore::load(path).map_err(Error::TrustStore),
332 None => Ok(lock(&self.mem).clone()),
333 }
334 }
335
336 fn save(&self, store: &TrustStore) -> Result<()> {
337 match &self.file {
338 Some(path) => store.save(path).map_err(|e| {
339 Error::TrustStore(format!("{} could not be written: {e}", path.display()))
340 }),
341 None => {
342 *lock(&self.mem) = store.clone();
343 Ok(())
344 }
345 }
346 }
347
348 fn fresh_record(&self, integration: &Integration, origin: String) -> IntegrationRecord {
350 let user = integration.user.as_ref();
351 IntegrationRecord {
352 id: integration.id.clone(),
353 origin,
354 account_id: user.map(|u| u.id.clone()).unwrap_or_default(),
355 account_login: user.map(|u| u.login.clone()).unwrap_or_default(),
356 recorded_at: unix_now(),
357 account_checked_at: 0,
358 allow_plain_http: self.lenient,
359 tls: None,
360 }
361 }
362
363 fn refuse<T>(&self, problem: TrustProblem) -> Result<T> {
364 report(&problem);
365 Err(Error::Trust(problem))
366 }
367
368 pub fn admit(&self, integration: &Integration) -> Result<Admitted> {
375 let origin = integration_origin(integration)?;
376 let subject = TrustSubject::Integration(integration.id.clone());
377 let mut store = self.store()?;
378 let record = match store.integration(&integration.id) {
379 Some(r) => r.clone(),
380 None => {
381 let record = lock(&self.provisional)
382 .get(&integration.id)
383 .cloned()
384 .unwrap_or_else(|| self.fresh_record(integration, origin.clone()));
385 if integration.user.is_some() {
386 store.put_integration(record.clone());
387 self.save(&store)?;
388 } else {
389 lock(&self.provisional).insert(integration.id.clone(), record.clone());
390 }
391 record
392 }
393 };
394 if origin::is_plain_http_remote(&origin) && !record.allow_plain_http {
395 return self.refuse(TrustProblem::PlainHttp {
396 subject,
397 origin: origin.clone(),
398 });
399 }
400 if record.origin != origin {
401 return self.refuse(TrustProblem::OriginChanged {
402 subject,
403 old: record.origin.clone(),
404 new: origin,
405 });
406 }
407 let origins = api_origins(integration.kind, &record.origin);
408 apply_tls_policy(&record.origin, record.tls.as_ref());
409 Ok(Admitted {
410 subject,
411 record,
412 origins,
413 })
414 }
415
416 pub fn adopt(&self, integration: &Integration) -> Result<()> {
420 if self.record_of(&integration.id).is_some() {
421 return Ok(());
422 }
423 self.update_record(integration, |_| ())
424 }
425
426 pub fn preflight(&self, integration: &Integration) -> Result<()> {
429 self.admit(integration).map(|_| ())
430 }
431
432 pub fn record_of(&self, id: &str) -> Option<IntegrationRecord> {
434 self.store().ok()?.integration(id).cloned()
435 }
436
437 pub fn update_record<R>(
441 &self,
442 integration: &Integration,
443 change: impl FnOnce(&mut IntegrationRecord) -> R,
444 ) -> Result<R> {
445 let origin = integration_origin(integration)?;
446 let mut store = self.store()?;
447 let mut record = match store.integration(&integration.id) {
448 Some(r) => r.clone(),
449 None => lock(&self.provisional)
450 .remove(&integration.id)
451 .unwrap_or_else(|| self.fresh_record(integration, origin)),
452 };
453 let out = change(&mut record);
454 apply_tls_policy(&record.origin, record.tls.as_ref());
455 store.put_integration(record);
456 self.save(&store)?;
457 lock(&self.provisional).remove(&integration.id);
458 clear_pending(&TrustSubject::Integration(integration.id.clone()));
459 Ok(out)
460 }
461
462 pub fn record_after_check(&self, integration: &Integration, account: &Account) -> Result<()> {
467 let origin = integration_origin(integration)?;
468 self.update_record(integration, |r| {
469 if r.origin != origin {
470 r.origin = origin;
471 }
472 r.account_id = account.id.clone();
473 r.account_login = account.login.clone();
474 r.account_checked_at = unix_now();
475 })
476 }
477
478 pub fn trust_origin(&self, integration: &Integration) -> Result<()> {
481 let origin = integration_origin(integration)?;
482 self.update_record(integration, |r| {
483 if r.origin != origin {
484 r.origin = origin;
485 r.account_id.clear();
486 r.account_login.clear();
487 r.account_checked_at = 0;
488 r.tls = None;
489 }
490 })
491 }
492
493 pub fn trust_account(&self, integration: &Integration, account: &Account) -> Result<()> {
495 self.update_record(integration, |r| {
496 r.account_id = account.id.clone();
497 r.account_login = account.login.clone();
498 r.account_checked_at = unix_now();
499 })
500 }
501
502 pub fn trust_certificate(
504 &self,
505 integration: &Integration,
506 cert: &CertInfo,
507 mode: TlsMode,
508 ) -> Result<()> {
509 self.update_record(integration, |r| {
510 r.tls = Some(TlsRecord {
511 mode,
512 cert: cert.clone(),
513 });
514 })
515 }
516
517 pub fn set_strict(&self, integration: &Integration, strict: bool) -> Result<bool> {
519 self.update_record(integration, |r| match &mut r.tls {
520 Some(tls) => {
521 tls.mode = if strict {
522 TlsMode::Strict
523 } else {
524 TlsMode::Tofu
525 };
526 true
527 }
528 None => false,
529 })
530 }
531
532 pub fn set_allow_plain_http(&self, integration: &Integration, on: bool) -> Result<()> {
533 self.update_record(integration, |r| r.allow_plain_http = on)
534 }
535
536 fn fresh_ai(&self, profile: &str, origin: String) -> AiRecord {
539 AiRecord {
540 profile: profile.to_string(),
541 origin,
542 recorded_at: unix_now(),
543 allow_plain_http: self.lenient,
544 tls: None,
545 }
546 }
547
548 pub fn admit_ai(&self, profile: &str, base_url: &str, has_key: bool) -> Result<Vec<String>> {
554 let origin = normalize(base_url).ok_or_else(|| Error::BadUrl(base_url.to_string()))?;
555 let subject = TrustSubject::Ai(profile.to_string());
556 let mut store = self.store()?;
557 let record = match store.ai_record(profile) {
558 Some(r) => r.clone(),
559 None => {
560 let record = lock(&self.provisional_ai)
561 .get(profile)
562 .cloned()
563 .unwrap_or_else(|| self.fresh_ai(profile, origin.clone()));
564 if has_key {
565 store.put_ai(record.clone());
566 self.save(&store)?;
567 } else {
568 lock(&self.provisional_ai).insert(profile.to_string(), record.clone());
569 }
570 record
571 }
572 };
573 if origin::is_plain_http_remote(&origin) && !record.allow_plain_http {
574 return self.refuse(TrustProblem::PlainHttp { subject, origin });
575 }
576 if record.origin != origin {
577 return self.refuse(TrustProblem::OriginChanged {
578 subject,
579 old: record.origin,
580 new: origin,
581 });
582 }
583 apply_tls_policy(&record.origin, record.tls.as_ref());
584 Ok(origin::origin_of(&record.origin).into_iter().collect())
585 }
586
587 pub fn ai_record_of(&self, profile: &str) -> Option<AiRecord> {
589 self.store().ok()?.ai_record(profile).cloned()
590 }
591
592 pub fn update_ai_record<R>(
595 &self,
596 profile: &str,
597 base_url: &str,
598 change: impl FnOnce(&mut AiRecord) -> R,
599 ) -> Result<R> {
600 let origin = normalize(base_url).ok_or_else(|| Error::BadUrl(base_url.to_string()))?;
601 let mut store = self.store()?;
602 let mut record = match store.ai_record(profile) {
603 Some(r) => r.clone(),
604 None => lock(&self.provisional_ai)
605 .remove(profile)
606 .unwrap_or_else(|| self.fresh_ai(profile, origin)),
607 };
608 let out = change(&mut record);
609 apply_tls_policy(&record.origin, record.tls.as_ref());
610 store.put_ai(record);
611 self.save(&store)?;
612 lock(&self.provisional_ai).remove(profile);
613 clear_pending(&TrustSubject::Ai(profile.to_string()));
614 Ok(out)
615 }
616
617 pub fn record_ai(&self, profile: &str, base_url: &str) -> Result<()> {
620 let origin = normalize(base_url).ok_or_else(|| Error::BadUrl(base_url.to_string()))?;
621 self.update_ai_record(profile, base_url, |r| r.origin = origin)
622 }
623
624 pub fn trust_ai_origin(&self, profile: &str, base_url: &str) -> Result<()> {
626 self.record_ai(profile, base_url)
627 }
628}
629
630#[cfg(feature = "network")]
632fn apply_tls_policy(origin: &str, tls: Option<&TlsRecord>) {
633 let Some(host) = origin::host_of(origin) else {
634 return;
635 };
636 tls::set_policy(
637 &host,
638 tls.map(|t| match t.mode {
639 TlsMode::Tofu => tls::TlsPolicy::Tofu {
640 spki: t.cert.spki_sha256.clone(),
641 },
642 TlsMode::Strict => tls::TlsPolicy::Strict {
643 spki: t.cert.spki_sha256.clone(),
644 },
645 }),
646 );
647}
648
649#[cfg(not(feature = "network"))]
650fn apply_tls_policy(_origin: &str, _tls: Option<&TlsRecord>) {}
651
652#[cfg(all(test, feature = "hosting"))]
653mod tests;