-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
auth.go
255 lines (213 loc) · 6.82 KB
/
auth.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package auth
import (
"context"
"database/sql"
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/smartcontractkit/chainlink/v2/core/auth"
"github.com/smartcontractkit/chainlink/v2/core/bridges"
clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions"
"github.com/smartcontractkit/chainlink/v2/core/static"
)
const (
// APIKey is the header name for the API token identifier for user authentication.
APIKey = "X-API-KEY"
// APISecret is the header name for the API token secret for user authentication.
APISecret = "X-API-SECRET"
// SessionName is the session name
SessionName = "clsession"
// SessionIDKey is the session ID key in the session map
SessionIDKey = "clsession_id"
// SessionUserKey is the User key in the session map
SessionUserKey = "user"
// SessionExternalInitiatorKey is the External Initiator key in the session map
SessionExternalInitiatorKey = "external_initiator"
)
// Authenticator defines the interface to authenticate requests against a
// datastore.
type Authenticator interface {
AuthorizedUserWithSession(ctx context.Context, sessionID string) (clsessions.User, error)
FindExternalInitiator(ctx context.Context, eia *auth.Token) (*bridges.ExternalInitiator, error)
FindUser(ctx context.Context, email string) (clsessions.User, error)
FindUserByAPIToken(ctx context.Context, apiToken string) (clsessions.User, error)
}
// authMethod defines a method which can be used to authenticate a request. This
// can be implemented according to your authentication method (i.e by session,
// token, etc)
type authMethod func(ctx *gin.Context, store Authenticator) error
// AuthenticateBySession authenticates the request by the session cookie.
//
// Implements authMethod
func AuthenticateBySession(c *gin.Context, authr Authenticator) error {
ctx := c.Request.Context()
session := sessions.Default(c)
sessionID, ok := session.Get(SessionIDKey).(string)
if !ok {
return auth.ErrorAuthFailed
}
user, err := authr.AuthorizedUserWithSession(ctx, sessionID)
if err != nil {
return err
}
c.Set(SessionUserKey, &user)
return nil
}
var _ authMethod = AuthenticateBySession
// AuthenticateByToken authenticates a User by their API token.
//
// Implements authMethod
func AuthenticateByToken(c *gin.Context, authr Authenticator) error {
ctx := c.Request.Context()
token := &auth.Token{
AccessKey: c.GetHeader(APIKey),
Secret: c.GetHeader(APISecret),
}
if token.AccessKey == "" {
return auth.ErrorAuthFailed
}
if token.AccessKey == "" {
return auth.ErrorAuthFailed
}
// We need to first load the user row so we can compare tokens using the stored salt
user, err := authr.FindUserByAPIToken(ctx, token.AccessKey)
if err != nil {
if errors.Is(err, sql.ErrNoRows) || errors.Is(err, clsessions.ErrUserSessionExpired) {
return auth.ErrorAuthFailed
}
return err
}
ok, err := clsessions.AuthenticateUserByToken(token, &user)
if err != nil {
return err
}
if !ok {
return auth.ErrorAuthFailed
}
c.Set(SessionUserKey, &user)
return nil
}
var _ authMethod = AuthenticateByToken
// AuthenticateExternalInitiator authenticates an external initiator request.
//
// Implements authMethod
func AuthenticateExternalInitiator(c *gin.Context, store Authenticator) error {
ctx := c.Request.Context()
eia := &auth.Token{
AccessKey: c.GetHeader(static.ExternalInitiatorAccessKeyHeader),
Secret: c.GetHeader(static.ExternalInitiatorSecretHeader),
}
ei, err := store.FindExternalInitiator(ctx, eia)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return auth.ErrorAuthFailed
}
return errors.Wrap(err, "finding external initiator")
}
ok, err := bridges.AuthenticateExternalInitiator(eia, ei)
if err != nil {
return err
}
if !ok {
return auth.ErrorAuthFailed
}
c.Set(SessionExternalInitiatorKey, ei)
// External initiator endpoints (wrapped with AuthenticateExternalInitiator) inherently assume the role
// of 'run' (required to trigger job runs)
c.Set(SessionExternalInitiatorKey, ei)
c.Set(SessionUserKey, &clsessions.User{Role: clsessions.UserRoleRun})
return nil
}
var _ authMethod = AuthenticateExternalInitiator
// Authenticate is middleware which authenticates the request by attempting to
// authenticate using all the provided methods.
func Authenticate(store Authenticator, methods ...authMethod) gin.HandlerFunc {
return func(c *gin.Context) {
var err error
for _, method := range methods {
err = method(c, store)
if !errors.Is(err, auth.ErrorAuthFailed) {
break
}
}
if err != nil {
c.Abort()
jsonAPIError(c, http.StatusUnauthorized, err)
return
}
c.Next()
}
}
// GetAuthenticatedUser extracts the authentication user from the context.
func GetAuthenticatedUser(c *gin.Context) (*clsessions.User, bool) {
obj, ok := c.Get(SessionUserKey)
if !ok {
return nil, false
}
user, ok := obj.(*clsessions.User)
return user, ok
}
// GetAuthenticatedExternalInitiator extracts the external initiator from the
// context.
func GetAuthenticatedExternalInitiator(c *gin.Context) (*bridges.ExternalInitiator, bool) {
obj, ok := c.Get(SessionExternalInitiatorKey)
if !ok {
return nil, false
}
return obj.(*bridges.ExternalInitiator), ok
}
// RequiresRunRole extracts the user object from the context, and asserts the user's role is at least
// 'run'
func RequiresRunRole(handler func(*gin.Context)) func(*gin.Context) {
return func(c *gin.Context) {
user, ok := GetAuthenticatedUser(c)
if !ok {
c.Abort()
jsonAPIError(c, http.StatusUnauthorized, errors.New("not a valid session"))
return
}
if user.Role == clsessions.UserRoleView {
c.Abort()
jsonAPIError(c, http.StatusUnauthorized, errors.New("Unauthorized"))
return
}
handler(c)
}
}
// RequiresEditRole extracts the user object from the context, and asserts the user's role is at least
// 'edit'
func RequiresEditRole(handler func(*gin.Context)) func(*gin.Context) {
return func(c *gin.Context) {
user, ok := GetAuthenticatedUser(c)
if !ok {
c.Abort()
jsonAPIError(c, http.StatusUnauthorized, errors.New("not a valid session"))
return
}
if user.Role == clsessions.UserRoleView || user.Role == clsessions.UserRoleRun {
c.Abort()
jsonAPIError(c, http.StatusUnauthorized, errors.New("Unauthorized"))
return
}
handler(c)
}
}
// RequiresAdminRole extracts the user object from the context, and asserts the user's role is 'admin'
func RequiresAdminRole(handler func(*gin.Context)) func(*gin.Context) {
return func(c *gin.Context) {
user, ok := GetAuthenticatedUser(c)
if !ok {
c.Abort()
jsonAPIError(c, http.StatusUnauthorized, errors.New("not a valid session"))
return
}
if user.Role != clsessions.UserRoleAdmin {
c.Abort()
addForbiddenErrorHeaders(c, "admin", string(user.Role), user.Email)
jsonAPIError(c, http.StatusForbidden, errors.New("Forbidden"))
return
}
handler(c)
}
}