Skip to main content

arks_server/
push_policy.rs

1//! Push policy seam for receive-pack: a host (the `arks serve` forge module) may
2//! refuse individual ref updates before any ref moves.
3//!
4//! The server stays forge-agnostic: it hands the policy the repository, who is
5//! pushing (as far as the transport knows) and the requested ref updates, and
6//! reports each refusal as `ng <ref> <reason>` in report-status, so the client
7//! prints `! [remote rejected] <ref> (<reason>)`. Cite:
8//! <https://git-scm.com/docs/gitprotocol-pack> (report-status),
9//! <https://git-scm.com/docs/git-push> (OUTPUT).
10
11use arks_oid::Oid;
12use arks_repo::Repository;
13use std::sync::{Arc, OnceLock, RwLock};
14
15/// One requested ref update; an all-zero `old` creates, an all-zero `new` deletes.
16#[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/// What the transport knows about the pusher.
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct Pusher {
36    /// `http`, `ssh` or `local`.
37    pub transport: &'static str,
38    /// User verified by the server's HTTP Basic or SSH public-key gate, if configured.
39    pub verified_user: Option<String>,
40    /// Raw `Authorization` header sent with the push (HTTP only).
41    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    /// SSH pusher bound to an authenticated user identity (`SEC-02`).
60    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
71/// Decides, per ref update, whether a push may proceed.
72pub trait PushPolicy: Send + Sync {
73    /// One entry per update, in order: `Some(reason)` refuses that ref.
74    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
87/// Install (or clear) the process-wide policy used by the serving receive-pack paths.
88pub fn install_push_policy(policy: Option<Arc<dyn PushPolicy>>) {
89    if let Ok(mut g) = slot().write() {
90        *g = policy;
91    }
92}
93
94/// The installed policy, if any.
95pub fn installed_push_policy() -> Option<Arc<dyn PushPolicy>> {
96    slot().read().ok().and_then(|g| g.clone())
97}
98
99/// Run `policy` and normalise its answer to one verdict per update (fail closed).
100pub(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}