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