/
entity_access.go
335 lines (309 loc) · 11.2 KB
/
entity_access.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
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
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package identityserver
import (
"context"
"fmt"
"runtime/trace"
"strings"
"time"
"github.com/gogo/protobuf/types"
"github.com/jinzhu/gorm"
"go.thethings.network/lorawan-stack/pkg/auth"
clusterauth "go.thethings.network/lorawan-stack/pkg/auth/cluster"
"go.thethings.network/lorawan-stack/pkg/errors"
"go.thethings.network/lorawan-stack/pkg/identityserver/store"
"go.thethings.network/lorawan-stack/pkg/rpcmetadata"
"go.thethings.network/lorawan-stack/pkg/rpcmiddleware/warning"
"go.thethings.network/lorawan-stack/pkg/ttnpb"
)
var (
errUnauthenticated = errors.DefineUnauthenticated("unauthenticated", "unauthenticated")
errUnsupportedAuthorization = errors.DefineUnauthenticated("unsupported_authorization", "unsupported authorization method")
errAPIKeyNotFound = errors.DefineUnauthenticated("api_key_not_found", "API key not found")
errInvalidAuthorization = errors.DefineUnauthenticated("invalid_authorization", "invalid authorization")
errTokenNotFound = errors.DefineUnauthenticated("token_not_found", "access token not found")
errTokenExpired = errors.DefineUnauthenticated("token_expired", "access token expired")
errUserRejected = errors.DefinePermissionDenied("user_rejected", "user account was rejected")
errUserRequested = errors.DefinePermissionDenied("user_requested", "user account approval is pending")
errUserSuspended = errors.DefinePermissionDenied("user_suspended", "user account was suspended")
errOAuthClientRejected = errors.DefinePermissionDenied("oauth_client_rejected", "OAuth client was rejected")
errOAuthClientSuspended = errors.DefinePermissionDenied("oauth_client_suspended", "OAuth client was suspended")
errPermissionDenied = errors.DefinePermissionDenied("permission_denied", "unauthorized request to restricted resource")
)
type requestAccessKeyType struct{}
var requestAccessKey requestAccessKeyType
type requestAccess struct {
authInfo *ttnpb.AuthInfoResponse
entityRights map[ttnpb.Identifiers]*ttnpb.Rights
}
func (is *IdentityServer) withRequestAccessCache(ctx context.Context) context.Context {
return context.WithValue(ctx, requestAccessKey, new(requestAccess))
}
func (is *IdentityServer) authInfo(ctx context.Context) (info *ttnpb.AuthInfoResponse, err error) {
if access, ok := ctx.Value(requestAccessKey).(*requestAccess); ok {
if access.authInfo != nil {
return access.authInfo, nil
}
defer func() {
if err == nil {
access.authInfo = info
}
}()
}
md := rpcmetadata.FromIncomingContext(ctx)
if md.AuthType == "" {
return &ttnpb.AuthInfoResponse{}, nil
}
if md.AuthType == clusterauth.AuthType {
if err := clusterauth.Authorized(ctx); err != nil {
return nil, err
}
return &ttnpb.AuthInfoResponse{
UniversalRights: ttnpb.AllClusterRights.Implied(),
}, nil
}
if strings.ToLower(md.AuthType) != "bearer" {
return nil, errUnsupportedAuthorization.New()
}
token := md.AuthValue
tokenType, tokenID, tokenKey, err := auth.SplitToken(token)
if err != nil {
return nil, err
}
var fetch func(db *gorm.DB) error
res := &ttnpb.AuthInfoResponse{}
userFieldMask := &types.FieldMask{Paths: []string{"admin", "state", "primary_email_address_validated_at"}}
clientFieldMask := &types.FieldMask{Paths: []string{"state"}}
var user *ttnpb.User
var userRights *ttnpb.Rights
switch tokenType {
case auth.APIKey:
fetch = func(db *gorm.DB) error {
ids, apiKey, err := store.GetAPIKeyStore(db).GetAPIKey(ctx, tokenID)
if err != nil {
if errors.IsNotFound(err) {
return errAPIKeyNotFound.WithCause(err)
}
return err
}
region := trace.StartRegion(ctx, "validate api key")
valid, err := auth.Validate(apiKey.GetKey(), tokenKey)
region.End()
if err != nil {
return errInvalidAuthorization.WithCause(err)
}
if !valid {
return errInvalidAuthorization.New()
}
apiKey.Key = ""
apiKey.Rights = ttnpb.RightsFrom(apiKey.Rights...).Implied().GetRights()
res.AccessMethod = &ttnpb.AuthInfoResponse_APIKey{
APIKey: &ttnpb.AuthInfoResponse_APIKeyAccess{
APIKey: *apiKey,
EntityIDs: *ids.EntityIdentifiers(),
},
}
if ids.EntityType() == "user" {
user, err = store.GetUserStore(db).GetUser(ctx, ids.Identifiers().(*ttnpb.UserIdentifiers), userFieldMask)
if err != nil {
if errors.IsNotFound(err) {
return errAPIKeyNotFound.WithCause(err)
}
return err
}
userRights = ttnpb.RightsFrom(apiKey.Rights...)
}
return nil
}
case auth.AccessToken:
fetch = func(db *gorm.DB) error {
accessToken, err := store.GetOAuthStore(db).GetAccessToken(ctx, tokenID)
if err != nil {
if errors.IsNotFound(err) {
return errTokenNotFound.WithCause(err)
}
return err
}
region := trace.StartRegion(ctx, "validate access token")
valid, err := auth.Validate(accessToken.GetAccessToken(), tokenKey)
region.End()
if err != nil {
return errInvalidAuthorization.WithCause(err)
}
if !valid {
return errInvalidAuthorization.New()
}
if accessToken.ExpiresAt.Before(time.Now()) {
return errTokenExpired.New()
}
accessToken.AccessToken, accessToken.RefreshToken = "", ""
accessToken.Rights = ttnpb.RightsFrom(accessToken.Rights...).Implied().GetRights()
res.AccessMethod = &ttnpb.AuthInfoResponse_OAuthAccessToken{
OAuthAccessToken: accessToken,
}
user, err = store.GetUserStore(db).GetUser(ctx, &accessToken.UserIDs, userFieldMask)
if err != nil {
if errors.IsNotFound(err) {
return errTokenNotFound.WithCause(err)
}
return err
}
client, err := store.GetClientStore(db).GetClient(ctx, &accessToken.ClientIDs, clientFieldMask)
if err != nil {
if errors.IsNotFound(err) {
return errTokenNotFound.WithCause(err)
}
return err
}
switch client.State {
case ttnpb.STATE_REQUESTED:
// OAuth authorization only passes for collaborators, so this is ok.
case ttnpb.STATE_APPROVED:
// Normal OAuth client.
case ttnpb.STATE_REJECTED:
return errOAuthClientRejected.New()
case ttnpb.STATE_FLAGGED:
// Innocent until proven guilty.
case ttnpb.STATE_SUSPENDED:
return errOAuthClientSuspended.New()
default:
panic(fmt.Sprintf("Unhandled client state: %s", client.State.String()))
}
userRights = ttnpb.RightsFrom(accessToken.Rights...)
return nil
}
default:
return nil, errUnsupportedAuthorization.New()
}
if err = is.withDatabase(ctx, fetch); err != nil {
return nil, err
}
if user != nil {
if is.configFromContext(ctx).UserRegistration.ContactInfoValidation.Required && user.PrimaryEmailAddressValidatedAt == nil {
// Go to profile page, edit basic settings (such as email), delete account.
restrictRights(res, ttnpb.RightsFrom(ttnpb.RIGHT_USER_INFO, ttnpb.RIGHT_USER_SETTINGS_BASIC, ttnpb.RIGHT_USER_DELETE))
warning.Add(ctx, "Restricted rights until email address validated")
}
switch user.State {
case ttnpb.STATE_REQUESTED:
// Go to profile page, edit basic settings (such as email), delete account.
restrictRights(res, ttnpb.RightsFrom(ttnpb.RIGHT_USER_INFO, ttnpb.RIGHT_USER_SETTINGS_BASIC, ttnpb.RIGHT_USER_DELETE))
warning.Add(ctx, "Restricted rights while account pending")
case ttnpb.STATE_APPROVED:
// Normal user.
if user.Admin {
res.IsAdmin = true
res.UniversalRights = ttnpb.AllAdminRights.Implied().Intersect(userRights)
}
case ttnpb.STATE_REJECTED:
// Go to profile page, delete account.
restrictRights(res, ttnpb.RightsFrom(ttnpb.RIGHT_USER_INFO, ttnpb.RIGHT_USER_DELETE))
warning.Add(ctx, "Restricted rights after account rejection")
case ttnpb.STATE_FLAGGED:
// Innocent until proven guilty.
case ttnpb.STATE_SUSPENDED:
// Go to profile page.
restrictRights(res, ttnpb.RightsFrom(ttnpb.RIGHT_USER_INFO))
warning.Add(ctx, "Restricted rights after account suspension")
default:
panic(fmt.Sprintf("Unhandled user state: %s", user.State.String()))
}
}
return res, nil
}
// RequireAuthenticated checks the request context for authentication presence
// and returns an error if there is none.
func (is *IdentityServer) RequireAuthenticated(ctx context.Context) error {
authInfo, err := is.authInfo(ctx)
if err != nil {
return err
}
if userID := authInfo.GetEntityIdentifiers().GetUserIDs(); userID != nil {
err = is.withDatabase(ctx, func(db *gorm.DB) (err error) {
user, err := store.GetUserStore(db).GetUser(ctx, userID, &types.FieldMask{Paths: []string{
"state",
}})
if err != nil {
return err
}
switch user.State {
case ttnpb.STATE_APPROVED:
return nil
case ttnpb.STATE_FLAGGED:
// Flagged users have the same authentication presence as approved users until proven guilty.
return nil
case ttnpb.STATE_REQUESTED:
return errUserRequested.New()
case ttnpb.STATE_REJECTED:
return errUserRejected.New()
case ttnpb.STATE_SUSPENDED:
return errUserSuspended.New()
default:
panic(fmt.Sprintf("Unhandled user state: %s", user.State.String()))
}
})
if err != nil {
return err
}
}
if apiKey := authInfo.GetAPIKey(); apiKey != nil {
return nil
} else if accessToken := authInfo.GetOAuthAccessToken(); accessToken != nil {
return nil
}
if len(authInfo.UniversalRights.GetRights()) > 0 {
return nil
}
return errUnauthenticated.New()
}
// UniversalRights returns the universal rights (that apply to any entity or
// outside entity scope) contained in the request context. This is used to determine
// admin rights.
func (is *IdentityServer) UniversalRights(ctx context.Context) *ttnpb.Rights {
info, err := is.authInfo(ctx)
if err == nil {
return info.GetUniversalRights()
}
return nil
}
// IsAdmin returns whether the caller is an admin.
func (is *IdentityServer) IsAdmin(ctx context.Context) bool {
authInfo, err := is.authInfo(ctx)
if err != nil {
return false
}
return authInfo.IsAdmin
}
// RequireAdmin returns an error when the caller is not an admin.
func (is *IdentityServer) RequireAdmin(ctx context.Context) error {
if !is.IsAdmin(ctx) {
return errPermissionDenied.New()
}
return nil
}
func restrictRights(info *ttnpb.AuthInfoResponse, rights *ttnpb.Rights) {
if apiKey := info.GetAPIKey(); apiKey != nil {
apiKey.Rights = ttnpb.RightsFrom(apiKey.Rights...).Intersect(rights).GetRights()
} else if token := info.GetOAuthAccessToken(); token != nil {
token.Rights = ttnpb.RightsFrom(token.Rights...).Intersect(rights).GetRights()
}
info.UniversalRights = info.UniversalRights.Intersect(rights)
}
type entityAccess struct {
*IdentityServer
}
func (ea *entityAccess) AuthInfo(ctx context.Context, _ *types.Empty) (*ttnpb.AuthInfoResponse, error) {
return ea.authInfo(ctx)
}