@@ -4,8 +4,13 @@ import (
44 "context"
55 "encoding/json"
66 "fmt"
7+ "net/url"
8+ "strings"
79
10+ apierrors "k8s.io/apimachinery/pkg/api/errors"
11+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
812 "k8s.io/client-go/rest"
13+ "k8s.io/klog/v2"
914
1015 "github.com/jetstack/preflight/api"
1116 "github.com/jetstack/preflight/pkg/datagatherer"
@@ -86,7 +91,7 @@ func (g *DataGathererOIDC) fetchOIDCConfig(ctx context.Context) (map[string]any,
8691 // Fetch the OIDC discovery document from the well-known endpoint.
8792 bytes , err := g .cl .Get ().AbsPath ("/.well-known/openid-configuration" ).Do (ctx ).Raw ()
8893 if err != nil {
89- return nil , fmt .Errorf ("failed to get OIDC discovery document: %v " , err )
94+ return nil , fmt .Errorf ("failed to get OIDC discovery document: %s " , k8sErrorMessage ( err ) )
9095 }
9196
9297 var oidcResponse map [string ]any
@@ -106,7 +111,7 @@ func (g *DataGathererOIDC) fetchJWKS(ctx context.Context) (map[string]any, error
106111 // So we are using the default path instead, which we think should work in most cases.
107112 bytes , err := g .cl .Get ().AbsPath ("/openid/v1/jwks" ).Do (ctx ).Raw ()
108113 if err != nil {
109- return nil , fmt .Errorf ("failed to get JWKS from jwks_uri: %v " , err )
114+ return nil , fmt .Errorf ("failed to get JWKS from jwks_uri: %s " , k8sErrorMessage ( err ) )
110115 }
111116
112117 var jwksResponse map [string ]any
@@ -116,3 +121,35 @@ func (g *DataGathererOIDC) fetchJWKS(ctx context.Context) (map[string]any, error
116121
117122 return jwksResponse , nil
118123}
124+
125+ // based on https://github.com/kubernetes/kubectl/blob/a64ceaeab69eed1f11a9e1bd91cf2c1446de811c/pkg/cmd/util/helpers.go#L244
126+ func k8sErrorMessage (err error ) string {
127+ if status , isStatus := err .(apierrors.APIStatus ); isStatus {
128+ switch s := status .Status (); {
129+ case s .Reason == metav1 .StatusReasonUnauthorized :
130+ return fmt .Sprintf ("error: You must be logged in to the server (%s)" , s .Message )
131+ case len (s .Reason ) > 0 :
132+ return fmt .Sprintf ("Error from server (%s): %s" , s .Reason , err .Error ())
133+ default :
134+ return fmt .Sprintf ("Error from server: %s" , err .Error ())
135+ }
136+ }
137+
138+ if apierrors .IsUnexpectedObjectError (err ) {
139+ return fmt .Sprintf ("Server returned an unexpected response: %s" , err .Error ())
140+ }
141+
142+ if t , isURL := err .(* url.Error ); isURL {
143+ klog .V (4 ).Infof ("Connection error: %s %s: %v" , t .Op , t .URL , t .Err )
144+ if strings .Contains (t .Err .Error (), "connection refused" ) {
145+ host := t .URL
146+ if server , err := url .Parse (t .URL ); err == nil {
147+ host = server .Host
148+ }
149+ return fmt .Sprintf ("The connection to the server %s was refused - did you specify the right host or port?" , host )
150+ }
151+ return fmt .Sprintf ("Unable to connect to the server: %v" , t .Err )
152+ }
153+
154+ return fmt .Sprintf ("error: %v" , err )
155+ }
0 commit comments