openlatch-provider 0.2.1

Self-service onboarding CLI + runtime daemon for OpenLatch Editors and Providers
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! axum + tokio-rustls listener — the runtime daemon's HTTP server.
//!
//! Pipeline per `POST /v1/event` (Non-Negotiable order — see
//! `.claude/rules/envelope-format.md`):
//!
//! ```text
//!   1. Read raw body bytes (Bytes — no parse)
//!   2. Verify HMAC over <id>.<ts>.<body>            ─── webhook::verify
//!   3. Skew check on webhook-timestamp              ─── inside webhook::verify
//!   4. Replay-cache lookup on webhook-id            ─── replay_cache::lookup
//!      └── hit → return cached signed verdict
//!   5. Resolve X-OpenLatch-Binding-Id → LocalRoute  ─── routes.snapshot()
//!   6. Parse body as JSON (typify-ish)              ─── (only after auth verified)
//!   7. Proxy to localhost:NNNN with deadline        ─── proxy::proxy
//!   8. Validate verdict size + JSON                 ─── verdict::validate / ensure_json
//!   9. HMAC-sign outbound headers                   ─── verdict::sign
//!  10. Insert into replay cache                     ─── replay_cache::insert
//!  11. Append audit-log line                        ─── audit_log::AuditTx
//!  12. Return signed response to platform
//! ```
//!
//! Errors short-circuit: a malformed signature MUST stop before
//! `serde_json::from_slice`. The replay-cache hit is informational, not an
//! error — a previously-cached signed verdict comes back byte-identical.

use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Instant;

use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::Router;
use secrecy::SecretString;
use serde::Serialize;
use tokio::sync::Mutex as AsyncMutex;
use tower_http::limit::RequestBodyLimitLayer;
use tracing::{error, info, warn};

use crate::auth::binding_secrets::BindingSecretStore;
use crate::error::{
    OlError, OL_4220_HMAC_FAILED, OL_4221_MALFORMED_BODY, OL_4222_BINDING_NOT_CONFIGURED,
};
use crate::runtime::audit_log::{AuditTx, Record};
use crate::runtime::deadline::Deadline;
use crate::runtime::multi_tool::LocalRoute;
use crate::runtime::proxy;
use crate::runtime::reload::SharedRoutes;
use crate::runtime::replay_cache::{CachedVerdict, ReplayCache};
use crate::runtime::verdict;
use crate::runtime::webhook::{self, VerifyFailure};
use crate::telemetry::{self, Event};

/// Cap inbound bodies at 1 MB. Manifest cap is 256 KB; an inbound event
/// payload can be larger (CloudEvents envelope + tool_call.input redaction
/// metadata + agent context), so we leave headroom.
pub const MAX_INBOUND_BYTES: usize = 1024 * 1024;

/// Default localhost port; matches PRD §6.5.
pub const DEFAULT_PORT: u16 = 8443;

/// State shared across every request handler. `Arc`-wrapped at the
/// `with_state` boundary; cloning is cheap.
pub struct RuntimeContext {
    pub routes: SharedRoutes,
    pub secrets: Arc<dyn BindingSecretStore>,
    pub replay_cache: ReplayCache,
    pub proxy_client: reqwest::Client,
    pub audit_tx: Option<AuditTx>,
    pub admin_token: Arc<AsyncMutex<String>>,
    pub started_at: Instant,
    pub events_processed: AtomicU64,
    pub events_failed: AtomicU64,
    /// Path of the active manifest — used by the reload trigger paths.
    pub manifest_path: std::path::PathBuf,
    /// Cached platform-side bindings list — refreshed on reload.
    pub live_bindings: AsyncMutex<Vec<crate::api::editor::EditorBindingRow>>,
    /// Manifest's known secret IDs — passed to the secret-store fallback
    /// when keyring's `list_known()` returns empty.
    pub manifest_secret_ids: AsyncMutex<Vec<String>>,
    /// P3.T2b — single-update lock. `compare_exchange(false, true, AcqRel,
    /// Acquire)` returns 503 on contention. Reused by the worker so manual
    /// + auto apply can never race.
    pub update_in_progress: std::sync::atomic::AtomicBool,
    /// P3.T2b — long-poll snapshot of the in-flight (or last) apply pipeline.
    pub update_status: std::sync::Mutex<crate::update::UpdateStatusSnapshot>,
    /// P3.T2b — fired by the apply task to trigger a graceful axum drain
    /// before re-exec. Listeners on the runtime side observe this and
    /// shut down the listener.
    pub admin_shutdown_request: tokio::sync::Notify,
    /// Managed-tool supervisor. `None` only in tests that don't exercise the
    /// supervised-process flow; the production `listen` path always sets it.
    pub supervisor: Option<Arc<crate::runtime::supervisor::Supervisor>>,
    /// Whether per-event log lines should emit ANSI color. Resolved once at
    /// startup so the hot path doesn't re-probe `NO_COLOR` / `is_terminal`
    /// on every event.
    pub log_ansi: bool,
}

impl RuntimeContext {
    pub fn uptime_ms(&self) -> u64 {
        self.started_at.elapsed().as_millis() as u64
    }
}

/// `serde`-shaped TLS mode tag for telemetry.
pub fn tls_mode_tag(no_tls: bool) -> &'static str {
    if no_tls {
        "proxy-fronted"
    } else {
        "direct"
    }
}

// ---------------------------------------------------------------------------
// Health endpoint
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
struct Health {
    status: &'static str,
    uptime_secs: u64,
    events_processed: u64,
    events_failed: u64,
    binding_count: usize,
    /// Per-binding managed-process status. Empty in tests that don't wire a
    /// supervisor; populated in production from `RuntimeContext.supervisor`.
    bindings: Vec<crate::runtime::supervisor::ToolStatus>,
}

async fn handle_health(State(ctx): State<Arc<RuntimeContext>>) -> Response {
    let snap = ctx.routes.snapshot();
    let bindings = if let Some(sup) = &ctx.supervisor {
        sup.snapshot().await
    } else {
        Vec::new()
    };
    let body = Health {
        status: "ok",
        uptime_secs: ctx.started_at.elapsed().as_secs(),
        events_processed: ctx.events_processed.load(Ordering::Relaxed),
        events_failed: ctx.events_failed.load(Ordering::Relaxed),
        binding_count: snap.len(),
        bindings,
    };
    (StatusCode::OK, axum::Json(body)).into_response()
}

// ---------------------------------------------------------------------------
// /v1/event — the hot path
// ---------------------------------------------------------------------------

async fn handle_event(
    State(ctx): State<Arc<RuntimeContext>>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    let started = Instant::now();
    let snap = ctx.routes.snapshot();

    // ---- 1. Required headers --------------------------------------------
    let webhook_id = match header_str(&headers, "webhook-id") {
        Some(v) => v.to_string(),
        None => return ol_4220_response("missing webhook-id header"),
    };
    let webhook_ts =
        match header_str(&headers, "webhook-timestamp").and_then(|s| s.parse::<i64>().ok()) {
            Some(v) => v,
            None => return ol_4220_response("missing or malformed webhook-timestamp header"),
        };
    let signature = match header_str(&headers, "webhook-signature") {
        Some(v) => v.to_string(),
        None => return ol_4220_response("missing webhook-signature header"),
    };
    let binding_id = match header_str(&headers, "x-openlatch-binding-id") {
        Some(v) => v.to_string(),
        None => return ol_4222_response("missing X-OpenLatch-Binding-Id header"),
    };
    let event_id = header_str(&headers, "x-openlatch-event-id")
        .map(str::to_string)
        .unwrap_or_else(|| format!("evt_{}", uuid::Uuid::now_v7().simple()));
    let deadline_ms: u64 = header_str(&headers, "x-openlatch-deadline-ms")
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(200);

    // ---- 2. Resolve route ------------------------------------------------
    let route: LocalRoute = match snap.lookup(&binding_id) {
        Some(r) => r.clone(),
        None => {
            ctx.events_failed.fetch_add(1, Ordering::Relaxed);
            audit(
                ctx.as_ref(),
                Record::now(&event_id, &binding_id, "not_configured"),
            );
            return ol_4222_response(&format!("binding `{binding_id}` is not configured locally"));
        }
    };

    // ---- 3. Load secret + verify HMAC -----------------------------------
    let secret: SecretString = match ctx.secrets.retrieve(&binding_id) {
        Ok(s) => s,
        Err(_) => {
            ctx.events_failed.fetch_add(1, Ordering::Relaxed);
            audit(
                ctx.as_ref(),
                Record::now(&event_id, &binding_id, "secret_missing"),
            );
            return ol_4222_response(&format!("no local secret for binding `{binding_id}`"));
        }
    };

    if let Err(err) = webhook::verify(&secret, &webhook_id, webhook_ts, &body, &signature) {
        let kind = match err.code.code {
            "OL-4226" => VerifyFailure::Timestamp,
            _ => VerifyFailure::Hmac,
        };
        warn!(
            binding_id = %binding_id,
            webhook_id = %webhook_id,
            code = %err.code,
            "webhook verification failed"
        );
        telemetry::capture_global(Event::webhook_verify_failed(
            &binding_id,
            kind.telemetry_kind(),
        ));
        ctx.events_failed.fetch_add(1, Ordering::Relaxed);
        audit(
            ctx.as_ref(),
            Record::now(&event_id, &binding_id, "hmac_failed"),
        );
        return error_response(StatusCode::UNAUTHORIZED, &err);
    }

    // ---- 4. Replay cache lookup -----------------------------------------
    if let Some(cached) = ctx.replay_cache.lookup(&webhook_id) {
        info!(
            binding_id = %binding_id,
            webhook_id = %webhook_id,
            "replay cache hit; returning cached verdict"
        );
        ctx.events_processed.fetch_add(1, Ordering::Relaxed);
        audit(
            ctx.as_ref(),
            Record::now(&event_id, &binding_id, "replay_cache_hit"),
        );
        return cached_response(&cached);
    }

    // ---- 5. Parse JSON (only after auth verified) -----------------------
    if let Err(e) = verdict::ensure_json(&body) {
        // The platform shouldn't be sending non-JSON; a malformed body
        // post-verify means a JSON corruption in transit (HMAC would have
        // caught a *change*, but if the body is technically authentic but
        // semantically broken we still surface OL-4221).
        ctx.events_failed.fetch_add(1, Ordering::Relaxed);
        audit(
            ctx.as_ref(),
            Record::now(&event_id, &binding_id, "malformed_body"),
        );
        return error_response(StatusCode::BAD_REQUEST, &e);
    }

    // ---- 6. Proxy to localhost ------------------------------------------
    let deadline = Deadline::from_budget_ms(deadline_ms);
    let proxy_started = Instant::now();
    let proxy_outcome = match proxy::proxy(&ctx.proxy_client, &route, body.clone(), deadline).await
    {
        Ok(o) => o,
        Err(err) => {
            let kind = proxy::telemetry_kind(&err);
            warn!(
                binding_id = %binding_id,
                code = %err.code,
                "localhost proxy call failed"
            );
            telemetry::capture_global(Event::proxy_call_failed(&binding_id, kind));
            ctx.events_failed.fetch_add(1, Ordering::Relaxed);
            let outcome = match err.code.code {
                "OL-4223" => "oversize",
                "OL-4224" => "tool_unreachable",
                "OL-4225" => "tool_5xx",
                "OL-4228" => "timeout",
                _ => "tool_unreachable",
            };
            audit(ctx.as_ref(), Record::now(&event_id, &binding_id, outcome));
            let status = if err.code.code == "OL-4228" {
                StatusCode::GATEWAY_TIMEOUT
            } else {
                StatusCode::BAD_GATEWAY
            };
            return error_response(status, &err);
        }
    };

    let tool_ms = proxy_started.elapsed().as_millis() as u64;

    // ---- 7. Validate + size cap -----------------------------------------
    if let Err(e) = verdict::validate_body_size(&proxy_outcome.body) {
        ctx.events_failed.fetch_add(1, Ordering::Relaxed);
        audit(
            ctx.as_ref(),
            Record::now(&event_id, &binding_id, "oversize"),
        );
        return error_response(StatusCode::BAD_GATEWAY, &e);
    }

    // ---- 8. Sign outbound -----------------------------------------------
    let signed = match verdict::sign(&secret, &proxy_outcome.body) {
        Ok(h) => h,
        Err(e) => {
            ctx.events_failed.fetch_add(1, Ordering::Relaxed);
            audit(
                ctx.as_ref(),
                Record::now(&event_id, &binding_id, "sign_failed"),
            );
            return error_response(StatusCode::INTERNAL_SERVER_ERROR, &e);
        }
    };

    let processing_ms = started.elapsed().as_millis() as u64;

    // ---- 9. Cache + audit -----------------------------------------------
    let cached = CachedVerdict {
        status: 200,
        body: proxy_outcome.body.clone(),
        webhook_id: signed.webhook_id.clone(),
        webhook_timestamp: signed.webhook_timestamp,
        webhook_signature: signed.webhook_signature.clone(),
        processing_ms,
    };
    ctx.replay_cache.insert(webhook_id.clone(), cached);
    ctx.events_processed.fetch_add(1, Ordering::Relaxed);

    let parsed_for_log = verdict::parse_lossy(&proxy_outcome.body);
    let parsed_value = parsed_for_log
        .as_ref()
        .and_then(|v| serde_json::to_value(v).ok());
    let record = crate::runtime::audit_log::record_from_verdict(
        &event_id,
        &binding_id,
        parsed_value.as_ref(),
        "delivered",
        processing_ms,
        tool_ms,
    );
    audit(ctx.as_ref(), record);

    let verdict_str = crate::observability::verdict_display(
        parsed_for_log.as_ref().and_then(|v| v.verdict_hint),
        ctx.log_ansi,
    );
    info!(
        event_id = %event_id,
        binding_id = %binding_id,
        verdict = %verdict_str,
        processing_ms,
        tool_ms,
        "event delivered"
    );

    success_response(&proxy_outcome.body, &signed, processing_ms)
}

// ---------------------------------------------------------------------------
// Response helpers
// ---------------------------------------------------------------------------

fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers.get(name).and_then(|v| v.to_str().ok())
}

fn ol_4220_response(message: &str) -> Response {
    let err = OlError::new(OL_4220_HMAC_FAILED, message);
    error_response(StatusCode::UNAUTHORIZED, &err)
}

fn ol_4222_response(message: &str) -> Response {
    let err = OlError::new(OL_4222_BINDING_NOT_CONFIGURED, message);
    error_response(StatusCode::NOT_FOUND, &err)
}

#[allow(dead_code)]
fn ol_4221_response(message: &str) -> Response {
    let err = OlError::new(OL_4221_MALFORMED_BODY, message);
    error_response(StatusCode::BAD_REQUEST, &err)
}

fn error_response(status: StatusCode, err: &OlError) -> Response {
    let body = serde_json::json!({
        "error": {
            "code": err.code.code,
            "message": err.message,
            "docs_url": err.code.docs_url,
        }
    });
    (status, axum::Json(body)).into_response()
}

fn cached_response(cached: &CachedVerdict) -> Response {
    let mut resp = (StatusCode::OK, cached.body.clone()).into_response();
    apply_signed_headers(
        resp.headers_mut(),
        &cached.webhook_id,
        cached.webhook_timestamp,
        &cached.webhook_signature,
        cached.processing_ms,
    );
    resp
}

fn success_response(body: &Bytes, signed: &webhook::SignedHeaders, processing_ms: u64) -> Response {
    let mut resp = (StatusCode::OK, body.clone()).into_response();
    apply_signed_headers(
        resp.headers_mut(),
        &signed.webhook_id,
        signed.webhook_timestamp,
        &signed.webhook_signature,
        processing_ms,
    );
    resp
}

fn apply_signed_headers(
    headers: &mut HeaderMap,
    webhook_id: &str,
    webhook_timestamp: i64,
    signature: &str,
    processing_ms: u64,
) {
    if let Ok(v) = HeaderValue::from_str(webhook_id) {
        headers.insert("webhook-id", v);
    }
    if let Ok(v) = HeaderValue::from_str(&webhook_timestamp.to_string()) {
        headers.insert("webhook-timestamp", v);
    }
    if let Ok(v) = HeaderValue::from_str(signature) {
        headers.insert("webhook-signature", v);
    }
    headers.insert("content-type", HeaderValue::from_static("application/json"));
    if let Ok(v) = HeaderValue::from_str(&processing_ms.to_string()) {
        headers.insert("X-OpenLatch-Provider-Processing-Ms", v);
    }
}

fn audit(ctx: &RuntimeContext, record: Record) {
    if let Some(tx) = &ctx.audit_tx {
        tx.append(record);
    }
}

// ---------------------------------------------------------------------------
// Router builder
// ---------------------------------------------------------------------------

/// Build the axum router for the runtime daemon. Test code uses this to
/// drive the server in-process without binding a TCP socket.
pub fn build_router(ctx: Arc<RuntimeContext>) -> Router {
    Router::new()
        .route("/v1/event", post(handle_event))
        .route("/v1/health", get(handle_health))
        .layer(RequestBodyLimitLayer::new(MAX_INBOUND_BYTES))
        .with_state(ctx)
}

/// Bind + serve. Plain TCP — TLS termination either happens in front (via
/// reverse proxy when `--no-tls`) or in `serve_tls`.
pub async fn serve_plain(
    bind_addr: SocketAddr,
    ctx: Arc<RuntimeContext>,
    shutdown: impl std::future::Future<Output = ()> + Send + 'static,
) -> Result<SocketAddr, OlError> {
    let listener = tokio::net::TcpListener::bind(bind_addr)
        .await
        .map_err(|e| OlError::new(OL_4220_HMAC_FAILED, format!("bind {bind_addr}: {e}")))?;
    let local = listener
        .local_addr()
        .map_err(|e| OlError::new(OL_4220_HMAC_FAILED, format!("local_addr: {e}")))?;
    let app = build_router(ctx);
    info!(addr = %local, "runtime listening (plain)");
    let server = axum::serve(listener, app).with_graceful_shutdown(shutdown);
    if let Err(e) = server.await {
        error!(error = %e, "axum serve error");
        return Err(OlError::new(OL_4220_HMAC_FAILED, format!("serve: {e}")));
    }
    Ok(local)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tls_mode_tag_branches() {
        assert_eq!(tls_mode_tag(true), "proxy-fronted");
        assert_eq!(tls_mode_tag(false), "direct");
    }
}