cognitox 0.1.2

AWS Cognito User Pools emulator for local development
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! OAuth 2.0 / OpenID Connect endpoints
//!
//! Implements the OAuth 2.0 Authorization Framework and OpenID Connect Core 1.0
//! compatible endpoints for Cognito Hosted UI emulation.

use axum::{
    Form, Json,
    extract::{Query, State},
    http::{HeaderMap, StatusCode, header},
    response::{IntoResponse, Redirect},
};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use chrono::{Duration, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use uuid::Uuid;

use crate::{
    error::OAuthError,
    jwt::{
        generate_access_token, generate_id_token, resolve_access_token_expiry,
        resolve_id_token_expiry, resolve_refresh_token_expiry, verify_access_token,
    },
    storage::Storage,
    types::{AuthorizationCode, ClientId, OAuthFlow, RefreshToken, UserStatus},
};

use super::super::action::user::helpers::verify_password;

/// Authorization endpoint query parameters
#[derive(Debug, Deserialize)]
pub struct AuthorizeParams {
    pub response_type: String,
    pub client_id: String,
    pub redirect_uri: String,
    #[serde(default)]
    pub scope: Option<String>,
    #[serde(default)]
    pub state: Option<String>,
    #[serde(default)]
    pub nonce: Option<String>,
    #[serde(default)]
    pub code_challenge: Option<String>,
    #[serde(default)]
    pub code_challenge_method: Option<String>,
    // For direct login (non-interactive for testing)
    #[serde(default)]
    pub username: Option<String>,
    #[serde(default)]
    pub password: Option<String>,
}

/// Token endpoint request body
#[derive(Debug, Deserialize)]
pub struct TokenRequest {
    pub grant_type: String,
    #[serde(default)]
    pub code: Option<String>,
    #[serde(default)]
    pub redirect_uri: Option<String>,
    #[serde(default)]
    pub client_id: Option<String>,
    #[serde(default)]
    pub client_secret: Option<String>,
    #[serde(default)]
    pub refresh_token: Option<String>,
    #[serde(default)]
    pub code_verifier: Option<String>,
    #[serde(default)]
    pub scope: Option<String>,
}

/// Token response
#[derive(Debug, Serialize)]
pub struct TokenResponse {
    pub access_token: String,
    pub token_type: String,
    pub expires_in: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refresh_token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id_token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
}

fn prefers_json_redirect(headers: &HeaderMap) -> bool {
    headers
        .get("x-requested-with")
        .and_then(|value| value.to_str().ok())
        .map(|value| value.eq_ignore_ascii_case("XMLHttpRequest"))
        .unwrap_or(false)
        || headers
            .get(header::ACCEPT)
            .and_then(|value| value.to_str().ok())
            .map(|value| value.contains("application/json"))
            .unwrap_or(false)
}

/// GET /oauth2/authorize - Authorization endpoint
///
/// For testing purposes, this endpoint can directly authenticate users
/// if username and password are provided as query parameters.
/// In production, this would redirect to a login page.
pub async fn authorize(
    State(storage): State<Storage>,
    headers: HeaderMap,
    Query(params): Query<AuthorizeParams>,
) -> Result<impl IntoResponse, OAuthError> {
    // Parse and validate client_id
    let parsed_client_id = ClientId::new(&params.client_id).map_err(|_| OAuthError {
        error: "invalid_client".to_string(),
        error_description: Some("Invalid client ID format".to_string()),
    })?;

    // Validate client
    let client = storage
        .get_user_pool_client(&parsed_client_id)
        .await
        .ok_or_else(|| OAuthError {
            error: "invalid_client".to_string(),
            error_description: Some("Client not found".to_string()),
        })?;

    // Validate redirect_uri
    if !client.callback_urls.is_empty() && !client.callback_urls.contains(&params.redirect_uri) {
        return Err(OAuthError {
            error: "invalid_request".to_string(),
            error_description: Some("Invalid redirect_uri".to_string()),
        });
    }

    if !client.allowed_oauth_flows_user_pool_client {
        return Err(OAuthError {
            error: "unauthorized_client".to_string(),
            error_description: Some("OAuth flows are not enabled for this client".to_string()),
        });
    }

    // Parse scopes
    let scopes: Vec<String> = params
        .scope
        .as_deref()
        .unwrap_or("openid")
        .split_whitespace()
        .map(String::from)
        .collect();

    // Validate response_type
    match params.response_type.as_str() {
        "code" => {
            // Authorization Code Flow
            if !client.allowed_oauth_flows.contains(&OAuthFlow::Code) {
                return Err(OAuthError {
                    error: "unauthorized_client".to_string(),
                    error_description: Some("Code flow not allowed for this client".to_string()),
                });
            }

            // For testing: direct authentication if credentials provided
            if let (Some(username), Some(password)) = (&params.username, &params.password) {
                let user = storage
                    .get_user_by_username(&client.user_pool_id, username)
                    .await
                    .ok_or_else(|| OAuthError {
                        error: "access_denied".to_string(),
                        error_description: Some("Invalid credentials".to_string()),
                    })?;

                // Check if user is enabled
                if !user.enabled {
                    return Err(OAuthError {
                        error: "access_denied".to_string(),
                        error_description: Some("User is disabled".to_string()),
                    });
                }

                if user.user_status != UserStatus::Confirmed {
                    return Err(OAuthError {
                        error: "access_denied".to_string(),
                        error_description: Some("User not confirmed".to_string()),
                    });
                }

                if !verify_password(password, &user.password_hash) {
                    return Err(OAuthError {
                        error: "access_denied".to_string(),
                        error_description: Some("Invalid credentials".to_string()),
                    });
                }

                // Generate authorization code
                let code = Uuid::new_v4().to_string();
                let auth_code = AuthorizationCode {
                    code: code.clone(),
                    user_id: user.id,
                    client_id: parsed_client_id.clone(),
                    redirect_uri: params.redirect_uri.clone(),
                    scope: scopes,
                    nonce: params.nonce.clone(),
                    code_challenge: params.code_challenge.clone(),
                    code_challenge_method: params.code_challenge_method.clone(),
                    expires_at: Utc::now() + Duration::minutes(5),
                };
                storage.save_authorization_code(auth_code).await;

                // Build redirect URL
                let mut redirect_url = params.redirect_uri.clone();
                redirect_url.push_str(if redirect_url.contains('?') { "&" } else { "?" });
                redirect_url.push_str(&format!("code={}", code));
                if let Some(state) = &params.state {
                    redirect_url.push_str(&format!("&state={}", state));
                }

                if prefers_json_redirect(&headers) {
                    return Ok(Json(json!({ "redirectUrl": redirect_url })).into_response());
                }

                return Ok(Redirect::temporary(&redirect_url).into_response());
            }

            // Without credentials, return login page HTML (simplified)
            let login_html = generate_login_html(&params);
            Ok((
                StatusCode::OK,
                [(header::CONTENT_TYPE, "text/html")],
                login_html,
            )
                .into_response())
        }
        "token" => {
            // Implicit Flow (legacy, not recommended)
            if !client.allowed_oauth_flows.contains(&OAuthFlow::Implicit) {
                return Err(OAuthError {
                    error: "unauthorized_client".to_string(),
                    error_description: Some(
                        "Implicit flow not allowed for this client".to_string(),
                    ),
                });
            }

            // For implicit flow with direct auth
            if let (Some(username), Some(password)) = (&params.username, &params.password) {
                let user = storage
                    .get_user_by_username(&client.user_pool_id, username)
                    .await
                    .ok_or_else(|| OAuthError {
                        error: "access_denied".to_string(),
                        error_description: Some("Invalid credentials".to_string()),
                    })?;

                // Check if user is enabled
                if !user.enabled {
                    return Err(OAuthError {
                        error: "access_denied".to_string(),
                        error_description: Some("User is disabled".to_string()),
                    });
                }

                if !verify_password(password, &user.password_hash) {
                    return Err(OAuthError {
                        error: "access_denied".to_string(),
                        error_description: Some("Invalid credentials".to_string()),
                    });
                }

                let groups = storage.get_groups_for_user(&user.id).await;

                let access_expiry = resolve_access_token_expiry(&client);
                let id_expiry = resolve_id_token_expiry(&client);

                let access_token = generate_access_token(
                    &user,
                    &params.client_id,
                    &client.user_pool_id,
                    &groups,
                    &scopes,
                    access_expiry,
                )
                .map_err(|e| OAuthError {
                    error: "server_error".to_string(),
                    error_description: Some(e),
                })?;

                let mut redirect_url = format!(
                    "{}#access_token={}&token_type=Bearer&expires_in={}",
                    params.redirect_uri,
                    access_token,
                    access_expiry.num_seconds()
                );

                if scopes.contains(&"openid".to_string()) {
                    let id_token = generate_id_token(
                        &user,
                        &params.client_id,
                        &client.user_pool_id,
                        &groups,
                        id_expiry,
                    )
                    .map_err(|e| OAuthError {
                        error: "server_error".to_string(),
                        error_description: Some(e),
                    })?;
                    redirect_url.push_str(&format!("&id_token={}", id_token));
                }

                if let Some(state) = &params.state {
                    redirect_url.push_str(&format!("&state={}", state));
                }

                return Ok(Redirect::temporary(&redirect_url).into_response());
            }

            let login_html = generate_login_html(&params);
            Ok((
                StatusCode::OK,
                [(header::CONTENT_TYPE, "text/html")],
                login_html,
            )
                .into_response())
        }
        _ => Err(OAuthError {
            error: "unsupported_response_type".to_string(),
            error_description: Some(format!(
                "Response type '{}' is not supported",
                params.response_type
            )),
        }),
    }
}

/// POST /oauth2/token - Token endpoint
pub async fn token(
    State(storage): State<Storage>,
    Form(req): Form<TokenRequest>,
) -> Result<Json<TokenResponse>, OAuthError> {
    match req.grant_type.as_str() {
        "authorization_code" => {
            let code = req.code.as_ref().ok_or_else(|| OAuthError {
                error: "invalid_request".to_string(),
                error_description: Some("Missing code parameter".to_string()),
            })?;

            let client_id_str = req.client_id.as_ref().ok_or_else(|| OAuthError {
                error: "invalid_request".to_string(),
                error_description: Some("Missing client_id parameter".to_string()),
            })?;

            // Parse client_id
            let client_id = ClientId::new(client_id_str).map_err(|_| OAuthError {
                error: "invalid_client".to_string(),
                error_description: Some("Invalid client ID format".to_string()),
            })?;

            // Get and validate authorization code
            let auth_code = storage
                .delete_authorization_code(code)
                .await
                .ok_or_else(|| OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("Invalid or expired authorization code".to_string()),
                })?;

            // Check expiration
            if auth_code.expires_at < Utc::now() {
                return Err(OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("Authorization code expired".to_string()),
                });
            }

            // Validate client_id
            if auth_code.client_id != client_id {
                return Err(OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("Client ID mismatch".to_string()),
                });
            }

            // Validate redirect_uri
            if let Some(redirect_uri) = &req.redirect_uri
                && redirect_uri != &auth_code.redirect_uri
            {
                return Err(OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("Redirect URI mismatch".to_string()),
                });
            }

            // Validate PKCE if code_challenge was provided
            if let Some(code_challenge) = &auth_code.code_challenge {
                let code_verifier = req.code_verifier.as_ref().ok_or_else(|| OAuthError {
                    error: "invalid_request".to_string(),
                    error_description: Some("Missing code_verifier parameter".to_string()),
                })?;

                let method = auth_code.code_challenge_method.as_deref().unwrap_or("S256");

                let computed_challenge = match method {
                    "S256" => {
                        let mut hasher = Sha256::new();
                        hasher.update(code_verifier.as_bytes());
                        URL_SAFE_NO_PAD.encode(hasher.finalize())
                    }
                    "plain" => code_verifier.clone(),
                    _ => {
                        return Err(OAuthError {
                            error: "invalid_request".to_string(),
                            error_description: Some(
                                "Unsupported code_challenge_method".to_string(),
                            ),
                        });
                    }
                };

                if &computed_challenge != code_challenge {
                    return Err(OAuthError {
                        error: "invalid_grant".to_string(),
                        error_description: Some("Code verifier mismatch".to_string()),
                    });
                }
            }

            // Get client and user
            let client = storage
                .get_user_pool_client(&client_id)
                .await
                .ok_or_else(|| OAuthError {
                    error: "invalid_client".to_string(),
                    error_description: Some("Client not found".to_string()),
                })?;

            // Validate client secret if required
            if client.client_secret.is_some() {
                let provided_secret = req.client_secret.as_ref().ok_or_else(|| OAuthError {
                    error: "invalid_client".to_string(),
                    error_description: Some("Client secret required".to_string()),
                })?;

                if client.client_secret.as_ref() != Some(provided_secret) {
                    return Err(OAuthError {
                        error: "invalid_client".to_string(),
                        error_description: Some("Invalid client secret".to_string()),
                    });
                }
            }

            let user = storage
                .get_user(&auth_code.user_id)
                .await
                .ok_or_else(|| OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("User not found".to_string()),
                })?;

            let groups = storage.get_groups_for_user(&user.id).await;

            let access_expiry = resolve_access_token_expiry(&client);
            let id_expiry = resolve_id_token_expiry(&client);
            let refresh_expiry = resolve_refresh_token_expiry(&client);

            // Generate tokens
            let access_token = generate_access_token(
                &user,
                client_id.as_str(),
                &client.user_pool_id,
                &groups,
                &auth_code.scope,
                access_expiry,
            )
            .map_err(|e| OAuthError {
                error: "server_error".to_string(),
                error_description: Some(e),
            })?;

            let id_token = if auth_code.scope.contains(&"openid".to_string()) {
                Some(
                    generate_id_token(
                        &user,
                        client_id.as_str(),
                        &client.user_pool_id,
                        &groups,
                        id_expiry,
                    )
                    .map_err(|e| OAuthError {
                        error: "server_error".to_string(),
                        error_description: Some(e),
                    })?,
                )
            } else {
                None
            };

            // Generate refresh token
            let refresh_token_str = Uuid::new_v4().to_string();
            let refresh = RefreshToken {
                token: refresh_token_str.clone(),
                user_id: user.id,
                client_id: client_id.clone(),
                expires_at: Utc::now() + refresh_expiry,
            };
            storage.save_refresh_token(refresh).await;

            Ok(Json(TokenResponse {
                access_token,
                token_type: "Bearer".to_string(),
                expires_in: access_expiry.num_seconds(),
                refresh_token: Some(refresh_token_str),
                id_token,
                scope: Some(auth_code.scope.join(" ")),
            }))
        }
        "refresh_token" => {
            let refresh_token = req.refresh_token.as_ref().ok_or_else(|| OAuthError {
                error: "invalid_request".to_string(),
                error_description: Some("Missing refresh_token parameter".to_string()),
            })?;

            let stored_token = storage
                .get_refresh_token(refresh_token)
                .await
                .ok_or_else(|| OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("Invalid refresh token".to_string()),
                })?;

            if stored_token.expires_at < Utc::now() {
                return Err(OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("Refresh token expired".to_string()),
                });
            }

            if let Some(requested_client_id) = req.client_id.as_deref() {
                let requested_client_id =
                    ClientId::new(requested_client_id).map_err(|_| OAuthError {
                        error: "invalid_client".to_string(),
                        error_description: Some("Invalid client ID format".to_string()),
                    })?;

                if requested_client_id != stored_token.client_id {
                    return Err(OAuthError {
                        error: "invalid_grant".to_string(),
                        error_description: Some("Client ID mismatch".to_string()),
                    });
                }
            }

            let client = storage
                .get_user_pool_client(&stored_token.client_id)
                .await
                .ok_or_else(|| OAuthError {
                    error: "invalid_client".to_string(),
                    error_description: Some("Client not found".to_string()),
                })?;

            if client.client_secret.is_some() {
                let provided_secret = req.client_secret.as_ref().ok_or_else(|| OAuthError {
                    error: "invalid_client".to_string(),
                    error_description: Some("Client secret required".to_string()),
                })?;

                if client.client_secret.as_ref() != Some(provided_secret) {
                    return Err(OAuthError {
                        error: "invalid_client".to_string(),
                        error_description: Some("Invalid client secret".to_string()),
                    });
                }
            }

            let user = storage
                .get_user(&stored_token.user_id)
                .await
                .ok_or_else(|| OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("User not found".to_string()),
                })?;

            if !user.enabled {
                return Err(OAuthError {
                    error: "invalid_grant".to_string(),
                    error_description: Some("User is disabled".to_string()),
                });
            }

            let groups = storage.get_groups_for_user(&user.id).await;
            let scopes: Vec<String> = req
                .scope
                .as_deref()
                .unwrap_or("openid")
                .split_whitespace()
                .map(String::from)
                .collect();

            let access_expiry = resolve_access_token_expiry(&client);
            let id_expiry = resolve_id_token_expiry(&client);

            let access_token = generate_access_token(
                &user,
                stored_token.client_id.as_str(),
                &client.user_pool_id,
                &groups,
                &scopes,
                access_expiry,
            )
            .map_err(|e| OAuthError {
                error: "server_error".to_string(),
                error_description: Some(e),
            })?;

            let id_token = if scopes.contains(&"openid".to_string()) {
                Some(
                    generate_id_token(
                        &user,
                        stored_token.client_id.as_str(),
                        &client.user_pool_id,
                        &groups,
                        id_expiry,
                    )
                    .map_err(|e| OAuthError {
                        error: "server_error".to_string(),
                        error_description: Some(e),
                    })?,
                )
            } else {
                None
            };

            Ok(Json(TokenResponse {
                access_token,
                token_type: "Bearer".to_string(),
                expires_in: access_expiry.num_seconds(),
                refresh_token: None, // Don't issue new refresh token
                id_token,
                scope: Some(scopes.join(" ")),
            }))
        }
        "client_credentials" => {
            let client_id_str = req.client_id.as_ref().ok_or_else(|| OAuthError {
                error: "invalid_request".to_string(),
                error_description: Some("Missing client_id".to_string()),
            })?;

            // Parse client_id
            let client_id = ClientId::new(client_id_str).map_err(|_| OAuthError {
                error: "invalid_client".to_string(),
                error_description: Some("Invalid client ID format".to_string()),
            })?;

            let client_secret = req.client_secret.as_ref().ok_or_else(|| OAuthError {
                error: "invalid_request".to_string(),
                error_description: Some("Missing client_secret".to_string()),
            })?;

            let client = storage
                .get_user_pool_client(&client_id)
                .await
                .ok_or_else(|| OAuthError {
                    error: "invalid_client".to_string(),
                    error_description: Some("Client not found".to_string()),
                })?;

            if client.client_secret.as_ref() != Some(client_secret) {
                return Err(OAuthError {
                    error: "invalid_client".to_string(),
                    error_description: Some("Invalid client credentials".to_string()),
                });
            }

            if !client.allowed_oauth_flows_user_pool_client {
                return Err(OAuthError {
                    error: "unauthorized_client".to_string(),
                    error_description: Some(
                        "OAuth flows are not enabled for this client".to_string(),
                    ),
                });
            }

            if !client
                .allowed_oauth_flows
                .contains(&OAuthFlow::ClientCredentials)
            {
                return Err(OAuthError {
                    error: "unauthorized_client".to_string(),
                    error_description: Some(
                        "Client credentials flow not allowed for this client".to_string(),
                    ),
                });
            }

            // For client_credentials, generate a minimal access token
            // Note: This is a simplified implementation
            let scopes: Vec<String> = req
                .scope
                .as_deref()
                .unwrap_or("")
                .split_whitespace()
                .map(String::from)
                .collect();

            let now = Utc::now();
            let access_expiry = resolve_access_token_expiry(&client);

            // Use a simple token format for client_credentials
            let access_token = format!(
                "client_{}_{}_{}",
                client_id,
                now.timestamp(),
                Uuid::new_v4()
            );

            Ok(Json(TokenResponse {
                access_token,
                token_type: "Bearer".to_string(),
                expires_in: access_expiry.num_seconds(),
                refresh_token: None,
                id_token: None,
                scope: if scopes.is_empty() {
                    None
                } else {
                    Some(scopes.join(" "))
                },
            }))
        }
        _ => Err(OAuthError {
            error: "unsupported_grant_type".to_string(),
            error_description: Some(format!("Grant type '{}' is not supported", req.grant_type)),
        }),
    }
}

/// UserInfo response
#[derive(Debug, Serialize)]
pub struct UserInfoResponse {
    pub sub: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email_verified: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_number: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_number_verified: Option<bool>,
    pub username: String,
    #[serde(rename = "cognito:groups", skip_serializing_if = "Vec::is_empty")]
    pub groups: Vec<String>,
}

/// GET /oauth2/userInfo - UserInfo endpoint
pub async fn userinfo(
    State(storage): State<Storage>,
    headers: axum::http::HeaderMap,
) -> Result<Json<UserInfoResponse>, OAuthError> {
    // Extract Bearer token from Authorization header
    let auth_header = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .ok_or_else(|| OAuthError {
            error: "invalid_token".to_string(),
            error_description: Some("Missing Authorization header".to_string()),
        })?;

    let token = auth_header
        .strip_prefix("Bearer ")
        .ok_or_else(|| OAuthError {
            error: "invalid_token".to_string(),
            error_description: Some("Invalid Authorization header format".to_string()),
        })?;

    // Verify token
    let token_data = verify_access_token(token).map_err(|e| OAuthError {
        error: "invalid_token".to_string(),
        error_description: Some(e),
    })?;

    let user_id = uuid::Uuid::parse_str(&token_data.claims.sub).map_err(|_| OAuthError {
        error: "invalid_token".to_string(),
        error_description: Some("Invalid user ID in token".to_string()),
    })?;

    let user = storage.get_user(&user_id).await.ok_or_else(|| OAuthError {
        error: "invalid_token".to_string(),
        error_description: Some("User not found".to_string()),
    })?;

    let groups = storage.get_groups_for_user(&user_id).await;

    Ok(Json(UserInfoResponse {
        sub: user.id.to_string(),
        email: user.email,
        email_verified: Some(true),
        phone_number: user.phone_number,
        phone_number_verified: Some(true),
        username: user.username,
        groups,
    }))
}

/// GET /.well-known/openid-configuration - OpenID Connect Discovery
pub async fn openid_configuration(headers: axum::http::HeaderMap) -> Json<Value> {
    // Get the host from the request to build proper URLs
    let host = headers
        .get(header::HOST)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("localhost:9229");

    let base_url = format!("http://{}", host);

    Json(json!({
        "issuer": format!("{}", base_url),
        "authorization_endpoint": format!("{}/oauth2/authorize", base_url),
        "token_endpoint": format!("{}/oauth2/token", base_url),
        "userinfo_endpoint": format!("{}/oauth2/userInfo", base_url),
        "jwks_uri": format!("{}/.well-known/jwks.json", base_url),
        "response_types_supported": ["code", "token", "code token"],
        "subject_types_supported": ["public"],
        "id_token_signing_alg_values_supported": ["RS256"],
        "scopes_supported": ["openid", "email", "phone", "profile", "aws.cognito.signin.user.admin"],
        "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
        "claims_supported": [
            "sub", "aud", "email", "email_verified", "exp", "iat", "iss",
            "phone_number", "phone_number_verified", "cognito:username", "cognito:groups"
        ],
        "code_challenge_methods_supported": ["S256", "plain"],
        "grant_types_supported": ["authorization_code", "refresh_token", "client_credentials"]
    }))
}

/// Generate a simple login HTML page
fn generate_login_html(params: &AuthorizeParams) -> String {
    format!(
        r#"<!DOCTYPE html>
<html>
<head>
    <title>Sign In - Cognito Emulator</title>
    <style>
        body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
               display: flex; justify-content: center; align-items: center; height: 100vh;
               margin: 0; background: #f5f5f5; }}
        .container {{ background: white; padding: 40px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); width: 300px; }}
        h1 {{ margin: 0 0 20px; font-size: 24px; text-align: center; }}
        input {{ width: 100%; padding: 12px; margin: 8px 0; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }}
        button {{ width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }}
        button:hover {{ background: #0056b3; }}
        .error {{ color: #dc3545; text-align: center; margin-top: 10px; }}
    </style>
</head>
<body>
    <div class="container">
        <h1>Sign In</h1>
        <form method="GET" action="/oauth2/authorize">
            <input type="hidden" name="response_type" value="{}">
            <input type="hidden" name="client_id" value="{}">
            <input type="hidden" name="redirect_uri" value="{}">
            <input type="hidden" name="scope" value="{}">
            {}
            {}
            {}
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit">Sign In</button>
        </form>
    </div>
</body>
</html>"#,
        params.response_type,
        params.client_id,
        params.redirect_uri,
        params.scope.as_deref().unwrap_or("openid"),
        params.state.as_ref().map(|s| format!(r#"<input type="hidden" name="state" value="{}">"#, s)).unwrap_or_default(),
        params.nonce.as_ref().map(|s| format!(r#"<input type="hidden" name="nonce" value="{}">"#, s)).unwrap_or_default(),
        params.code_challenge.as_ref().map(|s| format!(
            r#"<input type="hidden" name="code_challenge" value="{}"><input type="hidden" name="code_challenge_method" value="{}">"#,
            s,
            params.code_challenge_method.as_deref().unwrap_or("S256")
        )).unwrap_or_default(),
    )
}