Skip to main content

gitpoulpi_hosting/trust/
mod.rs

1//! Integration trust: what a token (or an AI key) may be sent to.
2//!
3//! A saved token is only as safe as the address it is sent to. The trust
4//! store (`<private>/trust.toml`, [`store`]) remembers, per integration, the
5//! normalized origin it was connected to, the account the token belongs to and
6//! (for a self-hosted server whose certificate does not chain to a public
7//! root, or when asked) the certificate key. [`TrustGate`] checks every
8//! client against it *before* the client exists, and [`GuardedTransport`]
9//! checks every request against the recorded origin. A change is a
10//! [`TrustProblem`]: nothing is sent, and only a person (the CLI's
11//! `integrations trust`, the TUI's dialog) can accept it.
12//!
13//! Read `docs/architecture/session-and-state.md` "Integration trust" for the
14//! traps (one shared client with pooling off, signature delegation, why the
15//! store is not in `config.toml`).
16
17pub 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/// Whom a trust problem is about.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum TrustSubject {
50    /// A configured integration, by id.
51    Integration(String),
52    /// An API-key AI profile, by id.
53    Ai(String),
54    /// Only the host is known (raised by the transport; the guard binds the
55    /// real subject).
56    Host(String),
57}
58
59impl TrustSubject {
60    /// The id or host.
61    pub fn name(&self) -> &str {
62        match self {
63            Self::Integration(s) | Self::Ai(s) | Self::Host(s) => s,
64        }
65    }
66}
67
68/// A login and the host's own id for the account.
69#[derive(Debug, Clone, Default, PartialEq, Eq)]
70pub struct Account {
71    pub login: String,
72    pub id: String,
73}
74
75/// Why a client was not built, or a request not sent. (The larger payloads
76/// are boxed: this travels inside `Error`, which is returned everywhere.)
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum TrustProblem {
79    /// The address now differs from the recorded one.
80    OriginChanged {
81        subject: TrustSubject,
82        old: String,
83        new: String,
84    },
85    /// The token now belongs to another account.
86    AccountChanged {
87        subject: TrustSubject,
88        old: Box<Account>,
89        new: Box<Account>,
90    },
91    /// First use of a certificate that does not chain to a known root.
92    UntrustedCertificate {
93        subject: TrustSubject,
94        new: Box<CertInfo>,
95    },
96    /// The certificate key is not the recorded one.
97    CertificateChanged {
98        subject: TrustSubject,
99        old: Box<CertInfo>,
100        new: Box<CertInfo>,
101    },
102    /// A non-loopback `http://` address that was not allowed.
103    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    /// The same problem about `subject`.
121    #[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    /// The stable spelling of the kind of change (CLI JSON `change`).
134    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    /// What was trusted (empty when nothing was).
145    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    /// What is there now: the value to accept.
155    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    /// The commands that resolve it, for a script or an agent to show a
167    /// person.
168    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
221// --- the pending queue --------------------------------------------------------
222
223static 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
229/// Queues `problem` for whoever asks a person (the TUI's dialog, the CLI's
230/// JSON answer). One entry per subject and kind: a refusal repeated by ten
231/// requests is one question.
232pub 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
240/// Takes every queued problem, oldest first.
241pub fn take_pending() -> Vec<TrustProblem> {
242    std::mem::take(&mut *pending())
243}
244
245/// The queued problems, left in place.
246pub fn peek_pending() -> Vec<TrustProblem> {
247    pending().clone()
248}
249
250/// Drops the queued problems about `subject`.
251pub 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// --- the gate -----------------------------------------------------------------
262
263/// A client's admission ticket: the record it was admitted under and the
264/// origins its requests may reach.
265#[derive(Debug, Clone)]
266pub struct Admitted {
267    pub subject: TrustSubject,
268    pub record: IntegrationRecord,
269    pub origins: Vec<String>,
270}
271
272/// Checks integrations and AI profiles against the trust store.
273///
274/// File-backed gates re-read `trust.toml` on every use, so a `trust` run in
275/// another process (or the TUI's dialog) takes effect at once.
276pub struct TrustGate {
277    file: Option<PathBuf>,
278    mem: Mutex<TrustStore>,
279    /// Records of integrations that were never connected: held for this
280    /// process only, written by [`TrustGate::record_after_check`].
281    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    /// The gate over `<private>/trust.toml` of `paths`.
302    pub fn load(paths: &ConfigPaths) -> Self {
303        Self::new(Some(TrustStore::file_in(paths)), false)
304    }
305
306    /// [`Self::load`] over the real config directory; with none to be found
307    /// the gate keeps its records in memory only.
308    pub fn ambient() -> Self {
309        match ConfigPaths::discover() {
310            Some(paths) => Self::load(&paths),
311            None => Self::new(None, false),
312        }
313    }
314
315    /// A gate that remembers in memory and allows plain http: for tests of
316    /// code that is not about trust. It still wraps every transport, so a
317    /// request off the integration's origin fails there too.
318    #[cfg(any(test, feature = "test-support"))]
319    pub fn for_tests() -> Self {
320        Self::new(None, true)
321    }
322
323    /// The same, over a store file in `dir`: for tests that look at the file.
324    #[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    /// The record `integration` would get from the config as it is now.
349    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    /// The first two checks, before anything (a token included) is resolved:
369    /// plain http, then origin. A record that does not exist yet is made from
370    /// the config as it stands: written at once for an integration that was
371    /// connected before (the migration: it keeps today's level of trust),
372    /// held in memory for one that never was, until
373    /// [`Self::record_after_check`] writes it.
374    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    /// Writes the record of `integration` now if there is none: for a caller
417    /// that holds a token for it (stored, from the environment or from the
418    /// credential helper), which is the migration case.
419    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    /// [`Self::admit`], for a caller that only wants to know it passes
427    /// before it resolves a token.
428    pub fn preflight(&self, integration: &Integration) -> Result<()> {
429        self.admit(integration).map(|_| ())
430    }
431
432    /// The record of `id`, if one was written.
433    pub fn record_of(&self, id: &str) -> Option<IntegrationRecord> {
434        self.store().ok()?.integration(id).cloned()
435    }
436
437    /// Changes the record of `integration` (made from the config first when
438    /// there is none) and writes it. The one door every acceptance goes
439    /// through.
440    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    /// Records (or refreshes) the trust of `integration` after a check that
463    /// succeeded: its current address, and the account the token belongs to.
464    /// Does not widen anything by itself: [`Self::admit`] has already passed
465    /// for this address.
466    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    /// Accepts the integration's current address as the trusted one. The
479    /// account is forgotten with it: another server has other ids.
480    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    /// Accepts `account` as the owner of the token.
494    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    /// Pins the certificate key of the integration's host.
503    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    /// Switches the pin between `tofu` and `strict` (it needs a pinned key).
518    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    // --- AI profiles ----------------------------------------------------------
537
538    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    /// The checks of [`Self::admit`] for an API-key AI profile bound to
549    /// `base_url`. `has_key`: a key is stored, so a missing record is written
550    /// now (migration); without one it is held in memory until the key is
551    /// stored and [`Self::record_ai`] runs. Returns the origins a request may
552    /// reach.
553    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    /// The AI record of `profile`, if one was written.
588    pub fn ai_record_of(&self, profile: &str) -> Option<AiRecord> {
589        self.store().ok()?.ai_record(profile).cloned()
590    }
591
592    /// Changes the AI record of `profile` (made from `base_url` first when
593    /// there is none) and writes it.
594    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    /// Binds the key of `profile` to the current origin of `base_url`: call
618    /// it when a key is stored.
619    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    /// Accepts the profile's current address as the trusted one.
625    pub fn trust_ai_origin(&self, profile: &str, base_url: &str) -> Result<()> {
626        self.record_ai(profile, base_url)
627    }
628}
629
630/// Feeds the TLS verifier the pin of `origin`'s host.
631#[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;