Skip to main content

gunnar_ssh/
control.rs

1//! The control plane this listener answers from: `gunnar-core`, directly
2//! (the ACL model).
3//!
4//! # What this replaced
5//!
6//! Two local traits, `seam::AuthDirectory` and `seam::RepoResolver`, written
7//! while `gunnar-core` was being built in parallel. They are gone, and this is
8//! not a trait: there is one identity table and one catalog, they are
9//! `gunnar-core`'s, and putting an interface in front of them would only be
10//! somewhere for a second answer to live (one implementation).
11//!
12//! # The bug the seam had, which is why this is a rewrite and not a rename
13//!
14//! Both seam traits returned `Option`. `gunnar-core` returns `Result`, and
15//! deliberately: the table lives in storage (the Arrow-IPC ref log), a read can fail, and
16//! the ACL model spells out that `may(...)` must not be a bare `bool` because the
17//! safe-looking invention for the failure case ("no access") turns a storage
18//! fault into a silent permission denial. Any adapter from `Result` to `Option`
19//! has to make exactly that invention.
20//!
21//! So the `Result` is carried all the way through
22//! [`Dispatch::authorise`](crate::server::Dispatch::authorise) and lands as its
23//! own [`DispatchError::Store`](crate::server::DispatchError::Store) variant:
24//! separate from `Denied`, logged as a fault, and never reported to the client
25//! as "you may not have this repository".
26
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::sync::Arc;
29
30use gunnar_core::{
31    AuthTable, ControlStore, Fingerprint, HashKind, Level, NewRepo, Principal, PrincipalKind, Repo,
32    RepoCatalog, RepoRef,
33};
34
35/// The identity table and the repository catalog, together.
36///
37/// Cheap to clone: both halves are handles onto the same stored documents.
38#[derive(Clone)]
39pub struct Control {
40    auth: AuthTable,
41    catalog: RepoCatalog,
42    /// **Is this box a frozen STANDBY?** `true` refuses a client `git push`.
43    ///
44    /// Shared by clone with the server's replication slot, which flips it on a
45    /// role change — so this front door and the control plane read ONE value
46    /// (one implementation) and never disagree about whether a write should be refused. The
47    /// default is an unshared `false`: a bare `Control` (a test, a build with no
48    /// replication) is a writable primary, exactly as before this existed.
49    writes_frozen: Arc<AtomicBool>,
50    /// **Is this box a browse replica**? Shared with
51    /// the replication slot the same way `writes_frozen` is; read for the
52    /// refusal WORDING (a browse box's refusal names itself) and to override
53    /// [`AnonymousPolicy::Refuse`] — the browse replica exists to serve
54    /// anonymous reads, so it serves them whatever the flag says.
55    browse: Arc<AtomicBool>,
56    /// **Is this box a TWIN right now?** `true` refuses every git service —
57    /// read and write, keyed and anonymous — at
58    /// [`Dispatch::authorise_service`](crate::server::Dispatch::authorise_service).
59    ///
60    /// Shared by clone with `ServerStores`' own flag, the way `writes_frozen`
61    /// and `browse` are, so the front door and the control plane read ONE value
62    /// and can never disagree. It has to be live, not a snapshot: a box is made
63    /// a twin over the wire by `Bootstrap.BecomeTwin` while it is already
64    /// running and serving, and under the owner's one-medium ruling that is the
65    /// ONLY way a twin is ever made. The default is an unshared `false` — a
66    /// bare `Control` is a primary, exactly as before this existed.
67    twin: Arc<AtomicBool>,
68    /// **Does this box serve anonymous reads at all?** The primary of a
69    /// browse-replica deployment says `Refuse`, and names where to go.
70    anonymous: AnonymousPolicy,
71    /// **The gate chain**: the server's answers to "may this namespace push
72    /// right now", asked IN ORDER by `Dispatch::authorise_service`; the first
73    /// `Refuse` wins. The server wires the disk-headroom gate first and, on a
74    /// `metered` build with a monetize key, the entitlement gate second. Empty
75    /// — a bare `Control`, a test — is every namespace Free with infinite disk,
76    /// which is what a test that is not about the gates wants.
77    plan: Vec<Arc<dyn crate::plan::PlanGate>>,
78    /// **The owner's enterprise list at the push door** (2026-10-05): the
79    /// name filter a first push's repository name is put to, and the
80    /// accounts' audit logs its creation is written into. `None` — a bare
81    /// `Control`, a test not about them — filters nothing and logs nothing.
82    enterprise: Option<(gunnar_core::name_filter::NameFilterStore, Arc<gunnar_core::account_audit::AccountAuditLog>)>,
83}
84
85/// **The `--anonymous` knob** (the browse replica). Anonymous reads of
86/// public repositories are either served here (`Allow`, the default and every
87/// pre-2026-09 server) or refused with a line that names the browse replica
88/// they are served by (`Refuse`). Strangers cost CPU and bandwidth on the box
89/// that also takes the paying writes; the browse replica is where that cost
90/// belongs, and the primary sends them there rather than quietly 404-ing.
91#[derive(Debug, Clone, PartialEq, Eq, Default)]
92pub enum AnonymousPolicy {
93    /// Serve anonymous reads of public repositories on this box.
94    #[default]
95    Allow,
96    /// Refuse every anonymous request; `browse_host`, when named, goes into
97    /// the refusal so `git clone` prints where to clone from instead.
98    Refuse {
99        /// `host[:port]` of the browse replica, for the refusal line.
100        browse_host: Option<String>,
101    },
102}
103
104impl Control {
105    /// Wrap an already-open table and catalog. Writable (a primary) until
106    /// [`Control::with_write_gate`] shares a standby's freeze flag in.
107    pub fn new(auth: AuthTable, catalog: RepoCatalog) -> Self {
108        Control {
109            auth,
110            catalog,
111            writes_frozen: Arc::new(AtomicBool::new(false)),
112            browse: Arc::new(AtomicBool::new(false)),
113            twin: Arc::new(AtomicBool::new(false)),
114            anonymous: AnonymousPolicy::Allow,
115            plan: Vec::new(),
116            enterprise: None,
117        }
118    }
119
120    /// **The name filter and the accounts' audit logs** (2026-10-05): a
121    /// repository a first push creates is named here too, and its creation is
122    /// in its account's log.
123    #[must_use]
124    pub fn with_enterprise(
125        mut self,
126        names: gunnar_core::name_filter::NameFilterStore,
127        audit: Arc<gunnar_core::account_audit::AccountAuditLog>,
128    ) -> Self {
129        self.enterprise = Some((names, audit));
130        self
131    }
132
133    /// Write one event into the account `namespace` belongs to, if a person
134    /// owns it. Best effort: one WARN when the log cannot be written.
135    fn account_event(&self, principal: &Principal, namespace: &str, kind: &str, target: &str, detail: &str, refused: bool) {
136        let Some((_, log)) = &self.enterprise else {
137            return;
138        };
139        let Ok(Some(account)) = self.auth.account_of_namespace(namespace) else {
140            return;
141        };
142        let role = self.auth.role_in_account(&principal.id, &account).unwrap_or("unknown");
143        let written = log.append(
144            &account,
145            gunnar_core::account_audit::AccountEvent {
146                kind,
147                actor: &principal.id,
148                actor_role: role,
149                target,
150                detail,
151                outcome: if refused {
152                    gunnar_core::account_audit::Outcome::Refused
153                } else {
154                    gunnar_core::account_audit::Outcome::Ok
155                },
156            },
157            gunnar_core::now_ms(),
158        );
159        if let Err(err) = written {
160            tracing::warn!(target: "gunnar::audit", event = "account_audit.not_written", account = %account, kind, error = %err, "an event could not be written to its account's audit log");
161        }
162    }
163
164    /// **The name filter at the push door**: the sentence a first push to
165    /// `path` is refused with, or `None`. A blocked name is noted for the
166    /// account admin; a borderline one is held for them (and refused until
167    /// they allow it). Reserved names are a person's and an account's, never
168    /// a repository's.
169    pub fn push_create_name_refusal(&self, principal: &Principal, path: &RepoRef) -> Option<String> {
170        use gunnar_core::name_filter::{NameKind, Verdict};
171        let (names, _) = self.enterprise.as_ref()?;
172        let account = self.auth.account_of_namespace(path.namespace()).ok().flatten();
173        let verdict = names.check(NameKind::Repo, path.name(), account.as_deref().unwrap_or("")).ok()?;
174        if verdict == Verdict::Clean || matches!(verdict, Verdict::Reserved { .. }) {
175            return None;
176        }
177        let hold = matches!(verdict, Verdict::Borderline { .. }) && account.is_some();
178        if let Some(account) = &account {
179            let now = gunnar_core::now_ms();
180            let queued = if hold {
181                names.hold(NameKind::Repo, path.name(), account, &principal.id, &verdict, now)
182            } else {
183                names.note(NameKind::Repo, path.name(), account, &principal.id, &verdict, now)
184            };
185            if let Err(err) = queued {
186                tracing::warn!(target: "gunnar::audit", event = "name_filter.not_queued", account = %account, error = %err, "a name the filter stopped could not be put in its account's queue");
187            }
188        }
189        self.account_event(
190            principal,
191            path.namespace(),
192            if hold { "name.held" } else { "name.refused" },
193            path.name(),
194            &format!("a repo name, {} by the name filter, at a first push", verdict.as_str()),
195            true,
196        );
197        Some(verdict.sentence(NameKind::Repo, path.name()))
198    }
199
200    /// **Share the standby write-gate in.** The `Arc` the server's replication
201    /// slot writes on a role change; reading it is how the front door learns,
202    /// per push, that this box has become a read-only standby.
203    #[must_use]
204    pub fn with_write_gate(mut self, writes_frozen: Arc<AtomicBool>) -> Self {
205        self.writes_frozen = writes_frozen;
206        self
207    }
208
209    /// Share the browse flag in — `ServerStores::browse()`, the same `Arc`
210    /// the replication slot flips.
211    #[must_use]
212    pub fn with_browse_flag(mut self, browse: Arc<AtomicBool>) -> Self {
213        self.browse = browse;
214        self
215    }
216
217    /// Set the anonymous policy. `Refuse` is overridden by the browse flag:
218    /// see [`Control::refuses_anonymous`].
219    #[must_use]
220    pub fn with_anonymous_policy(mut self, policy: AnonymousPolicy) -> Self {
221        self.anonymous = policy;
222        self
223    }
224
225    /// Share the twin flag in — `ServerStores::twin_flag()`, the same `Arc`
226    /// `Bootstrap.BecomeTwin` flips while the server runs.
227    #[must_use]
228    pub fn with_twin_flag(mut self, twin: Arc<AtomicBool>) -> Self {
229        self.twin = twin;
230        self
231    }
232
233    /// Is this box a browse replica right now?
234    pub fn is_browse(&self) -> bool {
235        self.browse.load(Ordering::SeqCst)
236    }
237
238    /// **Is this box a twin right now?** A live read: the answer changes under
239    /// a running server the moment `Bootstrap.BecomeTwin` returns.
240    pub fn is_twin(&self) -> bool {
241        self.twin.load(Ordering::SeqCst)
242    }
243
244    /// **Is an anonymous request refused here?** `Refuse` on a box that is
245    /// not a browse replica. A browse replica serves anonymous reads whatever
246    /// the knob says — it is the box the knob points AT, and a deployment that
247    /// flipped a primary into a browse box by `SetRole` must not carry the
248    /// primary's refusal along.
249    pub fn refuses_anonymous(&self) -> bool {
250        matches!(self.anonymous, AnonymousPolicy::Refuse { .. }) && !self.is_browse()
251    }
252
253    /// The browse host the refusal names, when the operator gave one.
254    pub fn browse_host(&self) -> Option<&str> {
255        match &self.anonymous {
256            AnonymousPolicy::Refuse { browse_host } => browse_host.as_deref(),
257            AnonymousPolicy::Allow => None,
258        }
259    }
260
261    /// **Append a gate to the chain.** Order is the call order: the server
262    /// hands the disk-headroom gate in first, then (`metered`) the entitlement
263    /// gate, so a full box is told it is full before it is told about its
264    /// plan. From here on every push asks each link in
265    /// `Dispatch::authorise_service`, and the first `Refuse` is the answer.
266    #[must_use]
267    pub fn with_plan_gate(mut self, gate: Arc<dyn crate::plan::PlanGate>) -> Self {
268        self.plan.push(gate);
269        self
270    }
271
272    /// The chain, in the order it is asked. Empty when nothing was wired.
273    pub fn plan_gates(&self) -> &[Arc<dyn crate::plan::PlanGate>] {
274        &self.plan
275    }
276
277    /// Open both over the server's control store (the certificate-identity plan).
278    pub fn open(store: Arc<dyn ControlStore>) -> Result<Self, gunnar_core::Error> {
279        Ok(Control {
280            auth: AuthTable::new(Arc::clone(&store))?,
281            catalog: RepoCatalog::new(store)?,
282            writes_frozen: Arc::new(AtomicBool::new(false)),
283            browse: Arc::new(AtomicBool::new(false)),
284            twin: Arc::new(AtomicBool::new(false)),
285            anonymous: AnonymousPolicy::Allow,
286            plan: Vec::new(),
287            enterprise: None,
288        })
289    }
290
291    /// **Would a client write be refused right now?** `true` on a standby.
292    ///
293    /// The replication push from a primary is a [`PrincipalKind::Machine`]
294    /// identity and is NOT a client write — a standby exists to receive it —
295    /// so the freeze is scoped to non-`Machine` principals by
296    /// [`Control::write_frozen_for`], which is what the dispatch actually calls.
297    pub fn writes_frozen(&self) -> bool {
298        self.writes_frozen.load(Ordering::SeqCst)
299    }
300
301    /// **Must this principal's write be refused because this box is a standby?**
302    ///
303    /// `true` only when the box is frozen AND the writer is not the replication
304    /// source. A `Machine` identity is how a primary authenticates its
305    /// replication push, and a standby is a box that exists precisely to accept
306    /// that — freezing it would stop the very copy the standby is for. A human
307    /// (`User`) or a `Deploy` key pushing directly to a standby is the write
308    /// that must be refused: it would land here and never reach the primary.
309    pub fn write_frozen_for(&self, principal: &Principal) -> bool {
310        self.writes_frozen() && principal.kind != PrincipalKind::Machine
311    }
312
313    /// The identity table.
314    pub fn auth(&self) -> &AuthTable {
315        &self.auth
316    }
317
318    /// The repository catalog.
319    pub fn catalog(&self) -> &RepoCatalog {
320        &self.catalog
321    }
322
323    /// **Who is this?** The principal that owns `fingerprint`, or `None` to
324    /// refuse the authentication.
325    ///
326    /// `Err` is a storage fault and is *not* the same as `Ok(None)`. The caller
327    /// must refuse the key either way, but it must say which happened, because
328    /// "nobody holds this key" and "the identity table could not be read" call
329    /// for entirely different operator action.
330    pub fn principal_for_key(
331        &self,
332        fingerprint: &Fingerprint,
333    ) -> Result<Option<Principal>, gunnar_core::Error> {
334        self.auth.principal_by_fingerprint(fingerprint)
335    }
336
337    /// **Does it exist?** The repository at `path`, or `None`.
338    ///
339    /// `None` here is only ever "no such repository". It must not be conflated
340    /// with "no permission" at this layer: the server merges the two into one
341    /// client-visible message on purpose, so a client cannot use the difference
342    /// to enumerate private repositories, but they arrive separately so the
343    /// server log can tell them apart.
344    pub fn resolve(&self, path: &RepoRef) -> Result<Option<Repo>, gunnar_core::Error> {
345        self.catalog.get(path)
346    }
347
348    /// **May they?** The highest level `principal` holds on `repo`, or `None`
349    /// for no access at all.
350    ///
351    /// Derived by asking [`AuthTable::may`] from the top down, so this is the
352    /// ACL's answer and not a second reading of the grant table. A namespace
353    /// grant matches its namespace **exactly**: `team` does not reach
354    /// `team/sub`. That is what closes the escalation the permissive path
355    /// sandbox would otherwise carry, and it is pinned by
356    /// `gunnar-core`'s `tests/acl.rs`.
357    pub fn access_for(
358        &self,
359        principal: &Principal,
360        repo: &Repo,
361    ) -> Result<Option<Level>, gunnar_core::Error> {
362        for level in [Level::Admin, Level::Write, Level::Read] {
363            if self.auth.may(&principal.id, repo, level)? {
364                return Ok(Some(level));
365            }
366        }
367        Ok(None)
368    }
369
370    /// **The first-repository door, the checks**: may `principal` create
371    /// `path` by pushing to it? `Some(spec)` is what would be created —
372    /// nothing has been written; `None` the dispatch MUST render as its
373    /// ordinary not-found, so the door is invisible to everyone it does not
374    /// admit.
375    ///
376    /// # Why this exists (the appliance brick, 2026-08-25)
377    ///
378    /// On an installed appliance the bootstrap admin from `--admin-key`
379    /// authenticates and can then do nothing: the exec surface is three git
380    /// verbs, all of which want a repository; the catalog is empty; gRPC —
381    /// the only surface with `Repos.Create` — is off by design;
382    /// and there is no shell by construction. Nobody could ever create the
383    /// first namespace. `a8ba0665` fixed "authorizes nobody"; this fixes
384    /// "can do nothing".
385    ///
386    /// # It asks gRPC's questions, verbatim (one implementation)
387    ///
388    /// This is deliberately NOT a new permission vocabulary. The two
389    /// predicates are exactly the ones the gRPC control plane gates creation
390    /// on, so SSH and gRPC can never disagree about who may create:
391    ///
392    /// * a namespace that does not exist needs what `Repos.CreateNamespace`
393    ///   needs: [`AuthTable::may_server`] at [`Level::Admin`] — creating a
394    ///   tenant is a server-wide act;
395    /// * the repository needs what `Repos.Create` needs:
396    ///   [`AuthTable::may_namespace`] at [`Level::Admin`] — namespace-scoped,
397    ///   because the repository does not exist yet, so there is nothing
398    ///   narrower to hold a grant on.
399    ///
400    /// So the door admits exactly who the RPC would admit: the gunnar-admin
401    /// anywhere, an account owner inside their own (existing) account
402    /// namespace, a namespace-admin inside that namespace exactly (no
403    /// inheritance into `team/sub`). The anonymous principal is refused by
404    /// construction inside both predicates.
405    ///
406    /// # Why the catalog's "never conjure a namespace" rule bends here
407    ///
408    /// [`RepoCatalog::create`] refuses a repository whose namespace does not
409    /// exist, "because then a typo in a push URL would silently become a
410    /// tenant". That rule is about *unprivileged* writers. Here the namespace
411    /// is only ever conjured by a principal holding `Server`/`Admin` — whose
412    /// grant already covers every namespace on the box, so no tenant boundary
413    /// is crossed; the blast radius of the admin's typo is a private, empty
414    /// repository on the admin's own server.
415    ///
416    /// # What it would create
417    ///
418    /// [`NewRepo::new`] and nothing else: sha256, private, default
419    /// branch. The one writer of defaults — a door that chose its own
420    /// defaults would be the second answer one implementation forbids.
421    ///
422    /// # Why the write is NOT here (the ghost repository, 2026-08-30)
423    ///
424    /// This used to create the catalog row at exec time, before the client
425    /// had seen the advertisement. A sha1 working tree pushing to the sha256
426    /// default reads `object-format=sha256` in that advertisement, prints
427    /// *"the receiving end does not support this repository's hash
428    /// algorithm"* and hangs up **having sent no command** — and the empty
429    /// repository it never pushed to was there afterwards: `repo get`
430    /// succeeded, `ls-remote` answered (the site test, two FAIL rows).
431    /// The server cannot know the client's hash before advertising, so the
432    /// only order that leaves nothing behind on a refusal is: advertise the
433    /// *prospect*, read the commands, check the hash, **then** write. The
434    /// write is [`Self::admit_push_create`], called by the transport once
435    /// there is a push to admit; the catalog is untouched until then.
436    pub fn push_create_spec(
437        &self,
438        principal: &Principal,
439        path: &RepoRef,
440    ) -> Result<Option<NewRepo>, gunnar_core::Error> {
441        let namespace = path.namespace();
442        let namespace_exists = self.catalog.namespace(namespace)?.is_some();
443        if !namespace_exists && !self.auth.may_server(&principal.id, Level::Admin)? {
444            return Ok(None);
445        }
446        // The account admin's door — and a CLAN's member's (clans 2026-10-05,
447        // the rule `Repos.Create` keeps): the member creates PRIVATE
448        // repositories in the clan with the Write its membership gives, and
449        // the prospect below is private. An invited account that has not
450        // accepted is no member.
451        let admin = self.auth.may_namespace(&principal.id, namespace, Level::Admin)?;
452        let member = !admin
453            && namespace_exists
454            && self.auth.clan_role(&principal.id, namespace)? == Some(gunnar_core::ClanRole::Member);
455        if !(admin || member) {
456            return Ok(None);
457        }
458        // **SHA-1, and only here.** `NewRepo::new` defaults to sha256, which is
459        // the right default for a repository somebody ASKS for: `repo create`
460        // takes a hash kind, and a caller that wants sha256 gets it. A
461        // first-push prospect is not asked for — it is inferred, before the
462        // client has said one word — and git's v1 receive-pack advertises the
463        // repository's object format BEFORE the client sends anything, so there
464        // is nothing to infer it from. The client then reads the capability and
465        // decides on its own.
466        //
467        // MEASURED on gunnar.rs, 2026-09-20, seeding a freshly re-imaged forge:
468        //
469        //     xtask: REFUSED [seed-push] nordisk/gunnar: protocol error:
470        //     local repository is Sha1 but the remote is Sha256;
471        //     git cannot push between object formats
472        //
473        // The push never reached the hash check this door's whole ordering was
474        // built around ("advertise the prospect, read the commands, check the
475        // hash, THEN write") — the client refused the advertisement. So the
476        // first-push door, as shipped, admitted only sha256 clients, and this
477        // estate has none: all four declared repositories are sha1, as is every
478        // clone of them and every repository git creates without being told
479        // otherwise.
480        //
481        // sha1 is what an un-negotiated client assumes, so it is the only
482        // prospect that can be right for a client that has not spoken yet. The
483        // hash check after the commands is unchanged and still has the final
484        // word; a sha256 pusher is still served by `repo create`, where the
485        // hash is a decision somebody made rather than one nobody could.
486        Ok(Some(NewRepo::new(path.clone()).hash_kind(HashKind::Sha1)))
487    }
488
489    /// **The first-repository door, the write**: the namespace, conjured if
490    /// it does not exist, and the catalog row — for a push that has sent its
491    /// commands and passed the hash check. Re-asks
492    /// [`Self::push_create_spec`]'s questions, so a grant revoked between the
493    /// advertisement and the pack is still a refusal; `Ok(None)` is that
494    /// refusal.
495    ///
496    /// The on-disk stores are NOT created here (this crate has no
497    /// filesystem): the transport creates them through `ServerStores`, and it
498    /// is the transport that makes the pair transactional — a store that
499    /// cannot be made rolls this row back, see `ServerStores::create_repo`.
500    ///
501    /// # Races
502    ///
503    /// Two admins pushing the same new name race on the catalog's
504    /// compare-and-swap. The loser of either CAS finds the thing it was
505    /// creating already there and proceeds — the repository exists, which is
506    /// what it wanted. `Err` is only ever a storage fault, and the caller
507    /// must report it as one ([`crate::server::DispatchError::Store`]), never
508    /// as not-found.
509    ///
510    /// Returns the repository and whether **this call** conjured the
511    /// namespace, so a caller that fails afterwards can take the namespace
512    /// back with the row and leave no trace at all.
513    pub fn admit_push_create(
514        &self,
515        principal: &Principal,
516        path: &RepoRef,
517    ) -> Result<Option<(Repo, bool)>, gunnar_core::Error> {
518        let Some(spec) = self.push_create_spec(principal, path)? else {
519            return Ok(None);
520        };
521        let namespace = path.namespace();
522        let mut conjured = false;
523        if self.catalog.namespace(namespace)?.is_none() {
524            match self.catalog.create_namespace(namespace) {
525                Ok(_) => conjured = true,
526                // Lost a race; it exists now, which is all that was wanted.
527                Err(gunnar_core::Error::NamespaceExists(_)) => {}
528                Err(err) => return Err(err),
529            }
530        }
531        let repo = match self.catalog.create(spec) {
532            Ok(repo) => repo,
533            // The other pusher won; serve the repository it created.
534            Err(gunnar_core::Error::RepoExists(_)) => self.catalog.open(path)?,
535            Err(err) => return Err(err),
536        };
537        self.account_event(
538            principal,
539            path.namespace(),
540            "repo.created",
541            &path.to_string(),
542            if conjured { "by its first push (the namespace with it)" } else { "by its first push" },
543            false,
544        );
545        tracing::warn!(
546            target: "gunnar::audit",
547            event = "repo.created_on_first_push",
548            principal = %principal.id,
549            repo = %path,
550            namespace_conjured = conjured,
551            "repository created by its first push; the creator's grant, not a new rule, \
552             is what authorised it"
553        );
554        Ok(Some((repo, conjured)))
555    }
556
557    /// Undo [`Self::admit_push_create`] after the store could not be made:
558    /// the row goes, and the namespace too if that call conjured it. Nothing
559    /// is left for `repo get` to find.
560    pub fn retract_push_create(
561        &self,
562        path: &RepoRef,
563        namespace_conjured: bool,
564    ) -> Result<(), gunnar_core::Error> {
565        match self.catalog.delete(path) {
566            Ok(_) | Err(gunnar_core::Error::NoSuchRepo(_)) => {}
567            Err(err) => return Err(err),
568        }
569        if namespace_conjured {
570            match self.catalog.delete_namespace(path.namespace(), false) {
571                Ok(_) | Err(gunnar_core::Error::NoSuchNamespace(_)) => {}
572                Err(err) => return Err(err),
573            }
574        }
575        Ok(())
576    }
577}
578
579impl std::fmt::Debug for Control {
580    /// By hand rather than derived, because the gates are `dyn` trait objects
581    /// with no `Debug` of their own — and what an operator wants to see of them
582    /// is which are wired and in what order, not their insides.
583    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
584        let gates: Vec<&'static str> = self.plan.iter().map(|g| g.name()).collect();
585        f.debug_struct("Control")
586            .field("auth", &self.auth)
587            .field("catalog", &self.catalog)
588            .field("writes_frozen", &self.writes_frozen())
589            .field("browse", &self.is_browse())
590            .field("anonymous", &self.anonymous)
591            .field("gates", &gates)
592            .finish()
593    }
594}