Debian Codegraph @

pkg/oidc/error.go

raw
1 package oidc
2
3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "log/slog"
8 )
9
10 type errorType string
11
12 const (
13 InvalidRequest errorType = "invalid_request"
14 InvalidScope errorType = "invalid_scope"
15 InvalidClient errorType = "invalid_client"
16 InvalidGrant errorType = "invalid_grant"
17 UnauthorizedClient errorType = "unauthorized_client"
18 UnsupportedGrantType errorType = "unsupported_grant_type"
19 ServerError errorType = "server_error"
20 InteractionRequired errorType = "interaction_required"
21 LoginRequired errorType = "login_required"
22 RequestNotSupported errorType = "request_not_supported"
23
24 // Additional error codes as defined in
25 // https://www.rfc-editor.org/rfc/rfc8628#section-3.5
26 // Device Access Token Response
27 AuthorizationPending errorType = "authorization_pending"
28 SlowDown errorType = "slow_down"
29 AccessDenied errorType = "access_denied"
30 ExpiredToken errorType = "expired_token"
31
32 // InvalidTarget error is returned by Token Exchange if
33 // the requested target or audience is invalid.
34 // [RFC 8693, Section 2.2.2: Error Response](https://www.rfc-editor.org/rfc/rfc8693#section-2.2.2)
35 InvalidTarget errorType = "invalid_target"
36 )
37
38 var (
39 ErrInvalidRequest = func() *Error {
40 return &Error{
41 ErrorType: InvalidRequest,
42 }
43 }
44 ErrInvalidRequestRedirectURI = func() *Error {
45 return &Error{
46 ErrorType: InvalidRequest,
47 redirectDisabled: true,
48 }
49 }
50 ErrInvalidScope = func() *Error {
51 return &Error{
52 ErrorType: InvalidScope,
53 }
54 }
55 ErrInvalidClient = func() *Error {
56 return &Error{
57 ErrorType: InvalidClient,
58 }
59 }
60 ErrInvalidGrant = func() *Error {
61 return &Error{
62 ErrorType: InvalidGrant,
63 }
64 }
65 ErrUnauthorizedClient = func() *Error {
66 return &Error{
67 ErrorType: UnauthorizedClient,
68 }
69 }
70 ErrUnsupportedGrantType = func() *Error {
71 return &Error{
72 ErrorType: UnsupportedGrantType,
73 }
74 }
75 ErrServerError = func() *Error {
76 return &Error{
77 ErrorType: ServerError,
78 }
79 }
80 ErrInteractionRequired = func() *Error {
81 return &Error{
82 ErrorType: InteractionRequired,
83 }
84 }
85 ErrLoginRequired = func() *Error {
86 return &Error{
87 ErrorType: LoginRequired,
88 }
89 }
90 ErrRequestNotSupported = func() *Error {
91 return &Error{
92 ErrorType: RequestNotSupported,
93 }
94 }
95
96 // Device Access Token errors:
97 ErrAuthorizationPending = func() *Error {
98 return &Error{
99 ErrorType: AuthorizationPending,
100 Description: "The client SHOULD repeat the access token request to the token endpoint, after interval from device authorization response.",
101 }
102 }
103 ErrSlowDown = func() *Error {
104 return &Error{
105 ErrorType: SlowDown,
106 Description: "Polling should continue, but the interval MUST be increased by 5 seconds for this and all subsequent requests.",
107 }
108 }
109 ErrAccessDenied = func() *Error {
110 return &Error{
111 ErrorType: AccessDenied,
112 Description: "The authorization request was denied.",
113 }
114 }
115 ErrExpiredDeviceCode = func() *Error {
116 return &Error{
117 ErrorType: ExpiredToken,
118 Description: "The \"device_code\" has expired.",
119 }
120 }
121
122 // Token exchange error
123 ErrInvalidTarget = func() *Error {
124 return &Error{
125 ErrorType: InvalidTarget,
126 Description: "The requested audience or target is invalid.",
127 }
128 }
129 )
130
131 type Error struct {
132 Parent error `json:"-" schema:"-"`
133 ErrorType errorType `json:"error" schema:"error"`
134 Description string `json:"error_description,omitempty" schema:"error_description,omitempty"`
135 State string `json:"state,omitempty" schema:"state,omitempty"`
136 SessionState string `json:"session_state,omitempty" schema:"session_state,omitempty"`
137 redirectDisabled bool `schema:"-"`
138 returnParent bool `schema:"-"`
139 }
140
141 func (e *Error) MarshalJSON() ([]byte, error) {
142 m := struct {
143 Error errorType `json:"error"`
144 ErrorDescription string `json:"error_description,omitempty"`
145 State string `json:"state,omitempty"`
146 SessionState string `json:"session_state,omitempty"`
147 Parent string `json:"parent,omitempty"`
148 }{
149 Error: e.ErrorType,
150 ErrorDescription: e.Description,
151 State: e.State,
152 SessionState: e.SessionState,
153 }
154 if e.returnParent {
155 m.Parent = e.Parent.Error()
156 }
157 return json.Marshal(m)
158 }
159
160 func (e *Error) Error() string {
161 message := "ErrorType=" + string(e.ErrorType)
162 if e.Description != "" {
163 message += " Description=" + e.Description
164 }
165 if e.Parent != nil {
166 message += " Parent=" + e.Parent.Error()
167 }
168 return message
169 }
170
171 func (e *Error) Unwrap() error {
172 return e.Parent
173 }
174
175 func (e *Error) Is(target error) bool {
176 t, ok := target.(*Error)
177 if !ok {
178 return false
179 }
180 return e.ErrorType == t.ErrorType &&
181 (e.Description == t.Description || t.Description == "") &&
182 (e.State == t.State || t.State == "") &&
183 (e.SessionState == t.SessionState || t.SessionState == "")
184 }
185
186 func (e *Error) WithParent(err error) *Error {
187 e.Parent = err
188 return e
189 }
190
191 // WithReturnParentToClient allows returning the set parent error to the HTTP client.
192 // Currently, it only supports setting the parent inside JSON responses, not redirect URLs.
193 // As Go errors don't unmarshal well, only the marshaller is implemented for the moment.
194 //
195 // Warning: parent errors may contain sensitive data or unwanted details about the server status.
196 // Also, the `parent` field is not a standard error field and might confuse certain clients
197 // that require fully compliant responses.
198 func (e *Error) WithReturnParentToClient(b bool) *Error {
199 e.returnParent = b
200 return e
201 }
202
203 func (e *Error) WithDescription(desc string, args ...any) *Error {
204 e.Description = fmt.Sprintf(desc, args...)
205 return e
206 }
207
208 func (e *Error) IsRedirectDisabled() bool {
209 return e.redirectDisabled
210 }
211
212 // DefaultToServerError checks if the error is an Error
213 // if not the provided error will be wrapped into a ServerError
214 func DefaultToServerError(err error, description string) *Error {
215 oidcErr := new(Error)
216 if ok := errors.As(err, &oidcErr); ok {
217 clone := *oidcErr
218 return &clone
219 }
220 switch {
221 case errors.Is(err, ErrParse):
222 oidcErr = ErrInvalidRequest().WithParent(err).WithDescription("%s", description)
223 case errors.Is(err, ErrIssuerInvalid),
224 errors.Is(err, ErrSubjectMissing),
225 errors.Is(err, ErrSubjectInvalid),
226 errors.Is(err, ErrAudience),
227 errors.Is(err, ErrAzpMissing),
228 errors.Is(err, ErrAzpInvalid),
229 errors.Is(err, ErrSignatureMissing),
230 errors.Is(err, ErrSignatureMultiple),
231 errors.Is(err, ErrSignatureUnsupportedAlg),
232 errors.Is(err, ErrSignatureInvalidPayload),
233 errors.Is(err, ErrSignatureInvalid),
234 errors.Is(err, ErrExpired),
235 errors.Is(err, ErrIatMissing),
236 errors.Is(err, ErrIatInFuture),
237 errors.Is(err, ErrIatToOld),
238 errors.Is(err, ErrNonceInvalid),
239 errors.Is(err, ErrAcrInvalid),
240 errors.Is(err, ErrAuthTimeNotPresent),
241 errors.Is(err, ErrAuthTimeToOld),
242 errors.Is(err, ErrAtHash):
243 oidcErr = ErrInvalidGrant().WithParent(err).WithDescription("%s", description)
244 case errors.Is(err, ErrDiscoveryFailed):
245 fallthrough
246 default:
247 oidcErr = ErrServerError().WithParent(err).WithDescription("%s", description)
248 }
249 return oidcErr
250 }
251
252 func (e *Error) LogLevel() slog.Level {
253 level := slog.LevelWarn
254 if e.ErrorType == ServerError {
255 level = slog.LevelError
256 }
257 if e.ErrorType == AuthorizationPending {
258 level = slog.LevelInfo
259 }
260 return level
261 }
262
263 func (e *Error) LogValue() slog.Value {
264 attrs := make([]slog.Attr, 0, 5)
265 if e.Parent != nil {
266 attrs = append(attrs, slog.Any("parent", e.Parent))
267 }
268 if e.Description != "" {
269 attrs = append(attrs, slog.String("description", e.Description))
270 }
271 if e.ErrorType != "" {
272 attrs = append(attrs, slog.String("type", string(e.ErrorType)))
273 }
274 if e.State != "" {
275 attrs = append(attrs, slog.String("state", e.State))
276 }
277 if e.SessionState != "" {
278 attrs = append(attrs, slog.String("session_state", e.SessionState))
279 }
280 if e.redirectDisabled {
281 attrs = append(attrs, slog.Bool("redirect_disabled", e.redirectDisabled))
282 }
283 return slog.GroupValue(attrs...)
284 }