arks_server/
push_policy.rs1use arks_oid::Oid;
12use arks_repo::Repository;
13use std::sync::{Arc, OnceLock, RwLock};
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct RefUpdate {
18 pub name: String,
19 pub old: Oid,
20 pub new: Oid,
21}
22
23impl RefUpdate {
24 pub fn is_create(&self) -> bool {
25 self.old.as_bytes().iter().all(|b| *b == 0)
26 }
27
28 pub fn is_delete(&self) -> bool {
29 self.new.as_bytes().iter().all(|b| *b == 0)
30 }
31}
32
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct Pusher {
36 pub transport: &'static str,
38 pub verified_user: Option<String>,
40 pub authorization: Option<String>,
42}
43
44impl Pusher {
45 pub fn local() -> Self {
46 Self {
47 transport: "local",
48 ..Self::default()
49 }
50 }
51
52 pub fn ssh() -> Self {
53 Self {
54 transport: "ssh",
55 ..Self::default()
56 }
57 }
58
59 pub fn ssh_user(user: impl Into<String>) -> Self {
61 let user = user.into();
62 let trimmed = user.trim();
63 Self {
64 transport: "ssh",
65 verified_user: (!trimmed.is_empty()).then(|| trimmed.to_string()),
66 authorization: None,
67 }
68 }
69}
70
71pub trait PushPolicy: Send + Sync {
73 fn check(
75 &self,
76 repo: &Repository,
77 pusher: &Pusher,
78 updates: &[RefUpdate],
79 ) -> Vec<Option<String>>;
80}
81
82fn slot() -> &'static RwLock<Option<Arc<dyn PushPolicy>>> {
83 static SLOT: OnceLock<RwLock<Option<Arc<dyn PushPolicy>>>> = OnceLock::new();
84 SLOT.get_or_init(|| RwLock::new(None))
85}
86
87pub fn install_push_policy(policy: Option<Arc<dyn PushPolicy>>) {
89 if let Ok(mut g) = slot().write() {
90 *g = policy;
91 }
92}
93
94pub fn installed_push_policy() -> Option<Arc<dyn PushPolicy>> {
96 slot().read().ok().and_then(|g| g.clone())
97}
98
99pub(crate) fn verdicts(
101 policy: Option<&dyn PushPolicy>,
102 repo: &Repository,
103 pusher: &Pusher,
104 updates: &[RefUpdate],
105) -> Vec<Option<String>> {
106 let Some(policy) = policy else {
107 return vec![None; updates.len()];
108 };
109 let out = policy.check(repo, pusher, updates);
110 if out.len() != updates.len() {
111 return vec![Some("push policy error".into()); updates.len()];
112 }
113 out.into_iter()
114 .map(|v| v.map(|r| r.replace(['\n', '\r'], " ")))
115 .collect()
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
123 fn ssh_user_binds_verified_user_and_transport() {
124 let p = Pusher::ssh_user("alice");
125 assert_eq!(p.transport, "ssh");
126 assert_eq!(p.verified_user.as_deref(), Some("alice"));
127 assert_eq!(p.authorization, None);
128
129 let blank = Pusher::ssh_user(" ");
130 assert_eq!(blank.transport, "ssh");
131 assert_eq!(blank.verified_user, None);
132 }
133}