Skip to main content

gitpoulpi_hosting/trust/
store.rs

1//! `<private>/trust.toml`: what each integration and AI profile was trusted
2//! to talk to.
3//!
4//! Deliberately **not** in `config.toml`: whoever (or whatever) can edit the
5//! config must not be able to widen trust by editing it. The file sits in the
6//! user-only private directory and is written through
7//! [`gitpoulpi_config::secure_fs::write_private`].
8
9use std::path::{Path, PathBuf};
10
11use gitpoulpi_config::ConfigPaths;
12use serde::{Deserialize, Serialize};
13
14/// File name inside [`ConfigPaths::private_dir`].
15pub const TRUST_FILE: &str = "trust.toml";
16
17/// How a pinned certificate is held to its record.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum TlsMode {
21    /// Accept the recorded key when the chain does not validate (a private
22    /// CA, a self-signed server); a chain that validates is accepted too.
23    Tofu,
24    /// The key must match the record, whatever the chain says.
25    Strict,
26}
27
28impl TlsMode {
29    pub fn as_str(self) -> &'static str {
30        match self {
31            Self::Tofu => "tofu",
32            Self::Strict => "strict",
33        }
34    }
35}
36
37/// What is known about one certificate: the key fingerprint it is pinned by
38/// and the fields a person compares.
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct CertInfo {
41    /// Lowercase hex SHA-256 of the SubjectPublicKeyInfo DER.
42    pub spki_sha256: String,
43    #[serde(default)]
44    pub subject: String,
45    #[serde(default)]
46    pub issuer: String,
47    #[serde(default)]
48    pub not_before: String,
49    #[serde(default)]
50    pub not_after: String,
51}
52
53impl CertInfo {
54    /// The fingerprint in groups of four hex digits (`ab12 cd34 ...`).
55    pub fn grouped(&self) -> String {
56        self.spki_sha256
57            .as_bytes()
58            .chunks(4)
59            .map(|c| String::from_utf8_lossy(c).into_owned())
60            .collect::<Vec<_>>()
61            .join(" ")
62    }
63}
64
65/// `[integration.tls]` / `[ai.tls]`.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct TlsRecord {
68    pub mode: TlsMode,
69    #[serde(flatten)]
70    pub cert: CertInfo,
71}
72
73/// One `[[integration]]`.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct IntegrationRecord {
76    pub id: String,
77    /// Normalized `scheme://host[:port]` plus base path.
78    pub origin: String,
79    /// The host's own id of the account the token belongs to; empty until
80    /// the first successful check (a migrated record learns it then).
81    #[serde(default)]
82    pub account_id: String,
83    #[serde(default)]
84    pub account_login: String,
85    #[serde(default)]
86    pub recorded_at: u64,
87    #[serde(default)]
88    pub account_checked_at: u64,
89    #[serde(default)]
90    pub allow_plain_http: bool,
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub tls: Option<TlsRecord>,
93}
94
95/// One `[[ai]]`: an API-key profile bound to the origin of its base URL.
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct AiRecord {
98    pub profile: String,
99    pub origin: String,
100    #[serde(default)]
101    pub recorded_at: u64,
102    #[serde(default)]
103    pub allow_plain_http: bool,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub tls: Option<TlsRecord>,
106}
107
108#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
109pub struct TrustStore {
110    #[serde(default, skip_serializing_if = "Vec::is_empty")]
111    pub integration: Vec<IntegrationRecord>,
112    #[serde(default, skip_serializing_if = "Vec::is_empty")]
113    pub ai: Vec<AiRecord>,
114}
115
116impl TrustStore {
117    /// `<private>/trust.toml`.
118    pub fn file_in(paths: &ConfigPaths) -> PathBuf {
119        paths.private_dir().join(TRUST_FILE)
120    }
121
122    /// The store at `path`. A missing file is an empty store; a file that is
123    /// there but cannot be read or parsed is an **error**, never an empty
124    /// store: an empty one would let the migration re-trust whatever the
125    /// config says now.
126    pub fn load(path: &Path) -> Result<Self, String> {
127        match std::fs::read_to_string(path) {
128            Ok(raw) => {
129                toml::from_str(&raw).map_err(|e| format!("{} is unreadable: {e}", path.display()))
130            }
131            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
132            Err(e) => Err(format!("{} is unreadable: {e}", path.display())),
133        }
134    }
135
136    pub fn save(&self, path: &Path) -> std::io::Result<()> {
137        if let Some(parent) = path.parent() {
138            gitpoulpi_config::secure_fs::create_private_dir_all(parent)?;
139        }
140        let text = toml::to_string_pretty(self).map_err(std::io::Error::other)?;
141        gitpoulpi_config::secure_fs::write_private(path, text.as_bytes())
142    }
143
144    pub fn integration(&self, id: &str) -> Option<&IntegrationRecord> {
145        self.integration.iter().find(|r| r.id == id)
146    }
147
148    pub fn integration_mut(&mut self, id: &str) -> Option<&mut IntegrationRecord> {
149        self.integration.iter_mut().find(|r| r.id == id)
150    }
151
152    pub fn put_integration(&mut self, record: IntegrationRecord) {
153        match self.integration_mut(&record.id.clone()) {
154            Some(slot) => *slot = record,
155            None => self.integration.push(record),
156        }
157    }
158
159    pub fn ai_record(&self, profile: &str) -> Option<&AiRecord> {
160        self.ai.iter().find(|r| r.profile == profile)
161    }
162
163    pub fn put_ai(&mut self, record: AiRecord) {
164        match self.ai.iter_mut().find(|r| r.profile == record.profile) {
165            Some(slot) => *slot = record,
166            None => self.ai.push(record),
167        }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn round_trips_and_a_corrupt_file_is_an_error_not_an_empty_store() {
177        let dir = tempfile::tempdir().unwrap();
178        let path = dir.path().join("private").join(TRUST_FILE);
179        assert_eq!(TrustStore::load(&path).unwrap(), TrustStore::default());
180        let mut store = TrustStore::default();
181        store.put_integration(IntegrationRecord {
182            id: "corp".into(),
183            origin: "https://git.corp.example".into(),
184            account_id: "7".into(),
185            account_login: "ada".into(),
186            recorded_at: 1,
187            account_checked_at: 2,
188            allow_plain_http: false,
189            tls: Some(TlsRecord {
190                mode: TlsMode::Tofu,
191                cert: CertInfo {
192                    spki_sha256: "ab".repeat(32),
193                    subject: "CN=git".into(),
194                    ..CertInfo::default()
195                },
196            }),
197        });
198        store.put_ai(AiRecord {
199            profile: "p".into(),
200            origin: "http://localhost:11434".into(),
201            recorded_at: 3,
202            allow_plain_http: false,
203            tls: None,
204        });
205        store.save(&path).unwrap();
206        assert_eq!(TrustStore::load(&path).unwrap(), store);
207        std::fs::write(&path, "[[integration]\nbroken").unwrap();
208        assert!(TrustStore::load(&path).is_err());
209    }
210
211    #[test]
212    fn fingerprints_group_by_four() {
213        let c = CertInfo {
214            spki_sha256: "0123456789abcdef".into(),
215            ..CertInfo::default()
216        };
217        assert_eq!(c.grouped(), "0123 4567 89ab cdef");
218    }
219}