-
Notifications
You must be signed in to change notification settings - Fork 167
/
auth-handler.go
179 lines (157 loc) · 5.11 KB
/
auth-handler.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
package hooks
import (
"context"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/gorilla/mux"
"github.com/minio/minio-go/v7/pkg/signer"
"github.com/minio/minio/cmd"
"github.com/pydio/cells/v4/common"
"github.com/pydio/cells/v4/common/auth"
"github.com/pydio/cells/v4/common/auth/claim"
"github.com/pydio/cells/v4/common/log"
"github.com/pydio/cells/v4/common/service/context"
"github.com/pydio/cells/v4/common/service/context/metadata"
"github.com/pydio/cells/v4/common/utils/permissions"
)
// authHandler - handles all the incoming authorization headers and validates them if possible.
type pydioAuthHandler struct {
handler http.Handler
jwtVerifier *auth.JWTVerifier
globalAccessKey string
}
// GetPydioAuthHandlerFunc validates Pydio authorization headers for the incoming request.
func GetPydioAuthHandlerFunc(globalAccessKey string) mux.MiddlewareFunc {
return func(h http.Handler) http.Handler {
return pydioAuthHandler{
handler: h,
jwtVerifier: auth.DefaultJWTVerifier(),
globalAccessKey: globalAccessKey,
}
}
}
// handler for validating incoming authorization headers.
func (a pydioAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//var md map[string]string
var userName string
ctx := r.Context()
ctx = servicecontext.HttpRequestInfoToMetadata(ctx, r)
ctx = servicecontext.WithServiceName(ctx, common.ServiceGatewayData)
resignRequestV4 := false
resignRequestV4Presigned := false
rq := r.URL.Query()
jwt := rq.Get("pydio_jwt")
if len(jwt) > 0 {
//logger.Info("Found JWT in URL: replace by header and remove from URL")
r.Header.Set("X-Pydio-Bearer", jwt)
rq.Del("pydio_jwt")
checkResignV4 := false
if r.Method == http.MethodGet {
// Force attachment (if not already set)
if !strings.HasPrefix(strings.TrimSpace(rq.Get("response-content-disposition")), "attachment") {
rq.Set("response-content-disposition", "attachment")
checkResignV4 = true
}
}
// Rebuild Query
r.URL.RawQuery = rq.Encode()
_ = r.ParseForm()
// If PresignedV4, flag for re-signing
if signedKey, err := cmd.ExposedParsePresignV4(r.Form); err == nil && (signedKey != a.globalAccessKey || checkResignV4) {
resignRequestV4Presigned = true
}
} else if bearer, ok := r.Header["X-Pydio-Bearer"]; !ok || len(bearer) == 0 {
// Copy request.
req := *r
// Save authorization header.
v4Auth := req.Header.Get("Authorization")
// Parse signature version '4' header.
if signedKey, err := cmd.ExposedParseSignV4(v4Auth); err == nil && signedKey != a.globalAccessKey {
log.Logger(ctx).Debug("Use AWS Api Key as JWT: " + signedKey)
resignRequestV4 = true
r.Header.Set("X-Pydio-Bearer", signedKey)
}
}
if bearer, ok := r.Header["X-Pydio-Bearer"]; ok && len(bearer) > 0 {
rawIDToken := strings.Join(bearer, "")
var err error
var claims claim.Claims
ctx, claims, err = a.jwtVerifier.Verify(ctx, rawIDToken)
if err != nil {
cmd.ExposedWriteErrorResponse(ctx, w, cmd.ErrAccessDenied, r.URL)
return
}
userName = claims.Name
if resignRequestV4 {
// User is OK, override signature with service account ID/Secret
r = signer.SignV4(*r, common.S3GatewayRootUser, common.S3GatewayRootPassword, "", common.S3GatewayDefaultRegion)
} else if resignRequestV4Presigned {
origUrl := r.URL
origHeader := r.Header
newUrl := &url.URL{
Scheme: origUrl.Scheme,
Host: origUrl.Host,
Path: origUrl.Path,
}
newV := newUrl.Query()
expire := int64(900)
for k, vv := range origUrl.Query() {
if k == "X-Amz-Expires" {
if ex, e := strconv.ParseInt(strings.Join(vv, ""), 10, 64); e == nil {
expire = ex
}
}
if strings.HasPrefix(k, "X-Amz-") || k == "pydio_jwt" {
continue
}
for _, v := range vv {
newV.Set(k, v)
}
}
if len(newV) > 0 {
newUrl.RawQuery = newV.Encode()
}
newReq := *r
newReq.URL = newUrl
newReq.RequestURI = newUrl.RequestURI()
_ = newReq.ParseForm()
r = signer.PreSignV4(newReq, common.S3GatewayRootUser, common.S3GatewayRootPassword, "", common.S3GatewayDefaultRegion, expire)
// Re-append headers
if len(origHeader) > 0 {
r.Header = http.Header{}
for k, vv := range origHeader {
for _, v := range vv {
r.Header.Set(k, v)
}
}
}
}
} else if agent, aOk := r.Header["User-Agent"]; aOk && strings.Contains(strings.Join(agent, ""), "pydio.sync.client.s3") {
userName = common.PydioSystemUsername
} else {
if user, er := permissions.SearchUniqueUser(ctx, common.PydioS3AnonUsername, ""); er == nil {
userName = common.PydioS3AnonUsername
var s []string
for _, role := range user.Roles {
if role.UserRole { // Just append the User Role
s = append(s, role.Uuid)
}
}
anonClaim := claim.Claims{
Name: common.PydioS3AnonUsername,
Roles: strings.Join(s, ","),
Profile: "anon",
GroupPath: "/",
}
ctx = context.WithValue(ctx, claim.ContextKey, anonClaim)
} else {
cmd.ExposedWriteErrorResponse(ctx, w, cmd.ErrAccessDenied, r.URL)
return
}
}
ctx = metadata.WithUserNameMetadata(ctx, userName)
newRequest := r.WithContext(ctx)
a.handler.ServeHTTP(w, newRequest)
}