railwayapp 5.31.1

Interact with Railway via CLI
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
//! Simulation harness for the CLI's OAuth refresh behaviour.
//!
//! These tests exist to answer one question with evidence rather than code
//! reading: when a user's refresh token is dead server-side, or when the token
//! endpoint is briefly 5xx, what actually happens to the credentials on disk
//! and to the user-facing outcome?
//!
//! Every experiment runs the REAL HTTP layer ([`oauth::attempt_refresh`]) and
//! the REAL config read/modify/write cycle ([`Configs`]) against a local
//! scripted token endpoint. `legacy_policy` reproduces production's current
//! behaviour; `refresh_with_policy` is the proposed replacement. Because both
//! share the same HTTP and config code, any difference is attributable to the
//! policy alone.

use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use crate::client::{RefreshOutcome, refresh_with_policy};
use crate::config::Configs;
use crate::oauth;

/// A scripted local endpoint. Serves `responses` in order, repeating the last
/// one once exhausted, and records every request it receives so tests can assert
/// both how many arrived and what headers they carried.
struct MockEndpoint {
    base_url: String,
    requests: Arc<std::sync::Mutex<Vec<String>>>,
}

impl MockEndpoint {
    fn spawn(responses: Vec<(u16, String)>) -> Self {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let requests = Arc::new(std::sync::Mutex::new(Vec::new()));
        let requests_for_thread = Arc::clone(&requests);

        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { break };

                // Drain headers and any body so the client never sees a broken
                // pipe on the next request.
                let mut buf = Vec::new();
                let mut tmp = [0u8; 1024];
                let mut content_length = 0usize;
                loop {
                    let Ok(read) = stream.read(&mut tmp) else {
                        break;
                    };
                    if read == 0 {
                        break;
                    }
                    buf.extend_from_slice(&tmp[..read]);
                    if let Some(pos) = find_headers_end(&buf) {
                        let headers = String::from_utf8_lossy(&buf[..pos]).to_lowercase();
                        for line in headers.lines() {
                            if let Some(v) = line.strip_prefix("content-length:") {
                                content_length = v.trim().parse().unwrap_or(0);
                            }
                        }
                        if buf.len() >= pos + 4 + content_length {
                            break;
                        }
                    }
                }

                let mut seen = requests_for_thread.lock().unwrap();
                let idx = seen.len().min(responses.len().saturating_sub(1));
                seen.push(String::from_utf8_lossy(&buf).to_string());
                drop(seen);

                let (status, body) = &responses[idx];
                let reason = match status {
                    200 => "OK",
                    400 => "Bad Request",
                    500 => "Internal Server Error",
                    503 => "Service Unavailable",
                    _ => "Unknown",
                };
                let resp = format!(
                    "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len()
                );
                let _ = stream.write_all(resp.as_bytes());
                let _ = stream.flush();
            }
        });

        Self {
            base_url: format!("http://127.0.0.1:{port}/oauth"),
            requests,
        }
    }

    fn hits(&self) -> usize {
        self.requests.lock().unwrap().len()
    }

    /// The `authorization` header of each request, in arrival order.
    fn auth_headers(&self) -> Vec<String> {
        self.requests
            .lock()
            .unwrap()
            .iter()
            .map(|req| {
                req.lines()
                    .find(|l| l.to_ascii_lowercase().starts_with("authorization:"))
                    .map(|l| l["authorization:".len()..].trim().to_string())
                    .unwrap_or_else(|| "(none)".to_string())
            })
            .collect()
    }
}

fn find_headers_end(buf: &[u8]) -> Option<usize> {
    buf.windows(4).position(|w| w == b"\r\n\r\n")
}

fn dead_grant() -> (u16, String) {
    (
        400,
        r#"{"error":"invalid_grant","error_description":"grant request is invalid"}"#.to_string(),
    )
}
fn server_error() -> (u16, String) {
    (500, r#"{"error":"server_error"}"#.to_string())
}
fn fresh_tokens() -> (u16, String) {
    (
        200,
        r#"{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600}"#
            .to_string(),
    )
}
fn ok_empty() -> (u16, String) {
    (200, r#"{"data":{}}"#.to_string())
}

/// A temp config file seeded with an expired access token and a refresh token,
/// i.e. exactly the state a CLI process is in when it starts up an hour after
/// the last command.
struct Fixture {
    path: PathBuf,
    _dir: tempfile::TempDir,
}

impl Fixture {
    fn new() -> Self {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        let mut configs = Configs::for_test(path.clone());
        // expires_in of 1s, then we treat it as already past: save_oauth_tokens
        // requires a positive expires_in, so age it directly afterwards.
        configs
            .save_oauth_tokens("stale-access", Some("the-refresh-token"), 1)
            .unwrap();
        configs.root_config.user.token_expires_at = Some(0); // long expired
        configs.write().unwrap();
        Self { path, _dir: dir }
    }

    /// A freshly-loaded Configs, standing in for a brand-new CLI process.
    fn load(&self) -> Configs {
        let mut configs = Configs::for_test(self.path.clone());
        configs.reload().unwrap();
        configs
    }
}

/// Reproduction of production's CURRENT refresh policy (cli 5.30.1):
/// one attempt, no 400-vs-5xx distinction, and credentials are never cleared.
/// Mirrors what `client::refresh_tokens` did at cli 5.30.1.
async fn legacy_policy(configs: &mut Configs, base_url: &str) -> Result<(), String> {
    let refresh_token = match configs.get_refresh_token() {
        Some(t) => t.to_owned(),
        None => return Err("No refresh token available".to_string()),
    };
    let client = reqwest::Client::new();
    match oauth::attempt_refresh(&client, base_url, &refresh_token).await {
        Ok(resp) => {
            configs
                .save_oauth_tokens(
                    &resp.access_token,
                    resp.refresh_token.as_deref(),
                    resp.expires_in,
                )
                .unwrap();
            Ok(())
        }
        // Production collapses every failure into one error and leaves the
        // stored credentials exactly as they were.
        Err(f) => Err(match f {
            oauth::RefreshFailure::Terminal(e) | oauth::RefreshFailure::Transient(e) => {
                e.to_string()
            }
        }),
    }
}

const INVOCATIONS: usize = 20;

#[tokio::test]
async fn legacy_dead_grant_retries_forever_and_keeps_dead_credentials() {
    let server = MockEndpoint::spawn(vec![dead_grant()]);
    let fixture = Fixture::new();

    for _ in 0..INVOCATIONS {
        let mut configs = fixture.load();
        let result = legacy_policy(&mut configs, &server.base_url).await;
        assert!(result.is_err(), "dead grant should fail");
    }

    // Every single invocation hit the token endpoint with the same dead token.
    assert_eq!(
        server.hits(),
        INVOCATIONS,
        "legacy policy re-presents a known-dead refresh token on every invocation"
    );

    // And the dead credentials are still sitting on disk, so this never ends.
    let configs = fixture.load();
    assert!(
        configs.has_oauth_token(),
        "legacy policy leaves the dead access token on disk"
    );
    assert_eq!(
        configs.get_refresh_token(),
        Some("the-refresh-token"),
        "legacy policy leaves the dead refresh token on disk"
    );
}

#[tokio::test]
async fn fixed_dead_grant_clears_credentials_and_stops_after_one_attempt() {
    let server = MockEndpoint::spawn(vec![dead_grant()]);
    let fixture = Fixture::new();

    let mut outcomes = Vec::new();
    for _ in 0..INVOCATIONS {
        let mut configs = fixture.load();
        outcomes.push(refresh_with_policy(&mut configs, &server.base_url, Duration::ZERO).await);
    }

    // The first invocation learns the grant is dead; the rest have nothing to
    // present, so the token endpoint is never touched again.
    assert_eq!(
        server.hits(),
        1,
        "fixed policy must present a dead refresh token exactly once, got {} hits",
        server.hits()
    );
    assert!(matches!(outcomes[0], RefreshOutcome::SessionExpired(_)));
    assert!(
        outcomes[1..]
            .iter()
            .all(|o| matches!(o, RefreshOutcome::NoRefreshToken)),
        "after clearing, later invocations have no token to retry"
    );

    let configs = fixture.load();
    assert!(!configs.has_oauth_token());
    assert_eq!(configs.get_refresh_token(), None);
}

#[tokio::test]
async fn legacy_transient_5xx_is_indistinguishable_from_a_dead_grant() {
    let dead = MockEndpoint::spawn(vec![dead_grant()]);
    let flaky = MockEndpoint::spawn(vec![server_error()]);
    let f1 = Fixture::new();
    let f2 = Fixture::new();

    let dead_err = legacy_policy(&mut f1.load(), &dead.base_url)
        .await
        .unwrap_err();
    let flaky_err = legacy_policy(&mut f2.load(), &flaky.base_url)
        .await
        .unwrap_err();

    // Both surface as the same RailwayError variant, whose message tells the
    // user to run `railway login` — even though in the 5xx case the stored
    // refresh token is perfectly good.
    let dead_rendered = crate::errors::RailwayError::OAuthRefreshFailed(dead_err).to_string();
    let flaky_rendered = crate::errors::RailwayError::OAuthRefreshFailed(flaky_err).to_string();
    assert!(dead_rendered.contains("Couldn't refresh") || dead_rendered.contains("railway login"));
    assert!(
        flaky_rendered.contains("Couldn't refresh") || flaky_rendered.contains("railway login")
    );

    // And critically: exactly one attempt. No retry for a transient failure.
    assert_eq!(
        flaky.hits(),
        1,
        "legacy policy does not retry a transient 5xx"
    );
}

#[tokio::test]
async fn fixed_transient_5xx_retries_and_preserves_credentials() {
    let server = MockEndpoint::spawn(vec![server_error()]);
    let fixture = Fixture::new();

    let mut configs = fixture.load();
    let outcome = refresh_with_policy(&mut configs, &server.base_url, Duration::ZERO).await;

    assert!(
        matches!(outcome, RefreshOutcome::Transient(_)),
        "a 5xx must be transient, got {outcome:?}"
    );
    assert_eq!(
        server.hits(),
        oauth::REFRESH_MAX_ATTEMPTS as usize,
        "fixed policy retries transient failures"
    );

    // The whole point: a backboard blip must not cost the user their session.
    let reloaded = fixture.load();
    assert_eq!(reloaded.get_refresh_token(), Some("the-refresh-token"));
    assert!(reloaded.has_oauth_token());
}

#[tokio::test]
async fn fixed_policy_recovers_when_the_token_endpoint_comes_back() {
    // Mirrors the 2026-07-30/31 backboard DB incidents: the token endpoint
    // 5xx'd for a window, then recovered.
    let server = MockEndpoint::spawn(vec![server_error(), server_error(), fresh_tokens()]);
    let fixture = Fixture::new();

    let mut configs = fixture.load();
    let outcome = refresh_with_policy(&mut configs, &server.base_url, Duration::ZERO).await;

    assert!(
        matches!(outcome, RefreshOutcome::Refreshed),
        "the user should never notice a brief outage, got {outcome:?}"
    );
    let reloaded = fixture.load();
    assert_eq!(reloaded.get_refresh_token(), Some("new-refresh"));
    assert!(
        !reloaded.is_token_expired(),
        "fresh token must not be expired"
    );
}

/// The property that stops a backboard misconfiguration from becoming a mass
/// logout: only `invalid_grant` may clear credentials. `invalid_client` and
/// friends describe the client registration or the request, not the user's
/// grant, and the CLI ships one hardcoded `client_id` for everybody.
#[tokio::test]
async fn only_invalid_grant_clears_credentials() {
    for code in [
        "invalid_client",
        "unauthorized_client",
        "invalid_scope",
        "invalid_request",
        "unsupported_grant_type",
        "server_error",
        "temporarily_unavailable",
        "slow_down",
        "unknown",
    ] {
        let body = format!(r#"{{"error":"{code}","error_description":"boom"}}"#);
        let server = MockEndpoint::spawn(vec![(400, body)]);
        let fixture = Fixture::new();
        let mut configs = fixture.load();

        let outcome = refresh_with_policy(&mut configs, &server.base_url, Duration::ZERO).await;

        assert!(
            matches!(outcome, RefreshOutcome::Transient(_)),
            "{code} must not be treated as a permanently dead credential, got {outcome:?}"
        );
        assert_eq!(
            fixture.load().get_refresh_token(),
            Some("the-refresh-token"),
            "{code} must leave the refresh token on disk"
        );
    }
}

#[tokio::test]
async fn fixed_policy_treats_unparseable_4xx_as_transient() {
    // A WAF block or proxy error page must not be mistaken for a dead grant —
    // discarding a working refresh token is the expensive mistake.
    let server = MockEndpoint::spawn(vec![(400, "<html>blocked by proxy</html>".to_string())]);
    let fixture = Fixture::new();

    let mut configs = fixture.load();
    let outcome = refresh_with_policy(&mut configs, &server.base_url, Duration::ZERO).await;

    assert!(
        matches!(outcome, RefreshOutcome::Transient(_)),
        "unparseable 4xx must not clear credentials, got {outcome:?}"
    );
    assert_eq!(
        fixture.load().get_refresh_token(),
        Some("the-refresh-token")
    );
}

/// Durability of the credential clear against a concurrent stale writer.
///
/// A process can hold a `Configs` for hours (`railway mcp` holds one for a whole
/// editor session) and then write it for an unrelated reason such as linking a
/// project. Serialising its whole snapshot used to put the credentials it loaded
/// at startup back on disk, undoing another process's refresh or clear and
/// restarting the retry loop. `write` now takes the credential fields from disk,
/// so only the auth path can move them.
#[tokio::test]
async fn stale_writer_cannot_resurrect_cleared_credentials() {
    let server = MockEndpoint::spawn(vec![dead_grant()]);
    let fixture = Fixture::new();

    // Process B starts and loads the config while the credentials still exist.
    let mut stale_process = fixture.load();
    assert!(stale_process.has_oauth_token());

    // Process A discovers the grant is dead and clears.
    let mut clearing_process = fixture.load();
    let outcome =
        refresh_with_policy(&mut clearing_process, &server.base_url, Duration::ZERO).await;
    assert!(matches!(outcome, RefreshOutcome::SessionExpired(_)));
    assert_eq!(fixture.load().get_refresh_token(), None, "clear persisted");

    // Process B now writes for an unrelated reason, using its stale snapshot.
    stale_process.root_config.user.id = Some("some-user".to_string());
    stale_process.write().unwrap();

    let after = fixture.load();
    assert_eq!(
        after.get_refresh_token(),
        None,
        "the stale writer must not resurrect the dead refresh token"
    );
    assert!(!after.has_oauth_token());
    // ...while its own, non-credential change still lands.
    assert_eq!(after.root_config.user.id.as_deref(), Some("some-user"));
}

/// The mirror case: a stale writer must not undo a successful refresh either.
#[tokio::test]
async fn stale_writer_cannot_undo_a_refresh() {
    let server = MockEndpoint::spawn(vec![fresh_tokens()]);
    let fixture = Fixture::new();

    let mut stale_process = fixture.load();
    let mut refreshing = fixture.load();
    assert!(matches!(
        refresh_with_policy(&mut refreshing, &server.base_url, Duration::ZERO).await,
        RefreshOutcome::Refreshed
    ));

    stale_process.root_config.user.id = Some("some-user".to_string());
    stale_process.write().unwrap();

    let after = fixture.load();
    assert_eq!(
        after.get_refresh_token(),
        Some("new-refresh"),
        "the refreshed credentials must survive an unrelated concurrent write"
    );
    assert_eq!(
        after.get_railway_auth_token().as_deref(),
        Some("new-access")
    );
}

/// `railway logout` must still be able to erase credentials. Ordinary writes
/// adopt whatever is on disk, so logout has to go through the credential-owning
/// write — mirrors `commands::logout`.
#[tokio::test]
async fn logout_clears_credentials() {
    let fixture = Fixture::new();
    let mut configs = fixture.load();
    assert!(configs.has_oauth_token());

    configs.reset().unwrap();
    configs.write_credentials().unwrap();

    let after = fixture.load();
    assert!(
        !after.has_oauth_token(),
        "logout must erase the access token"
    );
    assert_eq!(after.get_refresh_token(), None);
}

/// The other half of that invariant: a plain `write` must NOT be able to erase
/// credentials, which is what stops a stale in-memory snapshot from clobbering
/// them.
#[tokio::test]
async fn plain_write_cannot_erase_credentials() {
    let fixture = Fixture::new();
    let mut configs = fixture.load();

    configs.reset().unwrap();
    configs.write().unwrap();

    let after = fixture.load();
    assert_eq!(
        after.get_refresh_token(),
        Some("the-refresh-token"),
        "a non-credential write must leave the stored credentials alone"
    );
}

/// The local `railway mcp` defect, isolated: `GQLClient::new_authorized` bakes
/// the bearer into the client's default headers, so a client built at process
/// start keeps sending the startup token no matter what happens on disk.
#[tokio::test]
async fn baked_in_bearer_ignores_new_credentials_on_disk() {
    let backboard = MockEndpoint::spawn(vec![ok_empty()]);
    let fixture = Fixture::new();

    // Startup: build the client once, exactly as serve_stdio does.
    let startup_configs = fixture.load();
    let frozen = crate::client::GQLClient::new_authorized(&startup_configs).unwrap();

    // A `railway login` in another terminal replaces the credentials on disk.
    let mut relogin = fixture.load();
    relogin
        .save_oauth_tokens("brand-new-access", Some("brand-new-refresh"), 3600)
        .unwrap();
    assert_eq!(
        fixture.load().get_railway_auth_token().as_deref(),
        Some("brand-new-access")
    );

    // The frozen client still sends the startup token.
    let _ = frozen.post(&backboard.base_url).json(&()).send().await;
    assert_eq!(
        backboard.auth_headers(),
        vec!["Bearer stale-access".to_string()],
        "EXPECTED DEFECT: the client built at startup keeps using the startup token"
    );

    // Rebuilding from the current on-disk config is what picks up the new token.
    let rebuilt = crate::client::GQLClient::new_authorized(&fixture.load()).unwrap();
    let _ = rebuilt.post(&backboard.base_url).json(&()).send().await;
    assert_eq!(
        backboard.auth_headers()[1],
        "Bearer brand-new-access",
        "a per-request client adopts the new credentials"
    );
}

/// The mid-session expiry path: an expired access token must trigger a real
/// refresh and the resulting client must carry the NEW bearer.
#[tokio::test]
async fn expired_token_refreshes_and_new_bearer_reaches_the_wire() {
    let token_endpoint = MockEndpoint::spawn(vec![fresh_tokens()]);
    let backboard = MockEndpoint::spawn(vec![ok_empty()]);
    let fixture = Fixture::new();

    let mut configs = fixture.load();
    assert!(configs.is_token_expired(), "fixture starts expired");

    let outcome = refresh_with_policy(&mut configs, &token_endpoint.base_url, Duration::ZERO).await;
    assert!(matches!(outcome, RefreshOutcome::Refreshed));

    let client = crate::client::GQLClient::new_authorized(&fixture.load()).unwrap();
    let _ = client.post(&backboard.base_url).json(&()).send().await;

    assert_eq!(
        backboard.auth_headers(),
        vec!["Bearer new-access".to_string()],
        "the refreshed token must be the one used for the request"
    );
}

/// Load guard for the per-tool-call sync: the expiry predicate that gates the
/// network call must report a freshly-saved token as valid, so the steady-state
/// path does no refresh I/O at all.
#[tokio::test]
async fn a_freshly_saved_token_is_not_considered_expired() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.json");
    let mut configs = Configs::for_test(path.clone());
    configs
        .save_oauth_tokens("good-access", Some("good-refresh"), 3600)
        .unwrap();

    let mut reloaded = Configs::for_test(path);
    reloaded.reload().unwrap();
    assert!(
        !reloaded.is_token_expired(),
        "a token minted seconds ago must not be treated as expired, or every \
         tool call would refresh"
    );

    // ...and the 60s safety buffer still classifies a nearly-dead token as expired.
    reloaded.root_config.user.token_expires_at = Some(chrono::Utc::now().timestamp() + 30);
    assert!(reloaded.is_token_expired());
}

/// A dead grant inside a long-lived MCP session must not become a retry storm:
/// credentials are cleared once, and later tool calls have nothing to present.
#[tokio::test]
async fn dead_grant_in_a_long_session_refreshes_once_not_per_tool_call() {
    let token_endpoint = MockEndpoint::spawn(vec![dead_grant()]);
    let fixture = Fixture::new();

    for _ in 0..INVOCATIONS {
        let mut configs = fixture.load();
        if configs.get_refresh_token().is_some() {
            refresh_with_policy(&mut configs, &token_endpoint.base_url, Duration::ZERO).await;
        }
    }

    assert_eq!(
        token_endpoint.hits(),
        1,
        "a dead grant must be discovered once per session, not once per tool call"
    );
}