Skip to content

Commit f28717c

Browse files
weltekialexellis
authored andcommitted
Improve errors for token exchange functions
Signed-off-by: Han Verstraete (OpenFaaS Ltd) <[email protected]>
1 parent df1f645 commit f28717c

File tree

4 files changed

+31
-3
lines changed

4 files changed

+31
-3
lines changed

client_credentials_auth.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ func obtainClientCredentialsToken(clientID, clientSecret, tokenURL, scope, grant
111111
}
112112

113113
if code := res.StatusCode; code < 200 || code > 299 {
114-
return nil, fmt.Errorf("cannot fetch token: %v\nResponse: %s", res.Status, body)
114+
return nil, fmt.Errorf("unexpected status code: %v\nResponse: %s", res.Status, body)
115115
}
116116

117117
tj := &tokenJSON{}

exchange.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,15 @@ func ExchangeIDToken(tokenURL, rawIDToken string, options ...ExchangeOption) (*T
5555
return nil, fmt.Errorf("cannot fetch token: %v", err)
5656
}
5757

58+
if res.StatusCode == http.StatusBadRequest {
59+
authErr := &OAuthError{}
60+
if err := json.Unmarshal(body, authErr); err == nil {
61+
return nil, authErr
62+
}
63+
}
64+
5865
if code := res.StatusCode; code < 200 || code > 299 {
59-
return nil, fmt.Errorf("cannot fetch token: %v\nResponse: %s", res.Status, body)
66+
return nil, fmt.Errorf("unexpected status code: %v\nResponse: %s", res.Status, body)
6067
}
6168

6269
tj := &tokenJSON{}

iam_auth.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package sdk
22

33
import (
4+
"errors"
45
"fmt"
56
"net/http"
67
"os"
@@ -56,9 +57,15 @@ func (a *TokenAuth) getToken() (string, error) {
5657
}
5758

5859
token, err := ExchangeIDToken(a.TokenURL, idToken)
60+
61+
var authError *OAuthError
62+
if errors.As(err, &authError) {
63+
return "", fmt.Errorf("failed to exchange token for an OpenFaaS token: %s", authError.Description)
64+
}
5965
if err != nil {
60-
return "", err
66+
return "", fmt.Errorf("failed to exchange token for an OpenFaaS token: %s", err)
6167
}
68+
6269
a.token = token
6370
}
6471

token.go

+14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package sdk
22

33
import (
4+
"fmt"
45
"strings"
56
"time"
67
)
@@ -58,3 +59,16 @@ func (t *tokenJSON) scope() []string {
5859

5960
return []string{}
6061
}
62+
63+
// OAuthError represents an OAuth error response.
64+
type OAuthError struct {
65+
Err string `json:"error"`
66+
Description string `json:"error_description,omitempty"`
67+
}
68+
69+
func (e *OAuthError) Error() string {
70+
if len(e.Description) > 0 {
71+
return fmt.Sprintf("%s: %s", e.Err, e.Description)
72+
}
73+
return e.Err
74+
}

0 commit comments

Comments
 (0)