link-assistant-router 1.3.2

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
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
//! End-to-end HTTP coverage of the administrative surface (issue #49).
//!
//! The unit tests in `src/admin_auth.rs` pin the authorisation *rule*; this
//! file pins the thing the issue actually reported — that a real router
//! process, started with no admin key, answered `200` to an unauthenticated
//! `POST /api/management/tokens`. It boots the released binary on a loopback port and
//! speaks HTTP to it, so nothing about the wiring between the rule and the
//! routes is assumed.
//!
//! Unix only: the harness sends SIGTERM to shut the child down.
#![cfg(unix)]

use std::io::{BufRead, BufReader};
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// A router process on its own port, killed when the test ends.
struct Router {
    child: Child,
    port: u16,
    /// The bootstrap admin token the router printed at startup, if any.
    bootstrap_token: Option<String>,
    _data_dir: tempfile::TempDir,
}

impl Drop for Router {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// How many times to re-roll the port before declaring a real failure.
const ATTEMPTS: usize = 5;

fn free_port() -> u16 {
    // `bind(":0")` then drop releases the port before the child binds it, so
    // another test binary running concurrently can take it in that window.
    // The loser then sends its requests to the winner's router, which answers
    // with its own tokens -- seen on CI as a scoped token appearing
    // unrestricted, because the reply came from a router that had never heard
    // of the scope (issue #368).
    //
    // The OS still picks the port, since only it knows what is already in use.
    // What is added is that no port is handed out twice within this process,
    // which removes the collisions between the suites of one binary; a caller
    // that still loses to another binary retries (see `Router::start`).
    use std::sync::{Mutex, OnceLock};
    static HANDED_OUT: OnceLock<Mutex<std::collections::HashSet<u16>>> = OnceLock::new();
    let seen = HANDED_OUT.get_or_init(|| Mutex::new(std::collections::HashSet::new()));
    for _ in 0..4_000 {
        let port = TcpListener::bind("127.0.0.1:0")
            .expect("bind ephemeral")
            .local_addr()
            .expect("address")
            .port();
        if seen.lock().expect("port registry").insert(port) {
            return port;
        }
    }
    panic!("no unused ephemeral port")
}

impl Router {
    /// Start a router, retrying if the port was taken between reservation and
    /// use.
    ///
    /// `free_port` closes its listener before returning the number, so any
    /// other test in the same parallel run can claim that port in the interval
    /// before the child binds it. The child does not retry — `serve` propagates
    /// the bind error and exits — so the loser of that race waited the full
    /// health timeout and failed, which is how a green PR run turned red on
    /// main and held up a release (the run for #266). Retrying on a fresh port
    /// makes the race recoverable instead of fatal.
    fn start(extra_env: &[(&str, &str)]) -> Self {
        let mut last_port = 0;
        for _ in 0..ATTEMPTS {
            if let Some(router) = Self::try_start(extra_env, &mut last_port) {
                return router;
            }
        }
        panic!("router never became healthy after {ATTEMPTS} attempts (last port {last_port})");
    }

    /// One start attempt: `None` if the child died or never answered, which
    /// the caller retries on a different port.
    fn try_start(extra_env: &[(&str, &str)], last_port: &mut u16) -> Option<Self> {
        let data_dir = tempfile::tempdir().expect("temp data dir");
        let port = free_port();
        *last_port = port;
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_link-assistant-router"));
        cmd.arg("serve")
            .env("TOKEN_SECRET", "admin-endpoint-test-secret")
            .env("ROUTER_HOST", "127.0.0.1")
            .env("ROUTER_PORT", port.to_string())
            .env("STORAGE_POLICY", "text")
            .env("DATA_DIR", data_dir.path())
            // Keep the subscription-less start quiet and self-contained.
            .env("CLAUDE_CODE_HOME", data_dir.path().join("claude"))
            .env("DISABLE_LOGIN_API", "true")
            .stdout(Stdio::piped())
            .stderr(Stdio::null());
        for (k, v) in extra_env {
            cmd.env(k, v);
        }
        let mut child = cmd.spawn().expect("router should start");

        // Pump stdout on its own thread. With an admin key configured the
        // router prints no bootstrap token at all, so scanning for the line
        // inline would block until the process exits — i.e. forever.
        let stdout = child.stdout.take().expect("piped stdout");
        let lines = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&lines);
        std::thread::spawn(move || {
            for line in BufReader::new(stdout).lines().map_while(Result::ok) {
                sink.lock().expect("stdout lock").push(line);
            }
        });

        let mut router = Self {
            child,
            port,
            bootstrap_token: None,
            _data_dir: data_dir,
        };
        if !router.await_health() {
            return None;
        }
        // The banner is printed before the listener binds, so by the time
        // `/health` answers everything we care about has been captured.
        router.bootstrap_token = lines
            .lock()
            .expect("stdout lock")
            .iter()
            .find_map(|line| line.split("store it now): ").nth(1))
            .map(|token| token.trim().to_string());
        Some(router)
    }

    /// Wait for `/health`, giving up early if the child has already exited.
    ///
    /// A router that lost the port race dies within milliseconds, so polling
    /// the full timeout would turn each retry into a 30-second stall.
    fn await_health(&mut self) -> bool {
        let deadline = Instant::now() + Duration::from_secs(30);
        while Instant::now() < deadline {
            if ureq_get(&self.url("/api/health"), None).is_some() {
                return true;
            }
            if matches!(self.child.try_wait(), Ok(Some(_))) {
                return false;
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        false
    }

    fn url(&self, path: &str) -> String {
        format!("http://127.0.0.1:{}{path}", self.port)
    }
}

/// Minimal blocking HTTP helpers — the test only needs a status and a body,
/// and the crate's `reqwest` is async-only in this context.
fn ureq_get(url: &str, bearer: Option<&str>) -> Option<(u16, String)> {
    http_request("GET", url, bearer, None)
}

fn ureq_post(url: &str, bearer: Option<&str>, body: &str) -> Option<(u16, String)> {
    http_request("POST", url, bearer, Some(body))
}

fn http_request(
    method: &str,
    url: &str,
    bearer: Option<&str>,
    body: Option<&str>,
) -> Option<(u16, String)> {
    use std::io::{Read, Write};
    use std::net::TcpStream;

    let rest = url.strip_prefix("http://")?;
    let (authority, path) = rest.split_once('/')?;
    let path = format!("/{path}");

    let mut stream = TcpStream::connect(authority).ok()?;
    stream
        .set_read_timeout(Some(Duration::from_secs(10)))
        .ok()?;
    let body = body.unwrap_or("");
    let mut request = format!(
        "{method} {path} HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\
         Content-Type: application/json\r\nContent-Length: {}\r\n",
        body.len()
    );
    if let Some(bearer) = bearer {
        request.push_str("Authorization: Bearer ");
        request.push_str(bearer);
        request.push_str("\r\n");
    }
    request.push_str("\r\n");
    request.push_str(body);
    stream.write_all(request.as_bytes()).ok()?;

    let mut raw = String::new();
    stream.read_to_string(&mut raw).ok()?;
    let status = raw.split_whitespace().nth(1)?.parse().ok()?;
    let body = raw
        .split_once("\r\n\r\n")
        .map_or("", |(_, b)| b)
        .to_string();
    Some((status, body))
}

fn token_from(body: &str) -> String {
    let value: serde_json::Value = serde_json::from_str(strip_chunking(body).as_str())
        .unwrap_or_else(|e| panic!("response should be JSON ({e}): {body}"));
    value["token"]
        .as_str()
        .unwrap_or_else(|| panic!("response should carry a token: {body}"))
        .to_string()
}

/// Responses come back chunked; for these small single-chunk bodies, dropping
/// the size lines is enough to recover the JSON.
fn strip_chunking(body: &str) -> String {
    if body.trim_start().starts_with('{') {
        return body.trim().to_string();
    }
    body.lines()
        .filter(|line| line.trim_start().starts_with('{'))
        .collect::<Vec<_>>()
        .join("")
}

/// The reproduction from issue #49: with no admin credential configured, a
/// `POST /api/management/tokens` carrying no `Authorization` header used to return `200`
/// and a usable `la_sk_…` token.
#[test]
fn unauthenticated_token_issuance_is_refused_by_default() {
    let router = Router::start(&[]);

    let (status, body) = ureq_post(
        &router.url("/api/management/tokens"),
        None,
        r#"{"ttl_hours":1,"label":"anyone"}"#,
    )
    .expect("router should answer");

    assert_eq!(status, 401, "unexpected body: {body}");
    assert!(
        !body.contains("la_sk_"),
        "no token may be handed to an unauthenticated caller: {body}"
    );

    let (status, body) =
        ureq_get(&router.url("/api/management/tokens"), None).expect("should answer");
    assert_eq!(status, 401, "unexpected body: {body}");
}

/// The router must stay usable when nothing is configured: it mints an admin
/// credential at startup and prints it once.
#[test]
fn bootstrap_admin_token_is_printed_and_opens_the_admin_surface() {
    let router = Router::start(&[]);
    let token = router
        .bootstrap_token
        .clone()
        .expect("the router should print a bootstrap admin token");
    assert!(token.starts_with("la_sk_"), "unexpected token: {token}");

    let (status, body) =
        ureq_get(&router.url("/api/management/tokens"), Some(&token)).expect("should answer");
    assert_eq!(status, 200, "unexpected body: {body}");
}

/// Authorisation is by scope, not by "any valid token".
#[test]
fn client_tokens_cannot_reach_the_admin_surface() {
    let router = Router::start(&[]);
    let admin = router.bootstrap_token.clone().expect("bootstrap token");

    let (status, body) = ureq_post(
        &router.url("/api/management/tokens"),
        Some(&admin),
        r#"{"ttl_hours":1,"label":"task"}"#,
    )
    .expect("should answer");
    assert_eq!(status, 200, "unexpected body: {body}");
    let client = token_from(&body);

    let (status, body) =
        ureq_get(&router.url("/api/management/tokens"), Some(&client)).expect("should answer");
    assert_eq!(
        status, 401,
        "a client token must not read the admin surface: {body}"
    );
}

/// Managed-client issuance is a distinct, admin-only surface: the server owns
/// the principal and signs the client binding rather than trusting fields on
/// ordinary/manual token issuance (#389).
#[test]
fn managed_client_token_issuance_validates_and_persists_the_signed_binding() {
    let router = Router::start(&[]);
    let admin = router.bootstrap_token.clone().expect("bootstrap token");

    let (status, _) = ureq_post(
        &router.url("/api/management/tokens/client"),
        None,
        r#"{"client_kind":"codex"}"#,
    )
    .expect("should answer");
    assert_eq!(status, 401);

    for (body, expected) in [
        (r#"{"client_kind":"unknown"}"#, 400),
        (r#"{"client_kind":"cursor"}"#, 400),
        (r#"{"client_kind":"codex","ttl_hours":0}"#, 400),
    ] {
        let (status, response) = ureq_post(
            &router.url("/api/management/tokens/client"),
            Some(&admin),
            body,
        )
        .expect("should answer");
        assert_eq!(status, expected, "unexpected body: {response}");
    }

    let (status, defaulted) = ureq_post(
        &router.url("/api/management/tokens/client"),
        Some(&admin),
        r#"{"client_kind":"codex"}"#,
    )
    .expect("should answer");
    assert_eq!(status, 200, "unexpected body: {defaulted}");
    assert!(token_from(&defaulted).starts_with("la_sk_"));

    let (status, explicit) = ureq_post(
        &router.url("/api/management/tokens/client"),
        Some(&admin),
        r#"{"client_kind":"claude","label":"managed-claude","ttl_hours":2,"max_requests":7,"sliding_expiry":true}"#,
    )
    .expect("should answer");
    assert_eq!(status, 200, "unexpected body: {explicit}");
    let explicit: serde_json::Value =
        serde_json::from_str(&strip_chunking(&explicit)).expect("client token JSON");
    assert_eq!(explicit["client_kind"], "claude");
    assert_eq!(explicit["principal_id"], "primary");
    assert_eq!(explicit["label"], "managed-claude");

    let (status, listed) =
        ureq_get(&router.url("/api/management/tokens"), Some(&admin)).expect("should answer");
    assert_eq!(status, 200, "unexpected body: {listed}");
    let listed: serde_json::Value =
        serde_json::from_str(&strip_chunking(&listed)).expect("token list JSON");
    let managed = listed["data"]
        .as_array()
        .expect("token records")
        .iter()
        .find(|record| record["label"] == "managed-claude")
        .expect("managed token record");
    assert_eq!(managed["client_kind"], "claude");
    assert_eq!(managed["principal_id"], "primary");
    assert_eq!(managed["account"], "primary");
    assert_eq!(managed["max_requests"], 7);
}

/// An admin-scoped token minted over HTTP works, and can rotate itself.
#[test]
fn admin_scoped_tokens_are_issuable_and_rotatable_over_http() {
    let router = Router::start(&[]);
    let admin = router.bootstrap_token.clone().expect("bootstrap token");

    let (status, body) = ureq_post(
        &router.url("/api/management/tokens"),
        Some(&admin),
        r#"{"ttl_hours":1,"label":"ops","scope":"admin"}"#,
    )
    .expect("should answer");
    assert_eq!(status, 200, "unexpected body: {body}");
    let scoped = token_from(&body);

    let (status, body) =
        ureq_get(&router.url("/api/management/tokens"), Some(&scoped)).expect("should answer");
    assert_eq!(status, 200, "unexpected body: {body}");

    let (status, body) = ureq_post(
        &router.url("/api/management/tokens/rotate"),
        Some(&scoped),
        "{}",
    )
    .expect("should answer");
    assert_eq!(status, 200, "unexpected body: {body}");
    let replacement = token_from(&body);
    assert_ne!(replacement, scoped);

    // The rotated-away credential is revoked; its replacement works.
    let (status, _) =
        ureq_get(&router.url("/api/management/tokens"), Some(&scoped)).expect("should answer");
    assert_eq!(status, 401, "the rotated-away token must stop working");
    let (status, _) =
        ureq_get(&router.url("/api/management/tokens"), Some(&replacement)).expect("should answer");
    assert_eq!(status, 200);
}

/// An unknown scope is a client error, not a silently-ignored field.
#[test]
fn an_unknown_scope_is_rejected() {
    let router = Router::start(&[]);
    let admin = router.bootstrap_token.clone().expect("bootstrap token");

    let (status, body) = ureq_post(
        &router.url("/api/management/tokens"),
        Some(&admin),
        r#"{"ttl_hours":1,"label":"x","scope":"root"}"#,
    )
    .expect("should answer");
    assert_eq!(status, 400, "unexpected body: {body}");
}

/// The flat `TOKEN_ADMIN_KEY` keeps working unchanged as a bootstrap
/// credential, and suppresses the generated one.
#[test]
fn the_flat_admin_key_still_authorises() {
    let router = Router::start(&[("TOKEN_ADMIN_KEY", "s3cret-bootstrap-key")]);
    assert!(
        router.bootstrap_token.is_none(),
        "a configured admin key must not trigger token generation"
    );

    let (status, _) = ureq_get(&router.url("/api/management/tokens"), None).expect("should answer");
    assert_eq!(status, 401);

    let (status, _) =
        ureq_get(&router.url("/api/management/tokens"), Some("wrong-key")).expect("should answer");
    assert_eq!(status, 401);

    let (status, body) = ureq_get(
        &router.url("/api/management/tokens"),
        Some("s3cret-bootstrap-key"),
    )
    .expect("should answer");
    assert_eq!(status, 200, "unexpected body: {body}");
}

/// The historical open behaviour is still reachable, but only on purpose.
#[test]
fn allow_anonymous_admin_restores_the_open_surface() {
    let router = Router::start(&[("ALLOW_ANONYMOUS_ADMIN", "1")]);

    let (status, body) = ureq_post(
        &router.url("/api/management/tokens"),
        None,
        r#"{"ttl_hours":1,"label":"anyone"}"#,
    )
    .expect("should answer");
    assert_eq!(status, 200, "unexpected body: {body}");
    assert!(token_from(&body).starts_with("la_sk_"));
}

/// Guards the assumption that the binary under test is the one built from this
/// working tree (a stale `PATH` binary would make every assertion above lie).
#[test]
fn the_binary_under_test_comes_from_this_workspace() {
    let bin = PathBuf::from(env!("CARGO_BIN_EXE_link-assistant-router"));
    assert!(bin.exists(), "{} should exist", bin.display());
    assert!(bin.starts_with(env!("CARGO_MANIFEST_DIR")));
}