feather 0.8.1

Feather: A minimal HTTP framework for 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
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
# JWT Authentication in Feather


Feather includes built-in JWT (JSON Web Token) support for securing your APIs. This guide covers JWT authentication in Feather.

## Prerequisites


Enable the `jwt` feature in your `Cargo.toml`:

```toml
[dependencies]
feather = { version = "0.6", features = ["jwt"] }
```

## Setting Up JWT


### Creating a JWT Manager


Initialize JWT support in your application:

```rust,ignore
use feather::{App, jwt::JwtManager};

fn main() {
    let mut app = App::new();
    
    // Create a JWT manager with a secret key
    let secret = "your-super-secret-key-min-32-chars!".to_string();
    let jwt_manager = JwtManager::new(secret);
    
    // Set it in the app context
    app.context().set_jwt(jwt_manager);
    
    app.listen("127.0.0.1:5050");
}
```

## Token Generation


### Simple Tokens


Generate tokens with minimal setup:

```rust,ignore
use feather::jwt::JwtManager;

let jwt = JwtManager::new("secret-key".to_string());

// Generate a token with subject and TTL
match jwt.generate_simple("user123", 24) {  // 24 hour TTL
    Ok(token) => println!("Token: {}", token),
    Err(e) => println!("Error: {}", e),
}
```

### Custom Claims with Derive Macro


The easiest way to define custom claims is with the `#[derive(Claim)]` macro:

```rust,ignore
use feather::jwt::Claim;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Claim, Clone)]

pub struct UserClaims {
    #[required]
    pub sub: String,        // Subject (usually user ID)
    #[required]
    pub email: String,      // Custom field
    pub role: String,       // Custom field
    #[exp]
    pub exp: usize,         // Expiration time (automatically validated)
}
```

The `#[derive(Claim)]` macro automatically:
- Validates fields marked with `#[required]` are not empty
- Validates `#[exp]` fields are valid Unix timestamps in the future
- Implements the `Claim` trait for you

#### Manual Implementation (Advanced)


For custom validation logic, implement `Claim` manually:

```rust,ignore
use feather::jwt::Claim;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone)]

pub struct AdminClaims {
    pub sub: String,
    pub exp: usize,
    pub admin_id: u64,
    pub permissions: Vec<String>,
}

impl Claim for AdminClaims {
    fn validate(&self) -> Result<(), jsonwebtoken::errors::Error> {
        use std::time::{SystemTime, UNIX_EPOCH};
        
        if self.sub.is_empty() {
            return Err(jsonwebtoken::errors::Error::from(
                jsonwebtoken::errors::ErrorKind::InvalidToken
            ));
        }
        
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as usize;
        
        if self.exp < now {
            return Err(jsonwebtoken::errors::Error::from(
                jsonwebtoken::errors::ErrorKind::ExpiredSignature
            ));
        }
        
        Ok(())
    }
}
```

## Token Validation


### Decoding Tokens


Decode and validate tokens:

```rust,ignore
use feather::jwt::JwtManager;

let jwt = JwtManager::new("secret-key".to_string());
let token = "your-jwt-token";

match jwt.decode::<UserClaims>(token) {
    Ok(claims) => {
        println!("User ID: {}", claims.user_id);
        println!("Email: {}", claims.email);
    }
    Err(e) => {
        println!("Token validation failed: {}", e);
    }
}
```

## Protected Routes with JWT


### Using `#[jwt_required]` Macro (Recommended)


The easiest way to protect routes is with the `#[jwt_required]` and `#[middleware_fn]` macros:

```rust,ignore
use feather::{App, jwt::JwtManager, jwt_required, middleware_fn, Claim};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Claim, Clone)]

struct UserClaims {
    #[required]
    pub sub: String,
    pub email: String,
}

#[jwt_required]

#[middleware_fn]

fn get_profile(claims: UserClaims) {
    res.send_text(format!("Profile for: {}", claims.email));
    next!()
}

fn main() {
    let mut app = App::new();
    
    let jwt = JwtManager::new("secret-key".to_string());
    app.context().set_jwt(jwt);
    
    // Protected route - automatically validates JWT
    app.get("/api/profile", get_profile);
    
    app.listen("127.0.0.1:5050");
}
```

The `#[jwt_required]` macro automatically:
- Extracts the token from `Authorization: Bearer <token>` header
- Decodes and validates the token
- Validates claims (required fields, expiration)
- Returns 401 Unauthorized if anything fails

#### Multiple Protected Routes


```rust,ignore
#[jwt_required]

#[middleware_fn]

fn get_user_data(claims: UserClaims) {
    res.send_text(format!("Data for: {}", claims.sub));
    next!()
}

#[jwt_required]

#[middleware_fn]

fn update_user(claims: UserClaims) {
    res.send_text(format!("Updating user: {}", claims.sub));
    next!()
}

let mut app = App::new();
app.context().set_jwt(JwtManager::new("secret-key".to_string()));

app.get("/api/user", get_user_data);
app.put("/api/user", update_user);
```

### Manual JWT Protection (Advanced)


For custom error handling or conditional validation:

```rust,ignore
use feather::middleware;

app.get("/api/custom", middleware!(|req, res, ctx| {
    // Get token from Authorization header
    let token = match req.headers.get("Authorization")
        .and_then(|h| h.to_str().ok())
        .and_then(|h| h.strip_prefix("Bearer ")) {
        Some(t) => t,
        None => {
            res.set_status(401);
            res.send_text("Missing Authorization header");
            return next!();
        }
    };
    
    // Decode and validate token
    let jwt = ctx.jwt();
    let claims: UserClaims = match jwt.decode(token) {
        Ok(c) => c,
        Err(e) => {
            res.set_status(401);
            res.send_text(format!("Invalid token: {}", e));
            return next!();
        }
    };
    
    // Use claims in your handler
    res.send_text(format!("User: {}", claims.email));
    next!()
}));
```

### with_jwt_auth Middleware


Alternatively, use the `with_jwt_auth` middleware:

```rust,ignore
use feather::jwt::{with_jwt_auth, SimpleClaims};

app.get(
    "/protected",
    with_jwt_auth(|_req, res, _ctx, claims: SimpleClaims| {
        res.send_text(format!("Hello, {}!", claims.sub));
        next!()
    })
);
```

## Complete Authentication Flow


### Full Example with Login and Protected Routes


```rust,ignore
use feather::{App, jwt::JwtManager, jwt_required, middleware_fn, middleware, Claim};
use serde::{Deserialize, Serialize,json};

#[derive(Serialize, Deserialize, Claim, Clone)]

struct AuthClaims {
    #[required]
    sub: String,
    email: String,
    #[exp]
    exp: usize,
}

fn main() {
    let mut app = App::new();
    
    let jwt = JwtManager::new("your-secret-key".to_string());
    app.context().set_jwt(jwt);
    
    // Login endpoint (no auth required)
    app.post("/auth/login", middleware!(|req, res, ctx| {
        // Validate credentials (simplified)
        let body = String::from_utf8_lossy(&req.body);
        
        if body.contains("admin") && body.contains("password") {
            let jwt = ctx.jwt();
            
            // Generate token with 24 hour expiry
            match jwt.generate_simple("admin", 24) {
                Ok(token) => {
                    res.send_text(format!(r#"{{"token":"{}"}}"#, token));
                }
                Err(_) => {
                    res.set_status(500);
                    res.send_text("Failed to generate token");
                }
            }
        } else {
            res.set_status(401);
            res.send_text("Invalid credentials");
        }
        
        next!()
    }));
    
    // Protected endpoint using #[jwt_required]
    #[jwt_required]
    #[middleware_fn]
    fn get_profile(claims: AuthClaims) {
        res.send_text(format!(r#"{{"profile":"{}","email":"{}"}}"#, claims.sub, claims.email));
        next!()
    }
    
    app.get("/api/profile", get_profile);
    
    // Health check (no auth)
    app.get("/health", middleware!(|_req, res, _ctx| {
        res.send_json(json!({"status":"ok"}));
        next!()
    }));
    
    app.listen("127.0.0.1:5050");
}
```

### Alternative: Custom Validation Flow


```rust,ignore
#[derive(Serialize, Deserialize, Claim, Clone)]

struct AdminClaims {
    #[required]
    sub: String,
    role: String,
    #[exp]
    exp: usize,
}

#[jwt_required]

#[middleware_fn]

fn admin_only(claims: AdminClaims) {
    if claims.role != "admin" {
        res.set_status(403);
        res.send_text("Admin access required");
        return next!();
    }
    
    res.send_text(format!("Admin panel for: {}", claims.sub));
    next!()
}

let mut app = App::new();
app.get("/api/admin", admin_only);
```

## Token Claims


### Using `#[derive(Claim)]` (Recommended)


Define claims quickly with automatic validation:

```rust,ignore
use feather::jwt::Claim;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Claim, Clone)]

pub struct UserClaims {
    #[required]
    pub user_id: String,
    #[required]
    pub email: String,
    pub role: String,
    #[exp]
    pub exp: usize,
}

// Automatically validates:
// - user_id and email are not empty
// - exp is a valid Unix timestamp in the future
```

Validation attributes:
- `#[required]` - Field must not be empty
- `#[exp]` - Field must be a valid future Unix timestamp

### SimpleClaims


Built-in claims for quick use:

```rust,ignore
use feather::jwt::SimpleClaims;

pub struct SimpleClaims {
    pub sub: String,    // Subject (user ID)
    pub exp: usize,     // Expiration time (Unix timestamp)
}
```

### Custom Claims (Manual)


For advanced validation, implement `Claim` manually:

```rust,ignore
use feather::jwt::Claim;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone)]

pub struct AdminClaims {
    pub sub: String,
    pub exp: usize,
    pub admin_id: u64,
    pub permissions: Vec<String>,
}

impl Claim for AdminClaims {
    fn validate(&self) -> Result<(), jsonwebtoken::errors::Error> {
        // Add custom validation logic
        Ok(())
    }
}
```

## Best Practices


### Security


1. **Use strong secrets** - Use cryptographically secure random strings
2. **Use environment variables** - Don't hardcode secrets
3. **Use HTTPS** - Always transmit tokens over secure connections
4. **Short expiration** - Use reasonable TTLs (15 minutes to 24 hours)
5. **Refresh tokens** - Consider implementing refresh token flow for longer sessions

```rust,ignore
use std::env;

fn main() {
    let secret = env::var("JWT_SECRET")
        .expect("JWT_SECRET environment variable not set");
    
    let jwt = JwtManager::new(secret);
    // ... rest of app
}
```

### Error Handling


Proper token error handling:

```rust,ignore
use feather::jwt::ErrorKind;

let token = "invalid-token";
let jwt = ctx.jwt();

match jwt.decode::<SimpleClaims>(token) {
    Ok(claims) => {
        // Token is valid
    }
    Err(e) => {
        if e.kind() == jsonwebtoken::errors::ErrorKind::ExpiredSignature {
            res.set_status(401);
            res.send_text("Token expired");
        } else if e.kind() == jsonwebtoken::errors::ErrorKind::InvalidToken {
            res.set_status(401);
            res.send_text("Invalid token");
        } else {
            res.set_status(401);
            res.send_text("Authentication failed");
        }
    }
}
```

### Token Expiration


Generate tokens with appropriate TTL:

```rust,ignore
// Short-lived access token (15 minutes)
jwt.generate_simple("user123", 1/96)?;  // 15 minutes = 1/96 of a day

// Regular session (24 hours)
jwt.generate_simple("user123", 1)?;

// Extended session (7 days)
jwt.generate_simple("user123", 7)?;

// Long-lived token (30 days)
jwt.generate_simple("user123", 30)?;
```

### Rate Limiting with JWT


Combine with rate limiting middleware:

```rust,ignore
use std::collections::HashMap;
use feather::State;

#[derive(Clone)]

struct RateLimiter {
    requests: HashMap<String, usize>,
}

fn main() {
    let mut app = App::new();
    
    let jwt = JwtManager::new("secret-key".to_string());
    app.context().set_jwt(jwt);
    
    app.context().set_state(State::new(RateLimiter {
        requests: HashMap::new(),
    }));
    
    app.use_middleware(middleware!(|req, res, ctx| {
        // Check rate limit for authenticated users
        if let Some(auth) = req.headers.get("Authorization") {
            if let Ok(auth_str) = auth.to_str() {
                let token = auth_str.strip_prefix("Bearer ").unwrap_or("");
                
                let jwt = ctx.jwt();
                if jwt.decode::<SimpleClaims>(token).is_ok() {
                    // Authenticated request
                    // Add rate limiting logic here
                }
            }
        }
        
        next!()
    }));
}
```

## Example Applications


### API Server with JWT (Using Macros)


```rust,ignore
use feather::{App, jwt::JwtManager, jwt_required, middleware_fn, middleware, Claim};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Claim, Clone)]

struct ApiUser {
    #[required]
    sub: String,
    email: String,
    #[exp]
    exp: usize,
}

fn main() {
    let mut app = App::new();
    
    let jwt = JwtManager::new("your-secret-key".to_string());
    app.context().set_jwt(jwt);
    
    // Health check (no auth)
    app.get("/health", middleware!(|_req, res, _ctx| {
        res.send_text(r#"{"status":"ok"}"#);
        next!()
    }));
    
    // Login endpoint
    app.post("/auth/login", middleware!(|_req, res, ctx| {
        let jwt = ctx.jwt();
        match jwt.generate_simple("user@example.com", 24) {
            Ok(token) => res.send_text(token),
            Err(_) => {
                res.set_status(500);
                res.send_text("Token generation failed");
            }
        }
        next!()
    }));
    
    // Protected endpoints using #[jwt_required]
    #[jwt_required]
    #[middleware_fn]
    fn get_user_data(user: ApiUser) {
        res.send_text(format!(r#"{{"user":"{}"}}"#, user.sub));
        next!()
    }
    
    #[jwt_required]
    #[middleware_fn]
    fn update_user(user: ApiUser) {
        res.send_text(format!("Updated user: {}", user.sub));
        next!()
    }
    
    app.get("/api/user", get_user_data);
    app.put("/api/user", update_user);
    
    app.listen("127.0.0.1:5050");
}
```

### API Server with JWT (Manual Approach)


```rust,ignore
use feather::{App, jwt::JwtManager, middleware, jwt::SimpleClaims};

fn main() {
    let mut app = App::new();
    
    let jwt = JwtManager::new("app-secret-key".to_string());
    app.context().set_jwt(jwt);
    
    // Health check (no auth)
    app.get("/health", middleware!(|_req, res, _ctx| {
        res.send_text(r#"{"status":"ok"}"#);
        next!()
    }));
    
    // Login (no auth)
    app.post("/auth/login", middleware!(|req, res, ctx| {
        if req.body.is_empty() {
            res.set_status(400);
            res.send_text("Credentials required");
            return next!();
        }
        
        let jwt = ctx.jwt();
        match jwt.generate_simple("user123", 24) {
            Ok(token) => res.send_text(token),
            Err(_) => {
                res.set_status(500);
                res.send_text("Token generation failed");
            }
        }
        
        next!()
    }));
    
    // Protected endpoint with manual validation
    app.get("/api/data", middleware!(|req, res, ctx| {
        let token = req.headers.get("Authorization")
            .and_then(|h| h.to_str().ok())
            .and_then(|h| h.strip_prefix("Bearer "))
            .unwrap_or("");
        
        let jwt = ctx.jwt();
        match jwt.decode::<SimpleClaims>(token) {
            Ok(_) => res.send_json(json!({"data":"protected"})),
            Err(_) => {
                res.set_status(401);
                res.send_text("Unauthorized");
            }
        }
        
        next!()
    }));
    
    app.listen("127.0.0.1:5050");
}
```