pywatt_sdk 0.5.3

Standardized SDK for building PyWatt modules in Rust
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
use crate::secret_client::logging::{clear_redaction_registry, is_registered_for_redaction};
use axum::{
    Router,
    body::Body,
    extract::Extension,
    http::{Request, StatusCode, header::AUTHORIZATION},
    routing::get,
};
use jsonwebtoken::{Algorithm, EncodingKey, Header, Validation, encode};
use serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use serde_json::json; // Used in json! macro
use tower::ServiceExt; // for `.oneshot()` // Import the global registry and test helper functions

use super::middleware::JwtAuthenticationLayer;
use super::body_to_string;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct TestClaims {
    sub: String,
    role: Option<String>,
}

#[tokio::test]
async fn missing_header_is_unauthorized() {
    // Test with a type parameter for strong typing
    let layer = JwtAuthenticationLayer::<TestClaims>::new("secret".to_string());
    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(layer);

    let response = app
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn invalid_token_is_unauthorized() {
    // Test with dynamic JSON typing
    let layer = JwtAuthenticationLayer::<serde_json::Value>::new("secret".to_string());
    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(layer);

    let response = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header(AUTHORIZATION, "Bearer bad.token.here")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn valid_token_passes_and_claims_are_inserted() {
    let secret = "mysecret";
    // Test with strongly typed claims
    let layer = JwtAuthenticationLayer::<TestClaims>::new(secret.to_string());
    let app = Router::new()
        .route(
            "/claims",
            get(|Extension(claims): Extension<TestClaims>| async move { claims.sub }),
        )
        .layer(layer);

    // Create a token with test claims (include exp so default validation passes)
    let claims = serde_json::json!({
        "sub": "test-user",
        "role": "admin",
        "exp": 4102444800u64  // far future timestamp (2100-01-01)
    });

    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/claims")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);

    let body_str = body_to_string(response.into_body()).await;
    assert_eq!(body_str, "test-user");
}

#[tokio::test]
async fn custom_validation_rules_are_applied() {
    let secret = "mysecret";

    // Create a layer with custom validation that requires the "aud" claim
    let mut validation = Validation::new(Algorithm::HS256);
    validation.set_required_spec_claims(&["aud"]);
    validation.set_audience(&["my-app"]);

    let layer =
        JwtAuthenticationLayer::<TestClaims>::new(secret.to_string()).with_validation(validation);

    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(layer);

    // Create a token missing the required "aud" claim
    let claims = serde_json::json!({
        "sub": "test-user",
        "exp": 4102444800u64
    });

    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    // Should be unauthorized because a required claim is missing
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn expired_token_is_unauthorized_when_validation_enabled() {
    let secret = "mysecret-exp";

    // Enable expiration validation
    let mut validation = Validation::new(Algorithm::HS256);
    validation.validate_exp = true; // Explicitly enable expiration check

    let layer =
        JwtAuthenticationLayer::<TestClaims>::new(secret.to_string()).with_validation(validation);

    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(layer);

    // Create a token with an expired timestamp (e.g., 1970-01-01)
    let claims = serde_json::json!({
        "sub": "test-user-expired",
        "exp": 1u64 // Very old timestamp
    });

    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    // Should be unauthorized because the token is expired
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    // Optional: Check the body for the specific error if desired
    // let body = response.into_body();
    // let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
    // let body_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    // assert!(body_json["error"].as_str().unwrap().contains("ExpiredSignature"));
}

#[tokio::test]
async fn invalid_signature_is_unauthorized() {
    let correct_secret = "correct_secret";
    let wrong_secret = "wrong_secret";

    // Layer uses the correct secret
    let layer = JwtAuthenticationLayer::<TestClaims>::new(correct_secret.to_string());
    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(layer);

    // Create a token signed with the WRONG secret
    let claims = serde_json::json!({
        "sub": "test-user-sig",
        "exp": 4102444800u64 // Non-expired
    });

    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(wrong_secret.as_bytes()), // Sign with wrong key
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    // Should be unauthorized because the signature is invalid
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    // Optional: Check the body for the specific error
    // let body = response.into_body();
    // let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
    // let body_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    // assert!(body_json["error"].as_str().unwrap().contains("InvalidSignature"));
}

#[tokio::test]
async fn wrong_algorithm_is_unauthorized() {
    let secret = "algo_secret";

    // Layer expects HS256 by default
    let layer = JwtAuthenticationLayer::<TestClaims>::new(secret.to_string());
    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(layer);

    // Create a token signed with HS512
    let claims = serde_json::json!({
        "sub": "test-user-algo",
        "exp": 4102444800u64 // Non-expired
    });

    let token = encode(
        &Header::new(Algorithm::HS512), // Use wrong algorithm
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    // Should be unauthorized because the algorithm doesn't match
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);

    // Optional: Check the body for the specific error
    // let body = response.into_body();
    // let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
    // let body_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    // assert!(body_json["error"].as_str().unwrap().contains("InvalidAlgorithm"));
}

#[tokio::test]
async fn valid_token_with_optional_claim_present() {
    let secret = "optional_present_secret";
    let layer = JwtAuthenticationLayer::<TestClaims>::new(secret.to_string());
    let app = Router::new()
        .route(
            "/claims",
            get(|Extension(claims): Extension<TestClaims>| async move {
                format!("{}:{}", claims.sub, claims.role.unwrap_or_default())
            }),
        )
        .layer(layer);

    // Token includes the optional 'role' claim
    let claims = serde_json::json!({
        "sub": "test-user-opt-present",
        "role": "tester",
        "exp": 4102444800u64
    });
    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/claims")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body_str = body_to_string(response.into_body()).await;
    assert_eq!(body_str, "test-user-opt-present:tester");
}

#[tokio::test]
async fn valid_token_with_optional_claim_missing() {
    let secret = "optional_missing_secret";
    let layer = JwtAuthenticationLayer::<TestClaims>::new(secret.to_string());
    let app = Router::new()
        .route(
            "/claims",
            get(|Extension(claims): Extension<TestClaims>| async move {
                format!("{}:{}", claims.sub, claims.role.unwrap_or_default())
            }),
        )
        .layer(layer);

    // Token omits the optional 'role' claim
    let claims = serde_json::json!({
        "sub": "test-user-opt-missing",
        "exp": 4102444800u64
    });
    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/claims")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body_str = body_to_string(response.into_body()).await;
    // Role should be empty string as per unwrap_or_default()
    assert_eq!(body_str, "test-user-opt-missing:");
}

#[tokio::test]
async fn compatibility_alias_works() {
    let secret = "compat_secret";
    // Use the JwtAuthLayer type alias
    let layer = crate::jwt_auth::JwtAuthLayer::<TestClaims>::new(secret.to_string());
    let app = Router::new()
        .route(
            "/claims",
            get(|Extension(claims): Extension<TestClaims>| async move { claims.sub }),
        )
        .layer(layer);

    let claims = serde_json::json!({
        "sub": "test-user-compat",
        "role": "user",
        "exp": 4102444800u64
    });
    let token = encode(
        &Header::new(Algorithm::HS256),
        &claims,
        &EncodingKey::from_secret(secret.as_bytes()),
    )
    .unwrap();

    let response = app
        .oneshot(
            Request::builder()
                .uri("/claims")
                .header(AUTHORIZATION, format!("Bearer {}", token))
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    let body_str = body_to_string(response.into_body()).await;
    assert_eq!(body_str, "test-user-compat");
}

#[tokio::test]
async fn layer_registers_secret_for_redaction() {
    let secret = "super-secret-key-for-redaction-test";

    // Ensure it's not registered before
    assert!(
        !is_registered_for_redaction(secret),
        "Secret should not be registered initially"
    );

    let _layer = JwtAuthenticationLayer::<TestClaims>::new(secret.to_string());

    // Check if the secret was added using the helper function
    assert!(
        is_registered_for_redaction(secret),
        "Secret should be registered for redaction"
    );

    // Clean up the registry using the helper function
    // Note: This might clear other secrets if tests run in parallel.
    // A dedicated test secret and removing only that might be safer, but clear() is simpler for now.
    clear_redaction_registry();
    assert!(
        !is_registered_for_redaction(secret),
        "Secret should be removed after cleanup"
    );
}