package auth import ( "strings" "testing" "time" ) func TestAPIKeyAndScopes(t *testing.T) { raw, pref, hash := GenerateAPIKey() if !strings.HasPrefix(raw, APIKeyPrefix) || len(raw) != 73 { t.Fatalf("unexpected raw key format: len=%d", len(raw)) } if pref != raw[:14] || len(hash) != 64 || hash != HashSecret(raw) { t.Fatalf("hash/prefix mismatch") } if len(AgentScopes) != 9 { t.Fatalf("expected 9 scopes, got %d", len(AgentScopes)) } for _, s := range AgentScopes { if strings.Contains(s, "aprobar") { t.Fatalf("approval scope must never exist: %s", s) } } entrega := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer_aceptadas"}} if !entrega.EsAgenteSoloAceptadas() { t.Fatalf("expected EsAgenteSoloAceptadas=true") } ops := &Actor{Type: "agent", Scopes: []string{"cotizaciones:leer", "cotizaciones:leer_aceptadas"}} if ops.EsAgenteSoloAceptadas() { t.Fatalf("expected EsAgenteSoloAceptadas=false when cotizaciones:leer present") } } func TestRateLimiter(t *testing.T) { rl := NewRateLimiter() now := time.Now() for i := 0; i < 3; i++ { res := rl.Check("k1", 3, now.Add(time.Duration(i)*time.Second)) if !res.Allowed { t.Fatalf("request %d should be allowed", i) } } blocked := rl.Check("k1", 3, now.Add(4*time.Second)) if blocked.Allowed || blocked.Remaining != 0 { t.Fatalf("4th request should be blocked: %+v", blocked) } afterWindow := rl.Check("k1", 3, now.Add(65*time.Second)) if !afterWindow.Allowed { t.Fatalf("request after 60s window should be allowed") } } func TestCoincideContacto(t *testing.T) { if !CoincideContacto("ANA@Empresa.MX", "ana@empresa.mx", "") { t.Fatal("case-insensitive email should match") } if !CoincideContacto("+52 1 55 1234-5678", "", "5512345678") { t.Fatal("last 10 phone digits should match") } if CoincideContacto("otro@x.com", "ana@empresa.mx", "5512345678") { t.Fatal("mismatched contact should fail") } } func TestJWTSignAndVerify(t *testing.T) { svc := NewService("super-secret-test-key", false, nil) tok, err := svc.SignSession(SessionPayload{ UserID: "u1", Email: "admin@urieljareth.com", Name: "Admin", Role: "admin", }) if err != nil { t.Fatalf("sign failed: %v", err) } got, err := svc.VerifySession(tok) if err != nil || got.UserID != "u1" || got.Role != "admin" { t.Fatalf("verify failed: %+v, err=%v", got, err) } }