solari-browser 0.6.7

Rust binding for the Solari Browser platform control plane (sessions, profiles, replays, managed proxy).
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
//! HTTP transport for SDK ⇆ Solari Browser API. Owns auth headers, timeouts,
//! and the retry policy. Mirrors `Solari.request()` in `sdk/src/index.ts`.
//!
//! Retry policy (deliberately narrow, matching the reference): HTTP 502/503/504
//! and transport errors are retried, as is any IDEMPOTENT request the gateway
//! explicitly marked `"retryable": true`. Retries run `max_attempts` times
//! total, with a FIXED `backoff_ms` delay between attempts (not exponential).
//! Every other status — including 4xx and 500 — is returned to the caller
//! as-is on the first attempt.

use std::time::Duration;

use reqwest::Method;

use crate::error::SolariError;

/// `scheme://host[:port]/…` of a URL, for error messages and logs. A CDP endpoint, a signed
/// replay URL and a preview URL carry their credential in the path or query, so those never
/// go into an error. Anything that does not parse becomes `<url>`.
pub(crate) fn redact_url(url: &str) -> String {
    match url::Url::parse(url) {
        Ok(u) if u.host_str().is_some() => {
            let port = u.port().map(|p| format!(":{p}")).unwrap_or_default();
            format!(
                "{}://{}{}/…",
                u.scheme(),
                u.host_str().unwrap_or_default(),
                port
            )
        }
        _ => "<url>".to_string(),
    }
}

/// `path` with the session id in `/sessions/<id>` cut to its first 8 characters. The session id is
/// the credential inside the ws/cdp URLs, so it does not belong in error text or logs.
pub(crate) fn redact_path(path: &str) -> String {
    let mut out = String::with_capacity(path.len());
    let mut after_sessions = false;
    for (i, seg) in path.split('/').enumerate() {
        if i > 0 {
            out.push('/');
        }
        if after_sessions && !seg.is_empty() {
            let (head, rest) = match seg.find(['?', '#']) {
                Some(at) => seg.split_at(at),
                None => (seg, ""),
            };
            let keep: String = head.chars().take(8).collect();
            out.push_str(&keep);
            if head.chars().count() > 8 {
                out.push('…');
            }
            out.push_str(rest);
        } else {
            out.push_str(seg);
        }
        after_sessions = seg == "sessions";
    }
    out
}

/// Remove every occurrence of `secret_url` from a lower-level error's text, then redact any
/// other URL-looking token (the transport libraries print the URL they were given).
pub(crate) fn scrub_url_from(text: &str, secret_url: &str) -> String {
    let t = text.replace(secret_url, &redact_url(secret_url));
    t.split_whitespace()
        .map(|w| {
            let core = w.trim_matches(|c: char| {
                matches!(c, '(' | ')' | '"' | '\'' | ',' | ';' | ':' | '<' | '>')
            });
            if core.contains("://") && core != redact_url(core) {
                w.replace(core, &redact_url(core))
            } else {
                w.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// A raw, already-buffered HTTP response. Non-2xx statuses are *not* errors at
/// this layer — callers decide, exactly as the TS `request()` returns a
/// `Response` regardless of `res.ok`.
#[derive(Debug, Clone)]
pub(crate) struct RawResponse {
    pub status: u16,
    pub body: String,
}

impl RawResponse {
    pub fn ok(&self) -> bool {
        (200..300).contains(&self.status)
    }
}

/// Only 502/503/504 are worth another attempt.
// Spelled as three distinct statuses rather than the equivalent `502..=504`
// to mirror the reference `isRetryableStatus` — this is an allowlist of
// specific gateway conditions, not a numeric range.
#[allow(clippy::manual_range_patterns)]
fn is_retryable_status(status: u16) -> bool {
    // 507 is listed although THIS gateway does not emit one (censused 2026-09-22:
    // browser emits 501/502/503 only). Desktop's InsufficientCapacity 507 is
    // transient, and a client's correctness must not depend on which gateway build
    // it reaches. Inert today, deliberately — do not remove it as dead code.
    matches!(status, 502 | 503 | 504 | 507)
}

/// Whether THIS REQUEST may be sent again. Deliberately a per-request question,
/// not a per-method one: a `POST` is not idempotent by verb, but a `POST`
/// carrying an `Idempotency-Key` is safe to replay, because the server answers
/// the second copy from the first one's result instead of creating twice.
///
/// RETRACTED REASON, kept deliberately: this used to be method-only, because
/// "the browser API issues no Idempotency-Key, so a re-sent `POST /sessions`
/// could leave a second live session behind". Creates now mint one, so the
/// condition was removed rather than worked around.
fn is_safe_to_replay(method: &str, idempotency_key: Option<&str>) -> bool {
    is_idempotent_method(method) || idempotency_key.is_some()
}

/// A key identifies the CALL, not the attempt: minted once and reused by every
/// retry of that call. A key per attempt would make each retry a fresh create
/// and fix nothing.
///
/// Deliberately dependency-free — adding `uuid` to a published crate for one
/// opaque string is not worth the supply-chain surface. The server treats the
/// key as opaque and scopes it to (org, key), so process-uniqueness is enough.
pub(crate) fn new_idempotency_key() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    // RandomState is seeded per process, so this differs between processes
    // started in the same nanosecond.
    let seed = {
        use std::hash::{BuildHasher, Hasher};
        let mut h = std::collections::hash_map::RandomState::new().build_hasher();
        h.write_u64(nanos);
        h.finish()
    };
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("slr-{nanos:x}-{seed:x}-{n:x}")
}

/// Methods safe to send twice by verb alone.
fn is_idempotent_method(method: &str) -> bool {
    matches!(
        method.to_ascii_uppercase().as_str(),
        "GET" | "HEAD" | "DELETE" | "PUT"
    )
}

/// Whether the gateway explicitly marked this response retryable. The flag can
/// appear on a status OUTSIDE the 5xx allowlist — today `404 ReplayPending`,
/// where the recording upload is still in flight.
fn says_retryable(body: &str) -> bool {
    #[derive(serde::Deserialize)]
    struct Hint {
        retryable: Option<bool>,
    }
    // A non-JSON body carries no hint.
    serde_json::from_str::<Hint>(body)
        .ok()
        .and_then(|h| h.retryable)
        .unwrap_or(false)
}

/// Some 5xx are answers, not outages: retrying cannot change them, and the caller needs the code.
/// The gateway says so itself with `retryable: false` (502 `PoolResponseUnparseable`: the session may
/// already exist, so a retry creates a second one; 503 `EgressBlockPeekUnsupportedOnFlavor`).
/// A 503 `ProxyTierUnavailable` (an explicitly requested proxy tier cannot be served) is also terminal,
/// whatever its flag.
fn is_terminal(status: u16, body: &str) -> bool {
    #[derive(serde::Deserialize)]
    struct Coded {
        code: Option<String>,
        retryable: Option<bool>,
    }
    serde_json::from_str::<Coded>(body).ok().is_some_and(|c| {
        c.retryable == Some(false)
            || (status == 503 && c.code.is_some_and(|c| c == "ProxyTierUnavailable"))
    })
}

#[derive(Clone)]
pub(crate) struct HttpTransport {
    api_key: String,
    base_url: String,
    client: reqwest::Client,
    max_attempts: u32,
    backoff: Duration,
    timeout: Duration,
}

/// Hand-written so the API key is never printed. Do not derive this.
impl std::fmt::Debug for HttpTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpTransport")
            .field("api_key", &"<redacted>")
            .field("base_url", &self.base_url)
            .field("max_attempts", &self.max_attempts)
            .field("backoff", &self.backoff)
            .field("timeout", &self.timeout)
            .finish()
    }
}

impl HttpTransport {
    pub fn new(
        api_key: String,
        base_url: String,
        max_attempts: u32,
        backoff_ms: u64,
        timeout_ms: u64,
    ) -> Result<Self, SolariError> {
        let client = reqwest::Client::builder()
            .build()
            .map_err(|e| SolariError::config(format!("Solari: failed to build HTTP client: {e}")))?;
        Ok(HttpTransport {
            api_key,
            base_url,
            client,
            max_attempts: max_attempts.max(1),
            backoff: Duration::from_millis(backoff_ms),
            timeout: Duration::from_millis(timeout_ms),
        })
    }

    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Issue an authenticated request against the API, retrying per the policy
    /// above. `body` is serialized as JSON; `None` sends no body at all.
    pub async fn request(
        &self,
        method: &str,
        path: &str,
        body: Option<&serde_json::Value>,
    ) -> Result<RawResponse, SolariError> {
        self.request_with_key(method, path, body, None).await
    }

    /// As [`Self::request`], but sends `Idempotency-Key` on EVERY attempt and
    /// therefore treats the request as safe to replay.
    pub async fn request_with_key(
        &self,
        method: &str,
        path: &str,
        body: Option<&serde_json::Value>,
        idempotency_key: Option<&str>,
    ) -> Result<RawResponse, SolariError> {
        self.request_full(method, path, body, idempotency_key, &[], false).await
    }

    /// As [`Self::request_with_key`], plus extra request headers sent on every attempt.
    /// `no_retry` makes the call single-shot: a 502 or a transport error is returned as-is.
    pub async fn request_full(
        &self,
        method: &str,
        path: &str,
        body: Option<&serde_json::Value>,
        idempotency_key: Option<&str>,
        headers: &[(&str, &str)],
        no_retry: bool,
    ) -> Result<RawResponse, SolariError> {
        let m = Method::from_bytes(method.as_bytes())
            .map_err(|e| SolariError::config(format!("Solari: bad method {method}: {e}")))?;
        let url = format!("{}{}", self.base_url, path);
        let payload = body.map(|b| serde_json::to_string(b).unwrap_or_else(|_| "null".into()));

        let mut last_err: Option<String> = None;
        let max_attempts = if no_retry { 1 } else { self.max_attempts };
        for attempt in 1..=max_attempts {
            let mut rb = self
                .client
                .request(m.clone(), &url)
                .timeout(self.timeout)
                .header("Authorization", format!("Bearer {}", self.api_key))
                .header("Content-Type", "application/json");
            if let Some(k) = idempotency_key {
                rb = rb.header("Idempotency-Key", k);
            }
            for (k, v) in headers {
                rb = rb.header(*k, *v);
            }
            if let Some(p) = &payload {
                rb = rb.body(p.clone());
            } else if matches!(method, "POST" | "PUT" | "PATCH") {
                // reqwest sends NO Content-Length for a body-less POST and the hosted gateway's front end answers 411 Length
                // Required (a default-options `sessions().create()` failed that way). Say "empty body" explicitly.
                rb = rb.header("Content-Length", "0");
            }

            match rb.send().await {
                Ok(resp) => {
                    let status = resp.status().as_u16();
                    let body = resp.text().await.unwrap_or_default();
                    // Success, or a status we must not retry: hand it back.
                    let retry_this = (is_retryable_status(status) && !is_terminal(status, &body))
                        || (is_safe_to_replay(method, idempotency_key)
                            && says_retryable(&body));
                    // Out of attempts: hand the last response back so the caller maps its
                    // status and `code` like any other error, not a status-less Transport.
                    if (200..300).contains(&status) || !retry_this || attempt == max_attempts {
                        return Ok(RawResponse { status, body });
                    }
                    last_err = Some(format!("Solari {method} {}: {status}", redact_path(path)));
                }
                Err(e) => {
                    // Every transport error is retryable (mirrors isRetryableError).
                    last_err = Some(format!(
                        "Solari {method} {}: {}",
                        redact_path(path),
                        scrub_url_from(&e.to_string(), &url)
                    ));
                }
            }

            if attempt < max_attempts {
                tokio::time::sleep(self.backoff).await;
            }
        }

        Err(SolariError::transport(format!(
            "Solari {method} {}: exhausted {} attempts{}",
            redact_path(path),
            max_attempts,
            last_err.map(|e| format!(" ({e})")).unwrap_or_default(),
        )))
    }

    /// GET an unauthenticated URL (a presigned S3 link) with its own timeout.
    /// No retries — presigned URLs are short-lived and single-shot.
    pub async fn get_presigned(
        &self,
        url: &str,
        timeout: Duration,
    ) -> Result<RawResponse, SolariError> {
        let resp = self
            .client
            .get(url)
            .timeout(timeout)
            .send()
            .await
            .map_err(|e| {
                SolariError::transport(format!(
                    "Solari: GET {} failed: {}",
                    redact_url(url),
                    scrub_url_from(&e.to_string(), url)
                ))
            })?;
        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();
        Ok(RawResponse { status, body })
    }

    /// GET an unauthenticated URL, returning raw bytes (replay downloads).
    pub async fn get_presigned_bytes(&self, url: &str) -> Result<(u16, Vec<u8>), SolariError> {
        let resp = self
            .client
            .get(url)
            .timeout(self.timeout)
            .send()
            .await
            .map_err(|e| {
                SolariError::transport(format!(
                    "Solari: GET {} failed: {}",
                    redact_url(url),
                    scrub_url_from(&e.to_string(), url)
                ))
            })?;
        let status = resp.status().as_u16();
        let bytes = resp
            .bytes()
            .await
            .map_err(|e| {
                SolariError::transport(format!(
                    "Solari: reading {} failed: {}",
                    redact_url(url),
                    scrub_url_from(&e.to_string(), url)
                ))
            })?;
        Ok((status, bytes.to_vec()))
    }
}

#[cfg(test)]
mod tests {
    use super::{is_retryable_status, is_safe_to_replay, is_terminal, redact_path, redact_url, scrub_url_from, HttpTransport};
    use std::time::Duration;

    /// 507 is in the allowlist although this gateway emits none (censused
    /// 2026-09-22). Asserted so a "dead code" cleanup reddens a test rather
    /// than silently making correctness depend on which gateway build is
    /// reached.
    #[test]
    fn redact_url_keeps_scheme_host_and_port_only() {
        assert_eq!(
            redact_url("wss://api.getsolari.com/cdp/SECRETSESSION?token=abc"),
            "wss://api.getsolari.com/…"
        );
        assert_eq!(
            redact_url("ws://127.0.0.1:9222/devtools/browser/SECRET"),
            "ws://127.0.0.1:9222/…"
        );
        assert_eq!(
            redact_url("https://bucket.s3.amazonaws.com/replay.json?X-Amz-Signature=SECRET"),
            "https://bucket.s3.amazonaws.com/…"
        );
        assert_eq!(redact_url("not a url SECRET"), "<url>");
        assert_eq!(redact_url(""), "<url>");
    }

    #[test]
    fn scrub_url_from_removes_the_secret_wherever_the_library_printed_it() {
        let url = "wss://api.getsolari.com/cdp/SECRETSESSION";
        let out = scrub_url_from(
            &format!("IO error: connection refused (url: {url}) while dialling {url}."),
            url,
        );
        assert!(!out.contains("SECRETSESSION"), "{out}");
        assert!(out.contains("api.getsolari.com"), "{out}");
        // A URL the library printed that is not the one we passed is cut too.
        let out = scrub_url_from("redirected to https://other.example/path/SECRET2?x=1", url);
        assert!(!out.contains("SECRET2"), "{out}");
    }

    #[tokio::test]
    async fn a_failed_presigned_get_does_not_print_the_signed_url() {
        let http = HttpTransport::new("slr_live_x".into(), "http://127.0.0.1:1".into(), 1, 1, 500)
            .unwrap();
        let url = "http://127.0.0.1:1/replay.json?X-Amz-Signature=SIGSECRET";
        let err = http
            .get_presigned(url, Duration::from_millis(500))
            .await
            .unwrap_err()
            .to_string();
        assert!(!err.contains("SIGSECRET"), "{err}");
        let err = http.get_presigned_bytes(url).await.unwrap_err().to_string();
        assert!(!err.contains("SIGSECRET"), "{err}");
    }

    #[test]
    fn redact_path_cuts_the_session_id() {
        assert_eq!(redact_path("/sessions/pool:abc:org:123.SECRETSIGNATURE"), "/sessions/pool:abc…");
        assert_eq!(redact_path("/sessions/pool:abc:org:123.SECRET/replay-url"), "/sessions/pool:abc…/replay-url");
        assert_eq!(redact_path("/sessions/short"), "/sessions/short");
        assert_eq!(redact_path("/sessions"), "/sessions");
        assert_eq!(redact_path("/profiles/prof_123456789"), "/profiles/prof_123456789");
    }

    #[tokio::test]
    async fn a_transport_failure_does_not_print_the_session_id() {
        let http = HttpTransport::new("slr_live_x".into(), "http://127.0.0.1:1".into(), 1, 1, 500).unwrap();
        let err = http.request("GET", "/sessions/pool:abc:org:123.IDSECRET", None).await.unwrap_err().to_string();
        assert!(!err.contains("IDSECRET"), "{err}");
        assert!(err.contains("/sessions/pool:abc…"), "{err}");
    }

    #[test]
    fn retryable_status_includes_507() {
        for s in [502u16, 503, 504, 507] {
            assert!(is_retryable_status(s), "expected {s} retryable");
        }
        // Negative control: permanent statuses stay out.
        for s in [400u16, 429, 500, 501] {
            assert!(!is_retryable_status(s), "expected {s} NOT retryable");
        }
    }

    #[test]
    fn terminal_responses_are_not_retried_but_ordinary_ones_are() {
        let tier = r#"{"error":"Requested proxy tier 'residential' is unavailable","code":"ProxyTierUnavailable","tier":"residential"}"#;
        assert!(is_terminal(503, tier));
        assert!(!is_terminal(503, r#"{"error":"No stealth pool available","kind":"stealth"}"#));
        assert!(!is_terminal(503, "not json"));
        // The code only means something on a 503.
        assert!(!is_terminal(502, tier));
        // retryable:false ends the loop on any status (502 PoolResponseUnparseable).
        let unparseable = r#"{"error":"Pool returned an invalid response","code":"PoolResponseUnparseable","retryable":false}"#;
        assert!(is_terminal(502, unparseable));
        assert!(!is_terminal(502, r#"{"error":"bad gateway"}"#));
        assert!(!is_terminal(502, r#"{"retryable":true}"#));
    }

    #[test]
    fn a_post_is_replayable_only_with_a_key() {
        assert!(!is_safe_to_replay("POST", None));
        assert!(is_safe_to_replay("POST", Some("k")));
        assert!(is_safe_to_replay("GET", None));
    }
}