forked from minio/console
-
Notifications
You must be signed in to change notification settings - Fork 1
/
user_session.go
293 lines (258 loc) · 9.76 KB
/
user_session.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
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
// This file is part of MinIO Console Server
// Copyright (c) 2021 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package restapi
import (
"bytes"
"context"
"encoding/json"
"strconv"
"time"
"github.com/trinet2005/oss-admin-go"
policies "github.com/trinet2005/oss-console/restapi/policy"
jwtgo "github.com/golang-jwt/jwt/v4"
"github.com/trinet2005/oss-pkg/policy/condition"
minioIAMPolicy "github.com/trinet2005/oss-pkg/policy"
"github.com/go-openapi/runtime/middleware"
"github.com/trinet2005/oss-console/models"
"github.com/trinet2005/oss-console/pkg/auth/idp/oauth2"
"github.com/trinet2005/oss-console/pkg/auth/ldap"
"github.com/trinet2005/oss-console/restapi/operations"
authApi "github.com/trinet2005/oss-console/restapi/operations/auth"
)
type Conditions struct {
S3Prefix []string `json:"s3:prefix"`
}
func registerSessionHandlers(api *operations.ConsoleAPI) {
// session check
api.AuthSessionCheckHandler = authApi.SessionCheckHandlerFunc(func(params authApi.SessionCheckParams, session *models.Principal) middleware.Responder {
sessionResp, err := getSessionResponse(params.HTTPRequest.Context(), session)
if err != nil {
return authApi.NewSessionCheckDefault(err.Code).WithPayload(err.APIError)
}
return authApi.NewSessionCheckOK().WithPayload(sessionResp)
})
}
func getClaimsFromToken(sessionToken string) (map[string]interface{}, error) {
jp := new(jwtgo.Parser)
// nolint:staticcheck // ignore SA1019
jp.ValidMethods = []string{
"RS256", "RS384", "RS512", "ES256", "ES384", "ES512",
"RS3256", "RS3384", "RS3512", "ES3256", "ES3384", "ES3512",
}
var claims jwtgo.MapClaims
_, _, err := jp.ParseUnverified(sessionToken, &claims)
if err != nil {
return nil, err
}
return claims, nil
}
// getSessionResponse parse the token of the current session and returns a list of allowed actions to render in the UI
func getSessionResponse(ctx context.Context, session *models.Principal) (*models.SessionResponse, *CodedAPIError) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// serialize output
if session == nil {
return nil, ErrorWithContext(ctx, ErrInvalidSession)
}
tokenClaims, _ := getClaimsFromToken(session.STSSessionToken)
// initialize admin client
mAdminClient, err := NewMinioAdminClient(ctx, &models.Principal{
STSAccessKeyID: session.STSAccessKeyID,
STSSecretAccessKey: session.STSSecretAccessKey,
STSSessionToken: session.STSSessionToken,
})
if err != nil {
return nil, ErrorWithContext(ctx, err, ErrInvalidSession)
}
userAdminClient := AdminClient{Client: mAdminClient}
// Obtain the current policy assigned to this user
// necessary for generating the list of allowed endpoints
accountInfo, err := getAccountInfo(ctx, userAdminClient)
if err != nil {
return nil, ErrorWithContext(ctx, err, ErrInvalidSession)
}
erasure := accountInfo.Server.Type == madmin.Erasure
rawPolicy := policies.ReplacePolicyVariables(tokenClaims, accountInfo)
policy, err := minioIAMPolicy.ParseConfig(bytes.NewReader(rawPolicy))
if err != nil {
return nil, ErrorWithContext(ctx, err, ErrInvalidSession)
}
currTime := time.Now().UTC()
customStyles := session.CustomStyleOb
// This actions will be global, meaning has to be attached to all resources
conditionValues := map[string][]string{
condition.AWSUsername.Name(): {session.AccountAccessKey},
// All calls to MinIO from console use temporary credentials.
condition.AWSPrincipalType.Name(): {"AssumeRole"},
condition.AWSSecureTransport.Name(): {strconv.FormatBool(getMinIOEndpointIsSecure())},
condition.AWSCurrentTime.Name(): {currTime.Format(time.RFC3339)},
condition.AWSEpochTime.Name(): {strconv.FormatInt(currTime.Unix(), 10)},
// All calls from console are signature v4.
condition.S3SignatureVersion.Name(): {"AWS4-HMAC-SHA256"},
// All calls from console are signature v4.
condition.S3AuthType.Name(): {"REST-HEADER"},
// This is usually empty, may be set some times (rare).
condition.S3LocationConstraint.Name(): {GetMinIORegion()},
}
claims, err := getClaimsFromToken(session.STSSessionToken)
if err != nil {
return nil, ErrorWithContext(ctx, err, ErrInvalidSession)
}
// Support all LDAP, JWT variables
for k, v := range claims {
vstr, ok := v.(string)
if !ok {
// skip all non-strings
continue
}
// store all claims from sessionToken
conditionValues[k] = []string{vstr}
}
defaultActions := policy.IsAllowedActions("", "", conditionValues)
permissions := map[string]minioIAMPolicy.ActionSet{
ConsoleResourceName: defaultActions,
}
deniedActions := map[string]minioIAMPolicy.ActionSet{}
var allowResources []*models.PermissionResource
for _, statement := range policy.Statements {
for _, resource := range statement.Resources.ToSlice() {
resourceName := resource.String()
statementActions := statement.Actions.ToSlice()
var prefixes []string
if statement.Effect == "Allow" {
// check if val are denied before adding them to the map
var allowedActions []minioIAMPolicy.Action
if dActions, ok := deniedActions[resourceName]; ok {
for _, action := range statementActions {
if len(dActions.Intersection(minioIAMPolicy.NewActionSet(action))) == 0 {
// It's ok to allow this action
allowedActions = append(allowedActions, action)
}
}
} else {
allowedActions = statementActions
}
// Add validated actions
if resourceActions, ok := permissions[resourceName]; ok {
mergedActions := append(resourceActions.ToSlice(), allowedActions...)
permissions[resourceName] = minioIAMPolicy.NewActionSet(mergedActions...)
} else {
mergedActions := append(defaultActions.ToSlice(), allowedActions...)
permissions[resourceName] = minioIAMPolicy.NewActionSet(mergedActions...)
}
// Allow Permissions request
conditions, err := statement.Conditions.MarshalJSON()
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
var wrapper map[string]Conditions
if err := json.Unmarshal(conditions, &wrapper); err != nil {
return nil, ErrorWithContext(ctx, err)
}
for condition, elements := range wrapper {
prefixes = elements.S3Prefix
resourceElement := models.PermissionResource{
Resource: resourceName,
Prefixes: prefixes,
ConditionOperator: condition,
}
allowResources = append(allowResources, &resourceElement)
}
} else {
// Add new banned actions to the map
if resourceActions, ok := deniedActions[resourceName]; ok {
mergedActions := append(resourceActions.ToSlice(), statementActions...)
deniedActions[resourceName] = minioIAMPolicy.NewActionSet(mergedActions...)
} else {
deniedActions[resourceName] = statement.Actions
}
// Remove existing val from key if necessary
if currentResourceActions, ok := permissions[resourceName]; ok {
var newAllowedActions []minioIAMPolicy.Action
for _, action := range currentResourceActions.ToSlice() {
if len(deniedActions[resourceName].Intersection(minioIAMPolicy.NewActionSet(action))) == 0 {
// It's ok to allow this action
newAllowedActions = append(newAllowedActions, action)
}
}
permissions[resourceName] = minioIAMPolicy.NewActionSet(newAllowedActions...)
}
}
}
}
resourcePermissions := map[string][]string{}
for key, val := range permissions {
var resourceActions []string
for _, action := range val.ToSlice() {
resourceActions = append(resourceActions, string(action))
}
resourcePermissions[key] = resourceActions
}
serializedPolicy, err := json.Marshal(policy)
if err != nil {
return nil, ErrorWithContext(ctx, err, ErrInvalidSession)
}
var sessionPolicy *models.IamPolicy
err = json.Unmarshal(serializedPolicy, &sessionPolicy)
if err != nil {
return nil, ErrorWithContext(ctx, err)
}
// environment constants
var envConstants models.EnvironmentConstants
envConstants.MaxConcurrentUploads = getMaxConcurrentUploadsLimit()
envConstants.MaxConcurrentDownloads = getMaxConcurrentDownloadsLimit()
sessionResp := &models.SessionResponse{
Features: getListOfEnabledFeatures(ctx, userAdminClient, session),
Status: models.SessionResponseStatusOk,
Operator: false,
DistributedMode: erasure,
Permissions: resourcePermissions,
AllowResources: allowResources,
CustomStyles: customStyles,
EnvConstants: &envConstants,
ServerEndPoint: getMinIOServer(),
}
return sessionResp, nil
}
// getListOfEnabledFeatures returns a list of features
func getListOfEnabledFeatures(ctx context.Context, minioClient MinioAdmin, session *models.Principal) []string {
features := []string{}
logSearchURL := getLogSearchURL()
oidcEnabled := oauth2.IsIDPEnabled()
ldapEnabled := ldap.GetLDAPEnabled()
if logSearchURL != "" {
features = append(features, "log-search")
}
if oidcEnabled {
features = append(features, "oidc-idp", "external-idp")
}
if ldapEnabled {
features = append(features, "ldap-idp", "external-idp")
}
if session.Hm {
features = append(features, "hide-menu")
}
if session.Ob {
features = append(features, "object-browser-only")
}
if minioClient != nil {
_, err := minioClient.kmsStatus(ctx)
if err == nil {
features = append(features, "kms")
}
}
return features
}