gaze-proxy 0.14.0

Feature-gated multi-provider HTTP proxy for Gaze PII pseudonymization
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
use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::io::Read;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use chrono::{DateTime, Utc};
use fs2::FileExt;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::error::ProxyError;

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DaemonPaths {
    pub pidfile: PathBuf,
    pub config: PathBuf,
    pub log_file: PathBuf,
    pub stderr_file: PathBuf,
}

impl DaemonPaths {
    pub fn new(pidfile: PathBuf, config: PathBuf, log_file: PathBuf, stderr_file: PathBuf) -> Self {
        Self {
            pidfile,
            config,
            log_file,
            stderr_file,
        }
    }

    pub fn resolve() -> Result<Self, ProxyError> {
        let data_dir = dirs::data_local_dir()
            .ok_or_else(|| ProxyError::DaemonConfig {
                detail: "could not resolve local data directory".to_string(),
            })?
            .join("gaze");
        let config_dir = dirs::config_dir()
            .ok_or_else(|| ProxyError::DaemonConfig {
                detail: "could not resolve config directory".to_string(),
            })?
            .join("gaze");
        let log_dir = if cfg!(target_os = "macos") {
            dirs::home_dir()
                .ok_or_else(|| ProxyError::DaemonConfig {
                    detail: "could not resolve home directory".to_string(),
                })?
                .join("Library/Logs/gaze")
        } else {
            data_dir.join("Logs")
        };
        Ok(Self {
            pidfile: data_dir.join("proxy.pid"),
            config: config_dir.join("proxy.toml"),
            log_file: log_dir.join("proxy.log"),
            stderr_file: log_dir.join("proxy-stderr.log"),
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DaemonConfig {
    pub bind: SocketAddr,
    pub session_ttl: String,
    pub policy: Option<PathBuf>,
    pub rulepack: Option<String>,
    pub adapters: AdapterConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdapterConfig {
    pub openai: ProviderConfig,
    pub anthropic: ProviderConfig,
    pub gemini: ProviderConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProviderConfig {
    pub upstream: Url,
}

impl ProviderConfig {
    pub fn new(upstream: Url) -> Self {
        Self { upstream }
    }
}

impl AdapterConfig {
    pub fn new(openai: Url, anthropic: Url, gemini: Url) -> Self {
        Self {
            openai: ProviderConfig::new(openai),
            anthropic: ProviderConfig::new(anthropic),
            gemini: ProviderConfig::new(gemini),
        }
    }
}

impl Default for AdapterConfig {
    fn default() -> Self {
        Self {
            openai: ProviderConfig {
                upstream: Url::parse("https://api.openai.com").expect("static url"),
            },
            anthropic: ProviderConfig {
                upstream: Url::parse("https://api.anthropic.com").expect("static url"),
            },
            gemini: ProviderConfig {
                upstream: Url::parse("https://generativelanguage.googleapis.com")
                    .expect("static url"),
            },
        }
    }
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            bind: "127.0.0.1:8787".parse().expect("static bind addr"),
            session_ttl: "30m".to_string(),
            policy: None,
            rulepack: Some("core".to_string()),
            adapters: AdapterConfig::default(),
        }
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct StartOptions {
    pub paths: DaemonPaths,
    pub config: DaemonConfig,
    pub extra_args: Vec<String>,
}

impl StartOptions {
    pub fn new(paths: DaemonPaths, config: DaemonConfig) -> Self {
        Self {
            paths,
            config,
            extra_args: Vec::new(),
        }
    }

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

#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct StopOptions {
    pub paths: DaemonPaths,
    pub timeout: Duration,
    pub force: bool,
}

impl StopOptions {
    pub fn new(paths: DaemonPaths, timeout: Duration, force: bool) -> Self {
        Self {
            paths,
            timeout,
            force,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DaemonStatus {
    pub pid: u32,
    pub bind: Option<String>,
    pub started_at: Option<String>,
    pub running: bool,
}

pub fn read_or_default_config(paths: &DaemonPaths) -> Result<DaemonConfig, ProxyError> {
    if !paths.config.exists() {
        return Ok(DaemonConfig::default());
    }
    let text = fs::read_to_string(&paths.config).map_err(|source| ProxyError::DaemonIo {
        path: paths.config.clone(),
        source,
    })?;
    toml::from_str(&text).map_err(|err| ProxyError::DaemonConfig {
        detail: err.to_string(),
    })
}

pub fn write_config(paths: &DaemonPaths, config: &DaemonConfig) -> Result<(), ProxyError> {
    if let Some(parent) = paths.config.parent() {
        fs::create_dir_all(parent).map_err(|source| ProxyError::DaemonIo {
            path: parent.to_path_buf(),
            source,
        })?;
    }
    let text = toml::to_string_pretty(config).map_err(|err| ProxyError::DaemonConfig {
        detail: err.to_string(),
    })?;
    fs::write(&paths.config, text).map_err(|source| ProxyError::DaemonIo {
        path: paths.config.clone(),
        source,
    })
}

/// Rebuilds the daemon's configured surface as `gaze proxy serve` flags.
///
/// The persisted [`DaemonConfig`] is the single source of truth for a detached
/// proxy: `start` and `restart` write it, and the child is handed nothing but
/// what this derives from it, so `serve` keeps exactly one policy input whether
/// it runs in the foreground or as the daemon child. The exhaustive
/// destructuring is load-bearing — a new `DaemonConfig` field stops compiling
/// here instead of silently never reaching the daemon, which is how `--policy`,
/// `--rulepack`, and the adapter upstreams went missing (solo todo #2965).
fn serve_args(config: &DaemonConfig) -> Vec<OsString> {
    let DaemonConfig {
        bind,
        session_ttl,
        policy,
        rulepack,
        adapters,
    } = config;
    let AdapterConfig {
        openai,
        anthropic,
        gemini,
    } = adapters;

    let mut args: Vec<OsString> = vec![
        "--bind".into(),
        bind.to_string().into(),
        "--session-ttl".into(),
        session_ttl.into(),
    ];
    // The policy path travels, not its resolved contents: the child loads it
    // through the same sequence as `gaze clean`, and a path that has moved since
    // `start` fails the child closed instead of quietly demoting the chokepoint
    // to the bundled floor. Serializing resolved inputs into the config would
    // make that file a second, staleable copy of the policy.
    if let Some(policy) = policy {
        args.push("--policy".into());
        args.push(policy.into());
    }
    if let Some(rulepack) = rulepack {
        args.push("--rulepack".into());
        args.push(rulepack.into());
    }
    for (flag, ProviderConfig { upstream }) in [
        ("--upstream-openai", openai),
        ("--upstream-anthropic", anthropic),
        ("--upstream-gemini", gemini),
    ] {
        args.push(flag.into());
        args.push(upstream.to_string().into());
    }
    args
}

pub fn start(options: StartOptions) -> Result<u32, ProxyError> {
    cleanup_stale(&options.paths)?;
    if let Some(status) = status(&options.paths)? {
        if status.running {
            return Err(ProxyError::DaemonAlreadyRunning {
                pid: status.pid,
                pidfile: options.paths.pidfile,
            });
        }
    }
    write_config(&options.paths, &options.config)?;
    create_parent(&options.paths.pidfile)?;
    create_parent(&options.paths.log_file)?;
    let lock = lock_pidfile(&options.paths)?;

    let stdout = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&options.paths.log_file)
        .map_err(|source| ProxyError::DaemonIo {
            path: options.paths.log_file.clone(),
            source,
        })?;
    let stderr = OpenOptions::new()
        .create(true)
        .append(true)
        .open(&options.paths.stderr_file)
        .map_err(|source| ProxyError::DaemonIo {
            path: options.paths.stderr_file.clone(),
            source,
        })?;
    let mut command =
        Command::new(
            std::env::current_exe().map_err(|source| ProxyError::DaemonIo {
                path: PathBuf::from("current_exe"),
                source,
            })?,
        );
    command
        .args(["proxy", "serve", "--_foreground-daemon"])
        .args(serve_args(&options.config))
        .args(options.extra_args)
        .stdin(Stdio::null())
        .stdout(Stdio::from(stdout))
        .stderr(Stdio::from(stderr));
    drop(lock);
    let mut child = command.spawn().map_err(|source| ProxyError::DaemonIo {
        path: PathBuf::from("gaze proxy serve"),
        source,
    })?;
    confirm_started(&mut child, &options.paths)
}

/// Confirms the spawned child is still alive after a short probe window and
/// returns its pid.
///
/// The child resolves the configured policy, so a fail-closed load error
/// surfaces as an immediate exit. `kill(pid, 0)` cannot see that: an unreaped
/// child is a zombie and still answers as alive, which reported a dead daemon as
/// started (solo todo #2965). `try_wait` reaps and reports the real status
/// within the same 250ms budget, returning early on failure.
///
/// A failure slower than the probe window still reports success; that daemon is
/// dead rather than serving unprotected, and `gaze proxy status` shows it.
fn confirm_started(child: &mut Child, paths: &DaemonPaths) -> Result<u32, ProxyError> {
    let deadline = Instant::now() + Duration::from_millis(250);
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                // The parent created this pidfile before spawning and the child
                // never filled it in; leaving the empty file behind would fail
                // every later start as stale.
                let _ = fs::remove_file(&paths.pidfile);
                return Err(ProxyError::DaemonExitedEarly {
                    code: status.code(),
                    stderr_file: paths.stderr_file.clone(),
                });
            }
            Ok(None) if Instant::now() >= deadline => return Ok(child.id()),
            Ok(None) => std::thread::sleep(Duration::from_millis(25)),
            Err(source) => {
                return Err(ProxyError::DaemonIo {
                    path: PathBuf::from("gaze proxy serve"),
                    source,
                })
            }
        }
    }
}

pub fn init_foreground_daemon(paths: &DaemonPaths, bind: SocketAddr) -> Result<(), ProxyError> {
    create_parent(&paths.pidfile)?;
    create_parent(&paths.log_file)?;
    let _lock = lock_pidfile(paths)?;
    write_pidfile(&paths.pidfile, std::process::id(), bind, Utc::now())
}

pub fn stop(options: StopOptions) -> Result<(), ProxyError> {
    cleanup_stale(&options.paths)?;
    let Some(status) = status(&options.paths)? else {
        return Err(ProxyError::DaemonNotRunning);
    };
    terminate(status.pid, false)?;
    let started = Instant::now();
    while started.elapsed() < options.timeout {
        if !process_exists(status.pid) {
            let _ = fs::remove_file(&options.paths.pidfile);
            return Ok(());
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    if options.force {
        terminate(status.pid, true)?;
        let _ = fs::remove_file(&options.paths.pidfile);
        Ok(())
    } else {
        Err(ProxyError::DaemonAlreadyRunning {
            pid: status.pid,
            pidfile: options.paths.pidfile,
        })
    }
}

pub fn restart(options: StartOptions, timeout: Duration, force: bool) -> Result<u32, ProxyError> {
    let stop_result = stop(StopOptions {
        paths: options.paths.clone(),
        timeout,
        force,
    });
    if !matches!(stop_result, Ok(()) | Err(ProxyError::DaemonNotRunning)) {
        cleanup_stale(&options.paths)?;
    }
    start(options)
}

pub fn status(paths: &DaemonPaths) -> Result<Option<DaemonStatus>, ProxyError> {
    if !paths.pidfile.exists() {
        return Ok(None);
    }
    let record = read_pidfile(&paths.pidfile)?;
    Ok(Some(DaemonStatus {
        running: process_exists(record.pid),
        pid: record.pid,
        bind: record.bind,
        started_at: record.started_at,
    }))
}

pub fn cleanup_stale(paths: &DaemonPaths) -> Result<(), ProxyError> {
    if let Some(status) = status(paths)? {
        if !status.running {
            fs::remove_file(&paths.pidfile).map_err(|source| ProxyError::DaemonIo {
                path: paths.pidfile.clone(),
                source,
            })?;
        }
    }
    Ok(())
}

pub fn logs(paths: &DaemonPaths, follow: bool) -> Result<(), ProxyError> {
    if follow {
        Command::new("tail")
            .arg("-F")
            .arg(&paths.log_file)
            .status()
            .map_err(|source| ProxyError::DaemonIo {
                path: paths.log_file.clone(),
                source,
            })?;
    } else if paths.log_file.exists() {
        let text = fs::read_to_string(&paths.log_file).map_err(|source| ProxyError::DaemonIo {
            path: paths.log_file.clone(),
            source,
        })?;
        print!("{text}");
    }
    Ok(())
}

fn create_parent(path: &Path) -> Result<(), ProxyError> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|source| ProxyError::DaemonIo {
            path: parent.to_path_buf(),
            source,
        })?;
    }
    Ok(())
}

fn lock_pidfile(paths: &DaemonPaths) -> Result<File, ProxyError> {
    let file = OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(&paths.pidfile)
        .map_err(|source| ProxyError::DaemonIo {
            path: paths.pidfile.clone(),
            source,
        })?;
    file.try_lock_exclusive()
        .map_err(|source| ProxyError::DaemonIo {
            path: paths.pidfile.clone(),
            source,
        })?;
    Ok(file)
}

fn write_pidfile(
    path: &Path,
    pid: u32,
    bind: SocketAddr,
    started_at: DateTime<Utc>,
) -> Result<(), ProxyError> {
    let contents = format!(
        "{pid}\nbind={bind}\nstarted_at={}\n",
        started_at.to_rfc3339()
    );
    if contents.len() > 200 {
        return Err(ProxyError::DaemonConfig {
            detail: "pidfile content exceeds 200 bytes".to_string(),
        });
    }
    fs::write(path, contents).map_err(|source| ProxyError::DaemonIo {
        path: path.to_path_buf(),
        source,
    })
}

struct PidRecord {
    pid: u32,
    bind: Option<String>,
    started_at: Option<String>,
}

fn read_pidfile(path: &Path) -> Result<PidRecord, ProxyError> {
    let mut text = String::new();
    File::open(path)
        .and_then(|mut file| file.read_to_string(&mut text))
        .map_err(|source| ProxyError::DaemonIo {
            path: path.to_path_buf(),
            source,
        })?;
    let mut lines = text.lines();
    let pid = lines
        .next()
        .ok_or_else(|| ProxyError::DaemonPidfileStale {
            pidfile: path.to_path_buf(),
        })?
        .parse::<u32>()
        .map_err(|_| ProxyError::DaemonPidfileStale {
            pidfile: path.to_path_buf(),
        })?;
    let mut bind = None;
    let mut started_at = None;
    for line in lines {
        if let Some(rest) = line.strip_prefix("bind=") {
            bind = Some(rest.to_string());
        } else if let Some(rest) = line.strip_prefix("started_at=") {
            started_at = Some(rest.to_string());
        }
    }
    Ok(PidRecord {
        pid,
        bind,
        started_at,
    })
}

#[cfg(unix)]
fn process_exists(pid: u32) -> bool {
    unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}

#[cfg(not(unix))]
fn process_exists(_pid: u32) -> bool {
    false
}

#[cfg(unix)]
fn terminate(pid: u32, force: bool) -> Result<(), ProxyError> {
    let signal = if force { libc::SIGKILL } else { libc::SIGTERM };
    let rc = unsafe { libc::kill(pid as libc::pid_t, signal) };
    if rc == 0 {
        Ok(())
    } else {
        Err(ProxyError::DaemonNotRunning)
    }
}

#[cfg(not(unix))]
fn terminate(_pid: u32, _force: bool) -> Result<(), ProxyError> {
    Err(ProxyError::DaemonConfig {
        detail: "daemon stop is not implemented on this platform".to_string(),
    })
}

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

    fn temp_paths(dir: &tempfile::TempDir) -> DaemonPaths {
        DaemonPaths {
            pidfile: dir.path().join("proxy.pid"),
            config: dir.path().join("proxy.toml"),
            log_file: dir.path().join("proxy.log"),
            stderr_file: dir.path().join("proxy-stderr.log"),
        }
    }

    #[test]
    fn pidfile_round_trip_includes_bind_and_started_at() {
        let dir = tempfile::tempdir().unwrap();
        let paths = temp_paths(&dir);
        write_pidfile(
            &paths.pidfile,
            123,
            "127.0.0.1:8787".parse().unwrap(),
            DateTime::parse_from_rfc3339("2026-05-14T00:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
        )
        .unwrap();
        let status = status(&paths).unwrap().unwrap();
        assert_eq!(status.pid, 123);
        assert_eq!(status.bind.as_deref(), Some("127.0.0.1:8787"));
        assert!(!status.running);
    }

    #[test]
    fn cleanup_stale_unlinks_dead_pidfile() {
        let dir = tempfile::tempdir().unwrap();
        let paths = temp_paths(&dir);
        write_pidfile(
            &paths.pidfile,
            999_999,
            "127.0.0.1:8787".parse().unwrap(),
            Utc::now(),
        )
        .unwrap();
        cleanup_stale(&paths).unwrap();
        assert!(!paths.pidfile.exists());
    }

    // solo todo #2965: every field the adopter can configure has to reach the
    // detached child, because the child's argv is all it ever sees.
    #[test]
    fn serve_args_forward_every_configured_field_to_the_daemon_child() {
        let config = DaemonConfig {
            policy: Some(PathBuf::from("/etc/gaze/prod.toml")),
            rulepack: Some("core-extended".to_string()),
            adapters: AdapterConfig::new(
                Url::parse("http://127.0.0.1:4001").unwrap(),
                Url::parse("http://127.0.0.1:4002").unwrap(),
                Url::parse("http://127.0.0.1:4003").unwrap(),
            ),
            ..Default::default()
        };

        assert_eq!(
            serve_args(&config),
            [
                "--bind",
                "127.0.0.1:8787",
                "--session-ttl",
                "30m",
                "--policy",
                "/etc/gaze/prod.toml",
                "--rulepack",
                "core-extended",
                "--upstream-openai",
                "http://127.0.0.1:4001/",
                "--upstream-anthropic",
                "http://127.0.0.1:4002/",
                "--upstream-gemini",
                "http://127.0.0.1:4003/",
            ]
            .map(OsString::from)
        );
    }

    #[test]
    fn serve_args_omit_policy_when_the_daemon_has_none() {
        let args = serve_args(&DaemonConfig::default());

        assert!(!args.contains(&OsString::from("--policy")));
        assert!(args
            .windows(2)
            .any(|pair| pair == ["--rulepack", "core"].map(OsString::from)));
    }

    #[test]
    fn config_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let paths = temp_paths(&dir);
        let config = DaemonConfig::default();
        write_config(&paths, &config).unwrap();
        let loaded = read_or_default_config(&paths).unwrap();
        assert_eq!(loaded.bind, config.bind);
        assert_eq!(
            loaded.adapters.openai.upstream,
            config.adapters.openai.upstream
        );
    }
}