github.com/mendersoftware/go-lib-micro@v0.0.0-20240304135804-e8e39c59b148/rbac/rbac.go (about) 1 // Copyright 2023 Northern.tech AS 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package rbac 15 16 import ( 17 "context" 18 "net/http" 19 "strings" 20 ) 21 22 type scopeContextKeyType int 23 24 const ( 25 scopeContextKey scopeContextKeyType = 0 26 ScopeHeader = "X-MEN-RBAC-Inventory-Groups" 27 ScopeReleaseTagsHeader = "X-MEN-RBAC-Releases-Tags" 28 ) 29 30 type Scope struct { 31 DeviceGroups []string 32 ReleaseTags []string 33 } 34 35 // FromContext extracts current scope from context.Context 36 func FromContext(ctx context.Context) *Scope { 37 val := ctx.Value(scopeContextKey) 38 if v, ok := val.(*Scope); ok { 39 return v 40 } 41 return nil 42 } 43 44 // WithContext adds scope to context `ctx` and returns the resulting context. 45 func WithContext(ctx context.Context, scope *Scope) context.Context { 46 return context.WithValue(ctx, scopeContextKey, scope) 47 } 48 49 func ExtractScopeFromHeader(r *http.Request) *Scope { 50 groupStr := r.Header.Get(ScopeHeader) 51 tagsStr := r.Header.Get(ScopeReleaseTagsHeader) 52 if len(groupStr) > 0 { 53 return &Scope{ 54 DeviceGroups: strings.Split(groupStr, ","), 55 ReleaseTags: strings.Split(tagsStr, ","), 56 } 57 } 58 return nil 59 }