package sso import ( "testing" "time" ) func TestStoreAndConsume(t *testing.T) { code, err := Store("mcr", "https://mcr.example.com/cb", "state123", 42) if err != nil { t.Fatalf("Store: %v", err) } if code == "" { t.Fatal("Store returned empty code") } ac, ok := Consume(code) if !ok { t.Fatal("Consume returned false for valid code") } if ac.ClientID != "mcr" { t.Errorf("ClientID = %q, want %q", ac.ClientID, "mcr") } if ac.RedirectURI != "https://mcr.example.com/cb" { t.Errorf("RedirectURI = %q", ac.RedirectURI) } if ac.State != "state123" { t.Errorf("State = %q", ac.State) } if ac.AccountID != 42 { t.Errorf("AccountID = %d, want 42", ac.AccountID) } } func TestConsumeSingleUse(t *testing.T) { code, err := Store("mcr", "https://mcr.example.com/cb", "s", 1) if err != nil { t.Fatalf("Store: %v", err) } if _, ok := Consume(code); !ok { t.Fatal("first Consume should succeed") } if _, ok := Consume(code); ok { t.Error("second Consume should fail (single-use)") } } func TestConsumeUnknownCode(t *testing.T) { if _, ok := Consume("nonexistent"); ok { t.Error("Consume should fail for unknown code") } } func TestConsumeExpiredCode(t *testing.T) { code, err := Store("mcr", "https://mcr.example.com/cb", "s", 1) if err != nil { t.Fatalf("Store: %v", err) } // Manually expire the code. v, loaded := pendingCodes.Load(code) if !loaded { t.Fatal("code not found in pendingCodes") } ac, ok := v.(*AuthCode) if !ok { t.Fatal("unexpected type in pendingCodes") } ac.ExpiresAt = time.Now().Add(-1 * time.Second) if _, ok := Consume(code); ok { t.Error("Consume should fail for expired code") } } func TestStoreSessionAndConsume(t *testing.T) { nonce, err := StoreSession("mcr", "https://mcr.example.com/cb", "state456") if err != nil { t.Fatalf("StoreSession: %v", err) } if nonce == "" { t.Fatal("StoreSession returned empty nonce") } // GetSession should return it without consuming. s := GetSession(nonce) if s == nil { t.Fatal("GetSession returned nil") } if s.ClientID != "mcr" { t.Errorf("ClientID = %q", s.ClientID) } // Still available after GetSession. s2, ok := ConsumeSession(nonce) if !ok { t.Fatal("ConsumeSession returned false") } if s2.State != "state456" { t.Errorf("State = %q", s2.State) } // Consumed — should be gone. if _, ok := ConsumeSession(nonce); ok { t.Error("second ConsumeSession should fail") } if GetSession(nonce) != nil { t.Error("GetSession should return nil after consume") } } func TestConsumeSessionExpired(t *testing.T) { nonce, err := StoreSession("mcr", "https://mcr.example.com/cb", "s") if err != nil { t.Fatalf("StoreSession: %v", err) } v, loaded := pendingSessions.Load(nonce) if !loaded { t.Fatal("session not found in pendingSessions") } sess, ok := v.(*Session) if !ok { t.Fatal("unexpected type in pendingSessions") } sess.ExpiresAt = time.Now().Add(-1 * time.Second) if _, ok := ConsumeSession(nonce); ok { t.Error("ConsumeSession should fail for expired session") } }