Skip to main content

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