bird 0.1.3

X API CLI with entity caching, search, threads, and watchlists
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
//! xurl subprocess transport layer.
//!
//! All X API HTTP calls route through xurl as a subprocess. Bird owns the
//! intelligence layer (entity store, caching, cost tracking, UX); xurl owns
//! the transport layer (auth, HTTP, X API compatibility).
//!
//! # Security Invariants
//!
//! - NEVER use shell=true or compose a single string from multiple args.
//!   `Command::new(path).args(args)` calls execvp directly — no shell interpretation.
//! - NEVER pass tokens, credentials, or secrets as subprocess arguments.
//!   xurl reads auth from its own token store (~/.xurl).
//! - All user input (search queries, tweet text) passes as separate argv elements.

use crate::diag;
use crate::output;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use std::time::Duration;

/// Maximum stdout capture size (50 MB) to prevent memory exhaustion.
const MAX_STDOUT_BYTES: usize = 50 * 1024 * 1024;

/// Subprocess timeout before SIGTERM.
const TIMEOUT_SECS: u64 = 60;

/// Grace period after SIGTERM before SIGKILL.
const KILL_GRACE_SECS: u64 = 5;

/// Minimum supported xurl version.
const MIN_VERSION: &str = "1.0.3";

/// Centralized xurl install guidance (DRY across transport.rs and doctor.rs).
pub const XURL_INSTALL_HINT: &str = "Install xurl-rs: brew install brettdavies/tap/xurl-rs (or Go xurl: brew install xdevplatform/tap/xurl)";

/// Cached absolute path to the xurl binary, resolved once at startup.
static XURL_PATH: OnceLock<Result<PathBuf, String>> = OnceLock::new();

/// Resolve and cache the absolute path to the xurl binary.
/// Checks `BIRD_XURL_PATH` env var first, falls back to `which::which("xr")`
/// then `which::which("xurl")`. Resolved paths are canonicalized and version-checked
/// as an integrity gate (rejects binaries that don't report a valid version).
pub fn resolve_xurl_path() -> Result<&'static Path, Box<dyn std::error::Error + Send + Sync>> {
    let result = XURL_PATH.get_or_init(|| {
        if let Ok(path) = std::env::var("BIRD_XURL_PATH") {
            let p = PathBuf::from(&path);
            if !p.exists() {
                return Err(format!("BIRD_XURL_PATH={} does not exist", path));
            }
            let p = p
                .canonicalize()
                .map_err(|e| format!("BIRD_XURL_PATH={} cannot be resolved: {}", path, e))?;
            if !p.is_file() {
                return Err(format!("BIRD_XURL_PATH={} is not a file", p.display()));
            }
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = p
                    .metadata()
                    .map_err(|e| format!("BIRD_XURL_PATH={}: {}", path, e))?
                    .permissions()
                    .mode();
                if mode & 0o111 == 0 {
                    return Err(format!("BIRD_XURL_PATH={} is not executable", path));
                }
            }
            return Ok(p);
        }
        // Try xr (xurl-rs) first, then xurl (Go original).
        // Canonicalize to resolve symlinks and mitigate impersonation.
        // Version check acts as integrity gate: reject binaries that don't
        // report a parseable version with "xurl " or "xr " prefix.
        for name in &["xr", "xurl"] {
            if let Ok(found) = which::which(name) {
                let canonical = found.canonicalize().unwrap_or(found);
                if verify_xurl_binary(&canonical) {
                    return Ok(canonical);
                }
            }
        }
        Err(format!("xurl not found. {}", XURL_INSTALL_HINT))
    });
    match result {
        Ok(p) => Ok(p.as_path()),
        Err(e) => Err(e.clone().into()),
    }
}

/// Verify a candidate binary is a genuine xurl/xr by checking its version output.
/// Returns true if the binary reports a parseable version string.
fn verify_xurl_binary(path: &Path) -> bool {
    let Ok(output) = Command::new(path)
        .arg("version")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
    else {
        return false;
    };
    let stdout = String::from_utf8_lossy(&output.stdout);
    parse_version_string(stdout.trim()).is_some()
}

/// Parse a version string from xurl/xr version output.
/// Accepts formats: "xurl X.Y.Z", "xr X.Y.Z", or bare "X.Y.Z" (with optional v prefix).
fn parse_version_string(s: &str) -> Option<semver::Version> {
    let version_part = s
        .strip_prefix("xurl ")
        .or_else(|| s.strip_prefix("xr "))
        .unwrap_or(s);
    let clean = version_part.strip_prefix('v').unwrap_or(version_part);
    semver::Version::parse(clean).ok()
}

/// Run `xurl version` (or `xr version`) and return the version string.
/// Warns if below minimum. Handles both "xurl X.Y.Z" and "xr X.Y.Z" prefixes.
pub fn check_xurl_version(
    path: &Path,
    quiet: bool,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
    let output = Command::new(path)
        .arg("version")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .map_err(|e| format!("failed to run xurl version: {}", e))?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let trimmed = stdout.trim();

    if let Some(current) = parse_version_string(trimmed) {
        if let Ok(minimum) = semver::Version::parse(MIN_VERSION)
            && current < minimum
        {
            diag!(
                quiet,
                "[transport] warning: xurl {} is below minimum {}; consider upgrading",
                current,
                MIN_VERSION
            );
        }
        Ok(current.to_string())
    } else {
        // Return raw output if we can't parse — still useful for diagnostics
        Ok(trimmed.to_string())
    }
}

/// Error from an xurl subprocess call.
#[derive(Debug)]
pub enum XurlError {
    /// xurl binary not found (exit 78 — EX_CONFIG)
    NotFound(String),
    /// xurl returned an auth error (HTTP 401/403)
    Auth(String),
    /// xurl returned an API error (non-auth HTTP error)
    Api { status: u16, message: String },
    /// xurl process timed out
    Timeout,
    /// xurl process failed (non-JSON stderr, crash, etc.)
    Process(String),
}

impl std::fmt::Display for XurlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            XurlError::NotFound(msg) => write!(f, "{}", msg),
            XurlError::Auth(msg) => write!(f, "auth error: {}", msg),
            XurlError::Api { status, message } => write!(f, "API error {}: {}", status, message),
            XurlError::Timeout => write!(f, "xurl timed out after {}s", TIMEOUT_SECS),
            XurlError::Process(msg) => write!(f, "xurl process error: {}", msg),
        }
    }
}

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

/// Call xurl with the given arguments, capture stdout as JSON.
///
/// Spawns xurl with `NO_COLOR=1` to suppress ANSI escape codes in output.
/// Stdout is piped and parsed as JSON. On failure, classifies the error type
/// from the JSON body's `status` field or stderr content.
pub fn xurl_call(
    args: &[&str],
) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>> {
    let path = resolve_xurl_path()?;

    let mut child = match Command::new(path)
        .args(args)
        .env("NO_COLOR", "1")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(Box::new(XurlError::NotFound(format!(
                "xurl not found. {}",
                XURL_INSTALL_HINT
            ))));
        }
        Err(e) => {
            return Err(Box::new(XurlError::Process(format!(
                "failed to spawn xurl: {}",
                e
            ))));
        }
    };

    // Drain stdout/stderr in background threads to prevent pipe-buffer deadlock.
    // If we wait for exit before reading, the child can block writing to a full
    // pipe buffer (typically 64 KB on Linux), deadlocking both processes.
    let stdout_thread = child.stdout.take().map(|out| {
        std::thread::spawn(move || {
            let mut buf = Vec::new();
            out.take(MAX_STDOUT_BYTES as u64).read_to_end(&mut buf).ok();
            buf
        })
    });
    let stderr_thread = child.stderr.take().map(|err| {
        std::thread::spawn(move || {
            let mut buf = Vec::new();
            err.take(MAX_STDOUT_BYTES as u64).read_to_end(&mut buf).ok();
            buf
        })
    });

    // Wait with timeout (child can now write freely — readers are draining)
    let status = wait_with_timeout(&mut child, Duration::from_secs(TIMEOUT_SECS))?;

    // Join reader threads
    let stdout_buf = stdout_thread
        .map(|h| h.join().unwrap_or_default())
        .unwrap_or_default();
    let stdout_str = String::from_utf8_lossy(&stdout_buf);

    let stderr_buf = stderr_thread
        .map(|h| h.join().unwrap_or_default())
        .unwrap_or_default();
    let stderr_str = String::from_utf8_lossy(&stderr_buf);

    // Strip ANSI lines as fallback (hardcoded escape codes in xurl error paths)
    let clean_stdout = output::strip_ansi_lines(&stdout_str);

    if status.success() {
        // Exit 0: parse stdout as JSON
        let json: serde_json::Value = serde_json::from_str(&clean_stdout).map_err(|e| {
            XurlError::Process(format!(
                "xurl returned invalid JSON: {} (stdout: {})",
                e,
                output::sanitize_for_stderr(&clean_stdout, 200)
            ))
        })?;
        Ok(json)
    } else {
        // Exit non-zero: classify error
        classify_error(&clean_stdout, &stderr_str)
    }
}

/// Run xurl with inherited stdio (for interactive flows like `bird login`).
/// No timeout: OAuth2 flows require user interaction in a browser; user can Ctrl+C.
pub fn xurl_passthrough(args: &[&str]) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let path = resolve_xurl_path()?;

    let status = Command::new(path)
        .args(args)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                Box::new(XurlError::NotFound(format!(
                    "xurl not found. {}",
                    XURL_INSTALL_HINT
                ))) as Box<dyn std::error::Error + Send + Sync>
            } else {
                Box::new(XurlError::Process(format!("failed to run xurl: {}", e)))
                    as Box<dyn std::error::Error + Send + Sync>
            }
        })?;

    if status.success() {
        Ok(())
    } else {
        Err(Box::new(XurlError::Process(format!(
            "xurl exited with code {}",
            status.code().unwrap_or(-1)
        ))))
    }
}

/// Classify an xurl error from its stdout JSON and stderr.
fn classify_error(
    stdout: &str,
    stderr: &str,
) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>> {
    // Try to parse stdout as JSON error response
    if let Ok(json) = serde_json::from_str::<serde_json::Value>(stdout) {
        let status = json.get("status").and_then(|s| s.as_u64()).unwrap_or(0) as u16;

        let detail = json
            .get("detail")
            .and_then(|d| d.as_str())
            .or_else(|| json.get("title").and_then(|t| t.as_str()))
            .unwrap_or("unknown error")
            .to_string();

        return Err(match status {
            401 | 403 => Box::new(XurlError::Auth(detail)),
            _ if status > 0 => Box::new(XurlError::Api {
                status,
                message: detail,
            }),
            // status=0 means no HTTP status in response — treat as process error
            _ => Box::new(XurlError::Api {
                status: 0,
                message: detail,
            }),
        });
    }

    // No JSON in stdout — use stderr
    let msg = if stderr.is_empty() {
        output::sanitize_for_stderr(stdout, 200)
    } else {
        output::sanitize_for_stderr(stderr, 200)
    };

    Err(Box::new(XurlError::Process(msg)))
}

/// Wait for a child process with a timeout. Sends SIGTERM, then SIGKILL after grace period.
/// Always reaps the child to prevent zombies.
fn wait_with_timeout(
    child: &mut std::process::Child,
    timeout: Duration,
) -> Result<std::process::ExitStatus, Box<dyn std::error::Error + Send + Sync>> {
    let start = std::time::Instant::now();
    let poll_interval = Duration::from_millis(50);

    loop {
        match child.try_wait()? {
            Some(status) => return Ok(status),
            None => {
                if start.elapsed() >= timeout {
                    // Timeout: SIGTERM
                    #[cfg(unix)]
                    {
                        unsafe {
                            libc::kill(child.id() as libc::pid_t, libc::SIGTERM);
                        }
                    }
                    #[cfg(not(unix))]
                    {
                        let _ = child.kill();
                    }

                    // Grace period for SIGTERM
                    let grace_start = std::time::Instant::now();
                    loop {
                        match child.try_wait()? {
                            Some(status) => return Ok(status),
                            None => {
                                if grace_start.elapsed() >= Duration::from_secs(KILL_GRACE_SECS) {
                                    // SIGKILL and reap to prevent zombie
                                    let _ = child.kill();
                                    let _ = child.wait();
                                    return Err(Box::new(XurlError::Timeout));
                                }
                                std::thread::sleep(poll_interval);
                            }
                        }
                    }
                }
                std::thread::sleep(poll_interval);
            }
        }
    }
}

/// Transport trait for testability. Production uses XurlTransport; tests use MockTransport.
pub trait Transport {
    fn request(
        &self,
        args: &[String],
    ) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>>;
}

/// Production transport: delegates to xurl subprocess.
pub struct XurlTransport;

impl Transport for XurlTransport {
    fn request(
        &self,
        args: &[String],
    ) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>> {
        let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        xurl_call(&arg_refs)
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::collections::VecDeque;

    /// Mock transport for unit tests. Returns pre-configured responses in order.
    pub struct MockTransport {
        pub responses:
            RefCell<VecDeque<Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>>>>,
    }

    impl MockTransport {
        pub fn new(
            responses: Vec<Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>>>,
        ) -> Self {
            Self {
                responses: RefCell::new(VecDeque::from(responses)),
            }
        }
    }

    impl Transport for MockTransport {
        fn request(
            &self,
            _args: &[String],
        ) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>> {
            self.responses
                .borrow_mut()
                .pop_front()
                .unwrap_or_else(|| Err("MockTransport: no more responses".into()))
        }
    }

    #[test]
    fn xurl_error_display_not_found() {
        let e = XurlError::NotFound("xurl not found".into());
        assert_eq!(e.to_string(), "xurl not found");
    }

    #[test]
    fn xurl_error_display_auth() {
        let e = XurlError::Auth("Unauthorized".into());
        assert_eq!(e.to_string(), "auth error: Unauthorized");
    }

    #[test]
    fn xurl_error_display_api() {
        let e = XurlError::Api {
            status: 429,
            message: "Too Many Requests".into(),
        };
        assert_eq!(e.to_string(), "API error 429: Too Many Requests");
    }

    #[test]
    fn xurl_error_display_timeout() {
        let e = XurlError::Timeout;
        assert!(e.to_string().contains("timed out"));
    }

    #[test]
    fn classify_error_auth_401() {
        let stdout = r#"{"title":"Unauthorized","status":401,"detail":"Unauthorized"}"#;
        let result = classify_error(stdout, "");
        let err = result.unwrap_err();
        assert!(err.to_string().contains("auth error"));
    }

    #[test]
    fn classify_error_auth_403() {
        let stdout = r#"{"title":"Forbidden","status":403,"detail":"Forbidden"}"#;
        let result = classify_error(stdout, "");
        let err = result.unwrap_err();
        assert!(err.to_string().contains("auth error"));
    }

    #[test]
    fn classify_error_api_429() {
        let stdout = r#"{"title":"Too Many Requests","status":429,"detail":"Rate limit exceeded"}"#;
        let result = classify_error(stdout, "");
        let err = result.unwrap_err();
        assert!(err.to_string().contains("API error 429"));
    }

    #[test]
    fn classify_error_no_json_uses_stderr() {
        let result = classify_error("not json", "some error on stderr");
        let err = result.unwrap_err();
        assert!(err.to_string().contains("some error on stderr"));
    }

    #[test]
    fn classify_error_no_json_no_stderr_uses_stdout() {
        let result = classify_error("raw error output", "");
        let err = result.unwrap_err();
        assert!(err.to_string().contains("raw error output"));
    }

    #[test]
    fn mock_transport_returns_responses_in_order() {
        let mock = MockTransport::new(vec![
            Ok(serde_json::json!({"data": "first"})),
            Ok(serde_json::json!({"data": "second"})),
        ]);
        let r1 = mock.request(&[]).unwrap();
        assert_eq!(r1["data"], "first");
        let r2 = mock.request(&[]).unwrap();
        assert_eq!(r2["data"], "second");
    }

    #[test]
    fn mock_transport_exhausted_returns_error() {
        let mock = MockTransport::new(vec![]);
        let result = mock.request(&[]);
        assert!(result.is_err());
    }

    #[test]
    fn version_comparison_multi_digit() {
        // The bug: lexicographic "1.0.9" > "1.0.10" because '9' > '1'
        assert!(
            semver::Version::parse("1.0.9").unwrap() < semver::Version::parse("1.0.10").unwrap()
        );
        assert!(
            (semver::Version::parse("1.0.10").unwrap() >= semver::Version::parse("1.0.3").unwrap())
        );
    }

    #[test]
    fn version_comparison_major() {
        assert!(
            (semver::Version::parse("2.0.0").unwrap() >= semver::Version::parse("1.0.3").unwrap())
        );
    }

    #[test]
    fn version_comparison_prerelease() {
        // semver spec: pre-release < release
        assert!(
            semver::Version::parse("1.0.3-beta").unwrap()
                < semver::Version::parse("1.0.3").unwrap()
        );
    }
}