zeph-gateway 0.22.4

HTTP gateway for webhook ingestion with bearer auth for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use axum::Json;
use axum::extract::State;
use axum::extract::rejection::JsonRejection;
use axum::http::StatusCode;
use axum::response::IntoResponse;

use super::server::AppState;

/// JSON body returned for all error responses from `POST /webhook`.
#[derive(serde::Serialize)]
struct ErrorResponse {
    error: String,
    status: u16,
}

/// JSON body expected on `POST /webhook`.
///
/// All three fields are required.  Individual field limits are enforced by
/// [`WebhookPayload::validate`] before the message is forwarded to the agent.
#[derive(serde::Deserialize)]
pub(crate) struct WebhookPayload {
    /// Logical channel name (e.g. `"discord"`, `"slack"`). Maximum 256 bytes.
    pub channel: String,
    /// Display name or identifier of the message sender. Maximum 256 bytes.
    pub sender: String,
    /// Raw message content. Maximum 65 536 bytes.
    pub body: String,
}

impl WebhookPayload {
    /// Validate field lengths before forwarding to the agent.
    ///
    /// Returns `Ok(())` when all fields are within their limits, or `Err` with a
    /// human-readable description of the first violation.
    ///
    /// | Field | Limit |
    /// |---|---|
    /// | `sender` | 256 bytes |
    /// | `channel` | 256 bytes |
    /// | `body` | 65 536 bytes |
    pub(crate) fn validate(&self) -> Result<(), &'static str> {
        if self.sender.len() > 256 {
            return Err("sender exceeds 256 bytes");
        }
        if self.channel.len() > 256 {
            return Err("channel exceeds 256 bytes");
        }
        if self.body.len() > 65536 {
            return Err("body exceeds 65536 bytes");
        }
        Ok(())
    }
}

/// JSON body returned by a successful `POST /webhook` call.
#[derive(serde::Serialize)]
struct WebhookResponse {
    /// Always `"accepted"` on success.
    status: &'static str,
}

/// A validated, control-character-stripped webhook payload forwarded to the agent-input
/// forwarder (`forward_webhooks` in the `zeph` binary).
///
/// Deliberately carries `sender`/`channel`/`body` as separate fields rather than a
/// pre-formatted `"[sender@channel] body"` string: deciding whether `body` is a recognized
/// slash command (and, if so, skipping both the display prefix and the `ExternalUntrusted`
/// sanitizer wrap so the agent's dispatch registries see the raw command) requires
/// `zeph-commands`/`zeph-core`, neither of which this crate depends on. That decision is made
/// downstream by the forwarder, which already depends on both.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebhookMessage {
    /// Display name or identifier of the message sender, control-character-stripped.
    pub sender: String,
    /// Logical channel name (e.g. `"discord"`, `"slack"`), control-character-stripped.
    pub channel: String,
    /// Raw message body, control-character-stripped.
    pub body: String,
}

/// JSON body returned by `GET /health`.
#[derive(serde::Serialize)]
struct HealthResponse {
    /// Always `"ok"`.
    status: &'static str,
    /// Seconds elapsed since the server started.
    uptime_secs: u64,
}

/// Handler for `POST /webhook`.
///
/// Validates the payload, sanitises `sender`, `channel`, and `body` by stripping
/// control characters, then forwards a [`WebhookMessage`] on the internal webhook
/// channel. Display-prefix formatting, slash-command detection, and
/// `ExternalUntrusted` sanitization all happen downstream in the forwarder (see
/// [`WebhookMessage`]'s doc comment for why).
///
/// The send is wrapped in a timeout (`AppState::webhook_send_timeout`).  If the
/// agent cannot consume the message within that window, the handler returns
/// `503 Service Unavailable` rather than blocking the Axum worker indefinitely.
///
/// # Responses
///
/// | Status | Condition |
/// |---|---|
/// | 200 | Message accepted and queued |
/// | 422 | Payload failed field-length validation |
/// | 503 | Internal channel closed or send timed out due to backpressure |
#[tracing::instrument(name = "gateway.webhook", skip_all)]
pub(crate) async fn webhook_handler(
    State(state): State<AppState>,
    payload: Result<Json<WebhookPayload>, JsonRejection>,
) -> impl IntoResponse {
    let Json(payload) = match payload {
        Ok(p) => p,
        Err(e) => {
            return (
                e.status(),
                Json(ErrorResponse {
                    error: e.body_text(),
                    status: e.status().as_u16(),
                }),
            )
                .into_response();
        }
    };
    if let Err(e) = payload.validate() {
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(ErrorResponse {
                error: e.to_string(),
                status: StatusCode::UNPROCESSABLE_ENTITY.as_u16(),
            }),
        )
            .into_response();
    }
    let sender = zeph_common::sanitize::strip_control_chars_preserve_whitespace(&payload.sender);
    let channel = zeph_common::sanitize::strip_control_chars_preserve_whitespace(&payload.channel);
    let body = zeph_common::sanitize::strip_control_chars_preserve_whitespace(&payload.body);
    let msg = WebhookMessage {
        sender,
        channel,
        body,
    };
    match tokio::time::timeout(state.webhook_send_timeout, state.webhook_tx.send(msg)).await {
        Ok(Ok(())) => Json(WebhookResponse { status: "accepted" }).into_response(),
        Ok(Err(_)) => (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ErrorResponse {
                error: "agent unavailable".to_string(),
                status: StatusCode::SERVICE_UNAVAILABLE.as_u16(),
            }),
        )
            .into_response(),
        Err(_elapsed) => {
            tracing::warn!(
                timeout_secs = state.webhook_send_timeout.as_secs_f64(),
                "webhook send timed out: agent backpressure"
            );
            (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(ErrorResponse {
                    error: "service unavailable: agent backpressure".to_string(),
                    status: StatusCode::SERVICE_UNAVAILABLE.as_u16(),
                }),
            )
                .into_response()
        }
    }
}

/// Handler for `GET /health`.
///
/// Returns a JSON object with a static `"ok"` status and the server uptime in
/// seconds.  This endpoint bypasses authentication and rate limiting so that
/// load balancers can poll it freely.
///
/// # Response body
///
/// ```json
/// { "status": "ok", "uptime_secs": 42 }
/// ```
#[tracing::instrument(name = "gateway.health", skip_all)]
pub(crate) async fn health_handler(State(state): State<AppState>) -> impl IntoResponse {
    Json(HealthResponse {
        status: "ok",
        uptime_secs: state.started_at.elapsed().as_secs(),
    })
}

/// Handler for `GET /metrics` (Prometheus scrape endpoint).
///
/// Returns the current registry contents encoded as `OpenMetrics` 1.0.0 text format, suitable for
/// scraping by Prometheus or any compatible monitoring system.
///
/// This handler requires `State<Arc<Registry>>` injected via the nested router in
/// [`crate::GatewayServer::with_metrics_registry`].
///
/// # Responses
///
/// | Status | Condition |
/// |---|---|
/// | 200 | Registry encoded successfully; `Content-Type: application/openmetrics-text; version=1.0.0; charset=utf-8` |
/// | 500 | Registry encoding failed (logged as error) |
#[cfg(feature = "prometheus")]
#[tracing::instrument(name = "gateway.metrics", skip_all)]
pub(crate) async fn metrics_handler(
    axum::extract::State(registry): axum::extract::State<
        std::sync::Arc<prometheus_client::registry::Registry>,
    >,
) -> impl axum::response::IntoResponse {
    let mut buf = String::new();
    match prometheus_client::encoding::text::encode(&mut buf, &registry) {
        Ok(()) => (
            [(
                axum::http::header::CONTENT_TYPE,
                "application/openmetrics-text; version=1.0.0; charset=utf-8",
            )],
            buf,
        )
            .into_response(),
        Err(e) => {
            tracing::error!("failed to encode prometheus metrics: {e}");
            (
                axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                "metrics encoding failed",
            )
                .into_response()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{Duration, Instant};

    #[test]
    fn health_response_serializes() {
        let resp = HealthResponse {
            status: "ok",
            uptime_secs: 42,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("\"status\":\"ok\""));
    }

    #[test]
    fn webhook_payload_deserializes() {
        let json = r#"{"channel":"discord","sender":"user1","body":"hello"}"#;
        let payload: WebhookPayload = serde_json::from_str(json).unwrap();
        assert_eq!(payload.channel, "discord");
        assert_eq!(payload.sender, "user1");
        assert_eq!(payload.body, "hello");
    }

    #[test]
    fn validate_accepts_valid_payload() {
        let payload = WebhookPayload {
            channel: "ch".into(),
            sender: "user".into(),
            body: "hello".into(),
        };
        assert!(payload.validate().is_ok());
    }

    #[test]
    fn validate_rejects_oversized_sender() {
        let payload = WebhookPayload {
            channel: "ch".into(),
            sender: "a".repeat(257),
            body: "hello".into(),
        };
        assert!(payload.validate().is_err());
    }

    #[test]
    fn validate_rejects_oversized_channel() {
        let payload = WebhookPayload {
            channel: "c".repeat(257),
            sender: "user".into(),
            body: "hello".into(),
        };
        assert!(payload.validate().is_err());
    }

    #[test]
    fn validate_rejects_oversized_body() {
        let payload = WebhookPayload {
            channel: "ch".into(),
            sender: "user".into(),
            body: "b".repeat(65537),
        };
        assert!(payload.validate().is_err());
    }

    #[test]
    fn sanitize_strips_control_chars_keeps_newline() {
        let input = "hel\x01lo\x7f\nworld";
        let result = zeph_common::sanitize::strip_control_chars_preserve_whitespace(input);
        assert_eq!(result, "hello\nworld");
    }

    #[test]
    fn sanitize_strips_null_byte() {
        let input = "he\x00llo";
        let result = zeph_common::sanitize::strip_control_chars_preserve_whitespace(input);
        assert_eq!(result, "hello");
    }

    /// When the webhook channel is full and the send times out, the handler must
    /// return 503 rather than blocking the Axum worker indefinitely.
    #[tokio::test]
    async fn webhook_handler_returns_503_on_send_timeout() {
        use axum::extract::State;
        use axum::response::IntoResponse as _;

        let (tx, _rx) = tokio::sync::mpsc::channel::<WebhookMessage>(1);
        // Fill the channel so the next send() will block.
        tx.send(WebhookMessage {
            sender: "fill".into(),
            channel: "fill".into(),
            body: "fill".into(),
        })
        .await
        .unwrap();

        let state = AppState {
            webhook_tx: tx,
            started_at: Instant::now(),
            webhook_send_timeout: Duration::from_millis(5),
        };

        let payload = WebhookPayload {
            channel: "ch".into(),
            sender: "user".into(),
            body: "hello".into(),
        };

        let response = webhook_handler(State(state), Ok(axum::Json(payload)))
            .await
            .into_response();
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    #[test]
    fn validate_accepts_at_limit_sender() {
        let payload = WebhookPayload {
            channel: "ch".into(),
            sender: "a".repeat(256),
            body: "hello".into(),
        };
        assert!(payload.validate().is_ok());
    }

    #[test]
    fn validate_accepts_at_limit_channel() {
        let payload = WebhookPayload {
            channel: "c".repeat(256),
            sender: "user".into(),
            body: "hello".into(),
        };
        assert!(payload.validate().is_ok());
    }

    #[test]
    fn validate_accepts_at_limit_body() {
        let payload = WebhookPayload {
            channel: "ch".into(),
            sender: "user".into(),
            body: "b".repeat(65536),
        };
        assert!(payload.validate().is_ok());
    }

    #[tokio::test]
    async fn webhook_handler_sanitizes_body() {
        use axum::extract::State;
        use axum::response::IntoResponse as _;

        let (tx, mut rx) = tokio::sync::mpsc::channel::<WebhookMessage>(4);
        let state = AppState {
            webhook_tx: tx,
            started_at: Instant::now(),
            webhook_send_timeout: Duration::from_secs(1),
        };

        let payload = WebhookPayload {
            channel: "ch".into(),
            sender: "user".into(),
            body: "hel\x01lo\x7fworld".into(),
        };

        let response = webhook_handler(State(state), Ok(axum::Json(payload)))
            .await
            .into_response();
        assert_eq!(response.status(), StatusCode::OK);
        let msg = rx.try_recv().expect("message must be forwarded");
        assert_eq!(
            msg,
            WebhookMessage {
                sender: "user".into(),
                channel: "ch".into(),
                body: "helloworld".into(),
            }
        );
    }
}