gitpoulpi_hosting/trust/
verify.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum VerifyReason {
17 TokenStored,
19 ExternalToken,
22 Periodic,
24}
25
26pub 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 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 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 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}