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
//! Standard Webhooks v1 HMAC verification + outbound signing.
//!
//! Spec: <https://www.standardwebhooks.com/>. Signed payload is the byte
//! string `<webhook-id>.<webhook-timestamp>.<raw-body>`. Header layout:
//!
//! ```text
//!   webhook-signature: v1,<base64> v1,<base64-rotated> v1a,<base64-asym>
//! ```
//!
//! Multiple entries are SPACE-delimited (Codex review #4); the comma sits
//! INSIDE each entry between the version tag (`v1`) and the base64 payload.
//! Multiple entries occur during secret rotation grace windows or when both
//! symmetric (`v1`) and asymmetric (`v1a`) signatures are present.
//!
//! Secret format: `whsec_<base64>` (Codex review #5). The provider must strip
//! the `whsec_` prefix and base64-decode the remainder before using it as the
//! HMAC key. Raw-bytes secrets are rejected with OL-4220.

use std::time::{SystemTime, UNIX_EPOCH};

use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use hmac::digest::KeyInit;
use hmac::{Hmac, Mac};
use secrecy::{ExposeSecret, SecretString};
use sha2::Sha256;
use subtle::ConstantTimeEq;

use crate::error::{OlError, OL_4220_HMAC_FAILED, OL_4221_MALFORMED_BODY, OL_4226_TIMESTAMP_SKEW};

/// Maximum allowed clock skew between platform and provider, in seconds.
/// Mirrors the Standard Webhooks recommendation.
pub const MAX_TIMESTAMP_SKEW_SECS: i64 = 300;

/// Decode a `whsec_<base64>`-formatted secret into raw HMAC key bytes.
///
/// The Standard Webhooks spec stores secrets as base64-encoded byte strings
/// with a fixed `whsec_` prefix. Anything else (raw plaintext, missing
/// prefix, malformed base64) is rejected as OL-4220.
pub fn decode_secret(secret: &SecretString) -> Result<Vec<u8>, OlError> {
    let exposed = secret.expose_secret();
    let stripped = exposed.strip_prefix("whsec_").ok_or_else(|| {
        OlError::new(
            OL_4220_HMAC_FAILED,
            "secret missing `whsec_` prefix (per Standard Webhooks v1)",
        )
        .with_suggestion(
            "rotate the binding secret: `openlatch-provider bindings rotate-secret <id>`",
        )
    })?;
    STANDARD
        .decode(stripped)
        .map_err(|e| OlError::new(OL_4220_HMAC_FAILED, format!("secret base64 decode: {e}")))
}

/// Compute the canonical Standard Webhooks v1 signature for a payload.
///
/// Returns the base64-encoded HMAC-SHA256 digest (the payload of the `v1,…`
/// signature entry; callers prepend `v1,` themselves when constructing the
/// outbound `webhook-signature` header).
pub fn compute_signature(
    key: &[u8],
    webhook_id: &str,
    webhook_timestamp: i64,
    body: &[u8],
) -> String {
    let mut mac =
        <Hmac<Sha256> as KeyInit>::new_from_slice(key).expect("Hmac<Sha256> accepts any key size");
    mac.update(webhook_id.as_bytes());
    mac.update(b".");
    mac.update(webhook_timestamp.to_string().as_bytes());
    mac.update(b".");
    mac.update(body);
    STANDARD.encode(mac.finalize().into_bytes())
}

/// Possible reasons the verifier rejects an inbound request. Used both to
/// shape the OL-4xxx error and to drive the `webhook_verify_failed` telemetry
/// `failure_kind` tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerifyFailure {
    Hmac,
    Timestamp,
    MalformedHeader,
}

impl VerifyFailure {
    pub fn telemetry_kind(self) -> &'static str {
        match self {
            VerifyFailure::Hmac => "hmac",
            VerifyFailure::Timestamp => "timestamp",
            VerifyFailure::MalformedHeader => "hmac",
        }
    }
}

/// Verify an inbound Standard Webhooks v1 request.
///
/// Pipeline (Non-Negotiable order — see `.claude/rules/envelope-format.md`):
///   1. Timestamp skew check — fail-fast before parsing anything else.
///   2. Decode the secret.
///   3. Iterate over SPACE-delimited entries; for each `v1,<b64>` compute the
///      expected digest and constant-time compare. Any match → Ok.
///   4. `v1a,…` (asymmetric) entries are silently skipped — Ed25519 verify is
///      deferred to v0.2.
pub fn verify(
    secret: &SecretString,
    webhook_id: &str,
    webhook_timestamp: i64,
    raw_body: &[u8],
    signature_header: &str,
) -> Result<(), OlError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .map_err(|e| OlError::new(OL_4221_MALFORMED_BODY, format!("system clock: {e}")))?;
    let skew = (now - webhook_timestamp).abs();
    if skew > MAX_TIMESTAMP_SKEW_SECS {
        return Err(OlError::new(
            OL_4226_TIMESTAMP_SKEW,
            format!("timestamp skew {skew}s exceeds ±{MAX_TIMESTAMP_SKEW_SECS}s (sw v1 max)"),
        ));
    }

    if signature_header.trim().is_empty() {
        return Err(OlError::new(
            OL_4220_HMAC_FAILED,
            "webhook-signature header is empty",
        ));
    }

    let key = decode_secret(secret)?;
    let expected_b64 = compute_signature(&key, webhook_id, webhook_timestamp, raw_body);
    let expected_bytes = expected_b64.as_bytes();

    let mut saw_v1_entry = false;
    for entry in signature_header.split_whitespace() {
        let entry = entry.trim();
        if entry.is_empty() {
            continue;
        }
        if let Some(b64) = entry.strip_prefix("v1,") {
            saw_v1_entry = true;
            let candidate = b64.as_bytes();
            // Constant-time compare. ct_eq returns Choice; into() collapses to bool.
            if candidate.len() == expected_bytes.len()
                && bool::from(candidate.ct_eq(expected_bytes))
            {
                return Ok(());
            }
        }
        // Other versions (v1a — asymmetric, v2 — future) are skipped silently.
        // Logging "unsupported sig version" at debug level is the daemon's job.
    }

    if !saw_v1_entry {
        return Err(OlError::new(
            OL_4220_HMAC_FAILED,
            "webhook-signature header carries no v1 entry",
        ));
    }
    Err(OlError::new(OL_4220_HMAC_FAILED, "HMAC signature mismatch"))
}

/// Outbound signing — produces the headers we attach to the verdict response
/// to the platform.
#[derive(Debug, Clone)]
pub struct SignedHeaders {
    pub webhook_id: String,
    pub webhook_timestamp: i64,
    /// `v1,<base64>` — single entry; we don't run rotation overlap on outbound.
    pub webhook_signature: String,
}

/// Sign an outbound response body with the same `whsec_<base64>` secret that
/// authenticated the inbound request. UUIDv7 webhook-id, current Unix
/// timestamp.
pub fn sign_response(secret: &SecretString, body: &[u8]) -> Result<SignedHeaders, OlError> {
    let key = decode_secret(secret)?;
    let webhook_id = format!("msg_{}", uuid::Uuid::now_v7().simple());
    let webhook_timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .map_err(|e| OlError::new(OL_4221_MALFORMED_BODY, format!("system clock: {e}")))?;
    let sig_b64 = compute_signature(&key, &webhook_id, webhook_timestamp, body);
    Ok(SignedHeaders {
        webhook_id,
        webhook_timestamp,
        webhook_signature: format!("v1,{sig_b64}"),
    })
}

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

    fn now_secs() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64
    }

    /// Build a `whsec_<base64>` secret from raw key bytes. Mirrors what the
    /// platform does when minting a fresh binding secret.
    fn whsec(key_bytes: &[u8]) -> SecretString {
        SecretString::from(format!("whsec_{}", STANDARD.encode(key_bytes)))
    }

    #[test]
    fn decode_secret_strips_prefix_and_decodes_base64() {
        let s = SecretString::from("whsec_aGVsbG8=".to_string()); // "hello"
        let bytes = decode_secret(&s).unwrap();
        assert_eq!(bytes, b"hello");
    }

    #[test]
    fn decode_secret_rejects_missing_prefix() {
        let s = SecretString::from("rawbytes".to_string());
        let err = decode_secret(&s).unwrap_err();
        assert_eq!(err.code.code, "OL-4220");
    }

    #[test]
    fn decode_secret_rejects_malformed_base64() {
        let s = SecretString::from("whsec_!!!".to_string());
        let err = decode_secret(&s).unwrap_err();
        assert_eq!(err.code.code, "OL-4220");
    }

    #[test]
    fn verify_accepts_valid_signature() {
        let secret = whsec(b"my-key");
        let id = "msg_test";
        let ts = now_secs();
        let body = b"{\"event_id\":\"evt_x\"}";
        let key_bytes = b"my-key";
        let sig = compute_signature(key_bytes, id, ts, body);
        let header = format!("v1,{sig}");
        verify(&secret, id, ts, body, &header).unwrap();
    }

    #[test]
    fn verify_rejects_tampered_body() {
        let secret = whsec(b"my-key");
        let id = "msg_test";
        let ts = now_secs();
        let body = b"original body";
        let sig = compute_signature(b"my-key", id, ts, body);
        let header = format!("v1,{sig}");
        let err = verify(&secret, id, ts, b"tampered body", &header).unwrap_err();
        assert_eq!(err.code.code, "OL-4220");
    }

    #[test]
    fn verify_rejects_wrong_secret() {
        let actual = whsec(b"correct");
        let _attacker = whsec(b"wrong");
        let id = "msg_test";
        let ts = now_secs();
        let body = b"hello";
        let sig = compute_signature(b"wrong", id, ts, body);
        let header = format!("v1,{sig}");
        let err = verify(&actual, id, ts, body, &header).unwrap_err();
        assert_eq!(err.code.code, "OL-4220");
    }

    #[test]
    fn verify_rejects_stale_timestamp() {
        let secret = whsec(b"my-key");
        let id = "msg_test";
        let ts = now_secs() - 600;
        let body = b"hello";
        let sig = compute_signature(b"my-key", id, ts, body);
        let header = format!("v1,{sig}");
        let err = verify(&secret, id, ts, body, &header).unwrap_err();
        assert_eq!(err.code.code, "OL-4226");
    }

    #[test]
    fn verify_rejects_future_timestamp_beyond_skew() {
        let secret = whsec(b"my-key");
        let id = "msg_test";
        let ts = now_secs() + 600;
        let body = b"hello";
        let sig = compute_signature(b"my-key", id, ts, body);
        let header = format!("v1,{sig}");
        let err = verify(&secret, id, ts, body, &header).unwrap_err();
        assert_eq!(err.code.code, "OL-4226");
    }

    #[test]
    fn verify_accepts_multiple_space_delimited_entries_with_v1_match() {
        // During rotation overlap, the platform may send two v1 entries (one
        // signed by old secret, one by the new). Either matching means the
        // request is authentic.
        let secret = whsec(b"new-key");
        let id = "msg_test";
        let ts = now_secs();
        let body = b"hello";
        let real = compute_signature(b"new-key", id, ts, body);
        let bogus = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
        // Wrong sig first, valid second — make sure we iterate.
        let header = format!("v1,{bogus} v1,{real}");
        verify(&secret, id, ts, body, &header).unwrap();
    }

    #[test]
    fn verify_silently_skips_v1a_asymmetric_entries() {
        // v1a (asymmetric) is not yet implemented; we don't error on it, we
        // just look for v1.
        let secret = whsec(b"my-key");
        let id = "msg_test";
        let ts = now_secs();
        let body = b"hello";
        let real = compute_signature(b"my-key", id, ts, body);
        let header = format!("v1a,fakeAsymmetricSig v1,{real}");
        verify(&secret, id, ts, body, &header).unwrap();
    }

    #[test]
    fn verify_returns_4220_when_only_unknown_versions_present() {
        let secret = whsec(b"my-key");
        let err = verify(&secret, "id", now_secs(), b"x", "v1a,foo v2,bar").unwrap_err();
        assert_eq!(err.code.code, "OL-4220");
    }

    #[test]
    fn verify_returns_4220_on_empty_header() {
        let secret = whsec(b"my-key");
        let err = verify(&secret, "id", now_secs(), b"x", "").unwrap_err();
        assert_eq!(err.code.code, "OL-4220");
    }

    #[test]
    fn sign_response_round_trips_via_verify() {
        let secret = whsec(b"key");
        let body = b"{\"riskScore\":5}";
        let h = sign_response(&secret, body).unwrap();
        verify(
            &secret,
            &h.webhook_id,
            h.webhook_timestamp,
            body,
            &h.webhook_signature,
        )
        .unwrap();
        assert!(h.webhook_id.starts_with("msg_"));
        assert!(h.webhook_signature.starts_with("v1,"));
    }

    #[test]
    fn cross_impl_test_vectors_round_trip() {
        // Shared with npm/tool-sdk/tests/hmac.test.ts and
        // pypi/tool-sdk/tests/test_hmac.py — every implementation MUST agree
        // on these tuples or the wire format has drifted.
        const FIXTURE: &str =
            include_str!("../../tests/fixtures/standard_webhooks_test_vectors.json");
        let parsed: serde_json::Value = serde_json::from_str(FIXTURE).expect("fixture parses");
        let vectors = parsed["vectors"].as_array().expect("vectors[]");
        assert!(!vectors.is_empty(), "fixture should not be empty");
        for v in vectors {
            let secret = SecretString::from(v["secret"].as_str().unwrap().to_string());
            let webhook_id = v["webhook_id"].as_str().unwrap();
            let ts = v["webhook_timestamp"].as_i64().unwrap();
            let body = STANDARD
                .decode(v["body_b64"].as_str().unwrap())
                .expect("body_b64 decodes");
            let expected = v["expected_v1_sig"].as_str().unwrap();

            // 1. Recomputing the signature from the inputs MUST match.
            let key = decode_secret(&secret).expect("decode_secret");
            let computed = compute_signature(&key, webhook_id, ts, &body);
            assert_eq!(
                computed,
                expected,
                "computed != expected for `{}`",
                v["description"].as_str().unwrap_or("?")
            );

            // 2. verify() MUST accept the canonical (v1,<expected>) header.
            // The fixture has fixed timestamps that are well outside the
            // ±5 min skew window vs `now()`, so we drive `verify()` through
            // the inner constant-time-compare path by reusing the same
            // computed digest with the *current* timestamp instead.
            let now = now_secs();
            let live_sig = compute_signature(&key, webhook_id, now, &body);
            verify(&secret, webhook_id, now, &body, &format!("v1,{live_sig}"))
                .expect("verify() must accept a freshly-signed roundtrip");
        }
    }

    #[test]
    fn sign_response_flipped_byte_breaks_verify() {
        let secret = whsec(b"key");
        let body = b"{\"riskScore\":5}";
        let h = sign_response(&secret, body).unwrap();
        let mut tampered = body.to_vec();
        tampered[0] ^= 0x01;
        let err = verify(
            &secret,
            &h.webhook_id,
            h.webhook_timestamp,
            &tampered,
            &h.webhook_signature,
        )
        .unwrap_err();
        assert_eq!(err.code.code, "OL-4220");
    }
}