ironbridge-cli 2.0.1

Universal chat session manager - harvest, merge, and analyze AI chat history from VS Code, Cursor, and other editors
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
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
// Copyright (c) 2024-2026 Nervosys LLC
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-IronBridge-Commercial
//! Webhook integration module
//!
//! Provides webhook dispatch for session and system events.

use actix_web::{web, HttpResponse, Responder};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use uuid::Uuid;

/// Webhook event types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum WebhookEvent {
    /// Session created
    SessionCreated,
    /// Session updated
    SessionUpdated,
    /// Session deleted
    SessionDeleted,
    /// Session archived
    SessionArchived,
    /// Session merged
    SessionMerged,
    /// Session exported
    SessionExported,
    /// Workspace created
    WorkspaceCreated,
    /// Workspace deleted
    WorkspaceDeleted,
    /// Harvest completed
    HarvestCompleted,
    /// Sync completed
    SyncCompleted,
    /// Provider health changed
    ProviderHealthChanged,
}

impl std::fmt::Display for WebhookEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WebhookEvent::SessionCreated => write!(f, "session.created"),
            WebhookEvent::SessionUpdated => write!(f, "session.updated"),
            WebhookEvent::SessionDeleted => write!(f, "session.deleted"),
            WebhookEvent::SessionArchived => write!(f, "session.archived"),
            WebhookEvent::SessionMerged => write!(f, "session.merged"),
            WebhookEvent::SessionExported => write!(f, "session.exported"),
            WebhookEvent::WorkspaceCreated => write!(f, "workspace.created"),
            WebhookEvent::WorkspaceDeleted => write!(f, "workspace.deleted"),
            WebhookEvent::HarvestCompleted => write!(f, "harvest.completed"),
            WebhookEvent::SyncCompleted => write!(f, "sync.completed"),
            WebhookEvent::ProviderHealthChanged => write!(f, "provider.health_changed"),
        }
    }
}

/// Webhook configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookConfig {
    /// Unique ID
    pub id: String,
    /// Display name
    pub name: String,
    /// Target URL
    pub url: String,
    /// Secret for HMAC signature
    #[serde(skip_serializing)]
    pub secret: Option<String>,
    /// Events to subscribe to
    pub events: Vec<WebhookEvent>,
    /// Whether webhook is enabled
    pub enabled: bool,
    /// Custom headers
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// Retry configuration
    #[serde(default)]
    pub retry_count: u8,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
    /// Last triggered timestamp
    pub last_triggered: Option<DateTime<Utc>>,
    /// Failure count
    #[serde(default)]
    pub failure_count: u32,
}

/// Webhook payload
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookPayload {
    /// Event ID
    pub id: String,
    /// Event type
    pub event: String,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
    /// Event data
    pub data: serde_json::Value,
    /// Webhook ID
    pub webhook_id: String,
}

/// Webhook delivery result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookDelivery {
    /// Delivery ID
    pub id: String,
    /// Webhook ID
    pub webhook_id: String,
    /// Event type
    pub event: String,
    /// Response status code
    pub status_code: Option<u16>,
    /// Whether delivery succeeded
    pub success: bool,
    /// Error message if failed
    pub error: Option<String>,
    /// Delivery timestamp
    pub delivered_at: DateTime<Utc>,
    /// Response time in ms
    pub response_time_ms: u64,
}

/// Webhook state (in-memory for now)
pub struct WebhookState {
    /// Registered webhooks
    webhooks: RwLock<HashMap<String, WebhookConfig>>,
    /// Recent deliveries (circular buffer)
    deliveries: RwLock<Vec<WebhookDelivery>>,
    /// HTTP client
    client: reqwest::Client,
}

impl WebhookState {
    /// Create new webhook state
    pub fn new() -> Self {
        Self {
            webhooks: RwLock::new(HashMap::new()),
            deliveries: RwLock::new(Vec::new()),
            client: reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(30))
                // Validating the registered URL is worthless if the server
                // then follows wherever that URL points. reqwest's default is
                // to follow up to 10 redirects, so a target that passes
                // `validate_webhook_url` could answer `302 Location:
                // http://169.254.169.254/...` and have this server fetch the
                // instance credentials on the attacker's behalf -- the check
                // only ever saw the first hop.
                //
                // Each hop is re-validated rather than refused outright, so an
                // ordinary redirect (http to https, a moved path) still works
                // while a hop into metadata space does not. The cap is low
                // because a webhook receiver should answer directly.
                .redirect(reqwest::redirect::Policy::custom(|attempt| {
                    if attempt.previous().len() >= 3 {
                        return attempt.stop();
                    }
                    match validate_webhook_url(attempt.url().as_str()) {
                        Ok(()) => attempt.follow(),
                        Err(_) => attempt.stop(),
                    }
                }))
                .build()
                .unwrap_or_default(),
        }
    }

    /// Register a webhook
    pub fn register(&self, config: WebhookConfig) {
        let mut webhooks = self.webhooks.write().unwrap();
        webhooks.insert(config.id.clone(), config);
    }

    /// Remove a webhook
    pub fn remove(&self, id: &str) -> bool {
        let mut webhooks = self.webhooks.write().unwrap();
        webhooks.remove(id).is_some()
    }

    /// Get a webhook by ID
    pub fn get(&self, id: &str) -> Option<WebhookConfig> {
        let webhooks = self.webhooks.read().unwrap();
        webhooks.get(id).cloned()
    }

    /// List all webhooks
    pub fn list(&self) -> Vec<WebhookConfig> {
        let webhooks = self.webhooks.read().unwrap();
        webhooks.values().cloned().collect()
    }

    /// Get webhooks subscribed to an event
    pub fn get_for_event(&self, event: &WebhookEvent) -> Vec<WebhookConfig> {
        let webhooks = self.webhooks.read().unwrap();
        webhooks
            .values()
            .filter(|w| w.enabled && w.events.contains(event))
            .cloned()
            .collect()
    }

    /// Dispatch an event to all subscribed webhooks
    pub async fn dispatch(&self, event: WebhookEvent, data: serde_json::Value) {
        let webhooks = self.get_for_event(&event);

        for webhook in webhooks {
            let payload = WebhookPayload {
                id: Uuid::new_v4().to_string(),
                event: event.to_string(),
                timestamp: Utc::now(),
                data: data.clone(),
                webhook_id: webhook.id.clone(),
            };

            let delivery = self.deliver(&webhook, &payload).await;

            // Store delivery result
            let mut deliveries = self.deliveries.write().unwrap();
            deliveries.push(delivery);

            // Keep only last 1000 deliveries
            if deliveries.len() > 1000 {
                let drain_count = deliveries.len() - 1000;
                deliveries.drain(0..drain_count);
            }
        }
    }

    /// Deliver a webhook
    async fn deliver(&self, webhook: &WebhookConfig, payload: &WebhookPayload) -> WebhookDelivery {
        let start = std::time::Instant::now();
        let delivery_id = Uuid::new_v4().to_string();

        let mut request = self
            .client
            .post(&webhook.url)
            .header("Content-Type", "application/json")
            .header("X-IronBridge-Webhook-Id", &webhook.id)
            .header("X-IronBridge-Event", &payload.event)
            .header("X-IronBridge-Delivery-Id", &delivery_id);

        // Add signature if secret is configured
        if let Some(ref secret) = webhook.secret {
            if let Ok(body) = serde_json::to_string(payload) {
                let signature = compute_signature(secret, &body);
                request = request.header("X-IronBridge-Signature", format!("sha256={}", signature));
            }
        }

        // Add custom headers
        for (key, value) in &webhook.headers {
            request = request.header(key, value);
        }

        let result = request.json(payload).send().await;

        let elapsed = start.elapsed();

        match result {
            Ok(response) => {
                let status = response.status().as_u16();
                WebhookDelivery {
                    id: delivery_id,
                    webhook_id: webhook.id.clone(),
                    event: payload.event.clone(),
                    status_code: Some(status),
                    success: response.status().is_success(),
                    error: if response.status().is_success() {
                        None
                    } else {
                        Some(format!("HTTP {}", status))
                    },
                    delivered_at: Utc::now(),
                    response_time_ms: elapsed.as_millis() as u64,
                }
            }
            Err(e) => WebhookDelivery {
                id: delivery_id,
                webhook_id: webhook.id.clone(),
                event: payload.event.clone(),
                status_code: None,
                success: false,
                error: Some(e.to_string()),
                delivered_at: Utc::now(),
                response_time_ms: elapsed.as_millis() as u64,
            },
        }
    }

    /// Get recent deliveries
    pub fn get_deliveries(&self, limit: usize) -> Vec<WebhookDelivery> {
        let deliveries = self.deliveries.read().unwrap();
        deliveries.iter().rev().take(limit).cloned().collect()
    }

    /// Get deliveries for a specific webhook
    pub fn get_webhook_deliveries(&self, webhook_id: &str, limit: usize) -> Vec<WebhookDelivery> {
        let deliveries = self.deliveries.read().unwrap();
        deliveries
            .iter()
            .rev()
            .filter(|d| d.webhook_id == webhook_id)
            .take(limit)
            .cloned()
            .collect()
    }
}

impl Default for WebhookState {
    fn default() -> Self {
        Self::new()
    }
}

/// Compute HMAC-SHA256 signature
fn compute_signature(secret: &str, body: &str) -> String {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;

    type HmacSha256 = Hmac<Sha256>;

    let mut mac =
        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC can take key of any size");
    mac.update(body.as_bytes());

    let result = mac.finalize();
    hex::encode(result.into_bytes())
}

/// Hex encoding helper
mod hex {
    pub fn encode(bytes: impl AsRef<[u8]>) -> String {
        bytes
            .as_ref()
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect()
    }
}

// ============================================================================
// API Handlers
// ============================================================================

/// Request to create a webhook
#[derive(Debug, Deserialize)]
pub struct CreateWebhookRequest {
    pub name: String,
    pub url: String,
    pub secret: Option<String>,
    pub events: Vec<WebhookEvent>,
    #[serde(default)]
    pub headers: HashMap<String, String>,
    #[serde(default = "default_retry_count")]
    pub retry_count: u8,
}

fn default_retry_count() -> u8 {
    3
}

/// Request to update a webhook
#[derive(Debug, Deserialize)]
pub struct UpdateWebhookRequest {
    pub name: Option<String>,
    pub url: Option<String>,
    pub secret: Option<String>,
    pub events: Option<Vec<WebhookEvent>>,
    pub enabled: Option<bool>,
    pub headers: Option<HashMap<String, String>>,
    pub retry_count: Option<u8>,
}

/// Test webhook request
#[derive(Debug, Deserialize)]
pub struct TestWebhookRequest {
    pub event: Option<WebhookEvent>,
}

/// List webhooks
pub async fn list_webhooks(state: web::Data<Arc<WebhookState>>) -> impl Responder {
    let webhooks = state.list();
    HttpResponse::Ok().json(webhooks)
}

/// Reject webhook targets that turn "deliver a payload" into SSRF.
///
/// A webhook makes the server issue an outbound POST to a URL the caller
/// chose, so the URL is an SSRF primitive. This does not block private or
/// loopback addresses -- a local-first tool legitimately posts webhooks to
/// `localhost` during development, and blanket-blocking them would break that
/// -- but it does refuse the two things a webhook URL is never a good reason
/// to allow:
///
/// - non-HTTP(S) schemes (`file://`, `gopher://`, ...), the usual way SSRF is
///   escalated into file reads or protocol smuggling;
/// - the cloud metadata address `169.254.169.254`, whose only purpose to reach
///   from here would be to steal instance credentials.
///
/// The host is taken from a real URL parse, not by slicing the string. The
/// earlier version split on `/`, `:`, `?` and `#` but not `@`, and compared the
/// result literally, so every one of these reached the metadata service while
/// reading as some other host:
///
/// - `http://anything@169.254.169.254/` -- userinfo before the host; the
///   validator saw `anything@169.254.169.254`, the HTTP client connected to
///   what follows the `@`;
/// - `http://2852039166/` and `http://0xa9fea9fe/` -- the same address in
///   decimal and hex, which URL parsing normalises back to dotted quad;
/// - `http://169.254.169.254./` -- a trailing root dot, still the same host.
///
/// `Url::parse` resolves all of them to `169.254.169.254` before the check
/// runs, which is the point of parsing rather than pattern-matching.
fn validate_webhook_url(url: &str) -> Result<(), &'static str> {
    let parsed = reqwest::Url::parse(url.trim()).map_err(|_| "webhook url is not a valid url")?;

    if !matches!(parsed.scheme(), "http" | "https") {
        return Err("webhook url must be http or https");
    }

    let host = parsed.host_str().ok_or("webhook url must include a host")?;
    if is_metadata_host(host) {
        return Err("webhook url may not target the cloud metadata endpoint");
    }
    Ok(())
}

/// The link-local addresses and names that serve instance credentials.
///
/// Deliberately a small explicit set rather than "all private addresses": this
/// is a local-first tool and posting a webhook to `localhost` or a LAN host is
/// a legitimate thing to do, so blanket-blocking private space would break
/// normal use. What is never legitimate is asking this server to fetch its own
/// cloud credentials.
fn is_metadata_host(host: &str) -> bool {
    // A trailing dot is the DNS root and resolves identically.
    let host = host.trim_end_matches('.').to_ascii_lowercase();
    matches!(
        host.as_str(),
        // AWS, Azure, GCP, DigitalOcean, Oracle all answer here over IPv4.
        "169.254.169.254"
            // AWS IPv6. Url::parse renders bracketed literals without brackets.
            | "fd00:ec2::254"
            | "[fd00:ec2::254]"
            // GCP, including the short name that resolves on-instance.
            | "metadata.google.internal"
            | "metadata"
            // Alibaba Cloud.
            | "100.100.100.200"
    )
}

/// Create webhook
pub async fn create_webhook(
    state: web::Data<Arc<WebhookState>>,
    body: web::Json<CreateWebhookRequest>,
) -> impl Responder {
    if let Err(reason) = validate_webhook_url(&body.url) {
        return HttpResponse::BadRequest().json(serde_json::json!({
            "success": false,
            "error": reason,
        }));
    }
    let config = WebhookConfig {
        id: Uuid::new_v4().to_string(),
        name: body.name.clone(),
        url: body.url.clone(),
        secret: body.secret.clone(),
        events: body.events.clone(),
        enabled: true,
        headers: body.headers.clone(),
        retry_count: body.retry_count,
        created_at: Utc::now(),
        last_triggered: None,
        failure_count: 0,
    };

    state.register(config.clone());
    HttpResponse::Created().json(config)
}

/// Get webhook by ID
pub async fn get_webhook(
    state: web::Data<Arc<WebhookState>>,
    path: web::Path<String>,
) -> impl Responder {
    let id = path.into_inner();
    match state.get(&id) {
        Some(webhook) => HttpResponse::Ok().json(webhook),
        None => HttpResponse::NotFound().json(serde_json::json!({
            "error": "not_found",
            "message": "Webhook not found"
        })),
    }
}

/// Update webhook
pub async fn update_webhook(
    state: web::Data<Arc<WebhookState>>,
    path: web::Path<String>,
    body: web::Json<UpdateWebhookRequest>,
) -> impl Responder {
    let id = path.into_inner();

    if let Some(mut webhook) = state.get(&id) {
        if let Some(name) = &body.name {
            webhook.name = name.clone();
        }
        if let Some(url) = &body.url {
            if let Err(reason) = validate_webhook_url(url) {
                return HttpResponse::BadRequest().json(serde_json::json!({
                    "success": false,
                    "error": reason,
                }));
            }
            webhook.url = url.clone();
        }
        if let Some(secret) = &body.secret {
            webhook.secret = Some(secret.clone());
        }
        if let Some(events) = &body.events {
            webhook.events = events.clone();
        }
        if let Some(enabled) = body.enabled {
            webhook.enabled = enabled;
        }
        if let Some(headers) = &body.headers {
            webhook.headers = headers.clone();
        }
        if let Some(retry_count) = body.retry_count {
            webhook.retry_count = retry_count;
        }

        state.register(webhook.clone());
        HttpResponse::Ok().json(webhook)
    } else {
        HttpResponse::NotFound().json(serde_json::json!({
            "error": "not_found",
            "message": "Webhook not found"
        }))
    }
}

/// Delete webhook
pub async fn delete_webhook(
    state: web::Data<Arc<WebhookState>>,
    path: web::Path<String>,
) -> impl Responder {
    let id = path.into_inner();
    if state.remove(&id) {
        HttpResponse::NoContent().finish()
    } else {
        HttpResponse::NotFound().json(serde_json::json!({
            "error": "not_found",
            "message": "Webhook not found"
        }))
    }
}

/// Test webhook
pub async fn test_webhook(
    state: web::Data<Arc<WebhookState>>,
    path: web::Path<String>,
    body: web::Json<TestWebhookRequest>,
) -> impl Responder {
    let id = path.into_inner();

    if let Some(webhook) = state.get(&id) {
        let event = body.event.clone().unwrap_or(WebhookEvent::SessionCreated);
        let test_data = serde_json::json!({
            "test": true,
            "message": "This is a test webhook delivery from IronBridge"
        });

        let payload = WebhookPayload {
            id: Uuid::new_v4().to_string(),
            event: event.to_string(),
            timestamp: Utc::now(),
            data: test_data,
            webhook_id: webhook.id.clone(),
        };

        let delivery = state.deliver(&webhook, &payload).await;
        HttpResponse::Ok().json(delivery)
    } else {
        HttpResponse::NotFound().json(serde_json::json!({
            "error": "not_found",
            "message": "Webhook not found"
        }))
    }
}

/// Get webhook deliveries
pub async fn get_deliveries(
    state: web::Data<Arc<WebhookState>>,
    path: web::Path<String>,
    query: web::Query<HashMap<String, String>>,
) -> impl Responder {
    let id = path.into_inner();
    let limit: usize = query
        .get("limit")
        .and_then(|s| s.parse().ok())
        .unwrap_or(50);

    let deliveries = state.get_webhook_deliveries(&id, limit);
    HttpResponse::Ok().json(deliveries)
}

/// Get all recent deliveries
pub async fn get_all_deliveries(
    state: web::Data<Arc<WebhookState>>,
    query: web::Query<HashMap<String, String>>,
) -> impl Responder {
    let limit: usize = query
        .get("limit")
        .and_then(|s| s.parse().ok())
        .unwrap_or(50);

    let deliveries = state.get_deliveries(limit);
    HttpResponse::Ok().json(deliveries)
}

/// Configure webhook routes
pub fn configure_webhook_routes(cfg: &mut web::ServiceConfig, state: web::Data<Arc<WebhookState>>) {
    cfg.app_data(state).service(
        web::scope("/webhooks")
            .route("", web::get().to(list_webhooks))
            .route("", web::post().to(create_webhook))
            .route("/deliveries", web::get().to(get_all_deliveries))
            .route("/{id}", web::get().to(get_webhook))
            .route("/{id}", web::put().to(update_webhook))
            .route("/{id}", web::delete().to(delete_webhook))
            .route("/{id}/test", web::post().to(test_webhook))
            .route("/{id}/deliveries", web::get().to(get_deliveries)),
    );
}

/// Create webhook state
pub fn create_webhook_state() -> Arc<WebhookState> {
    Arc::new(WebhookState::new())
}

#[cfg(test)]
mod ssrf_tests {
    use super::validate_webhook_url;

    #[test]
    fn rejects_non_http_schemes_and_metadata() {
        assert!(validate_webhook_url("file:///etc/passwd").is_err());
        assert!(validate_webhook_url("gopher://x/").is_err());
        assert!(validate_webhook_url("http://169.254.169.254/latest/meta-data/").is_err());
        assert!(validate_webhook_url("https://metadata.google.internal/x").is_err());
    }

    #[test]
    fn allows_ordinary_and_local_targets() {
        // Local targets stay allowed: a dev legitimately posts to localhost.
        assert!(validate_webhook_url("http://localhost:9000/hook").is_ok());
        assert!(validate_webhook_url("https://example.com/webhooks/ironbridge").is_ok());
    }

    /// Spellings of the metadata address that a literal string comparison
    /// misses but an HTTP client resolves to it anyway.
    ///
    /// Every one of these reached `169.254.169.254` while the previous
    /// validator, which sliced the string on `/`, `:`, `?` and `#`, read a
    /// different host. Confirmed against `Url::parse` before the fix: each
    /// line's `host_str()` is exactly `169.254.169.254`.
    #[test]
    fn metadata_is_blocked_however_the_address_is_written() {
        // Userinfo: the validator saw `anything@169.254.169.254`, the client
        // connected to what follows the `@`. The sharpest of the four.
        assert!(validate_webhook_url("http://anything@169.254.169.254/latest/meta-data/").is_err());
        assert!(validate_webhook_url("http://user:pass@169.254.169.254/").is_err());

        // The same address in decimal and hex.
        assert!(validate_webhook_url("http://2852039166/").is_err());
        assert!(validate_webhook_url("http://0xa9fea9fe/").is_err());

        // Trailing root dot, and an explicit port.
        assert!(validate_webhook_url("http://169.254.169.254./").is_err());
        assert!(validate_webhook_url("http://169.254.169.254:80/").is_err());

        // Case is not an escape hatch for the named hosts.
        assert!(validate_webhook_url("https://METADATA.GOOGLE.INTERNAL/x").is_err());
        assert!(validate_webhook_url("http://Metadata/computeMetadata/v1/").is_err());

        // Other clouds' equivalents.
        assert!(validate_webhook_url("http://100.100.100.200/").is_err());
        assert!(validate_webhook_url("http://[fd00:ec2::254]/").is_err());
    }

    /// Hosts that merely resemble the blocked ones must still work -- a false
    /// positive here silently breaks a legitimate webhook.
    #[test]
    fn lookalike_hosts_are_not_blocked() {
        assert!(validate_webhook_url("https://metadata.google.internal.evil.com/x").is_ok());
        assert!(validate_webhook_url("https://metadata.example.com/x").is_ok());
        assert!(validate_webhook_url("https://my-metadata.internal/x").is_ok());
        assert!(validate_webhook_url("http://169.254.169.253/").is_ok());
        assert!(validate_webhook_url("http://100.100.100.201/").is_ok());
    }

    /// Garbage in the URL field is a rejection, not a panic or a silent pass.
    #[test]
    fn unparseable_urls_are_refused() {
        assert!(validate_webhook_url("").is_err());
        assert!(validate_webhook_url("not a url").is_err());
        assert!(validate_webhook_url("http://").is_err());
        assert!(validate_webhook_url("://missing-scheme").is_err());
    }
}