armature-framework 0.2.2

A modern, type-safe HTTP framework for Rust inspired by Angular and NestJS. Features dependency injection, decorators, middleware, authentication (JWT/OAuth2/SAML), validation, OpenAPI/Swagger, caching, job queues, and observability.
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
# Webhooks Module

Webhook orchestration for sending and receiving HTTP callbacks in the Armature framework.

## Table of Contents

- [Overview]#overview
- [Features]#features
- [Installation]#installation
- [Sending Webhooks]#sending-webhooks
- [Receiving Webhooks]#receiving-webhooks
- [Endpoint Registry]#endpoint-registry
- [Signature Security]#signature-security
- [Retry Policies]#retry-policies
- [Best Practices]#best-practices
- [API Reference]#api-reference
- [Summary]#summary

## Overview

The `armature-webhooks` module provides comprehensive webhook support including:

- **Outgoing Webhooks**: Send HTTP callbacks to registered endpoints
- **Incoming Webhooks**: Receive and verify webhooks from external services
- **Signature Verification**: HMAC-SHA256 signing and verification
- **Automatic Retries**: Configurable retry policies with exponential backoff
- **Event System**: Subscribe endpoints to specific event types

## Features

- ✅ Send webhooks with automatic HMAC-SHA256 signatures
- ✅ Receive and verify incoming webhooks
- ✅ Event-based endpoint subscriptions with wildcards
- ✅ Configurable retry policies (fixed, exponential backoff)
- ✅ Delivery tracking and status monitoring
- ✅ Endpoint registry with failure tracking
- ✅ Timestamp validation to prevent replay attacks
- ✅ Custom headers per endpoint

## Installation

Add the webhooks feature to your `Cargo.toml`:

```toml
[dependencies]
armature-framework = { version = "0.1", features = ["webhooks"] }
```

Or use the crate directly:

```toml
[dependencies]
armature-webhooks = "0.1"
```

## Sending Webhooks

### Basic Usage

```rust
use armature_webhooks::{WebhookClient, WebhookConfig, WebhookPayload};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = WebhookClient::new(WebhookConfig::default());

    let payload = WebhookPayload::new("user.created")
        .with_data(serde_json::json!({
            "user_id": "usr_123",
            "email": "user@example.com"
        }));

    // Send to a specific URL
    let delivery = client.send("https://example.com/webhook", payload).await?;

    println!("Delivery status: {:?}", delivery.status);
    Ok(())
}
```

### With Signing Secret

```rust
let delivery = client
    .send_with_secret(
        "https://example.com/webhook",
        payload,
        Some("your-signing-secret"),
    )
    .await?;
```

### Dispatching to Multiple Endpoints

```rust
use std::sync::Arc;

let registry = Arc::new(WebhookRegistry::new());

// Register endpoints
registry.register(
    WebhookEndpoint::builder("https://api1.example.com/webhook")
        .events(vec!["user.*"])
        .build()
);

registry.register(
    WebhookEndpoint::builder("https://api2.example.com/webhook")
        .events(vec!["user.created", "order.*"])
        .build()
);

let client = WebhookClient::with_registry(WebhookConfig::default(), registry);

// Dispatch to all subscribed endpoints
let payload = WebhookPayload::new("user.created")
    .with_data(serde_json::json!({"user_id": "123"}));

let deliveries = client.dispatch(payload).await?;
println!("Sent to {} endpoints", deliveries.len());
```

## Receiving Webhooks

### Verify and Parse

```rust
use armature_webhooks::WebhookReceiver;

let receiver = WebhookReceiver::new("your-signing-secret");

// In your HTTP handler
fn handle_webhook(body: &[u8], signature_header: &str) -> Result<(), WebhookError> {
    // Verify and parse in one step
    let payload = receiver.receive(body, signature_header)?;

    println!("Received event: {}", payload.event);
    println!("Data: {:?}", payload.data);

    Ok(())
}
```

### Verify from HTTP Headers

```rust
use std::collections::HashMap;

let mut headers = HashMap::new();
headers.insert("X-Webhook-Signature".to_string(), signature.to_string());

let is_valid = receiver.verify_from_headers(&body, &headers)?;
```

### Event Handlers

```rust
let handler = receiver.handler("user.*", |payload| {
    println!("Received user event: {}", payload.event);
    // Process the webhook
    Ok(())
});

// Handle incoming request
let handled = handler.handle(&body, &signature)?;
```

## Endpoint Registry

### Creating and Managing Endpoints

```rust
use armature_webhooks::{WebhookRegistry, WebhookEndpoint};

let registry = WebhookRegistry::new();

// Create an endpoint with builder
let endpoint = WebhookEndpoint::builder("https://api.example.com/webhooks")
    .events(vec!["user.created", "user.updated", "order.*"])
    .description("Main API webhook")
    .header("X-Custom-Header", "custom-value")
    .build();

let endpoint_id = registry.register(endpoint);

// Query endpoints
let user_endpoints = registry.get_endpoints_for_event("user.created");
let all_endpoints = registry.get_all();

// Manage endpoints
registry.enable(&endpoint_id)?;
registry.disable(&endpoint_id)?;
registry.unregister(&endpoint_id);
```

### Event Wildcards

```rust
// Subscribe to all user events
let endpoint = WebhookEndpoint::builder("https://example.com")
    .events(vec!["user.*"])
    .build();

// Subscribe to all events
let endpoint = WebhookEndpoint::builder("https://example.com")
    .all_events()
    .build();

// Subscribe to specific events only
let endpoint = WebhookEndpoint::builder("https://example.com")
    .events(vec!["user.created", "order.completed"])
    .build();
```

### Failure Tracking

```rust
// Record delivery results
registry.record_success(&endpoint_id)?;
registry.record_failure(&endpoint_id)?;

// Find problematic endpoints
let failing = registry.get_failing_endpoints(5); // ≥5 consecutive failures

// Auto-disable failing endpoints
if endpoint.failure_count >= 10 {
    registry.disable(&endpoint.id)?;
}
```

## Signature Security

### How Signatures Work

Webhooks are signed using HMAC-SHA256:

1. A timestamp is included to prevent replay attacks
2. The signature covers both timestamp and payload
3. Format: `t=1234567890,v1=<hex-encoded-signature>`

### Signature Format

```
X-Webhook-Signature: t=1234567890,v1=abc123def456...
```

Where:
- `t` = Unix timestamp when signature was created
- `v1` = HMAC-SHA256 signature (hex encoded)

### Timestamp Validation

```rust
// Default: 5 minutes tolerance
let receiver = WebhookReceiver::new("secret");

// Custom tolerance
let receiver = WebhookReceiver::new("secret")
    .with_tolerance(60); // 60 seconds
```

### Secret Rotation

```rust
let mut endpoint = registry.get(&endpoint_id).unwrap();

// Rotate to a new secret
let new_secret = endpoint.rotate_secret();
println!("New secret: {}", new_secret);

// Update in registry
registry.update(&endpoint_id, endpoint)?;
```

## Retry Policies

### Available Policies

```rust
use armature_webhooks::RetryPolicy;
use std::time::Duration;

// No retries
let policy = RetryPolicy::none();

// Fixed delay between retries
let policy = RetryPolicy::fixed(3, Duration::from_secs(5));
// Retries: 5s, 5s, 5s

// Exponential backoff (default)
let policy = RetryPolicy::exponential(5);
// Retries: 1s, 2s, 4s, 8s, 16s (capped at max_delay)

// Custom configuration
let policy = RetryPolicy {
    max_attempts: 5,
    initial_delay: Duration::from_secs(2),
    max_delay: Duration::from_secs(120),
    backoff_multiplier: 3.0,
    jitter: true,
};
```

### Configuring the Client

```rust
let config = WebhookConfig::builder()
    .retry_policy(RetryPolicy::exponential(5))
    .timeout_secs(30)
    .build();

let client = WebhookClient::new(config);
```

### Retryable Status Codes

The client automatically retries on these HTTP status codes:
- `408` - Request Timeout
- `429` - Too Many Requests
- `500` - Internal Server Error
- `502` - Bad Gateway
- `503` - Service Unavailable
- `504` - Gateway Timeout

## Best Practices

### 1. Always Verify Signatures

```rust
// ❌ Bad - no verification
let payload: WebhookPayload = serde_json::from_slice(&body)?;

// ✅ Good - verify first
let payload = receiver.receive(&body, &signature)?;
```

### 2. Use Idempotency

```rust
// Store the webhook ID to prevent duplicate processing
let payload = receiver.receive(&body, &signature)?;

if already_processed(&payload.id) {
    return Ok(()); // Skip duplicate
}

process_webhook(&payload)?;
mark_processed(&payload.id);
```

### 3. Return Quickly

```rust
// ❌ Bad - slow processing blocks response
let payload = receiver.receive(&body, &signature)?;
heavy_processing(&payload)?; // Takes 30 seconds

// ✅ Good - queue for async processing
let payload = receiver.receive(&body, &signature)?;
queue.enqueue(payload)?;
Ok(()) // Return 200 immediately
```

### 4. Handle Failures Gracefully

```rust
let delivery = client.send(url, payload).await?;

match delivery.status {
    WebhookDeliveryStatus::Succeeded => {
        log::info!("Webhook delivered: {}", delivery.id);
    }
    WebhookDeliveryStatus::PermanentlyFailed => {
        log::error!("Webhook failed after {} attempts", delivery.attempts);
        // Alert, disable endpoint, etc.
    }
    _ => {
        // Pending or in-progress
    }
}
```

## Common Pitfalls

- **Don't** trust unverified webhooks
-**Don't** process webhooks synchronously if they take time
-**Don't** ignore timestamp validation (replay attacks)
-**Do** implement idempotency
-**Do** return 200 quickly and process asynchronously
-**Do** monitor and alert on failing endpoints

## API Reference

### WebhookClient

```rust
impl WebhookClient {
    fn new(config: WebhookConfig) -> Self;
    fn with_registry(config: WebhookConfig, registry: Arc<WebhookRegistry>) -> Self;
    async fn send(&self, url: &str, payload: WebhookPayload) -> Result<WebhookDelivery>;
    async fn send_with_secret(&self, url: &str, payload: WebhookPayload, secret: Option<&str>) -> Result<WebhookDelivery>;
    async fn send_to_endpoint(&self, endpoint: &WebhookEndpoint, payload: WebhookPayload) -> Result<WebhookDelivery>;
    async fn dispatch(&self, payload: WebhookPayload) -> Result<Vec<WebhookDelivery>>;
}
```

### WebhookReceiver

```rust
impl WebhookReceiver {
    fn new(secret: impl Into<String>) -> Self;
    fn with_tolerance(self, seconds: u64) -> Self;
    fn verify(&self, payload: &[u8], signature: &str) -> Result<bool>;
    fn receive(&self, payload: &[u8], signature: &str) -> Result<WebhookPayload>;
}
```

### WebhookPayload

```rust
impl WebhookPayload {
    fn new(event: impl Into<String>) -> Self;
    fn with_data(self, data: serde_json::Value) -> Self;
    fn with_metadata(self, metadata: serde_json::Value) -> Self;
    fn to_bytes(&self) -> Result<Vec<u8>>;
    fn to_json(&self) -> Result<String>;
}
```

### WebhookEndpoint

```rust
impl WebhookEndpoint {
    fn new(url: impl Into<String>) -> Self;
    fn builder(url: impl Into<String>) -> WebhookEndpointBuilder;
    fn is_subscribed_to(&self, event: &str) -> bool;
    fn rotate_secret(&mut self) -> String;
}
```

### WebhookRegistry

```rust
impl WebhookRegistry {
    fn new() -> Self;
    fn register(&self, endpoint: WebhookEndpoint) -> String;
    fn unregister(&self, id: &str) -> Option<WebhookEndpoint>;
    fn get(&self, id: &str) -> Option<WebhookEndpoint>;
    fn get_endpoints_for_event(&self, event: &str) -> Vec<WebhookEndpoint>;
    fn enable(&self, id: &str) -> Result<()>;
    fn disable(&self, id: &str) -> Result<()>;
    fn record_success(&self, id: &str) -> Result<()>;
    fn record_failure(&self, id: &str) -> Result<()>;
}
```

## Summary

**Key Points:**

1. Use `WebhookClient` to send outgoing webhooks
2. Use `WebhookReceiver` to verify incoming webhooks
3. Use `WebhookRegistry` to manage multiple endpoints
4. Always verify signatures before processing
5. Implement idempotency for reliable processing
6. Configure appropriate retry policies

**Quick Start:**

```rust
use armature_webhooks::{WebhookClient, WebhookConfig, WebhookPayload};

// Send a webhook
let client = WebhookClient::new(WebhookConfig::default());
let payload = WebhookPayload::new("user.created")
    .with_data(json!({"user_id": "123"}));
client.send("https://example.com/webhook", payload).await?;

// Receive a webhook
let receiver = WebhookReceiver::new("secret");
let payload = receiver.receive(&body, &signature)?;
```