eyes-subscriber 0.4.1

Tracing subscriber for sending traces to Eyes (eyes.coreyja.com)
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
//! Boot-time app manifests.
//!
//! Telemetry shows what happened; the manifest tells Eyes what the app's
//! *shape* is — every registered job type, every cron entry with its
//! schedule, and the build version. Apps send one manifest at boot via
//! [`send_manifest`] (or [`send_manifest_from_env`]); each stored manifest
//! doubles as a boot/deploy marker on the server.

use chrono::{DateTime, Utc};
use serde::Serialize;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use url::Url;
use uuid::Uuid;

/// The manifest schema version this crate emits.
pub const MANIFEST_VERSION: u32 = 2;

/// The shape of the application, as reported once at boot.
///
/// `manifest_version` and `booted_at` are filled in internally when the
/// manifest is sent ([`MANIFEST_VERSION`] and `Utc::now()` respectively).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct AppManifest {
    /// Application build version (e.g. from `CARGO_PKG_VERSION`).
    pub app_version: Option<String>,
    /// Git commit SHA of the running build.
    pub git_sha: Option<String>,
    /// Names of every registered job type.
    pub jobs: Vec<String>,
    /// Every registered cron entry with its schedule.
    pub crons: Vec<CronEntry>,
    /// Public origin used to resolve root-relative monitor targets.
    pub base_url: Option<String>,
    /// `None` does not participate in monitor authority; `Some(vec![])`
    /// explicitly removes every declaration for this app.
    pub monitors: Option<Vec<HttpMonitor>>,
}

impl AppManifest {
    pub fn app_version(mut self, app_version: impl Into<String>) -> Self {
        self.app_version = Some(app_version.into());
        self
    }

    pub fn git_sha(mut self, git_sha: impl Into<String>) -> Self {
        self.git_sha = Some(git_sha.into());
        self
    }

    pub fn jobs(mut self, jobs: Vec<String>) -> Self {
        self.jobs = jobs;
        self
    }

    pub fn crons(mut self, crons: Vec<CronEntry>) -> Self {
        self.crons = crons;
        self
    }

    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    pub fn monitors(mut self, monitors: Vec<HttpMonitor>) -> Self {
        self.monitors = Some(monitors);
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HttpMethod {
    Get,
    Head,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HttpMonitor {
    pub id: String,
    pub target: String,
    pub method: HttpMethod,
    pub interval_seconds: u64,
    pub timeout_seconds: u64,
    pub expected_status_min: u16,
    pub expected_status_max: u16,
    pub failure_threshold: u32,
    pub enabled: bool,
}

impl HttpMonitor {
    pub fn new(id: impl Into<String>, target: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            target: target.into(),
            method: HttpMethod::Get,
            interval_seconds: 60,
            timeout_seconds: 10,
            expected_status_min: 200,
            expected_status_max: 299,
            failure_threshold: 3,
            enabled: true,
        }
    }

    pub fn method(mut self, method: HttpMethod) -> Self {
        self.method = method;
        self
    }
    pub fn interval_seconds(mut self, seconds: u64) -> Self {
        self.interval_seconds = seconds;
        self
    }
    pub fn timeout_seconds(mut self, seconds: u64) -> Self {
        self.timeout_seconds = seconds;
        self
    }
    pub fn expected_status(mut self, min: u16, max: u16) -> Self {
        self.expected_status_min = min;
        self.expected_status_max = max;
        self
    }
    pub fn failure_threshold(mut self, threshold: u32) -> Self {
        self.failure_threshold = threshold;
        self
    }
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum MonitorTargetError {
    #[error("relative monitor target requires base_url")]
    MissingBaseUrl,
    #[error("monitor target must be an absolute URL or root-relative path")]
    NonRootRelative,
    #[error("network-path monitor targets are not allowed")]
    NetworkPath,
    #[error("invalid monitor target URL: {0}")]
    InvalidTarget(String),
    #[error("invalid monitor base URL: {0}")]
    InvalidBase(String),
    #[error("only HTTP and HTTPS monitor URLs are supported")]
    UnsupportedScheme,
    #[error("monitor URLs may not contain credentials")]
    Credentials,
    #[error("monitor URLs may not contain fragments")]
    Fragment,
    #[error("monitor URL must contain a host")]
    MissingHost,
    #[error("localhost monitor targets are not allowed")]
    Localhost,
    #[error("monitor target uses a forbidden IP address")]
    ForbiddenIp,
}

/// Resolve and validate an absolute HTTP(S) URL or a root-relative path.
pub fn resolve_monitor_target(
    base_url: Option<&str>,
    target: &str,
) -> Result<Url, MonitorTargetError> {
    if target.starts_with("//") {
        return Err(MonitorTargetError::NetworkPath);
    }
    let url = if target.starts_with('/') {
        // WHATWG parsing treats backslashes as slashes for special schemes and
        // strips ASCII tabs/newlines. Reject those spellings before Url::join
        // can reinterpret a path as an authority.
        if target
            .bytes()
            .any(|byte| matches!(byte, b'\\' | b'\t' | b'\r' | b'\n'))
        {
            return Err(MonitorTargetError::NetworkPath);
        }
        let base = base_url.ok_or(MonitorTargetError::MissingBaseUrl)?;
        let parsed =
            Url::parse(base).map_err(|e| MonitorTargetError::InvalidBase(e.to_string()))?;
        validate_url(&parsed).map_err(|error| match error {
            MonitorTargetError::InvalidTarget(message) => MonitorTargetError::InvalidBase(message),
            other => other,
        })?;
        let joined = parsed
            .join(target)
            .map_err(|e| MonitorTargetError::InvalidTarget(e.to_string()))?;
        if monitor_origin(&joined)? != monitor_origin(&parsed)? {
            return Err(MonitorTargetError::NetworkPath);
        }
        joined
    } else {
        Url::parse(target).map_err(|e| {
            if e == url::ParseError::RelativeUrlWithoutBase {
                MonitorTargetError::NonRootRelative
            } else {
                MonitorTargetError::InvalidTarget(e.to_string())
            }
        })?
    };
    validate_url(&url)?;
    Ok(url)
}

/// Return the normalized HTTP origin used for monitor security comparisons.
///
/// Domain names are lowercase without a trailing root dot and default ports
/// are omitted, so equivalent DNS spellings cannot bypass origin checks.
pub fn monitor_origin(url: &Url) -> Result<String, MonitorTargetError> {
    validate_url(url)?;
    let host = match url.host().ok_or(MonitorTargetError::MissingHost)? {
        url::Host::Domain(name) => name.trim_end_matches('.').to_ascii_lowercase(),
        url::Host::Ipv4(ip) => ip.to_string(),
        url::Host::Ipv6(ip) => format!("[{ip}]"),
    };
    let port = match (url.scheme(), url.port()) {
        ("http", Some(80)) | ("https", Some(443)) | (_, None) => String::new(),
        (_, Some(port)) => format!(":{port}"),
    };
    Ok(format!("{}://{host}{port}", url.scheme()))
}

fn validate_url(url: &Url) -> Result<(), MonitorTargetError> {
    if !matches!(url.scheme(), "http" | "https") {
        return Err(MonitorTargetError::UnsupportedScheme);
    }
    if !url.username().is_empty() || url.password().is_some() {
        return Err(MonitorTargetError::Credentials);
    }
    if url.fragment().is_some() {
        return Err(MonitorTargetError::Fragment);
    }
    let host = url.host().ok_or(MonitorTargetError::MissingHost)?;
    match host {
        url::Host::Domain(name)
            if name.trim_end_matches('.').eq_ignore_ascii_case("localhost")
                || name
                    .trim_end_matches('.')
                    .to_ascii_lowercase()
                    .ends_with(".localhost") =>
        {
            Err(MonitorTargetError::Localhost)
        }
        url::Host::Ipv4(ip) if is_forbidden_monitor_ip(ip.into()) => {
            Err(MonitorTargetError::ForbiddenIp)
        }
        url::Host::Ipv6(ip) if is_forbidden_monitor_ip(ip.into()) => {
            Err(MonitorTargetError::ForbiddenIp)
        }
        _ => Ok(()),
    }
}

/// Returns true when an address is not an acceptable monitor egress target.
/// This is shared by declaration validation and the connection-time resolver.
pub fn is_forbidden_monitor_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => forbidden_v4(ip),
        IpAddr::V6(ip) => forbidden_v6(ip),
    }
}

fn forbidden_v4(ip: Ipv4Addr) -> bool {
    let value = u32::from(ip);
    ip.is_unspecified()
        || ip.is_loopback()
        || ip.is_private()
        || ip.is_link_local()
        || ip.is_multicast()
        || ip.is_broadcast()
        || ip.is_documentation()
        || value >> 24 == 0
        || value & 0xffc0_0000 == 0x6440_0000 // 100.64.0.0/10
        || value & 0xffff_ff00 == 0xc000_0000 // 192.0.0.0/24
        || value & 0xffff_ff00 == 0xc058_6300 // 192.88.99.0/24
        || value & 0xfffe_0000 == 0xc612_0000 // 198.18.0.0/15
        || value & 0xf000_0000 == 0xf000_0000 // 240.0.0.0/4
}

fn forbidden_v6(ip: Ipv6Addr) -> bool {
    let octets = ip.octets();
    let compatible_v4 = octets[..12]
        .iter()
        .all(|byte| *byte == 0)
        .then(|| Ipv4Addr::new(octets[12], octets[13], octets[14], octets[15]));
    ip.is_unspecified()
        || ip.is_loopback()
        || ip.is_multicast()
        || ip.is_unique_local()
        || ip.is_unicast_link_local()
        || ip.to_ipv4_mapped().is_some_and(forbidden_v4)
        || compatible_v4.is_some_and(forbidden_v4)
        // Deny the IANA special-purpose blocks as groups. Some contain narrow
        // protocol exceptions, but none are appropriate arbitrary HTTP egress
        // targets and denying the containing allocation is the safer default.
        || octets[..12] == [0x00, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0] // 64:ff9b::/96
        || (ip.segments()[0] == 0x0064 && ip.segments()[1] == 0xff9b
            && ip.segments()[2] == 0x0001) // 64:ff9b:1::/48
        || (ip.segments()[0] == 0x0100 && ip.segments()[1..4] == [0, 0, 0]) // 100::/64
        || (ip.segments()[0] == 0x2001 && ip.segments()[1] < 0x0200) // 2001::/23
        || (ip.segments()[0] == 0x2001 && ip.segments()[1] == 0x0db8) // documentation /32
        || ip.segments()[0] == 0x2002 // 6to4, whose embedded IPv4 may be private
        || (ip.segments()[0] == 0x3fff && (ip.segments()[1] & 0xf000) == 0) // documentation /20
        || ip.segments()[0] == 0x5f00 // segment-routing SIDs /16
        || (ip.segments()[0] & 0xffc0) == 0xfec0 // deprecated site-local /10
        || (ip.segments()[0] & 0xe000) != 0x2000 // outside global-unicast 2000::/3
}

/// A single cron registration: its name and schedule string.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct CronEntry {
    pub name: String,
    /// Human/cron schedule string as the app reports it
    /// (e.g. "every 300s" or "0 0 * * *").
    pub schedule: String,
}

/// Error sending a boot manifest.
#[derive(Debug, thiserror::Error)]
pub enum ManifestError {
    /// Bad base URL or missing/invalid environment configuration.
    #[error("Configuration error: {0}")]
    Configuration(String),
    /// The HTTP request itself failed (connect, timeout, ...).
    #[error("HTTP request failed: {0}")]
    Request(#[from] reqwest::Error),
    /// The server answered with a non-2xx status.
    #[error("Server returned error status: {0}")]
    Status(reqwest::StatusCode),
}

/// Wire payload for `POST /api/orgs/:org_id/apps/:app_id/manifest`.
///
/// Jobs are serialized as `{"name": "..."}` objects (not bare strings) so
/// per-job fields can be added later without a server migration.
#[derive(Debug, Serialize)]
struct ManifestPayload<'a> {
    manifest_version: u32,
    app_version: Option<&'a str>,
    git_sha: Option<&'a str>,
    jobs: Vec<JobPayload<'a>>,
    crons: &'a [CronEntry],
    base_url: Option<&'a str>,
    monitors: Option<&'a [HttpMonitor]>,
    booted_at: DateTime<Utc>,
}

#[derive(Debug, Serialize)]
struct JobPayload<'a> {
    name: &'a str,
}

impl<'a> ManifestPayload<'a> {
    fn new(manifest: &'a AppManifest, booted_at: DateTime<Utc>) -> Self {
        Self {
            manifest_version: MANIFEST_VERSION,
            app_version: manifest.app_version.as_deref(),
            git_sha: manifest.git_sha.as_deref(),
            jobs: manifest
                .jobs
                .iter()
                .map(|name| JobPayload { name })
                .collect(),
            crons: &manifest.crons,
            base_url: manifest.base_url.as_deref(),
            monitors: manifest.monitors.as_deref(),
            booted_at,
        }
    }
}

/// Send a boot-time manifest to the Eyes server as a one-shot HTTP POST.
///
/// `booted_at` is stamped with `Utc::now()` at send time and
/// `manifest_version` with [`MANIFEST_VERSION`]. There is no queueing,
/// batching, or retrying involved — this is a single request.
///
/// Callers should fire-and-forget with a warning on failure: a manifest
/// failure must never block app boot. For example:
///
/// ```no_run
/// # use eyes_subscriber::AppManifest;
/// # async fn example(base_url: &str, org_id: uuid::Uuid, app_id: uuid::Uuid) {
/// let manifest = AppManifest::default();
/// if let Err(e) = eyes_subscriber::send_manifest(base_url, org_id, app_id, &manifest).await {
///     tracing::warn!("Failed to send app manifest to eyes: {e}");
/// }
/// # }
/// ```
pub async fn send_manifest(
    base_url: &str,
    org_id: Uuid,
    app_id: Uuid,
    manifest: &AppManifest,
) -> Result<(), ManifestError> {
    let url = Url::parse(base_url)
        .and_then(|base| base.join(&format!("/api/orgs/{}/apps/{}/manifest", org_id, app_id)))
        .map_err(|e| ManifestError::Configuration(format!("Invalid URL: {}", e)))?;

    let payload = ManifestPayload::new(manifest, Utc::now());

    let response = reqwest::Client::new()
        .post(url)
        .json(&payload)
        .send()
        .await?;

    if !response.status().is_success() {
        return Err(ManifestError::Status(response.status()));
    }

    Ok(())
}

/// [`send_manifest`], reading the destination from the environment:
///
/// - `EYES_URL`: base URL (defaults to `https://eyes.coreyja.com`, matching
///   [`crate::EyesSubscriberBuilder`])
/// - `EYES_ORG_ID`: org UUID (required)
/// - `EYES_APP_ID`: app UUID (required)
///
/// Returns [`ManifestError::Configuration`] if `EYES_ORG_ID`/`EYES_APP_ID`
/// are unset or not valid UUIDs. As with [`send_manifest`], failures should
/// be logged and ignored by callers — never block app boot on this.
pub async fn send_manifest_from_env(manifest: &AppManifest) -> Result<(), ManifestError> {
    let base_url =
        std::env::var("EYES_URL").unwrap_or_else(|_| "https://eyes.coreyja.com".to_string());

    let org_id = uuid_from_env("EYES_ORG_ID")?;
    let app_id = uuid_from_env("EYES_APP_ID")?;

    send_manifest(&base_url, org_id, app_id, manifest).await
}

fn uuid_from_env(var: &str) -> Result<Uuid, ManifestError> {
    let value = std::env::var(var)
        .map_err(|_| ManifestError::Configuration(format!("{var} must be set")))?;
    Uuid::parse_str(value.trim())
        .map_err(|e| ManifestError::Configuration(format!("{var} is not a valid UUID: {e}")))
}

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

    #[test]
    fn test_manifest_payload_serialization_shape() {
        let manifest = AppManifest::default()
            .app_version("1.2.3")
            .git_sha("abc123")
            .jobs(vec!["SendEmail".to_string(), "RefreshCache".to_string()])
            .crons(vec![CronEntry {
                name: "DailyDigest".to_string(),
                schedule: "0 0 * * *".to_string(),
            }]);

        let booted_at = Utc::now();
        let payload = ManifestPayload::new(&manifest, booted_at);
        let json = serde_json::to_value(&payload).unwrap();

        assert_eq!(
            json,
            serde_json::json!({
                "manifest_version": 2,
                "app_version": "1.2.3",
                "git_sha": "abc123",
                "jobs": [
                    { "name": "SendEmail" },
                    { "name": "RefreshCache" },
                ],
                "crons": [
                    { "name": "DailyDigest", "schedule": "0 0 * * *" },
                ],
                "base_url": null,
                "monitors": null,
                "booted_at": serde_json::to_value(booted_at).unwrap(),
            })
        );
    }

    #[test]
    fn test_empty_manifest_payload_serialization_shape() {
        let manifest = AppManifest::default();
        let booted_at = Utc::now();
        let json = serde_json::to_value(ManifestPayload::new(&manifest, booted_at)).unwrap();

        assert_eq!(json["manifest_version"], 2);
        assert_eq!(json["app_version"], serde_json::Value::Null);
        assert_eq!(json["git_sha"], serde_json::Value::Null);
        assert_eq!(json["jobs"], serde_json::json!([]));
        assert_eq!(json["crons"], serde_json::json!([]));
        assert!(json["booted_at"].is_string());
    }

    #[test]
    fn resolves_absolute_and_root_relative_targets() {
        assert_eq!(
            resolve_monitor_target(Some("https://example.com/app/"), "/health?full=1")
                .unwrap()
                .as_str(),
            "https://example.com/health?full=1"
        );
        assert_eq!(
            resolve_monitor_target(Some("https://example.com/app"), "/health")
                .unwrap()
                .as_str(),
            "https://example.com/health"
        );
        assert_eq!(
            resolve_monitor_target(None, "https://status.example.net/ping")
                .unwrap()
                .as_str(),
            "https://status.example.net/ping"
        );
    }

    #[test]
    fn rejects_unsafe_or_ambiguous_targets() {
        assert_eq!(
            resolve_monitor_target(None, "/health"),
            Err(MonitorTargetError::MissingBaseUrl)
        );
        assert_eq!(
            resolve_monitor_target(None, "health"),
            Err(MonitorTargetError::NonRootRelative)
        );
        assert_eq!(
            resolve_monitor_target(Some("https://example.com"), "//evil.example"),
            Err(MonitorTargetError::NetworkPath)
        );
        for target in [
            "/\\evil.example/x",
            "/\t/evil.example/x",
            "/\n/evil.example/x",
            "ftp://example.com/a",
            "https://user@example.com/a",
            "https://example.com/a#fragment",
            "http://localhost/a",
            "http://api.localhost/a",
            "http://localhost./a",
            "http://127.0.0.1/a",
            "http://10.0.0.1/a",
            "http://169.254.1.1/a",
            "http://192.0.2.1/a",
            "http://0.1.2.3/a",
            "http://100.64.1.1/a",
            "http://192.0.0.1/a",
            "http://192.88.99.1/a",
            "http://198.18.0.1/a",
            "http://240.0.0.1/a",
            "http://[::1]/a",
            "http://[::7f00:1]/a",
            "http://[fc00::1]/a",
            "http://[2001:db8::1]/a",
            "http://[fec0::1]/a",
            "http://[64:ff9b::c000:201]/a",
            "http://[3fff::1]/a",
            "http://[5f00::1]/a",
        ] {
            assert!(
                resolve_monitor_target(None, target).is_err(),
                "accepted {target}"
            );
        }
        for target in [
            "https://1.1.1.1/a",
            "https://8.8.8.8/a",
            "https://[2606:4700:4700::1111]/a",
        ] {
            assert!(
                resolve_monitor_target(None, target).is_ok(),
                "rejected public target {target}"
            );
        }
    }

    #[test]
    fn monitor_builder_serializes_stable_defaults() {
        let monitor = HttpMonitor::new("public-health", "/health");
        assert_eq!(
            serde_json::to_value(monitor).unwrap(),
            serde_json::json!({
                "id": "public-health", "target": "/health", "method": "GET",
                "interval_seconds": 60, "timeout_seconds": 10,
                "expected_status_min": 200, "expected_status_max": 299,
                "failure_threshold": 3, "enabled": true
            })
        );
    }
}