auth_test.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. package pia
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "sync/atomic"
  10. "testing"
  11. "time"
  12. )
  13. func TestAuthClientSuccessAndReject(t *testing.T) {
  14. successFixture, err := os.ReadFile(filepath.Join("testdata", "auth", "success.json"))
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  19. if err := r.ParseMultipartForm(1 << 20); err != nil {
  20. t.Errorf("parse form: %v", err)
  21. }
  22. if r.FormValue("username") != "p123" || r.FormValue("password") != "password" {
  23. t.Errorf("unexpected credentials")
  24. }
  25. w.Header().Set("Content-Type", "application/json")
  26. _, _ = w.Write(successFixture)
  27. }))
  28. defer server.Close()
  29. client := NewAuthClient(server.URL)
  30. token, err := client.Authenticate(context.Background(), "p123", []byte("password"))
  31. if err != nil || string(token.Value) != "test-token-value-that-is-long-enough" {
  32. t.Fatalf("unexpected auth result: token=%q err=%v", token.Value, err)
  33. }
  34. rejected := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }))
  35. defer rejected.Close()
  36. client = NewAuthClient(rejected.URL)
  37. _, err = client.Authenticate(context.Background(), "p123", []byte("wrong"))
  38. if CodeOf(err) != CodeInvalidCredentials {
  39. t.Fatalf("got %s, want %s", CodeOf(err), CodeInvalidCredentials)
  40. }
  41. }
  42. func TestAuthClientRejectsInvalidResponsesAndTimeout(t *testing.T) {
  43. htmlFixture, err := os.ReadFile(filepath.Join("testdata", "auth", "html.txt"))
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. tests := []struct {
  48. name, contentType, body string
  49. status int
  50. maxBody int64
  51. wantCode string
  52. }{
  53. {name: "forbidden", status: http.StatusForbidden, contentType: "application/json", body: `{}`, wantCode: CodeInvalidCredentials},
  54. {name: "html fixture", status: http.StatusOK, contentType: "text/html", body: string(htmlFixture), wantCode: CodeAuthenticationUnavailable},
  55. {name: "malformed JSON", status: http.StatusOK, contentType: "application/json", body: `{`, wantCode: CodeAuthenticationUnavailable},
  56. {name: "trailing JSON", status: http.StatusOK, contentType: "application/json", body: `{"token":"test-token-value-that-is-long-enough"}{}`, wantCode: CodeAuthenticationUnavailable},
  57. {name: "short token", status: http.StatusOK, contentType: "application/json", body: `{"token":"short"}`, wantCode: CodeAuthenticationUnavailable},
  58. {name: "oversized", status: http.StatusOK, contentType: "application/json", body: `{"token":"` + strings.Repeat("a", 100) + `"}`, maxBody: 32, wantCode: CodeAuthenticationUnavailable},
  59. }
  60. for _, test := range tests {
  61. t.Run(test.name, func(t *testing.T) {
  62. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  63. w.Header().Set("Content-Type", test.contentType)
  64. w.WriteHeader(test.status)
  65. _, _ = w.Write([]byte(test.body))
  66. }))
  67. defer server.Close()
  68. client := NewAuthClient(server.URL)
  69. if test.maxBody > 0 {
  70. client.MaxBody = test.maxBody
  71. }
  72. _, err := client.Authenticate(context.Background(), "p123", []byte("password"))
  73. if CodeOf(err) != test.wantCode {
  74. t.Fatalf("got %s, want %s: %v", CodeOf(err), test.wantCode, err)
  75. }
  76. })
  77. }
  78. timeoutServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  79. time.Sleep(100 * time.Millisecond)
  80. w.Header().Set("Content-Type", "application/json")
  81. _, _ = w.Write([]byte(`{"token":"test-token-value-that-is-long-enough"}`))
  82. }))
  83. defer timeoutServer.Close()
  84. client := NewAuthClient(timeoutServer.URL)
  85. client.HTTPClient.Timeout = 25 * time.Millisecond
  86. _, err = client.Authenticate(context.Background(), "p123", []byte("password"))
  87. if CodeOf(err) != CodeTimeout {
  88. t.Fatalf("timeout returned %s, want %s: %v", CodeOf(err), CodeTimeout, err)
  89. }
  90. }
  91. func TestAuthClientDoesNotFollowRedirectWithSecrets(t *testing.T) {
  92. var destinationHits atomic.Int32
  93. destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  94. destinationHits.Add(1)
  95. w.WriteHeader(http.StatusOK)
  96. }))
  97. defer destination.Close()
  98. origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  99. http.Redirect(w, r, destination.URL, http.StatusTemporaryRedirect)
  100. }))
  101. defer origin.Close()
  102. client := NewAuthClient(origin.URL)
  103. _, _ = client.Authenticate(context.Background(), "p123", []byte("password"))
  104. if destinationHits.Load() != 0 {
  105. t.Fatal("authentication request followed a redirect and exposed credentials")
  106. }
  107. }
  108. func TestAuthClientRejectsControlCharactersBeforeNetwork(t *testing.T) {
  109. var hits atomic.Int32
  110. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  111. hits.Add(1)
  112. w.WriteHeader(http.StatusOK)
  113. }))
  114. defer server.Close()
  115. client := NewAuthClient(server.URL)
  116. _, err := client.Authenticate(context.Background(), "p123\r\nInjected", []byte("password"))
  117. if CodeOf(err) != CodeInvalidCredentials || hits.Load() != 0 {
  118. t.Fatalf("invalid credentials reached the network: code=%s hits=%d err=%v", CodeOf(err), hits.Load(), err)
  119. }
  120. }
  121. func TestAuthErrorsOmitPassword(t *testing.T) {
  122. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  123. w.WriteHeader(http.StatusInternalServerError)
  124. }))
  125. defer server.Close()
  126. client := NewAuthClient(server.URL)
  127. password := "TEST-PIA-PASSWORD-MUST-NOT-LEAK"
  128. _, err := client.Authenticate(context.Background(), "p123", []byte(password))
  129. if err == nil {
  130. t.Fatal("expected error")
  131. }
  132. if containsSecret(err.Error(), password) {
  133. t.Fatalf("password leaked in error: %v", err)
  134. }
  135. }