Debian Codegraph @

pkg/op/error.go

raw
1 package op
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "log/slog"
8 "net/http"
9
10 httphelper "github.com/zitadel/oidc/v3/pkg/http"
11 "github.com/zitadel/oidc/v3/pkg/oidc"
12 )
13
14 type ErrAuthRequest interface {
15 GetRedirectURI() string
16 GetResponseType() oidc.ResponseType
17 GetState() string
18 }
19
20 // LogAuthRequest is an optional interface,
21 // that allows logging AuthRequest fields.
22 // If the AuthRequest does not implement this interface,
23 // no details shall be printed to the logs.
24 type LogAuthRequest interface {
25 ErrAuthRequest
26 slog.LogValuer
27 }
28
29 func AuthRequestError(w http.ResponseWriter, r *http.Request, authReq ErrAuthRequest, err error, authorizer Authorizer) {
30 e := oidc.DefaultToServerError(err, err.Error())
31 args := []any{slog.Any("oidc_error", e)}
32
33 if authReq == nil {
34 slog.Log(r.Context(), e.LogLevel(), "auth request", args...)
35 http.Error(w, err.Error(), http.StatusBadRequest)
36 return
37 }
38
39 if logAuthReq, ok := authReq.(LogAuthRequest); ok {
40 args = append(args, slog.Any("auth_request", logAuthReq))
41 }
42
43 if authReq.GetRedirectURI() == "" || e.IsRedirectDisabled() {
44 slog.Log(r.Context(), e.LogLevel(), "auth request: not redirecting", args...)
45 http.Error(w, e.Description, http.StatusBadRequest)
46 return
47 }
48 e.State = authReq.GetState()
49 var sessionState string
50 authRequestSessionState, ok := authReq.(AuthRequestSessionState)
51 if ok {
52 sessionState = authRequestSessionState.GetSessionState()
53 }
54 e.SessionState = sessionState
55 var responseMode oidc.ResponseMode
56 if rm, ok := authReq.(interface{ GetResponseMode() oidc.ResponseMode }); ok {
57 responseMode = rm.GetResponseMode()
58 }
59 url, err := AuthResponseURL(authReq.GetRedirectURI(), authReq.GetResponseType(), responseMode, e, authorizer.Encoder())
60 if err != nil {
61 args = append(args, slog.Any("error", err))
62 slog.ErrorContext(r.Context(), "auth response URL", args...)
63 http.Error(w, err.Error(), http.StatusBadRequest)
64 return
65 }
66 slog.Log(r.Context(), e.LogLevel(), "auth request", args...)
67 http.Redirect(w, r, url, http.StatusFound)
68 }
69
70 func RequestError(w http.ResponseWriter, r *http.Request, err error, _ *slog.Logger) {
71 e := oidc.DefaultToServerError(err, err.Error())
72 status := http.StatusBadRequest
73 if e.ErrorType == oidc.InvalidClient {
74 status = http.StatusUnauthorized
75 }
76 if e.ErrorType == oidc.ServerError {
77 status = http.StatusInternalServerError
78 }
79 slog.Log(r.Context(), e.LogLevel(), "request error", slog.Any("oidc_error", e))
80 httphelper.MarshalJSONWithStatus(w, e, status)
81 }
82
83 // TryErrorRedirect tries to handle an error by redirecting a client.
84 // If this attempt fails, an error is returned that must be returned
85 // to the client instead.
86 func TryErrorRedirect(ctx context.Context, authReq ErrAuthRequest, parent error, encoder httphelper.Encoder, _ *slog.Logger) (*Redirect, error) {
87 e := oidc.DefaultToServerError(parent, parent.Error())
88 args := []any{slog.Any("oidc_error", e)}
89
90 if authReq == nil {
91 slog.Log(ctx, e.LogLevel(), "auth request", args...)
92 return nil, AsStatusError(e, http.StatusBadRequest)
93 }
94
95 if logAuthReq, ok := authReq.(LogAuthRequest); ok {
96 args = append(args, slog.Any("auth_request", logAuthReq))
97 }
98
99 if authReq.GetRedirectURI() == "" || e.IsRedirectDisabled() {
100 slog.Log(ctx, e.LogLevel(), "auth request: not redirecting", args...)
101 return nil, AsStatusError(e, http.StatusBadRequest)
102 }
103
104 e.State = authReq.GetState()
105 var sessionState string
106 authRequestSessionState, ok := authReq.(AuthRequestSessionState)
107 if ok {
108 sessionState = authRequestSessionState.GetSessionState()
109 }
110 e.SessionState = sessionState
111 var responseMode oidc.ResponseMode
112 if rm, ok := authReq.(interface{ GetResponseMode() oidc.ResponseMode }); ok {
113 responseMode = rm.GetResponseMode()
114 }
115 url, err := AuthResponseURL(authReq.GetRedirectURI(), authReq.GetResponseType(), responseMode, e, encoder)
116 if err != nil {
117 args = append(args, slog.Any("error", err))
118 slog.ErrorContext(ctx, "auth response URL", args...)
119 return nil, AsStatusError(err, http.StatusBadRequest)
120 }
121 args = append(args, slog.String("url", url))
122 slog.Log(ctx, e.LogLevel(), "auth request redirect", args...)
123 return NewRedirect(url), nil
124 }
125
126 // StatusError wraps an error with an HTTP status code.
127 // The status code is passed to the handler's writer.
128 type StatusError struct {
129 parent error
130 statusCode int
131 }
132
133 // NewStatusError sets the parent and statusCode to a new StatusError.
134 // It is recommended for parent to be an [oidc.Error].
135 //
136 // Typically, implementations should only use this to signal something
137 // very specific, like an internal server error.
138 // If a returned error is not a StatusError, the framework
139 // will set a statusCode based on what the standard specifies,
140 // which is [http.StatusBadRequest] for most of the time.
141 // If the encountered error can be clearly described by an [oidc.Error],
142 // do not use this function, as it might break standard rules!
143 func NewStatusError(parent error, statusCode int) StatusError {
144 return StatusError{
145 parent: parent,
146 statusCode: statusCode,
147 }
148 }
149
150 // AsStatusError unwraps a StatusError from err
151 // and returns it unmodified if found.
152 // If no StatusError was found, a new one is returned
153 // with statusCode set to it as a default.
154 func AsStatusError(err error, statusCode int) (target StatusError) {
155 if errors.As(err, &target) {
156 return target
157 }
158 return NewStatusError(err, statusCode)
159 }
160
161 func (e StatusError) Error() string {
162 return fmt.Sprintf("%s: %s", http.StatusText(e.statusCode), e.parent.Error())
163 }
164
165 func (e StatusError) Unwrap() error {
166 return e.parent
167 }
168
169 func (e StatusError) Is(err error) bool {
170 var target StatusError
171 if !errors.As(err, &target) {
172 return false
173 }
174 return errors.Is(e.parent, target.parent) &&
175 e.statusCode == target.statusCode
176 }
177
178 // WriteError asserts for a [StatusError] containing an [oidc.Error].
179 // If no `StatusError` is found, the status code will default to [http.StatusBadRequest].
180 // If no `oidc.Error` was found in the parent, the error type defaults to [oidc.ServerError].
181 // When there was no `StatusError` and the `oidc.Error` is of type `oidc.ServerError`,
182 // the status code will be set to [http.StatusInternalServerError]
183 func WriteError(w http.ResponseWriter, r *http.Request, err error, _ *slog.Logger) {
184 var statusError StatusError
185 if errors.As(err, &statusError) {
186 writeError(w, r,
187 oidc.DefaultToServerError(statusError.parent, statusError.parent.Error()),
188 statusError.statusCode,
189 )
190 return
191 }
192 statusCode := http.StatusBadRequest
193 e := oidc.DefaultToServerError(err, err.Error())
194 if e.ErrorType == oidc.ServerError {
195 statusCode = http.StatusInternalServerError
196 }
197 writeError(w, r, e, statusCode)
198 }
199
200 func writeError(w http.ResponseWriter, r *http.Request, err *oidc.Error, statusCode int) {
201 slog.Log(r.Context(), err.LogLevel(), "request error", slog.Any("oidc_error", err), slog.Int("status_code", statusCode))
202 httphelper.MarshalJSONWithStatus(w, err, statusCode)
203 }