tatara_github_watcher/handler.rs
1//! axum HTTP handler — verify signature, dispatch on event kind, apply
2//! resulting Allocation via kube-rs.
3
4use std::sync::Arc;
5
6use axum::body::Bytes;
7use axum::extract::State;
8use axum::http::{HeaderMap, StatusCode};
9use axum::response::IntoResponse;
10use kube::api::{Api, DeleteParams};
11use kube::Client;
12use tracing::{info, warn};
13
14use tatara_process::allocation::EphemeralAllocation;
15
16use crate::allocation_factory::{allocation_name, build_allocation, FactoryError};
17use crate::config::WatcherConfig;
18use crate::event::{EventKind, PullRequestEvent};
19use crate::verify::verify_signature;
20
21/// Handler state shared across requests.
22#[derive(Clone)]
23pub struct HandlerState {
24 pub config: Arc<WatcherConfig>,
25 pub kube: Client,
26}
27
28impl HandlerState {
29 /// Namespaced `Api<EphemeralAllocation>` bound to this handler's
30 /// client + configured watcher namespace — the ONE substrate
31 /// primitive that owns the `Api::namespaced(self.kube.clone(),
32 /// &self.config.namespace)` shape for the github-watcher.
33 ///
34 /// Pre-lift the two-slot `(self.kube.clone(), &self.config.
35 /// namespace)` incantation was hand-authored at TWO sites in
36 /// `handler::handle_pr_event`, past the ★★ PRIME-DIRECTIVE ≥ 2
37 /// duplication threshold — the `PrAction::Closed` delete-branch
38 /// slot (`api.delete(&name, …)`) plus the `PrAction::{Opened,
39 /// Reopened, Synchronize}` create-branch slot (`api.create(&pp,
40 /// &alloc)`) each restated the SAME `Api::namespaced(state.kube.
41 /// clone(), &state.config.namespace)` chain verbatim. Post-lift
42 /// the two consumers share ONE substrate owner; a future emitter
43 /// of `Api<EphemeralAllocation>` on the handler reaches for
44 /// `state.allocation_api()` rather than re-authoring the two-slot
45 /// chain a third time — matching the composition discipline the
46 /// peer [`tatara_pool_reconciler::context::PoolContext::
47 /// allocation_api`] substrate primitive already establishes on
48 /// the pool-reconciler side of the same CRD.
49 ///
50 /// The typed `Api<EphemeralAllocation>` return pins the resource
51 /// kind at rustc time — a future consumer that reaches for a
52 /// different CRD via this primitive's client-slot fails to
53 /// compile rather than silently issuing a REST request under the
54 /// wrong resource plural.
55 pub fn allocation_api(&self) -> Api<EphemeralAllocation> {
56 Api::namespaced(self.kube.clone(), &self.config.namespace)
57 }
58}
59
60/// POST handler for GitHub webhooks.
61pub async fn webhook(
62 State(state): State<HandlerState>,
63 headers: HeaderMap,
64 body: Bytes,
65) -> impl IntoResponse {
66 // 1. Verify HMAC.
67 let sig_header = headers
68 .get("X-Hub-Signature-256")
69 .and_then(|v| v.to_str().ok())
70 .unwrap_or("");
71 if let Err(e) = verify_signature(sig_header, &body, state.config.secret.as_bytes()) {
72 warn!(error = %e, "webhook signature verification failed");
73 return (StatusCode::UNAUTHORIZED, format!("signature: {e}")).into_response();
74 }
75
76 // 2. Dispatch on event kind.
77 let event_header = headers
78 .get("X-GitHub-Event")
79 .and_then(|v| v.to_str().ok())
80 .unwrap_or("");
81 let kind = EventKind::from_header(event_header);
82
83 match kind {
84 EventKind::PullRequest => handle_pr_event(&state, &body).await,
85 EventKind::Push => {
86 // Push events handled by a separate path (e.g., main-branch
87 // attestation runs). v0 just acknowledges.
88 (StatusCode::OK, "push event acknowledged (not allocated)").into_response()
89 }
90 EventKind::Other => (StatusCode::OK, "event ignored").into_response(),
91 }
92}
93
94async fn handle_pr_event(state: &HandlerState, body: &[u8]) -> axum::response::Response {
95 let evt: PullRequestEvent = match serde_json::from_slice(body) {
96 Ok(e) => e,
97 Err(e) => {
98 warn!(error = %e, "failed to parse PR event");
99 return (StatusCode::BAD_REQUEST, format!("parse: {e}")).into_response();
100 }
101 };
102
103 // Repo allowlist.
104 if !state.config.allow_repos.is_empty()
105 && !repo_allowed(&evt.repository.full_name, &state.config.allow_repos)
106 {
107 info!(repo = %evt.repository.full_name, "repo not in allowlist; skipping");
108 return (StatusCode::OK, "repo not in allowlist").into_response();
109 }
110
111 use crate::event::PrAction;
112 match evt.action {
113 PrAction::Closed => {
114 // Delete the allocation; pool reconciler returns the member.
115 let name = allocation_name(&evt.repository.full_name, evt.number);
116 // `Api<EphemeralAllocation>` binds via the ONE substrate
117 // primitive `HandlerState::allocation_api` — pre-lift this
118 // was a hand-authored `Api::namespaced(state.kube.clone(),
119 // &state.config.namespace)` chain, one of TWO workspace-
120 // wide restatements past the ★★ PRIME-DIRECTIVE ≥ 2
121 // duplication threshold (peer at the `PrAction::{Opened,
122 // Reopened, Synchronize}` create-branch slot below). Post-
123 // lift the two consumers share ONE substrate owner.
124 let api = state.allocation_api();
125 match api.delete(&name, &DeleteParams::default()).await {
126 Ok(_) => {
127 info!(
128 namespace = %state.config.namespace,
129 allocation = %name,
130 "closed PR → deleted Allocation"
131 );
132 (StatusCode::OK, "allocation deleted").into_response()
133 }
134 // 404 detection rides the substrate primitive
135 // `tatara_process::kube_error::is_not_found` — pre-lift
136 // this was a hand-authored `Err(kube::Error::Api(e)) if
137 // e.code == 404` match-arm guard, one of FIVE workspace-
138 // wide restatements past the ★★ PRIME-DIRECTIVE ≥ 2
139 // duplication threshold (the OTHER four sites all key
140 // off 409, routed through the peer `is_conflict`).
141 Err(ref e) if tatara_process::kube_error::is_not_found(e) => {
142 (StatusCode::OK, "allocation already gone").into_response()
143 }
144 Err(e) => {
145 warn!(error = %e, "delete failed");
146 (StatusCode::INTERNAL_SERVER_ERROR, format!("delete: {e}")).into_response()
147 }
148 }
149 }
150 PrAction::Opened | PrAction::Reopened | PrAction::Synchronize => {
151 // Build + create-or-replace the allocation.
152 let alloc = match build_allocation(
153 &evt,
154 &state.config.namespace,
155 state.config.pin_pool.as_deref(),
156 state.config.include_drafts,
157 ) {
158 Ok(a) => a,
159 Err(FactoryError::DraftExcluded) => {
160 info!("draft PR — skipping allocation");
161 return (StatusCode::OK, "draft excluded").into_response();
162 }
163 Err(FactoryError::NotAllocatable(_)) => {
164 return (StatusCode::OK, "action not allocatable").into_response();
165 }
166 };
167 // `Api<EphemeralAllocation>` binds via the ONE substrate
168 // primitive `HandlerState::allocation_api` — pre-lift this
169 // was a hand-authored `Api::namespaced(state.kube.clone(),
170 // &state.config.namespace)` chain, peer to the
171 // `PrAction::Closed` delete-branch slot already routed
172 // through the primitive above. Post-lift both consumers
173 // share ONE substrate owner.
174 let api = state.allocation_api();
175 // Create-verb dispatch rides the substrate primitive
176 // `tatara_process::create::default` — pre-lift this was a
177 // hand-authored `api.create(&PostParams::default(), &alloc)`
178 // chain, one of FIVE workspace-wide restatements past the
179 // ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold. Post-lift
180 // the create-verb family lives at ONE substrate owner and
181 // the compound "create-or-treat-409-as-ok" idiom (pairing
182 // this call with `kube_error::is_conflict` below) reads as
183 // TWO substrate primitives composed at the callsite.
184 match tatara_process::create::default(&api, &alloc).await {
185 Ok(_) => {
186 info!(
187 namespace = %state.config.namespace,
188 allocation = alloc.metadata.name.as_deref().unwrap_or("?"),
189 pr_number = evt.number,
190 repo = %evt.repository.full_name,
191 "PR event → created Allocation"
192 );
193 (StatusCode::CREATED, "allocation created").into_response()
194 }
195 // 409 detection rides the substrate primitive
196 // `tatara_process::kube_error::is_conflict` — pre-lift
197 // this was a hand-authored `Err(kube::Error::Api(e)) if
198 // e.code == 409` match-arm guard, sibling to the 404
199 // arm above (both routed through the same substrate
200 // module's paired predicates).
201 Err(ref e) if tatara_process::kube_error::is_conflict(e) => {
202 // Already exists — refresh via PATCH (synchronize event).
203 (StatusCode::OK, "allocation already exists (synchronize)").into_response()
204 }
205 Err(e) => {
206 warn!(error = %e, "create allocation failed");
207 (StatusCode::INTERNAL_SERVER_ERROR, format!("create: {e}")).into_response()
208 }
209 }
210 }
211 PrAction::Other => (StatusCode::OK, "action ignored").into_response(),
212 }
213}
214
215fn repo_allowed(repo: &str, allowlist: &[String]) -> bool {
216 allowlist.iter().any(|p| repo_matches(p, repo))
217}
218
219fn repo_matches(pattern: &str, repo: &str) -> bool {
220 if let Some(prefix) = pattern.strip_suffix("/*") {
221 repo.starts_with(&format!("{prefix}/"))
222 } else {
223 pattern == repo
224 }
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230
231 // ─── HandlerState api-primitive substrate pins ─────────────────
232 //
233 // The two-slot `(state.kube.clone(), &state.config.namespace)`
234 // incantation was hand-authored at TWO sites in
235 // `handle_pr_event` before `HandlerState::allocation_api` closed
236 // it. These pins bind the primitive at fail-before-pass-after
237 // granularity so a regression that drifts the configured
238 // namespace, the resource kind, or the reused client-slot
239 // surfaces here rather than as silent operator-facing drift at
240 // every downstream webhook path.
241 //
242 // `Client::try_from(Config::new(url))` needs a live tokio
243 // reactor (`tower::buffer::Buffer::new` spawns a background task
244 // on construction), so every pin runs under `#[tokio::test]`.
245 #[cfg(test)]
246 mod api_primitive_pins {
247 use super::*;
248 use kube::Config;
249
250 fn state_with_namespace(namespace: &str) -> HandlerState {
251 let url = "http://localhost:9999".parse().expect("valid probe url");
252 let client = Client::try_from(Config::new(url)).expect("build kube client");
253 let config = WatcherConfig {
254 listen: "0.0.0.0:8080".into(),
255 secret: "test-secret".into(),
256 namespace: namespace.into(),
257 pin_pool: None,
258 include_drafts: false,
259 allow_repos: Vec::new(),
260 };
261 HandlerState {
262 config: Arc::new(config),
263 kube: client,
264 }
265 }
266
267 #[tokio::test]
268 async fn allocation_api_binds_configured_namespace_into_resource_url() {
269 // The webhook handler reads the target namespace from
270 // `state.config.namespace` (operator-configured via
271 // `TATARA_WATCHER_NAMESPACE`) and expects
272 // `state.allocation_api()` to bind that namespace onto
273 // the returned Api's REST path — the primitive routes
274 // the configured slot through to the `Api::namespaced`
275 // dispatcher's `ns` argument unchanged.
276 let state = state_with_namespace("watcher-test-ns");
277 let api = state.allocation_api();
278 let url = api.resource_url();
279 assert!(
280 url.contains("/namespaces/watcher-test-ns/"),
281 "allocation_api resource url must carry the configured namespace verbatim; got {url}"
282 );
283 }
284
285 #[tokio::test]
286 async fn allocation_api_binds_the_ephemeral_allocation_kind() {
287 // The typed `Api<EphemeralAllocation>` return pins the
288 // resource kind at rustc time; this pin adds the runtime
289 // witness — the emitted REST path targets the
290 // `tatara.pleme.io/v1alpha1/ephemeralallocations`
291 // collection matching the `#[kube(group =
292 // "tatara.pleme.io", version = "v1alpha1", plural =
293 // "ephemeralallocations")]` attribute on
294 // `AllocationSpec`.
295 let state = state_with_namespace("default");
296 let api = state.allocation_api();
297 let url = api.resource_url();
298 assert!(
299 url.starts_with("/apis/tatara.pleme.io/v1alpha1/"),
300 "Api resource url must be scoped to the tatara.pleme.io/v1alpha1 group; got {url}"
301 );
302 assert!(
303 url.ends_with("/ephemeralallocations"),
304 "Api resource url must terminate at the `ephemeralallocations` collection; got {url}"
305 );
306 }
307
308 #[tokio::test]
309 async fn allocation_api_matches_hand_authored_pre_lift_bytewise() {
310 // Bytewise equivalence with the pre-lift `Api::namespaced
311 // (state.kube.clone(), &state.config.namespace)` chain —
312 // the primitive changes the authoring surface, not the
313 // observable REST path, so a regression that drifts the
314 // routing on this primitive surfaces here rather than as
315 // silent operator-facing drift at every handler branch.
316 for ns in ["default", "ephemeral-pools", "watcher-alt"] {
317 let state = state_with_namespace(ns);
318 let via_primitive = state.allocation_api();
319 let via_pre_lift: Api<EphemeralAllocation> =
320 Api::namespaced(state.kube.clone(), &state.config.namespace);
321 assert_eq!(
322 via_primitive.resource_url(),
323 via_pre_lift.resource_url(),
324 "allocation_api must be byte-identical to the pre-lift chain for ns={ns:?}"
325 );
326 }
327 }
328 }
329
330 #[test]
331 fn repo_matches_exact() {
332 assert!(repo_matches("pleme-io/demo-app", "pleme-io/demo-app"));
333 assert!(!repo_matches("pleme-io/demo-app", "pleme-io/other"));
334 }
335
336 #[test]
337 fn repo_matches_org_wildcard() {
338 assert!(repo_matches("pleme-io/*", "pleme-io/demo-app"));
339 assert!(repo_matches("pleme-io/*", "pleme-io/tatara"));
340 assert!(!repo_matches("pleme-io/*", "drzln/dotfiles"));
341 }
342
343 #[test]
344 fn empty_allowlist_skipped_at_caller() {
345 // The caller's check `!allowlist.is_empty()` gates this function;
346 // sanity test that an empty allowlist would reject everything if
347 // called directly.
348 assert!(!repo_allowed("anything", &[]));
349 }
350
351 #[test]
352 fn allowlist_with_one_pattern_filters() {
353 let allow = vec!["pleme-io/*".to_string()];
354 assert!(repo_allowed("pleme-io/demo-app", &allow));
355 assert!(!repo_allowed("drzln/dotfiles", &allow));
356 }
357}