Skip to main content

gitpoulpi_hosting/trust/
verify.rs

1//! The account id check: the token still belongs to the account it was
2//! trusted for.
3
4use std::collections::HashSet;
5use std::sync::Mutex;
6
7use gitpoulpi_config::Integration;
8
9use crate::client::HostingClient;
10use crate::{Error, Result};
11
12use super::{report, unix_now, Account, TrustGate, TrustProblem, TrustSubject};
13
14/// Why the account is being asked.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum VerifyReason {
17    /// A token was just stored: always check.
18    TokenStored,
19    /// The token came from `GITPOULPI_TOKEN_*` or the credential helper:
20    /// once per process.
21    ExternalToken,
22    /// An ordinary use: when the last check is older than a day.
23    Periodic,
24}
25
26/// How long a successful check is good for.
27pub const RECHECK_SECS: u64 = 24 * 3600;
28
29static CHECKED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
30
31fn first_time_this_process(id: &str) -> bool {
32    CHECKED
33        .lock()
34        .unwrap_or_else(|p| p.into_inner())
35        .get_or_insert_with(HashSet::new)
36        .insert(id.to_string())
37}
38
39impl TrustGate {
40    /// Compares the account `client`'s token belongs to with the recorded
41    /// one, when [`VerifyReason`] says it is due. The **id** is compared, not
42    /// the login (a login can be renamed or re-registered). A record with no
43    /// account yet (a migrated one) learns it here.
44    pub async fn verify_account(
45        &self,
46        integration: &Integration,
47        client: &dyn HostingClient,
48        reason: VerifyReason,
49    ) -> Result<()> {
50        let record = self.record_of(&integration.id);
51        let due = match reason {
52            VerifyReason::TokenStored => true,
53            VerifyReason::ExternalToken => first_time_this_process(&integration.id),
54            VerifyReason::Periodic => record
55                .as_ref()
56                .is_none_or(|r| unix_now().saturating_sub(r.account_checked_at) >= RECHECK_SECS),
57        };
58        if !due {
59            return Ok(());
60        }
61        let user = match client.current_user().await {
62            Ok(u) => u,
63            // A kind that cannot say who the token is has nothing to compare.
64            Err(Error::Unsupported(_) | Error::NotImplemented(_) | Error::BotToken) => {
65                return Ok(())
66            }
67            Err(e) => return Err(e),
68        };
69        let new = Account {
70            login: user.login,
71            id: user.id,
72        };
73        self.check_account(integration, &new)
74    }
75
76    /// Compares `new` with the recorded account and, when it is the same one
77    /// (or none was recorded yet), refreshes the record. The part of
78    /// [`Self::verify_account`] for a caller that already holds the account,
79    /// from a token check it just ran.
80    pub fn check_account(&self, integration: &Integration, new: &Account) -> Result<()> {
81        let record = self.record_of(&integration.id);
82        if let Some(r) = &record {
83            let same = if r.account_id.is_empty() || new.id.is_empty() {
84                r.account_login.is_empty() || r.account_login == new.login
85            } else {
86                r.account_id == new.id
87            };
88            if !same {
89                let problem = TrustProblem::AccountChanged {
90                    subject: TrustSubject::Integration(integration.id.clone()),
91                    old: Box::new(Account {
92                        login: r.account_login.clone(),
93                        id: r.account_id.clone(),
94                    }),
95                    new: Box::new(new.clone()),
96                };
97                report(&problem);
98                return Err(Error::Trust(problem));
99            }
100        }
101        self.record_after_check(integration, new)
102    }
103}