|
| 1 | +// Copyright 2025 Chainguard, Inc. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package provider |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "errors" |
| 9 | + "net/http" |
| 10 | + "net/http/httptest" |
| 11 | + "sync/atomic" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/coreos/go-oidc/v3/oidc" |
| 16 | +) |
| 17 | + |
| 18 | +func TestNewProviderWithRetry_Success(t *testing.T) { |
| 19 | + // Create a test server that responds successfully |
| 20 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 21 | + w.Header().Set("Content-Type", "application/json") |
| 22 | + w.WriteHeader(http.StatusOK) |
| 23 | + issuerURL := "http://" + r.Host |
| 24 | + w.Write([]byte(`{"issuer":"` + issuerURL + `","authorization_endpoint":"` + issuerURL + `/auth","token_endpoint":"` + issuerURL + `/token","jwks_uri":"` + issuerURL + `/jwks"}`)) |
| 25 | + })) |
| 26 | + defer server.Close() |
| 27 | + |
| 28 | + ctx := context.Background() |
| 29 | + provider, err := newProviderWithRetry(ctx, server.URL) |
| 30 | + if err != nil { |
| 31 | + t.Fatalf("Expected success, got error: %v", err) |
| 32 | + } |
| 33 | + if provider == nil { |
| 34 | + t.Fatal("Expected provider, got nil") |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +func TestNewProviderWithRetry_EventualSuccess(t *testing.T) { |
| 39 | + var attempts int32 |
| 40 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 41 | + attempt := atomic.AddInt32(&attempts, 1) |
| 42 | + if attempt < 3 { |
| 43 | + // Fail the first 2 attempts |
| 44 | + w.WriteHeader(http.StatusInternalServerError) |
| 45 | + return |
| 46 | + } |
| 47 | + // Succeed on the 3rd attempt |
| 48 | + w.Header().Set("Content-Type", "application/json") |
| 49 | + w.WriteHeader(http.StatusOK) |
| 50 | + issuerURL := "http://" + r.Host |
| 51 | + w.Write([]byte(`{"issuer":"` + issuerURL + `","authorization_endpoint":"` + issuerURL + `/auth","token_endpoint":"` + issuerURL + `/token","jwks_uri":"` + issuerURL + `/jwks"}`)) |
| 52 | + })) |
| 53 | + defer server.Close() |
| 54 | + |
| 55 | + ctx := context.Background() |
| 56 | + start := time.Now() |
| 57 | + provider, err := newProviderWithRetry(ctx, server.URL) |
| 58 | + duration := time.Since(start) |
| 59 | + |
| 60 | + if err != nil { |
| 61 | + t.Fatalf("Expected eventual success, got error: %v", err) |
| 62 | + } |
| 63 | + if provider == nil { |
| 64 | + t.Fatal("Expected provider, got nil") |
| 65 | + } |
| 66 | + // The test server fails twice then succeeds on the third attempt |
| 67 | + if atomic.LoadInt32(&attempts) != 3 { |
| 68 | + t.Fatalf("Expected 3 attempts, got %d", attempts) |
| 69 | + } |
| 70 | + // Should have taken at least 1 second due to backoff after first failure |
| 71 | + if duration < 1*time.Second { |
| 72 | + t.Fatalf("Expected retry backoff, but completed too quickly: %v", duration) |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +func TestNewProviderWithRetry_AllAttemptsFail(t *testing.T) { |
| 77 | + var attempts int32 |
| 78 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 79 | + atomic.AddInt32(&attempts, 1) |
| 80 | + w.WriteHeader(http.StatusInternalServerError) |
| 81 | + })) |
| 82 | + defer server.Close() |
| 83 | + |
| 84 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 85 | + defer cancel() |
| 86 | + |
| 87 | + provider, err := newProviderWithRetry(ctx, server.URL) |
| 88 | + |
| 89 | + if err == nil { |
| 90 | + t.Fatal("Expected error after all retries failed") |
| 91 | + } |
| 92 | + if provider != nil { |
| 93 | + t.Fatal("Expected nil provider after all retries failed") |
| 94 | + } |
| 95 | + // With backoff library, we expect multiple attempts but don't need to check exact count |
| 96 | + if atomic.LoadInt32(&attempts) < 3 { |
| 97 | + t.Fatalf("Expected at least 3 attempts, got %d", attempts) |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +func TestNewProviderWithRetry_ContextCancellation(t *testing.T) { |
| 102 | + var attempts int32 |
| 103 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 104 | + atomic.AddInt32(&attempts, 1) |
| 105 | + // Always fail to trigger retries |
| 106 | + w.WriteHeader(http.StatusInternalServerError) |
| 107 | + })) |
| 108 | + defer server.Close() |
| 109 | + |
| 110 | + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 111 | + defer cancel() |
| 112 | + |
| 113 | + start := time.Now() |
| 114 | + provider, err := newProviderWithRetry(ctx, server.URL) |
| 115 | + duration := time.Since(start) |
| 116 | + |
| 117 | + if !errors.Is(err, context.DeadlineExceeded) { |
| 118 | + t.Fatalf("Expected context deadline exceeded, got: %v", err) |
| 119 | + } |
| 120 | + if provider != nil { |
| 121 | + t.Fatal("Expected nil provider after context cancellation") |
| 122 | + } |
| 123 | + // Should have attempted at least once but been canceled before completing all retries |
| 124 | + totalAttempts := atomic.LoadInt32(&attempts) |
| 125 | + if totalAttempts == 0 { |
| 126 | + t.Fatal("Expected at least one attempt before context cancellation") |
| 127 | + } |
| 128 | + // With backoff library and timeout, we expect some attempts but not too many |
| 129 | + if totalAttempts > 10 { |
| 130 | + t.Fatalf("Expected reasonable number of attempts due to context cancellation, got %d", totalAttempts) |
| 131 | + } |
| 132 | + // Should have been canceled around the timeout duration |
| 133 | + if duration > 3*time.Second { |
| 134 | + t.Fatalf("Expected cancellation around 2s, but took %v", duration) |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +func TestIsPermanentError_GoOIDCErrorPatterns(t *testing.T) { |
| 139 | + tests := []struct { |
| 140 | + statusCode int |
| 141 | + body string |
| 142 | + permanent bool |
| 143 | + name string |
| 144 | + }{ |
| 145 | + // Permanent errors - using actual HTTP status codes that will generate real go-oidc errors |
| 146 | + {400, `{"error":"invalid_request"}`, true, "400 Bad Request should be permanent"}, |
| 147 | + {401, `{"error":"access_denied"}`, true, "401 Unauthorized should be permanent"}, |
| 148 | + {403, `{"error":"insufficient_scope"}`, true, "403 Forbidden should be permanent"}, |
| 149 | + {404, `{"error":"not_found"}`, true, "404 Not Found should be permanent"}, |
| 150 | + {405, `{"error":"method_not_allowed"}`, true, "405 Method Not Allowed should be permanent"}, |
| 151 | + {406, `{"error":"not_acceptable"}`, true, "406 Not Acceptable should be permanent"}, |
| 152 | + {410, `{"error":"gone"}`, true, "410 Gone should be permanent"}, |
| 153 | + {415, `{"error":"unsupported_media_type"}`, true, "415 Unsupported Media Type should be permanent"}, |
| 154 | + {422, `{"error":"unprocessable_entity"}`, true, "422 Unprocessable Entity should be permanent"}, |
| 155 | + {501, `{"error":"not_implemented"}`, true, "501 Not Implemented should be permanent"}, |
| 156 | + |
| 157 | + // Temporary errors - should be retryable |
| 158 | + {429, `{"error":"rate_limited"}`, false, "429 Too Many Requests should be retryable"}, |
| 159 | + {500, `{"error":"internal_server_error"}`, false, "500 Internal Server Error should be retryable"}, |
| 160 | + {502, `{"error":"bad_gateway"}`, false, "502 Bad Gateway should be retryable"}, |
| 161 | + {503, `{"error":"service_unavailable"}`, false, "503 Service Unavailable should be retryable"}, |
| 162 | + {504, `{"error":"gateway_timeout"}`, false, "504 Gateway Timeout should be retryable"}, |
| 163 | + } |
| 164 | + |
| 165 | + for _, tc := range tests { |
| 166 | + t.Run(tc.name, func(t *testing.T) { |
| 167 | + // Create a test server that returns the specific HTTP status code |
| 168 | + // This will generate actual go-oidc errors that we can test against |
| 169 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 170 | + w.Header().Set("Content-Type", "application/json") |
| 171 | + w.WriteHeader(tc.statusCode) |
| 172 | + w.Write([]byte(tc.body)) |
| 173 | + })) |
| 174 | + defer server.Close() |
| 175 | + |
| 176 | + // Use go-oidc to generate the actual error |
| 177 | + ctx := context.Background() |
| 178 | + _, err := oidc.NewProvider(ctx, server.URL) |
| 179 | + |
| 180 | + // go-oidc should return an error for non-200 responses |
| 181 | + if err == nil { |
| 182 | + t.Fatalf("Expected go-oidc to return an error for status %d, but got nil", tc.statusCode) |
| 183 | + } |
| 184 | + |
| 185 | + // Test our error classification function on the real go-oidc error |
| 186 | + result := isPermanentError(err) |
| 187 | + if result != tc.permanent { |
| 188 | + t.Errorf("isPermanentError() for real go-oidc error %q = %v, want %v", err.Error(), result, tc.permanent) |
| 189 | + } |
| 190 | + }) |
| 191 | + } |
| 192 | +} |
0 commit comments