everruns-core 0.8.34

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
// Shared URL validation for SSRF prevention
//
// THREAT[TM-API-008]: Blocks requests to internal/private networks.
// Used by MCP server registration (create/update) and execution-time checks.
//
// Validates:
// - Scheme restricted to https/http
// - Hostname not localhost, loopback, or private IP
// - Blocks link-local (169.254.x.x), cloud metadata (169.254.169.254)
// - Blocks RFC1918 (10.x, 172.16-31.x, 192.168.x)
// - Blocks IPv6 loopback (::1) and link-local (fe80::)

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use url::Url;

/// Errors from URL safety validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UrlValidationError {
    /// URL could not be parsed.
    InvalidUrl(String),
    /// Scheme not allowed (must be http or https).
    DisallowedScheme(String),
    /// Hostname is missing.
    MissingHostname,
    /// Hostname resolves to or is a blocked target.
    BlockedHost(String),
}

impl std::fmt::Display for UrlValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidUrl(msg) => write!(f, "Invalid URL: {msg}"),
            Self::DisallowedScheme(scheme) => {
                write!(f, "Disallowed URL scheme: {scheme} (must be http or https)")
            }
            Self::MissingHostname => write!(f, "URL must have a hostname"),
            Self::BlockedHost(host) => {
                write!(f, "Blocked host: {host} (private/internal address)")
            }
        }
    }
}

impl std::error::Error for UrlValidationError {}

/// Validate a URL is safe for server-side requests (anti-SSRF).
///
/// Checks scheme, hostname patterns, and IP address ranges.
/// Does NOT perform DNS resolution — this is a static check suitable for
/// write-time validation. Complement with runtime DNS-pinned checks where possible.
pub fn validate_safe_url(raw_url: &str) -> Result<Url, UrlValidationError> {
    let url = Url::parse(raw_url).map_err(|e| UrlValidationError::InvalidUrl(e.to_string()))?;

    // Scheme check
    match url.scheme() {
        "http" | "https" => {}
        other => return Err(UrlValidationError::DisallowedScheme(other.to_string())),
    }

    // Must have a host
    let host = url.host_str().ok_or(UrlValidationError::MissingHostname)?;

    // Check hostname patterns
    if is_blocked_host(host) {
        return Err(UrlValidationError::BlockedHost(host.to_string()));
    }

    Ok(url)
}

/// Check if a hostname string is blocked (localhost, private IPs, metadata endpoints).
fn is_blocked_host(host: &str) -> bool {
    let host_lower = host.to_lowercase();

    // Localhost variants
    if host_lower == "localhost"
        || host_lower == "localhost."
        || host_lower.ends_with(".localhost")
        || host_lower.ends_with(".localhost.")
    {
        return true;
    }

    // Strip brackets from IPv6
    let bare = host_lower
        .strip_prefix('[')
        .and_then(|s| s.strip_suffix(']'))
        .unwrap_or(&host_lower);

    // Try parsing as IP
    if let Ok(ip) = bare.parse::<IpAddr>() {
        return is_blocked_ip(ip);
    }

    // Cloud metadata hostname
    if host_lower == "metadata.google.internal" || host_lower == "metadata.google.internal." {
        return true;
    }

    false
}

/// Check if an IP address is in a blocked range (loopback, private, link-local,
/// CGNAT, documentation, IPv4-mapped IPv6 variants of any of those).
///
/// Use this for runtime DNS-pinned checks where the caller has already resolved
/// a hostname to its actual address. Static URL/hostname checks should use
/// [`validate_safe_url`] instead.
pub fn is_blocked_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => is_blocked_ipv4(v4),
        IpAddr::V6(v6) => is_blocked_ipv6(v6),
    }
}

fn is_blocked_ipv4(ip: Ipv4Addr) -> bool {
    let octets = ip.octets();

    // Loopback 127.0.0.0/8
    if octets[0] == 127 {
        return true;
    }

    // 0.0.0.0
    if ip.is_unspecified() {
        return true;
    }

    // RFC1918: 10.0.0.0/8
    if octets[0] == 10 {
        return true;
    }

    // RFC1918: 172.16.0.0/12
    if octets[0] == 172 && (16..=31).contains(&octets[1]) {
        return true;
    }

    // RFC1918: 192.168.0.0/16
    if octets[0] == 192 && octets[1] == 168 {
        return true;
    }

    // Link-local 169.254.0.0/16 (includes cloud metadata 169.254.169.254)
    if octets[0] == 169 && octets[1] == 254 {
        return true;
    }

    // RFC6598 Carrier-grade NAT: 100.64.0.0/10
    if octets[0] == 100 && (64..=127).contains(&octets[1]) {
        return true;
    }

    // RFC5737 Documentation: 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24
    if (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
        || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
        || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
    {
        return true;
    }

    false
}

fn is_blocked_ipv6(ip: Ipv6Addr) -> bool {
    // Loopback ::1
    if ip.is_loopback() {
        return true;
    }

    // Unspecified ::
    if ip.is_unspecified() {
        return true;
    }

    // Link-local fe80::/10
    let segments = ip.segments();
    if segments[0] & 0xffc0 == 0xfe80 {
        return true;
    }

    // Unique local fc00::/7
    if segments[0] & 0xfe00 == 0xfc00 {
        return true;
    }

    // IPv4-mapped IPv6 (::ffff:x.x.x.x) — check the embedded v4
    if let Some(v4) = ip.to_ipv4_mapped() {
        return is_blocked_ipv4(v4);
    }

    false
}

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

    // --- Positive: valid public URLs ---

    #[test]
    fn accepts_https_public_url() {
        assert!(validate_safe_url("https://mcp.example.com/v1/mcp").is_ok());
    }

    #[test]
    fn accepts_http_public_url() {
        assert!(validate_safe_url("http://mcp.example.com/v1/mcp").is_ok());
    }

    #[test]
    fn accepts_url_with_port() {
        assert!(validate_safe_url("https://mcp.example.com:8443/v1/mcp").is_ok());
    }

    #[test]
    fn accepts_url_with_path_and_query() {
        assert!(validate_safe_url("https://api.example.com/mcp?key=val").is_ok());
    }

    // --- Negative: blocked schemes ---

    #[test]
    fn rejects_ftp_scheme() {
        let err = validate_safe_url("ftp://evil.com/file").unwrap_err();
        assert!(matches!(err, UrlValidationError::DisallowedScheme(_)));
    }

    #[test]
    fn rejects_file_scheme() {
        let err = validate_safe_url("file:///etc/passwd").unwrap_err();
        assert!(matches!(err, UrlValidationError::DisallowedScheme(_)));
    }

    #[test]
    fn rejects_javascript_scheme() {
        let err = validate_safe_url("javascript:alert(1)").unwrap_err();
        // url crate may parse this as opaque or as scheme error
        assert!(
            matches!(err, UrlValidationError::DisallowedScheme(_))
                || matches!(err, UrlValidationError::MissingHostname)
        );
    }

    #[test]
    fn rejects_data_scheme() {
        let err = validate_safe_url("data:text/plain,hello").unwrap_err();
        assert!(
            matches!(err, UrlValidationError::DisallowedScheme(_))
                || matches!(err, UrlValidationError::MissingHostname)
        );
    }

    // --- Negative: invalid URLs ---

    #[test]
    fn rejects_empty_string() {
        assert!(validate_safe_url("").is_err());
    }

    #[test]
    fn rejects_not_a_url() {
        assert!(validate_safe_url("not a url").is_err());
    }

    // --- Negative: localhost ---

    #[test]
    fn rejects_localhost() {
        let err = validate_safe_url("http://localhost/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_localhost_with_port() {
        let err = validate_safe_url("http://localhost:8080/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_subdomain_of_localhost() {
        let err = validate_safe_url("http://foo.localhost/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    // --- Negative: loopback IPs ---

    #[test]
    fn rejects_127_0_0_1() {
        let err = validate_safe_url("http://127.0.0.1/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_127_x_x_x() {
        let err = validate_safe_url("http://127.255.0.1/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_ipv6_loopback() {
        let err = validate_safe_url("http://[::1]/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    // --- Negative: private RFC1918 ---

    #[test]
    fn rejects_10_x() {
        let err = validate_safe_url("http://10.0.0.1/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_172_16_x() {
        let err = validate_safe_url("http://172.16.0.1/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_172_31_x() {
        let err = validate_safe_url("http://172.31.255.255/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn accepts_172_32_x() {
        // 172.32.x.x is NOT private
        assert!(validate_safe_url("http://172.32.0.1/path").is_ok());
    }

    #[test]
    fn rejects_192_168_x() {
        let err = validate_safe_url("http://192.168.1.1/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    // --- Negative: link-local / cloud metadata ---

    #[test]
    fn rejects_link_local() {
        let err = validate_safe_url("http://169.254.1.1/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_cloud_metadata_ip() {
        let err = validate_safe_url("http://169.254.169.254/latest/meta-data/").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_gce_metadata_hostname() {
        let err =
            validate_safe_url("http://metadata.google.internal/computeMetadata/v1/").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    // --- Negative: 0.0.0.0 ---

    #[test]
    fn rejects_unspecified_v4() {
        let err = validate_safe_url("http://0.0.0.0/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    // --- Negative: IPv6 special ---

    #[test]
    fn rejects_ipv6_unspecified() {
        let err = validate_safe_url("http://[::]/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_ipv6_link_local() {
        let err = validate_safe_url("http://[fe80::1]/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_ipv6_unique_local() {
        let err = validate_safe_url("http://[fd00::1]/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_ipv4_mapped_ipv6_private() {
        let err = validate_safe_url("http://[::ffff:127.0.0.1]/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    #[test]
    fn rejects_ipv4_mapped_ipv6_metadata() {
        let err =
            validate_safe_url("http://[::ffff:169.254.169.254]/latest/meta-data/").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    // --- Negative: carrier-grade NAT ---

    #[test]
    fn rejects_cgnat() {
        let err = validate_safe_url("http://100.64.0.1/path").unwrap_err();
        assert!(matches!(err, UrlValidationError::BlockedHost(_)));
    }

    // --- Display ---

    #[test]
    fn error_display_messages() {
        assert!(
            UrlValidationError::BlockedHost("localhost".into())
                .to_string()
                .contains("private/internal")
        );
        assert!(
            UrlValidationError::DisallowedScheme("ftp".into())
                .to_string()
                .contains("http or https")
        );
    }
}