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, PostParams};
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 Err(kube::Error::Api(e)) if e.code == 404 => {
135 (StatusCode::OK, "allocation already gone").into_response()
136 }
137 Err(e) => {
138 warn!(error = %e, "delete failed");
139 (StatusCode::INTERNAL_SERVER_ERROR, format!("delete: {e}")).into_response()
140 }
141 }
142 }
143 PrAction::Opened | PrAction::Reopened | PrAction::Synchronize => {
144 // Build + create-or-replace the allocation.
145 let alloc = match build_allocation(
146 &evt,
147 &state.config.namespace,
148 state.config.pin_pool.as_deref(),
149 state.config.include_drafts,
150 ) {
151 Ok(a) => a,
152 Err(FactoryError::DraftExcluded) => {
153 info!("draft PR — skipping allocation");
154 return (StatusCode::OK, "draft excluded").into_response();
155 }
156 Err(FactoryError::NotAllocatable(_)) => {
157 return (StatusCode::OK, "action not allocatable").into_response();
158 }
159 };
160 // `Api<EphemeralAllocation>` binds via the ONE substrate
161 // primitive `HandlerState::allocation_api` — pre-lift this
162 // was a hand-authored `Api::namespaced(state.kube.clone(),
163 // &state.config.namespace)` chain, peer to the
164 // `PrAction::Closed` delete-branch slot already routed
165 // through the primitive above. Post-lift both consumers
166 // share ONE substrate owner.
167 let api = state.allocation_api();
168 match api.create(&PostParams::default(), &alloc).await {
169 Ok(_) => {
170 info!(
171 namespace = %state.config.namespace,
172 allocation = alloc.metadata.name.as_deref().unwrap_or("?"),
173 pr_number = evt.number,
174 repo = %evt.repository.full_name,
175 "PR event → created Allocation"
176 );
177 (StatusCode::CREATED, "allocation created").into_response()
178 }
179 Err(kube::Error::Api(e)) if e.code == 409 => {
180 // Already exists — refresh via PATCH (synchronize event).
181 (StatusCode::OK, "allocation already exists (synchronize)").into_response()
182 }
183 Err(e) => {
184 warn!(error = %e, "create allocation failed");
185 (StatusCode::INTERNAL_SERVER_ERROR, format!("create: {e}")).into_response()
186 }
187 }
188 }
189 PrAction::Other => (StatusCode::OK, "action ignored").into_response(),
190 }
191}
192
193fn repo_allowed(repo: &str, allowlist: &[String]) -> bool {
194 allowlist.iter().any(|p| repo_matches(p, repo))
195}
196
197fn repo_matches(pattern: &str, repo: &str) -> bool {
198 if let Some(prefix) = pattern.strip_suffix("/*") {
199 repo.starts_with(&format!("{prefix}/"))
200 } else {
201 pattern == repo
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 // ─── HandlerState api-primitive substrate pins ─────────────────
210 //
211 // The two-slot `(state.kube.clone(), &state.config.namespace)`
212 // incantation was hand-authored at TWO sites in
213 // `handle_pr_event` before `HandlerState::allocation_api` closed
214 // it. These pins bind the primitive at fail-before-pass-after
215 // granularity so a regression that drifts the configured
216 // namespace, the resource kind, or the reused client-slot
217 // surfaces here rather than as silent operator-facing drift at
218 // every downstream webhook path.
219 //
220 // `Client::try_from(Config::new(url))` needs a live tokio
221 // reactor (`tower::buffer::Buffer::new` spawns a background task
222 // on construction), so every pin runs under `#[tokio::test]`.
223 #[cfg(test)]
224 mod api_primitive_pins {
225 use super::*;
226 use kube::Config;
227
228 fn state_with_namespace(namespace: &str) -> HandlerState {
229 let url = "http://localhost:9999".parse().expect("valid probe url");
230 let client = Client::try_from(Config::new(url)).expect("build kube client");
231 let config = WatcherConfig {
232 listen: "0.0.0.0:8080".into(),
233 secret: "test-secret".into(),
234 namespace: namespace.into(),
235 pin_pool: None,
236 include_drafts: false,
237 allow_repos: Vec::new(),
238 };
239 HandlerState {
240 config: Arc::new(config),
241 kube: client,
242 }
243 }
244
245 #[tokio::test]
246 async fn allocation_api_binds_configured_namespace_into_resource_url() {
247 // The webhook handler reads the target namespace from
248 // `state.config.namespace` (operator-configured via
249 // `TATARA_WATCHER_NAMESPACE`) and expects
250 // `state.allocation_api()` to bind that namespace onto
251 // the returned Api's REST path — the primitive routes
252 // the configured slot through to the `Api::namespaced`
253 // dispatcher's `ns` argument unchanged.
254 let state = state_with_namespace("watcher-test-ns");
255 let api = state.allocation_api();
256 let url = api.resource_url();
257 assert!(
258 url.contains("/namespaces/watcher-test-ns/"),
259 "allocation_api resource url must carry the configured namespace verbatim; got {url}"
260 );
261 }
262
263 #[tokio::test]
264 async fn allocation_api_binds_the_ephemeral_allocation_kind() {
265 // The typed `Api<EphemeralAllocation>` return pins the
266 // resource kind at rustc time; this pin adds the runtime
267 // witness — the emitted REST path targets the
268 // `tatara.pleme.io/v1alpha1/ephemeralallocations`
269 // collection matching the `#[kube(group =
270 // "tatara.pleme.io", version = "v1alpha1", plural =
271 // "ephemeralallocations")]` attribute on
272 // `AllocationSpec`.
273 let state = state_with_namespace("default");
274 let api = state.allocation_api();
275 let url = api.resource_url();
276 assert!(
277 url.starts_with("/apis/tatara.pleme.io/v1alpha1/"),
278 "Api resource url must be scoped to the tatara.pleme.io/v1alpha1 group; got {url}"
279 );
280 assert!(
281 url.ends_with("/ephemeralallocations"),
282 "Api resource url must terminate at the `ephemeralallocations` collection; got {url}"
283 );
284 }
285
286 #[tokio::test]
287 async fn allocation_api_matches_hand_authored_pre_lift_bytewise() {
288 // Bytewise equivalence with the pre-lift `Api::namespaced
289 // (state.kube.clone(), &state.config.namespace)` chain —
290 // the primitive changes the authoring surface, not the
291 // observable REST path, so a regression that drifts the
292 // routing on this primitive surfaces here rather than as
293 // silent operator-facing drift at every handler branch.
294 for ns in ["default", "ephemeral-pools", "watcher-alt"] {
295 let state = state_with_namespace(ns);
296 let via_primitive = state.allocation_api();
297 let via_pre_lift: Api<EphemeralAllocation> =
298 Api::namespaced(state.kube.clone(), &state.config.namespace);
299 assert_eq!(
300 via_primitive.resource_url(),
301 via_pre_lift.resource_url(),
302 "allocation_api must be byte-identical to the pre-lift chain for ns={ns:?}"
303 );
304 }
305 }
306 }
307
308 #[test]
309 fn repo_matches_exact() {
310 assert!(repo_matches("pleme-io/demo-app", "pleme-io/demo-app"));
311 assert!(!repo_matches("pleme-io/demo-app", "pleme-io/other"));
312 }
313
314 #[test]
315 fn repo_matches_org_wildcard() {
316 assert!(repo_matches("pleme-io/*", "pleme-io/demo-app"));
317 assert!(repo_matches("pleme-io/*", "pleme-io/tatara"));
318 assert!(!repo_matches("pleme-io/*", "drzln/dotfiles"));
319 }
320
321 #[test]
322 fn empty_allowlist_skipped_at_caller() {
323 // The caller's check `!allowlist.is_empty()` gates this function;
324 // sanity test that an empty allowlist would reject everything if
325 // called directly.
326 assert!(!repo_allowed("anything", &[]));
327 }
328
329 #[test]
330 fn allowlist_with_one_pattern_filters() {
331 let allow = vec!["pleme-io/*".to_string()];
332 assert!(repo_allowed("pleme-io/demo-app", &allow));
333 assert!(!repo_allowed("drzln/dotfiles", &allow));
334 }
335}