gunnar_proto/lib.rs
1//! # gunnar-proto: the control-plane surface
2//!
3//! The `.proto` files in `proto/gunnar/v1/` and their `tonic-build` output.
4//! This crate is generated code plus a small amount of hand-written glue; it
5//! holds no behaviour. The service implementations live in `gunnar-grpc`.
6//!
7//! ## What is here
8//!
9//! Seven services:
10//!
11//! | service | what it owns |
12//! |---|---|
13//! | [`repos_client`] / [`repos_server`] | namespaces and repositories, i.e. the catalogue |
14//! | [`refs_client`] / [`refs_server`] | refs, commit log, object reads, diffs. READ ONLY |
15//! | [`access_client`] / [`access_server`] | principals, public keys, grants |
16//! | [`policy_client`] / [`policy_server`] | branch protection, ref-name policy, gates |
17//! | [`events_client`] / [`events_server`] | `Watch`, the server-streaming event feed |
18//! | [`admin_client`] / [`admin_server`] | health, stats, storage backend info |
19//! | [`mirror_client`] / [`mirror_server`] | pull-mirroring a remote forge |
20//! | [`bootstrap_client`] / [`bootstrap_server`] | first-boot enrolment; the ONE unauthenticated service |
21//! | [`forge_client`] / [`forge_server`] | issues, change proposals and review, as signed events |
22//! | [`webhooks_client`] / [`webhooks_server`] | outbound webhook delivery to external URLs |
23//!
24//! ## Two invariants that hold across the whole surface
25//!
26//! **Namespaces are first class.** Every repo-scoped request and every
27//! repo-scoped event carries a [`RepoPath`] of `<namespace>/<repo>`, matching
28//! the SSH path `git@host:<namespace>/<repo>.git`. Multi-tenancy is in from
29//! day 1 because adding it later would mean migrating every stored path and
30//! every ACL row; adding it now costs one field.
31//!
32//! **No `google.protobuf.Any`.** [`Event`] carries an explicit `oneof` of named
33//! payloads. A UI must be able to render an event without a type registry.
34//!
35//! ## What is deliberately absent
36//!
37//! There is no RPC that moves a ref. Refs move through `git-receive-pack` on
38//! the SSH listener, behind the policy gate. A `Refs.Set` would route a
39//! push around every gate, so it does not exist — see [`refs_server`].
40#![doc(html_logo_url = "https://gunnar.rs/download/gunnar.webp", html_favicon_url = "https://gunnar.rs/download/favicon.svg")]
41
42// Generated by `build.rs`. Both halves are built: dwarves and korp consume the
43// client, `gunnar-grpc` implements the server.
44#[allow(clippy::doc_overindented_list_items, clippy::doc_lazy_continuation)]
45mod generated {
46 tonic::include_proto!("gunnar.v1");
47}
48
49pub use generated::*;
50
51/// `gunnar/<version>`, the agent string reported by `Admin.Health`, written
52/// into every [`PushAttestation`], and advertised as `agent=` on the git wire.
53pub const AGENT: &str = concat!("gunnar/", env!("CARGO_PKG_VERSION"));
54
55/// `HealthResponse.status` of a box with nothing to act on.
56pub const HEALTH_SERVING: &str = "serving";
57/// `HealthResponse.status` of a box that serves and needs an operator (see its alarms).
58pub const HEALTH_MAINTENANCE: &str = "maintenance";
59
60/// The all-zeroes oid: git's "this ref did not exist" / "this ref is being
61/// deleted" sentinel. Length differs per hash kind, so use [`null_oid`].
62pub fn null_oid(kind: HashKind) -> &'static str {
63 match kind {
64 HashKind::Sha256 => "0000000000000000000000000000000000000000000000000000000000000000",
65 // Unspecified is treated as sha1 here on purpose: an unspecified hash
66 // kind on the wire comes from an older peer, and sha1 is what those
67 // speak. Nothing writes an unspecified kind.
68 HashKind::Sha1 | HashKind::Unspecified => "0000000000000000000000000000000000000000",
69 }
70}
71
72/// Most components a repository path may have: up to three namespace levels
73/// plus the repository name.
74///
75/// **This must equal `gunnar_core::sandbox::MAX_COMPONENTS`**, and there is no
76/// construction that keeps it so: the two crates cannot depend on each other
77/// (see `tests/nested_namespace.rs`). `the_component_bound_is_the_sandboxs_and_
78/// not_a_second_number` is the guard that says they still agree; it reads the
79/// real constant, so it goes red the day either side moves.
80pub const MAX_COMPONENTS: usize = 4;
81
82/// Why a `<namespace>/<repo>` string was rejected.
83///
84/// This is a *shape* check, not the SSH path sandbox. That one guards a
85/// resolved filesystem-ish path and lives in `gunnar-core`. This one exists so
86/// a malformed path is rejected at the edge of the control plane with a
87/// specific reason rather than becoming a confusing NotFound. It is
88/// deliberately the **laxer** of the two: everything the sandbox accepts must
89/// pass here, and the sandbox itself is what refuses the rest one layer
90/// down.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum RepoPathError {
93 Empty,
94 /// No `/` at all, or a `/` in the repository half, which is one component
95 /// by definition however deeply the namespace nests.
96 NotTwoSegments,
97 EmptyNamespace,
98 EmptyRepo,
99 /// `.`, `..`, a NUL, a control character, a backslash or a colon.
100 IllegalCharacter(&'static str),
101 /// More than [`MAX_COMPONENTS`] components: namespace levels plus the
102 /// repository name.
103 TooManyComponents,
104}
105
106impl std::fmt::Display for RepoPathError {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 match self {
109 Self::Empty => f.write_str("repository path is empty"),
110 Self::NotTwoSegments => {
111 f.write_str("repository path must be exactly `<namespace>/<repo>`")
112 }
113 Self::EmptyNamespace => f.write_str("namespace is empty"),
114 Self::EmptyRepo => f.write_str("repository name is empty"),
115 Self::IllegalCharacter(what) => write!(f, "illegal in a repository path: {what}"),
116 Self::TooManyComponents => write!(
117 f,
118 "repository path has more than {MAX_COMPONENTS} components"
119 ),
120 }
121 }
122}
123
124impl std::error::Error for RepoPathError {}
125
126/// **The one renderer of `gunnar issuer show`.**
127///
128/// Both halves of the verb print through this: the offline one, which builds
129/// this message out of the data root under its feet, and the `--at` one, which
130/// receives it over `Admin.IssuerInfo`. The lines are therefore identical by
131/// construction rather than by two people keeping two `println!` blocks in
132/// step — and "the box answers something different over the wire than it says
133/// on its own disk" is not a state this verb can reach.
134///
135/// It lives in `gunnar-proto` because that is the one crate both the server
136/// and the control client already depend on, and because the wire message IS
137/// the shape of the answer; a renderer beside it in either crate would make
138/// the other one the copy.
139impl IssuerInfoResponse {
140 /// The `issuer show` report, ending in a newline.
141 ///
142 /// `pem` additionally prints the issuer certificate itself, so it can be
143 /// piped straight to a client that needs to pin it.
144 pub fn render(&self, pem: bool) -> String {
145 let mut out = String::new();
146 if self.has_issuer {
147 out.push_str(&format!(
148 "issuer\t{}\t{}\t{}\n",
149 self.subject, self.fingerprint, self.origin
150 ));
151 if pem {
152 out.push_str(&self.cert_pem);
153 if !self.cert_pem.ends_with('\n') {
154 out.push('\n');
155 }
156 }
157 } else {
158 out.push_str("no issuer. `gunnar issuer create` mints one\n");
159 }
160 // Printed even when it holds only the issuer, because "which CAs does
161 // this server verify against" is a different question from "which one
162 // does it mint with", and an operator mid-rotation is asking the first.
163 for ca in &self.trusted {
164 out.push_str(&format!(
165 "trusted\t{}\t{}\t{}\n",
166 ca.fingerprint,
167 if ca.is_issuer { "issuer" } else { "ca" },
168 ca.label
169 ));
170 }
171 out
172 }
173}
174
175impl RepoPath {
176 pub fn new(namespace: impl Into<String>, repo: impl Into<String>) -> Self {
177 Self {
178 namespace: namespace.into(),
179 repo: repo.into(),
180 }
181 }
182
183 /// Parse `"<namespace>/<repo>"`, tolerating a trailing `.git` because that
184 /// is how the same repo is spelled over SSH.
185 ///
186 /// **The split is at the LAST `/`.** A namespace may itself be nested, so
187 /// `team/sub/repo.git` is `team/sub` and `repo`. Nested
188 /// namespaces are first class and the SSH sandbox already serves them. A
189 /// `RepoPath` that could not spell one made those repositories invisible to
190 /// every gRPC consumer while `git` cloned them happily.
191 ///
192 /// Rejects: empty halves, no `/` at all, more than [`MAX_COMPONENTS`]
193 /// components, `.`/`..`, NUL, control characters, `\` and `:`.
194 pub fn parse(s: &str) -> Result<Self, RepoPathError> {
195 let s = s.strip_suffix(".git").unwrap_or(s);
196 if s.is_empty() {
197 return Err(RepoPathError::Empty);
198 }
199 let Some((namespace, repo)) = s.rsplit_once('/') else {
200 return Err(RepoPathError::NotTwoSegments);
201 };
202 if namespace.is_empty() {
203 return Err(RepoPathError::EmptyNamespace);
204 }
205 if repo.is_empty() {
206 return Err(RepoPathError::EmptyRepo);
207 }
208 let path = Self::new(namespace, repo);
209 path.validate()?;
210 Ok(path)
211 }
212
213 /// The same checks [`RepoPath::parse`] applies, against an already-split
214 /// path, which is the form every request carries.
215 pub fn validate(&self) -> Result<(), RepoPathError> {
216 if self.namespace.is_empty() {
217 return Err(RepoPathError::EmptyNamespace);
218 }
219 if self.repo.is_empty() {
220 return Err(RepoPathError::EmptyRepo);
221 }
222 // The repository half is exactly one component, however deeply the
223 // namespace nests. A `/` here is a path that was split in the wrong
224 // place; `parse` splits at the last one for precisely this reason.
225 if self.repo.contains('/') {
226 return Err(RepoPathError::NotTwoSegments);
227 }
228
229 // Content before count, matching `gunnar_core::sandbox`: a traversal is
230 // reported as a traversal rather than as "too many components", because
231 // the reason ends up in a log line an operator has to act on.
232 let mut components = 0usize;
233 for segment in self.namespace.split('/').chain([self.repo.as_str()]) {
234 components += 1;
235 // A leading, trailing or doubled `/` in the namespace. The repo
236 // half was ruled out above, so this can only be a namespace level.
237 if segment.is_empty() {
238 return Err(RepoPathError::EmptyNamespace);
239 }
240 if segment == "." || segment == ".." {
241 return Err(RepoPathError::IllegalCharacter("`.` or `..`"));
242 }
243 if segment.contains('\0') {
244 return Err(RepoPathError::IllegalCharacter("a NUL byte"));
245 }
246 if segment.chars().any(char::is_control) {
247 return Err(RepoPathError::IllegalCharacter("a control character"));
248 }
249 if segment.contains('\\') {
250 return Err(RepoPathError::IllegalCharacter("a backslash"));
251 }
252 if segment.contains(':') {
253 return Err(RepoPathError::IllegalCharacter("a colon"));
254 }
255 }
256 if components > MAX_COMPONENTS {
257 return Err(RepoPathError::TooManyComponents);
258 }
259 Ok(())
260 }
261}
262
263impl std::fmt::Display for RepoPath {
264 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265 write!(f, "{}/{}", self.namespace, self.repo)
266 }
267}
268
269impl Event {
270 /// The [`EventKind`] a payload belongs to.
271 ///
272 /// `Event.kind` is a separate field from the `oneof` so that a subscriber
273 /// can filter without matching, but two sources of truth is exactly the
274 /// shape that drifts. This is the one writer both go through (one
275 /// implementation), and [`Event::kind_matches_payload`] is the guard that
276 /// says they agree.
277 pub fn kind_of(payload: &event::Payload) -> EventKind {
278 match payload {
279 event::Payload::RefUpdated(_) => EventKind::RefUpdated,
280 event::Payload::RefDeleted(_) => EventKind::RefDeleted,
281 event::Payload::PushRejected(_) => EventKind::PushRejected,
282 event::Payload::RepoCreated(_) => EventKind::RepoCreated,
283 event::Payload::RepoDeleted(_) => EventKind::RepoDeleted,
284 event::Payload::MirrorSynced(_) => EventKind::MirrorSynced,
285 event::Payload::KeyUsed(_) => EventKind::KeyUsed,
286 event::Payload::PushAttestation(_) => EventKind::PushAttestation,
287 event::Payload::Gap(_) => EventKind::Gap,
288 event::Payload::ReplicationFailed(_) => EventKind::ReplicationFailed,
289 event::Payload::PullRequestOpened(_) => EventKind::PullRequestOpened,
290 event::Payload::PullRequestMerged(_) => EventKind::PullRequestMerged,
291 event::Payload::PullRequestClosed(_) => EventKind::PullRequestClosed,
292 event::Payload::StreamOpened(_) => EventKind::StreamOpened,
293 event::Payload::VisibilityChanged(_) => EventKind::VisibilityChanged,
294 event::Payload::EncryptedChanged(_) => EventKind::EncryptedChanged,
295 }
296 }
297
298 /// Build an event whose `kind` cannot disagree with its payload.
299 pub fn new(seq: u64, at_unix_ms: i64, payload: event::Payload) -> Self {
300 Self {
301 seq,
302 at_unix_ms,
303 kind: Self::kind_of(&payload) as i32,
304 payload: Some(payload),
305 }
306 }
307
308 /// False when `kind` and the payload variant disagree, or when the payload
309 /// is missing. Used by tests and by the bus as a cheap self-check.
310 pub fn kind_matches_payload(&self) -> bool {
311 match &self.payload {
312 Some(payload) => self.kind == Self::kind_of(payload) as i32,
313 None => false,
314 }
315 }
316
317 /// The repository this event is about, when it is about one. `KeyUsed` may
318 /// have none (an auth event is not repo-scoped), and neither `EventGap` nor
319 /// `StreamOpened` ever has: both are facts about the STREAM, not about a
320 /// repository.
321 pub fn repo_path(&self) -> Option<&RepoPath> {
322 match self.payload.as_ref()? {
323 event::Payload::RefUpdated(e) => e.repo.as_ref(),
324 event::Payload::RefDeleted(e) => e.repo.as_ref(),
325 event::Payload::PushRejected(e) => e.repo.as_ref(),
326 event::Payload::RepoCreated(e) => e.repo.as_ref()?.path.as_ref(),
327 event::Payload::RepoDeleted(e) => e.repo.as_ref(),
328 event::Payload::MirrorSynced(e) => e.repo.as_ref(),
329 event::Payload::KeyUsed(e) => e.repo.as_ref(),
330 event::Payload::PushAttestation(e) => e.repo.as_ref(),
331 event::Payload::Gap(_) => None,
332 event::Payload::ReplicationFailed(e) => e.repo.as_ref(),
333 event::Payload::PullRequestOpened(e) => e.repo.as_ref(),
334 event::Payload::PullRequestMerged(e) => e.repo.as_ref(),
335 event::Payload::PullRequestClosed(e) => e.repo.as_ref(),
336 event::Payload::StreamOpened(_) => None,
337 event::Payload::VisibilityChanged(e) => e.repo.as_ref(),
338 event::Payload::EncryptedChanged(e) => e.repo.as_ref(),
339 }
340 }
341}
342
343/// **The most of a peer's CLAIMED length this process reserves before the bytes arrive**
344/// (2026-09-16, lane AUDIT-TWIN).
345///
346/// `LogChunk.blob_len` is a number the other end sent. Every reassembler in the tree used it
347/// directly — `Vec::with_capacity(chunk.blob_len as usize)` — in `Bootstrap.Restore`'s handler,
348/// in the twin's `Mirror.LogFetch` client and in the CLI's replay pump. A frame's blob is a
349/// whole pack and may legitimately be gigabytes, so there is no honest ceiling on the VALUE;
350/// there is one on what may be reserved on the strength of it, because the claim is checked
351/// only after the item ends (`{} of {} blob bytes arrived`) — which is after the allocator has
352/// already been asked.
353///
354/// What that cost, on the two shapes that matter:
355///
356/// * `u64::MAX` — `Vec::with_capacity` panics `capacity overflow` (over `isize::MAX`), and the
357/// panic is inside a tonic handler, so the call dies and takes its connection with it;
358/// * a merely impossible number, say 1 TiB on a 1 GiB appliance — no overflow, so the allocator
359/// is asked for it, Linux's default overcommit heuristic refuses an obviously impossible
360/// request, and a Rust allocation failure is not catchable: the PROCESS ABORTS.
361///
362/// `Bootstrap.Restore` is served WITHOUT a credential while a box is fresh — which is exactly
363/// when it is sitting on the network waiting to be enrolled — so that abort is unauthenticated.
364///
365/// 8 MiB is eight `CHUNK_BYTES` pieces: the common case still reserves its blob in one go, and
366/// a lie costs 8 MiB and a few `Vec` growths before the length check refuses it by name.
367pub const TRUSTED_PREALLOC_BYTES: u64 = 8 << 20;
368
369/// The tunnel answer as `key value` lines — what the SSH door prints and
370/// `gunnar control tunnel` parses back ([`parse_tunnel_answer`]): the output of the
371/// SSH door's `gunnar-tunnel-address` (2026-09-21, T17). One writer, one reader, both here.
372pub fn render_tunnel_answer(a: &AssignTunnelAddressResponse) -> String {
373 format!(
374 "wg_public_key {}\naddress {}\nchanged {}\ntunnel_up {}\ndetail {}\n",
375 a.wg_public_key,
376 if a.address.is_empty() { "-" } else { &a.address },
377 a.changed,
378 a.tunnel_up,
379 a.detail.replace('\n', " ")
380 )
381}
382
383/// The inverse of [`render_tunnel_answer`]; `error: …` lines are the door's
384/// refusal and come back as `Err`.
385pub fn parse_tunnel_answer(text: &str) -> std::result::Result<AssignTunnelAddressResponse, String> {
386 if let Some(why) = text.lines().find_map(|l| l.strip_prefix("error: ")) {
387 return Err(why.to_string());
388 }
389 let mut a = AssignTunnelAddressResponse::default();
390 for line in text.lines() {
391 let (k, v) = line.split_once(' ').unwrap_or((line, ""));
392 match k {
393 "wg_public_key" => a.wg_public_key = v.to_string(),
394 "address" => a.address = if v == "-" { String::new() } else { v.to_string() },
395 "changed" => a.changed = v == "true",
396 "tunnel_up" => a.tunnel_up = v == "true",
397 "detail" => a.detail = v.to_string(),
398 _ => {}
399 }
400 }
401 if a.wg_public_key.is_empty() {
402 return Err(format!("not a tunnel answer: {text:?}"));
403 }
404 Ok(a)
405}
406
407/// How much to reserve for a blob the other end says is `claimed` bytes long. Never more than
408/// [`TRUSTED_PREALLOC_BYTES`]; the rest is grown as the bytes actually arrive.
409pub fn reserve_for(claimed: u64) -> usize {
410 claimed.min(TRUSTED_PREALLOC_BYTES) as usize
411}
412
413/// `812 MB/s` / `1.9 GB/s` — a `disk_seq_*_bps` field read as a human reads
414/// it, in decimal units, as disks are sold.
415///
416/// It lives HERE, beside the fields, because two callers need the same
417/// spelling and they are in different crates: the server's own
418/// `disktest::fmt_rate` writes the console row, and `gunnar control capacity`
419/// prints the wire field. A second spelling of a unit is a drift with no
420/// symptom until two numbers that are equal read differently.
421pub fn fmt_rate_bps(bps: u64) -> String {
422 let v = bps as f64;
423 if v >= 1e9 {
424 format!("{:.1} GB/s", v / 1e9)
425 } else if v >= 1e6 {
426 format!("{:.0} MB/s", v / 1e6)
427 } else {
428 format!("{:.0} kB/s", v / 1e3)
429 }
430}
431
432#[cfg(test)]
433mod rate_tests {
434 /// The same three cases `gunnar_server::disktest::fmt_rate` is asserted
435 /// on, so the two spellings cannot drift apart unnoticed.
436 #[test]
437 fn a_rate_reads_in_the_units_disks_are_sold_in() {
438 assert_eq!(super::fmt_rate_bps(812_000_000), "812 MB/s");
439 assert_eq!(super::fmt_rate_bps(1_900_000_000), "1.9 GB/s");
440 assert_eq!(super::fmt_rate_bps(512_000), "512 kB/s");
441 }
442}
443
444#[cfg(test)]
445mod prealloc_tests {
446 use super::*;
447
448 /// **A length a peer sent is not a length to allocate.**
449 ///
450 /// Red with the old expression (`claimed as usize`): `u64::MAX` reaches
451 /// `Vec::with_capacity` and panics `capacity overflow` inside whatever handler is
452 /// reassembling — and `Bootstrap.Restore`'s handler needs no credential on a fresh box.
453 #[test]
454 fn a_claimed_length_never_becomes_a_reservation_on_its_own() {
455 for claimed in [u64::MAX, u64::MAX / 2, 1 << 40, (8 << 20) + 1] {
456 let reserved = reserve_for(claimed);
457 assert!(reserved as u64 <= TRUSTED_PREALLOC_BYTES, "{claimed} reserved {reserved}");
458 // The reservation is one the allocator will actually take.
459 let v: Vec<u8> = Vec::with_capacity(reserved);
460 assert!(v.capacity() >= reserved);
461 }
462 // An honest small length is still reserved exactly, so the common case allocates once.
463 for claimed in [0u64, 1, 4096, 8 << 20] {
464 assert_eq!(reserve_for(claimed) as u64, claimed);
465 }
466 }
467}