Skip to content

Agent Mesh

fix(console): retry OIDC discovery instead of permanently disabling login

Antonio Ojea08475943ab10
diff --git a/internal/console/server.go b/internal/console/server.go
index 0f9f93bb..90d76afb 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -66,7 +66,7 @@ func NewServer(cfg Config) (*Server, error) {
}
if info.OidcIssuer != "" && info.ClientId != "" {
- provider, err = oidc.NewProvider(context.Background(), info.OidcIssuer)
+ provider, err = discoverProviderWithRetry(context.Background(), info.OidcIssuer, oidcDiscoveryMaxAttempts, oidcDiscoveryBaseDelay, oidcDiscoveryMaxDelay)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed OIDC discovery on %s: %v\n", info.OidcIssuer, err)
} else if provider.Endpoint().AuthURL != "" && provider.Endpoint().TokenURL != "" {
@@ -84,7 +84,6 @@ func NewServer(cfg Config) (*Server, error) {
provider: provider,
clientID: clientID,
}
-
// Create reverse proxy to the control plane
proxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
@@ -127,6 +126,43 @@ func NewServer(cfg Config) (*Server, error) {
return s, nil
}
+// Defaults for discoverProviderWithRetry; matches sam-control-plane's
+// discoverProviders so a transient hiccup during rollout (e.g. Dex still
+// starting up) doesn't permanently disable console OIDC login, since the
+// console's /info reports healthy either way and Kubernetes won't restart it.
+const (
+ oidcDiscoveryMaxAttempts = 5
+ oidcDiscoveryBaseDelay = 1 * time.Second
+ oidcDiscoveryMaxDelay = 8 * time.Second
+)
+
+// discoverProviderWithRetry retries OIDC discovery with exponential backoff so a
+// transient upstream hiccup (e.g. the identity provider mid-rollout) doesn't
+// permanently disable the console's OIDC login endpoints.
+func discoverProviderWithRetry(ctx context.Context, issuer string, maxAttempts int, baseDelay, maxDelay time.Duration) (*oidc.Provider, error) {
+ var lastErr error
+ for attempt := 0; attempt < maxAttempts; attempt++ {
+ if attempt > 0 {
+ delay := baseDelay * time.Duration(1<<uint(attempt-1))
+ if delay > maxDelay {
+ delay = maxDelay
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(delay):
+ }
+ }
+ provider, err := oidc.NewProvider(ctx, issuer)
+ if err == nil {
+ return provider, nil
+ }
+ lastErr = err
+ fmt.Fprintf(os.Stderr, "Warning: OIDC discovery attempt %d/%d for %s failed: %v\n", attempt+1, maxAttempts, issuer, err)
+ }
+ return nil, lastErr
+}
+
func (s *Server) Handler() http.Handler {
return s.mux
}
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index d3da0092..583b9483 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -1,12 +1,15 @@
package console
import (
+ "context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"net/http"
"net/http/httptest"
+ "sync/atomic"
"testing"
+ "time"
"github.com/google/sam/api"
"google.golang.org/protobuf/proto"
@@ -96,3 +99,109 @@ func TestNewServer_OIDCAutoDiscovery(t *testing.T) {
t.Errorf("expected AuthURL '%s', got '%s'", serverURL+"/auth", srv.provider.Endpoint().AuthURL)
}
}
+
+// TestNewServer_OIDCDiscoveryRetriesTransientFailure guards against a real
+// deployment race: if the OIDC issuer (e.g. Dex) is still starting up when
+// sam-console boots, discovery must retry instead of permanently disabling
+// login for the life of the pod (console's /info reports healthy either way,
+// so Kubernetes never restarts it to retry on its own).
+func TestNewServer_OIDCDiscoveryRetriesTransientFailure(t *testing.T) {
+ var attempts int32
+ var serverURL string
+ mux := http.NewServeMux()
+
+ mux.HandleFunc("/info", func(w http.ResponseWriter, r *http.Request) {
+ resp := &api.ControlPlaneInfoResponse{
+ OidcIssuer: serverURL,
+ ClientId: "mock-console-client",
+ }
+ data, err := proto.Marshal(resp)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(data)
+ })
+
+ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
+ if atomic.AddInt32(&attempts, 1) < 3 {
+ http.Error(w, "upstream connect error", http.StatusServiceUnavailable)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "issuer": serverURL,
+ "authorization_endpoint": serverURL + "/auth",
+ "token_endpoint": serverURL + "/token",
+ "jwks_uri": serverURL + "/keys",
+ })
+ })
+
+ mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]any{}})
+ })
+
+ mockSrv := httptest.NewServer(mux)
+ defer mockSrv.Close()
+ serverURL = mockSrv.URL
+
+ srv, err := NewServer(Config{
+ ControlPlaneURL: serverURL,
+ AdminToken: "test-admin-token",
+ StaticDir: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("failed to create server: %v", err)
+ }
+ if srv.provider == nil {
+ t.Fatal("expected OIDC discovery to succeed after transient failures, provider is nil")
+ }
+ if got := atomic.LoadInt32(&attempts); got != 3 {
+ t.Errorf("expected discovery to take 3 attempts, got %d", got)
+ }
+}
+
+func TestDiscoverProviderWithRetry(t *testing.T) {
+ t.Run("succeeds after transient failures", func(t *testing.T) {
+ var attempts int32
+ mux := http.NewServeMux()
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+ issuer := srv.URL
+
+ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
+ if atomic.AddInt32(&attempts, 1) < 3 {
+ http.Error(w, "upstream connect error", http.StatusServiceUnavailable)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "issuer": issuer,
+ "jwks_uri": issuer + "/keys",
+ })
+ })
+
+ if _, err := discoverProviderWithRetry(context.Background(), issuer, 5, time.Millisecond, 5*time.Millisecond); err != nil {
+ t.Fatalf("expected discovery to eventually succeed, got: %v", err)
+ }
+ if got := atomic.LoadInt32(&attempts); got != 3 {
+ t.Errorf("expected 3 attempts, got %d", got)
+ }
+ })
+
+ t.Run("gives up after max attempts", func(t *testing.T) {
+ mux := http.NewServeMux()
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "always down", http.StatusServiceUnavailable)
+ })
+
+ if _, err := discoverProviderWithRetry(context.Background(), srv.URL, 3, time.Millisecond, 5*time.Millisecond); err == nil {
+ t.Fatal("expected discovery to fail after exhausting retries")
+ }
+ })
+}