/
error.go
145 lines (116 loc) · 4.07 KB
/
error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package handler
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5/middleware"
log "github.com/sirupsen/logrus"
"github.com/nais/wonderwall/pkg/cookie"
"github.com/nais/wonderwall/pkg/handler/templates"
mw "github.com/nais/wonderwall/pkg/middleware"
"github.com/nais/wonderwall/pkg/openid"
"github.com/nais/wonderwall/pkg/router/paths"
urlpkg "github.com/nais/wonderwall/pkg/url"
)
const (
// MaxAutoRetryAttempts is the maximum number of times to automatically redirect the user to retry their original request.
MaxAutoRetryAttempts = 3
)
type Page struct {
CorrelationID string
RetryURI string
}
func (s *Standalone) InternalError(w http.ResponseWriter, r *http.Request, cause error) {
s.respondError(w, r, http.StatusInternalServerError, cause, log.ErrorLevel)
}
func (s *Standalone) BadRequest(w http.ResponseWriter, r *http.Request, cause error) {
s.respondError(w, r, http.StatusBadRequest, cause, log.ErrorLevel)
}
func (s *Standalone) Unauthorized(w http.ResponseWriter, r *http.Request, cause error) {
s.respondError(w, r, http.StatusUnauthorized, cause, log.WarnLevel)
}
// Retry returns a URI that should retry the desired route that failed.
// It only handles the routes exposed by Wonderwall, i.e. `/oauth2/*`. As these routes
// are related to the authentication flow, we default to redirecting back to the handled
// `/oauth2/login` endpoint unless the original request attempted to reach the logout-flow.
func (s *Standalone) Retry(r *http.Request, loginCookie *openid.LoginCookie) string {
requestPath := r.URL.Path
ingressPath := s.GetPath(r)
// redirect failed logout callbacks to logout
if strings.HasSuffix(requestPath, paths.OAuth2+paths.LogoutCallback) {
return ingressPath + paths.OAuth2 + paths.Logout
}
// redirect failed login callbacks to login with original referer as the redirect_uri
if strings.HasSuffix(requestPath, paths.OAuth2+paths.LoginCallback) {
redirect := s.Redirect.Canonical(r)
if loginCookie != nil && len(loginCookie.Referer) > 0 {
redirect = s.Redirect.Clean(r, loginCookie.Referer)
}
return urlpkg.LoginRelative(ingressPath, redirect)
}
u := *r.URL
u.Host = ""
u.Scheme = ""
return u.String()
}
func (s *Standalone) respondError(w http.ResponseWriter, r *http.Request, statusCode int, cause error, level log.Level) {
logger := mw.LogEntryFrom(r)
msg := "error in route: %+v"
incrementRetryAttempt(w, r, s.GetCookieOptions(r))
attempts, ok := getRetryAttempts(r)
if !ok || attempts < MaxAutoRetryAttempts {
loginCookie, err := openid.GetLoginCookie(r, s.Crypter)
if err != nil {
loginCookie = nil
}
retryUri := s.Retry(r, loginCookie)
logger.Infof(msg, cause)
logger.Infof("errorhandler: auto-retry (attempt %d/%d) redirecting to %q...", attempts+1, MaxAutoRetryAttempts, retryUri)
http.Redirect(w, r, retryUri, http.StatusTemporaryRedirect)
return
}
if level == log.WarnLevel || errors.Is(cause, context.Canceled) {
logger.Warnf(msg, cause)
} else {
logger.Errorf(msg, cause)
}
logger.Infof("errorhandler: maximum retry attempts exceeded; executing error template...")
s.defaultErrorResponse(w, r, statusCode)
}
func (s *Standalone) defaultErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int) {
w.WriteHeader(statusCode)
loginCookie, err := openid.GetLoginCookie(r, s.Crypter)
if err != nil {
loginCookie = nil
}
errorPage := Page{
CorrelationID: middleware.GetReqID(r.Context()),
RetryURI: s.Retry(r, loginCookie),
}
err = templates.ErrorTemplate.Execute(w, errorPage)
if err != nil {
mw.LogEntryFrom(r).Errorf("errorhandler: executing error template: %+v", err)
}
}
func getRetryAttempts(r *http.Request) (int, bool) {
c, err := cookie.Get(r, cookie.Retry)
if err != nil {
return 0, false
}
val, err := strconv.Atoi(c.Value)
if err != nil {
return 0, false
}
return val, true
}
func incrementRetryAttempt(w http.ResponseWriter, r *http.Request, opts cookie.Options) {
val := 1
prev, ok := getRetryAttempts(r)
if ok {
val = prev + 1
}
c := cookie.Make(cookie.Retry, strconv.Itoa(val), opts)
cookie.Set(w, c)
}