-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
448 lines (424 loc) · 14.2 KB
/
Copy pathhandlers.go
File metadata and controls
448 lines (424 loc) · 14.2 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package main
// HTTP handlers module
//
// Copyright (c) 2023 - Valentin Kuznetsov <vkuznet@gmail.com>
//
import (
"embed"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"log"
"net/http"
"strings"
"time"
authz "github.com/CHESSComputing/golib/authz"
srvConfig "github.com/CHESSComputing/golib/config"
server "github.com/CHESSComputing/golib/server"
services "github.com/CHESSComputing/golib/services"
utils "github.com/CHESSComputing/golib/utils"
"github.com/gin-gonic/gin"
oauth2 "github.com/go-oauth2/oauth2/v4"
credentials "gopkg.in/jcmturner/gokrb5.v7/credentials"
)
type DocsParams struct {
Login string `json:"login" uri:"login" binding:"required"`
}
type UserParams struct {
Login string `json:"login" uri:"login" binding:"required"`
Password string `json:"password" uri:"password" binding:"required"`
}
// content is our static web server content.
//
//go:embed static
var StaticFs embed.FS
// helper function to handle http server errors
func handleError(c *gin.Context, msg string, err error) {
w := c.Writer
log.Printf("ERROR: %v\n", err)
tmpl := server.MakeTmpl(StaticFs, "Error")
tmpl["Message"] = strings.ToTitle(msg)
page := server.TmplPage(StaticFs, "error.tmpl", tmpl)
w.WriteHeader(http.StatusOK)
w.Write([]byte(page))
}
// helper function to get valid token
func validToken(c *gin.Context, user, scope string) (oauth2.GrantType, *oauth2.TokenGenerateRequest, error) {
var gt oauth2.GrantType
// for grant type we must use AuthorizationCode which force creation of access token with valid scope
// gt = oauth2.AuthorizationCode
gt = oauth2.ClientCredentials
// gt = oauth2.PasswordCredentials
duration := srvConfig.Config.Authz.TokenExpires
tgr := &oauth2.TokenGenerateRequest{
ClientID: srvConfig.Config.Authz.ClientID,
ClientSecret: srvConfig.Config.Authz.ClientSecret,
UserID: user,
Scope: scope,
AccessTokenExp: time.Duration(duration),
Request: c.Request,
}
return gt, tgr, nil
}
// helper function to generate valid token map
func tokenMap(user, scope, kind, app string, expires int64) (authz.TokenMap, error) {
auser := authz.AuthUser{
Name: user,
Scope: scope,
Kind: "client_credentials",
App: "Authz service",
}
if kind != "" {
auser.Kind = kind
}
duration := srvConfig.Config.Authz.TokenExpires
if expires != 0 {
auser.Expires = expires
}
if duration == 0 {
auser.Expires = 7200
}
// service_user is set when we perform inter-service requests between FOXDEN servies
if user != "" && user != "service_user" && kind != "trusted_client" {
// only check user attributes if user name is provided
if fuser, err := _foxdenUser.Get(user); err == nil {
auser.Btrs = fuser.Btrs
auser.Groups = fuser.Groups
auser.Scopes = fuser.Scopes
}
}
return auser.TokenMap()
}
// AttributesHandler provides access to GET /attrs end-point
func AttributesHandler(c *gin.Context) {
r := c.Request
user := r.URL.Query().Get("user")
if fuser, err := _foxdenUser.Get(user); err == nil {
c.JSON(http.StatusOK, fuser)
return
}
rec := services.Response("Authz", http.StatusBadRequest, services.CredentialsError, errors.New("No user attributes"))
c.JSON(http.StatusBadRequest, rec)
}
// TokenHandler provides access to GET /oauth/token end-point
func TokenHandler(c *gin.Context) {
r := c.Request
scope := r.URL.Query().Get("scope")
user := r.URL.Query().Get("user")
clientId := r.URL.Query().Get("client_id")
clientSecret := r.URL.Query().Get("client_secret")
if user == "" && clientId == srvConfig.Config.Authz.ClientID && clientSecret == srvConfig.Config.Authz.ClientSecret {
user = "service_user"
}
tmap, err := tokenMap(user, scope, "client_credentials", "Authz", 0)
if Verbose > 2 {
log.Println("token map", tmap, err)
}
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
c.JSON(http.StatusOK, tmap)
}
// LoginHandler handlers Login requests
func LoginHandler(w http.ResponseWriter, r *http.Request) {
// func LoginHandler(c *gin.Context) {
// w := c.Writer
// r := c.Request
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
tmpl := server.MakeTmpl(StaticFs, "Login")
tmpl["Title"] = "Login"
tmpl["Base"] = srvConfig.Config.Frontend.WebServer.Base
tmpl["ServerInfo"] = srvConfig.Info()
top := server.TmplPage(StaticFs, "header.tmpl", tmpl)
bottom := server.TmplPage(StaticFs, "footer.tmpl", tmpl)
tmpl["StartTime"] = time.Now().Unix()
page := server.TmplPage(StaticFs, "login.tmpl", tmpl)
w.WriteHeader(http.StatusOK)
w.Write([]byte(top + page + bottom))
}
// ClientAuthHandler provides kerberos authentication for CLI requests
// func ClientAuthHandler(w http.ResponseWriter, r *http.Request) {
func ClientAuthHandler(c *gin.Context) {
r := c.Request
// in testmode we do not go through authorization process and issue token right away
if srvConfig.Config.Authz.TestMode {
tmap, err := tokenMap("testuser", "read+write", "testmode", "Authz", 3600)
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
c.JSON(http.StatusOK, tmap)
return
}
var rec authz.Kerberos
defer r.Body.Close()
data, err := io.ReadAll(r.Body)
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.ReaderError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
err = json.Unmarshal(data, &rec)
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.UnmarshalError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
creds, err := rec.Credentials()
if err != nil || creds.Expired() {
rec := services.Response("Authz", http.StatusBadRequest, services.CredentialsError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
if creds.Expired() {
rec := services.Response("Authz", http.StatusBadRequest, services.CredentialsError, errors.New("Expired token"))
c.JSON(http.StatusBadRequest, rec)
return
}
if creds.UserName() != rec.User {
rec := services.Response("Authz", http.StatusBadRequest, services.CredentialsError, errors.New("User credentials error"))
c.JSON(http.StatusBadRequest, rec)
return
}
/*
// check LDAP group for this user
if srvConfig.Config.Authz.CheckLDAP {
entry, err := ldapCache.Search(srvConfig.Config.LDAP.Login, srvConfig.Config.LDAP.Password, rec.User)
if err != nil {
msg := fmt.Sprintf("No LDAP entry, error: %v", err)
rec := services.Response("Authz", http.StatusBadRequest, services.LDAPSearchError, errors.New(msg))
c.JSON(http.StatusBadRequest, rec)
return
}
group := "" // by default all users will have right access privilege
if strings.Contains(rec.Scope, "write") {
group = srvConfig.Config.AccessRules.WriteGroup
} else if strings.Contains(rec.Scope, "delete") {
group = srvConfig.Config.AccessRules.AdminGroup
}
if group != "" && !entry.Belong(group) {
msg := fmt.Sprintf("User %s with scope %s is not allowed", rec.User, rec.Scope)
rec := services.Response("Authz", http.StatusBadRequest, services.LDAPGroupError, errors.New(msg))
c.JSON(http.StatusBadRequest, rec)
return
}
}
*/
// check user privileges
if fuser, err := _foxdenUser.Get(rec.User); err == nil {
group := "" // by default all users will have right access privilege
if strings.Contains(rec.Scope, "write") {
group = srvConfig.Config.AccessRules.WriteGroup
} else if strings.Contains(rec.Scope, "delete") {
group = srvConfig.Config.AccessRules.AdminGroup
}
if group != "" && !utils.InList(group, fuser.Groups) {
msg := fmt.Sprintf("User %s with scope %s is not allowed, user btrs=%+v groups=%+v", rec.User, rec.Scope, fuser.Btrs, fuser.Groups)
rec := services.Response("Authz", http.StatusBadRequest, services.LDAPGroupError, errors.New(msg))
c.JSON(http.StatusBadRequest, rec)
return
}
} else {
msg := fmt.Sprintf("No foxden user found, error: %v", err)
rec := services.Response("Authz", http.StatusBadRequest, services.LDAPSearchError, errors.New(msg))
c.JSON(http.StatusBadRequest, rec)
return
}
tmap, err := tokenMap(rec.User, rec.Scope, "kerberos", "Authz", rec.Expires)
if Verbose > 2 {
log.Println("token map", tmap, err)
}
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
c.JSON(http.StatusOK, tmap)
}
// TrustedClientInfo represents trusted client system info to be send to /trusted_client
// end-point via POST HTTP request
type TrustedClientInfo struct {
User string `json:"user"`
IPs []string `json:"ips"`
MACs []string `json:"macs"`
}
// TrustedClientHandler perform trusted client check
func TrustedClientHandler(c *gin.Context) {
r := c.Request
data, err := io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.ParametersError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
var rec TrustedClientInfo
err = json.Unmarshal(data, &rec)
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.UnmarshalError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
// using provided trusted client info validate that it is accepted by Authz server based on its TrustedUsers configuration
found := false
for _, tuser := range srvConfig.Config.TrustedUsers {
for _, ip := range rec.IPs {
for _, mac := range rec.MACs {
if tuser.User == rec.User && tuser.IP == ip && tuser.MAC == mac {
found = true
break
}
}
}
}
if !found {
msg := "trusted client info does not match"
rec := services.Response("Authz", http.StatusBadRequest, services.AuthError, errors.New(msg))
c.JSON(http.StatusBadRequest, rec)
return
}
resp := services.Response("Authz", http.StatusOK, services.OK, nil)
c.JSON(http.StatusBadRequest, resp)
}
// TrustedHandler handles request for trusted client
func TrustedHandler(c *gin.Context) {
r := c.Request
if Verbose > 0 {
log.Println("Trusted HTTP request from", getIP(r))
}
edata, err := io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
var t utils.TrustedClient
salt := authz.ReadSecret(srvConfig.Config.Encryption.Secret)
err = t.Decrypt([]byte(edata), salt)
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
// check if user/IP/Mac are matched with our configuration
var foundIP, foundMAC string
for _, tuser := range srvConfig.Config.TrustedUsers {
if tuser.User == t.User {
for _, ip := range t.IPs {
if tuser.IP == ip {
foundIP = ip
for _, mac := range t.MACs {
if tuser.MAC == mac.Address {
foundMAC = mac.Address
}
}
}
}
}
}
if foundIP == "" || foundMAC == "" {
log.Printf("ERROR: client %+v not found in trusted list", t)
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, errors.New("user not found in trusted list"))
c.JSON(http.StatusBadRequest, rec)
return
}
clientIP := getIP(r)
// check if request comes from remote host and skip check for localhost
if clientIP != "::1" && foundIP != clientIP {
log.Printf("ERROR: client IP %s does not match with HTTP IP %s", foundIP, clientIP)
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, errors.New("client IP does not match with HTTP one"))
c.JSON(http.StatusBadRequest, rec)
return
}
tmap, err := tokenMap(t.User, "read+write", "trusted_client", "Authz", 0)
if Verbose > 2 {
log.Println("token map", tmap, err)
}
if err != nil {
rec := services.Response("Authz", http.StatusBadRequest, services.TokenError, err)
c.JSON(http.StatusBadRequest, rec)
return
}
c.JSON(http.StatusOK, tmap)
}
// KAuthHandler provides KAuth authentication to our app
// func KAuthHandler(w http.ResponseWriter, r *http.Request) {
func KAuthHandler(c *gin.Context) {
// get http request/writer
w := c.Writer
r := c.Request
// First, we need to get the value of the `code` query param
err := r.ParseForm()
if err != nil {
log.Printf("could not parse http form, error %v\n", err)
w.WriteHeader(http.StatusBadRequest)
}
name := r.FormValue("name")
password := r.FormValue("password")
var creds *credentials.Credentials
if name != "" && password != "" {
creds, err = kuser(name, password)
if err != nil {
msg := "wrong user credentials"
handleError(c, msg, err)
return
}
} else {
msg := "user/password is empty"
handleError(c, msg, err)
return
}
if creds == nil {
msg := "unable to obtain user credentials"
handleError(c, msg, err)
return
}
expiration := time.Now().Add(24 * time.Hour)
msg := fmt.Sprintf("%s-%v", creds.UserName(), creds.Authenticated())
// byteArray := encrypt([]byte(msg), Config.StoreSecret)
// n := bytes.IndexByte(byteArray, 0)
// s := string(byteArray[:n])
cookie := http.Cookie{Name: "auth-session", Value: msg, Expires: expiration}
http.SetCookie(w, &cookie)
// w.WriteHeader(http.StatusFound)
// get user access token
tmap, err := tokenMap(name, "read", "kerberos", "Authz", 0)
if Verbose > 2 {
log.Println("token map", tmap, err)
}
tmpl := server.MakeTmpl(StaticFs, "Login")
tmpl["Base"] = srvConfig.Config.Authz.WebServer.Base
header := server.TmplPage(StaticFs, "header.tmpl", tmpl)
footer := server.TmplPage(StaticFs, "footer.tmpl", tmpl)
if tmap.AccessToken != "" {
token := tmap.AccessToken
tmpl["AccessToken"] = token
claims, err := authz.TokenClaims(token, srvConfig.Config.Authz.ClientID)
if err != nil {
log.Println("ERROR", err)
tmpl["Content"] = err.Error()
content := server.TmplPage(StaticFs, "error.tmpl", tmpl)
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(header+content+footer))
return
}
data, err := json.MarshalIndent(claims, "", " ")
if err == nil {
tmpl["TokenData"] = string(data)
} else {
log.Println("ERROR", err)
}
content := server.TmplPage(StaticFs, "token.tmpl", tmpl)
tmpl["Content"] = template.HTML(content)
}
content := server.TmplPage(StaticFs, "success.tmpl", tmpl)
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(header+content+footer))
}