-
Notifications
You must be signed in to change notification settings - Fork 126
/
middleware.go
213 lines (154 loc) · 4.82 KB
/
middleware.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package authn
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
"github.com/hatchet-dev/hatchet/api/v1/server/middleware"
"github.com/hatchet-dev/hatchet/api/v1/server/middleware/redirect"
"github.com/hatchet-dev/hatchet/internal/config/server"
"github.com/hatchet-dev/hatchet/internal/repository/prisma/db"
)
type AuthN struct {
config *server.ServerConfig
helpers *SessionHelpers
l *zerolog.Logger
}
func NewAuthN(config *server.ServerConfig) *AuthN {
return &AuthN{
config: config,
helpers: NewSessionHelpers(config),
l: config.Logger,
}
}
func (a *AuthN) Middleware(r *middleware.RouteInfo) echo.HandlerFunc {
return func(c echo.Context) error {
err := a.authenticate(c, r)
if err != nil {
return err
}
return nil
}
}
func (a *AuthN) authenticate(c echo.Context, r *middleware.RouteInfo) error {
// if security is optional, continue
if r.Security.IsOptional() {
return nil
}
if r.Security.NoAuth() {
return a.handleNoAuth(c)
}
var err error
if r.Security.CookieAuth() {
err = a.handleCookieAuth(c)
c.Set("auth_strategy", "cookie")
}
if err != nil && !r.Security.BearerAuth() {
return err
}
if err != nil && r.Security.BearerAuth() {
err = a.handleBearerAuth(c)
c.Set("auth_strategy", "bearer")
if err == nil {
return nil
}
}
return err
}
func (a *AuthN) handleNoAuth(c echo.Context) error {
store := a.config.SessionStore
session, err := store.Get(c.Request(), store.GetName())
if err != nil {
a.l.Debug().Err(err).Msg("error getting session")
return redirect.GetRedirectWithError(c, a.l, err, "Could not log in. Please try again and make sure cookies are enabled.")
}
if auth, ok := session.Values["authenticated"].(bool); ok && auth {
a.l.Debug().Msgf("user was authenticated when no security schemes permit auth")
return redirect.GetRedirectNoError(c, a.config.Runtime.ServerURL)
}
// set unauthenticated session in context
c.Set("session", session)
return nil
}
func (a *AuthN) handleCookieAuth(c echo.Context) error {
forbidden := echo.NewHTTPError(http.StatusForbidden, "Please provide valid credentials")
store := a.config.SessionStore
session, err := store.Get(c.Request(), store.GetName())
if err != nil {
err = a.helpers.SaveUnauthenticated(c)
if err != nil {
a.l.Error().Err(err).Msg("error saving unauthenticated session")
return fmt.Errorf("error saving unauthenticated session")
}
return forbidden
}
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
// if the session is new, make sure we write a Set-Cookie header to the response
if session.IsNew {
if err := saveNewSession(c, session); err != nil {
a.l.Error().Err(err).Msg("error saving unauthenticated session")
return fmt.Errorf("error saving unauthenticated session")
}
c.Set("session", session)
}
return forbidden
}
// read the user id in the token
userID, ok := session.Values["user_id"].(string)
if !ok {
a.l.Debug().Msgf("could not cast user_id to string")
return forbidden
}
user, err := a.config.APIRepository.User().GetUserByID(userID)
if err != nil {
a.l.Debug().Err(err).Msg("error getting user by id")
if errors.Is(err, db.ErrNotFound) {
return forbidden
}
return fmt.Errorf("error getting user by id: %w", err)
}
// set the user and session in context
c.Set("user", user)
c.Set("session", session)
return nil
}
func (a *AuthN) handleBearerAuth(c echo.Context) error {
forbidden := echo.NewHTTPError(http.StatusForbidden, "Please provide valid credentials")
// a tenant id must exist in the context in order for the bearer auth to succeed, since
// these tokens are tenant-scoped
queriedTenant, ok := c.Get("tenant").(*db.TenantModel)
if !ok {
a.l.Debug().Msgf("tenant not found in context")
return fmt.Errorf("tenant not found in context")
}
token, err := getBearerTokenFromRequest(c.Request())
if err != nil {
a.l.Debug().Err(err).Msg("error getting bearer token from request")
return forbidden
}
// Validate the token.
tenantId, err := a.config.Auth.JWTManager.ValidateTenantToken(c.Request().Context(), token)
if err != nil {
a.l.Debug().Err(err).Msg("error validating tenant token")
return forbidden
}
// Verify that the tenant id which exists in the context is the same as the tenant id
// in the token.
if queriedTenant.ID != tenantId {
a.l.Debug().Msgf("tenant id in token does not match tenant id in context")
return forbidden
}
return nil
}
var errInvalidAuthHeader = fmt.Errorf("invalid authorization header in request")
func getBearerTokenFromRequest(r *http.Request) (string, error) {
reqToken := r.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer")
if len(splitToken) != 2 {
return "", errInvalidAuthHeader
}
reqToken = strings.TrimSpace(splitToken[1])
return reqToken, nil
}