stack-auth 0.34.1-alpha.2

Authentication library for CipherStash services
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
use super::*;
use cts_common::Region;
use mocktail::prelude::*;
use tempfile::TempDir;

fn device_code_json() -> serde_json::Value {
    serde_json::json!({
        "device_code": "test_device_code",
        "user_code": "ABCD-EFGH",
        "verification_uri": "http://example.com/activate",
        "verification_uri_complete": "http://example.com/activate?user_code=ABCD-EFGH",
        "expires_in": 900
    })
}

/// Build a valid JWT access token containing a workspace claim.
fn test_access_token() -> String {
    use jsonwebtoken::{encode, EncodingKey, Header};
    use std::time::{SystemTime, UNIX_EPOCH};

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let claims = serde_json::json!({
        "iss": "https://cts.example.com/",
        "sub": "CS|test-user",
        "aud": "test-audience",
        "iat": now,
        "exp": now + 3600,
        "workspace": "ZVATKW3VHMFG27DY",
        "scope": "",
    });

    encode(
        &Header::default(),
        &claims,
        &EncodingKey::from_secret(b"test-secret"),
    )
    .unwrap()
}

fn token_json() -> serde_json::Value {
    serde_json::json!({
        "access_token": test_access_token(),
        "token_type": "Bearer",
        "expires_in": 3600
    })
}

fn error_json(error: &str) -> serde_json::Value {
    serde_json::json!({
        "error": error,
        "error_description": format!("{error} occurred")
    })
}

fn mock_code_endpoint(mocks: &mut MockSet) {
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/code");
        then.json(device_code_json());
    });
}

async fn start_server(mocks: MockSet) -> MockServer {
    let server = MockServer::new_http("stack-auth-test").with_mocks(mocks);
    server.start().await.unwrap();
    server
}

fn strategy_for(server: &MockServer, dir: &TempDir) -> DeviceCodeStrategy {
    DeviceCodeStrategy::builder(Region::aws("ap-southeast-2").unwrap(), "cli")
        .base_url(server.url(""))
        .profile_dir(dir.path())
        .build()
        .unwrap()
}

// ---- begin() tests ----

#[tokio::test]
async fn test_begin_returns_pending_device_code() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    let server = start_server(mocks).await;

    let pending = strategy_for(&server, &dir).begin().await.unwrap();

    assert_eq!(pending.user_code(), "ABCD-EFGH");
    assert_eq!(pending.verification_uri(), "http://example.com/activate");
    assert_eq!(
        pending.verification_uri_complete(),
        "http://example.com/activate?user_code=ABCD-EFGH"
    );
    assert_eq!(pending.expires_in(), 900);
}

#[tokio::test]
async fn test_begin_invalid_client() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/code");
        then.bad_request().json(error_json("invalid_client"));
    });
    let server = start_server(mocks).await;

    let err = strategy_for(&server, &dir).begin().await.unwrap_err();

    assert!(matches!(err, AuthError::InvalidClient));
}

#[tokio::test]
async fn test_begin_server_error() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/code");
        then.bad_request().json(error_json("server_error"));
    });
    let server = start_server(mocks).await;

    let err = strategy_for(&server, &dir).begin().await.unwrap_err();

    assert!(matches!(&err, AuthError::Server(desc) if desc == "server_error occurred"));
}

// ---- poll_for_token() tests ----

/// Helper: calls begin() against a server that already has the code mock,
/// then returns the PendingDeviceCode ready for polling.
async fn begin_pending(server: &MockServer, dir: &TempDir) -> PendingDeviceCode {
    strategy_for(server, dir).begin().await.unwrap()
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_success() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.json(token_json());
    });
    let server = start_server(mocks).await;

    let token = begin_pending(&server, &dir)
        .await
        .poll_for_token()
        .await
        .unwrap();

    assert_eq!(token.token_type(), "Bearer");
    assert!(!token.is_expired());
    assert!((3598..=3600).contains(&token.expires_in()));
    assert_eq!(
        token.workspace_id().unwrap().as_str(),
        "ZVATKW3VHMFG27DY",
        "workspace ID should be extracted from the JWT"
    );

    // Verify the token was persisted to the workspace directory
    let store = ProfileStore::new(dir.path());
    assert_eq!(
        store.current_workspace().unwrap(),
        "ZVATKW3VHMFG27DY",
        "current workspace should be set after poll_for_token"
    );
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_access_denied() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("access_denied"));
    });
    let server = start_server(mocks).await;

    let err = begin_pending(&server, &dir)
        .await
        .poll_for_token()
        .await
        .unwrap_err();

    assert!(matches!(err, AuthError::AccessDenied));
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_expired_token() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("expired_token"));
    });
    let server = start_server(mocks).await;

    let err = begin_pending(&server, &dir)
        .await
        .poll_for_token()
        .await
        .unwrap_err();

    assert!(matches!(err, AuthError::TokenExpired));
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_invalid_grant() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("invalid_grant"));
    });
    let server = start_server(mocks).await;

    let err = begin_pending(&server, &dir)
        .await
        .poll_for_token()
        .await
        .unwrap_err();

    assert!(matches!(err, AuthError::InvalidGrant));
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_invalid_client() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("invalid_client"));
    });
    let server = start_server(mocks).await;

    let err = begin_pending(&server, &dir)
        .await
        .poll_for_token()
        .await
        .unwrap_err();

    assert!(matches!(err, AuthError::InvalidClient));
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_unknown_error() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("something_unexpected"));
    });
    let server = start_server(mocks).await;

    let err = begin_pending(&server, &dir)
        .await
        .poll_for_token()
        .await
        .unwrap_err();

    assert!(matches!(&err, AuthError::Server(desc) if desc == "something_unexpected occurred"));
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_authorization_pending_then_success() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("authorization_pending"));
    });
    let server = start_server(mocks).await;
    let pending = begin_pending(&server, &dir).await;

    // Use tokio::join! so the swap future can borrow server.mocks() directly
    // (the shared RwLock) rather than cloning the MockSet.
    // First poll at T=5s returns "authorization_pending".
    // At T=6s the mock is swapped. Second poll at T=10s returns success.
    let (result, _) = tokio::join!(pending.poll_for_token(), async {
        tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
        server.mocks().clear();
        server.mocks().mock(|when, then| {
            when.post().path("/oauth/device/token");
            then.json(token_json());
        });
    });

    let token = result.unwrap();
    assert_eq!(token.token_type(), "Bearer");
    assert!(
        token.workspace_id().is_ok(),
        "token should contain a valid workspace claim"
    );
}

#[tokio::test(start_paused = true)]
async fn test_poll_for_token_slow_down_then_success() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("slow_down"));
    });
    let server = start_server(mocks).await;
    let pending = begin_pending(&server, &dir).await;

    // First poll returns "slow_down", interval increases to 10s.
    // Swap the mock to return success before the second poll.
    let (result, _) = tokio::join!(pending.poll_for_token(), async {
        tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
        server.mocks().clear();
        server.mocks().mock(|when, then| {
            when.post().path("/oauth/device/token");
            then.json(token_json());
        });
    });

    let token = result.unwrap();
    assert_eq!(token.token_type(), "Bearer");
    assert!(
        token.workspace_id().is_ok(),
        "token should contain a valid workspace claim"
    );
}

/// Proves that `slow_down` increases the poll interval: with a short
/// `expires_in`, the increased interval pushes the next poll past the
/// deadline, causing a `TokenExpired` error.
#[tokio::test(start_paused = true)]
async fn test_poll_for_token_slow_down_increases_interval() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    // expires_in = 12: without slow_down, second poll at T=10 is within
    // the deadline. With slow_down, interval becomes 10s, so second poll
    // at T=15 exceeds the 12s deadline.
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/code");
        then.json(serde_json::json!({
            "device_code": "test_device_code",
            "user_code": "ABCD-EFGH",
            "verification_uri": "http://example.com/activate",
            "verification_uri_complete": "http://example.com/activate?user_code=ABCD-EFGH",
            "expires_in": 12
        }));
    });
    mocks.mock(|when, then| {
        when.post().path("/oauth/device/token");
        then.bad_request().json(error_json("slow_down"));
    });
    let server = start_server(mocks).await;
    let pending = begin_pending(&server, &dir).await;

    let err = pending.poll_for_token().await.unwrap_err();

    assert!(matches!(err, AuthError::TokenExpired));
}

// ---- ensure_trailing_slash / URL join tests ----

#[test]
fn test_ensure_trailing_slash_adds_slash() {
    let url = Url::parse("http://localhost:3001").unwrap();
    let result = ensure_trailing_slash(url);
    assert_eq!(result.as_str(), "http://localhost:3001/");
}

#[test]
fn test_ensure_trailing_slash_preserves_existing() {
    let url = Url::parse("http://localhost:3001/").unwrap();
    let result = ensure_trailing_slash(url);
    assert_eq!(result.as_str(), "http://localhost:3001/");
}

#[test]
fn test_ensure_trailing_slash_with_path() {
    let url = Url::parse("http://localhost:3001/api/v1").unwrap();
    let result = ensure_trailing_slash(url);
    assert_eq!(result.as_str(), "http://localhost:3001/api/v1/");
}

#[test]
fn test_relative_join_preserves_base_path() {
    let base = ensure_trailing_slash(Url::parse("http://localhost:3001/api/v1").unwrap());
    let joined = base.join("oauth/device/code").unwrap();
    assert_eq!(
        joined.as_str(),
        "http://localhost:3001/api/v1/oauth/device/code"
    );
}

#[test]
fn test_relative_join_on_root_url() {
    let base = ensure_trailing_slash(Url::parse("http://localhost:3001").unwrap());
    let joined = base.join("oauth/device/code").unwrap();
    assert_eq!(joined.as_str(), "http://localhost:3001/oauth/device/code");
}

#[tokio::test]
async fn test_pending_device_code_debug_does_not_leak() {
    let dir = TempDir::new().unwrap();
    let mut mocks = MockSet::new();
    mock_code_endpoint(&mut mocks);
    let server = start_server(mocks).await;

    let pending = begin_pending(&server, &dir).await;
    let debug = format!("{:?}", pending);

    assert!(
        !debug.contains("test_device_code"),
        "PendingDeviceCode Debug should not contain the device code, got: {debug}"
    );
}