github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/doltcore/sqle/dsess/branch_control.go (about) 1 // Copyright 2023 Dolthub, Inc. 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 15 package dsess 16 17 import ( 18 "context" 19 20 "github.com/dolthub/dolt/go/libraries/doltcore/branch_control" 21 ) 22 23 // CheckAccessForDb checks whether the current user has the given permissions for the given database. 24 // This has to live here, rather than in the branch_control package, to prevent a dependency cycle with that package. 25 // We could also avoid this by defining branchController as an interface used by dsess. 26 func CheckAccessForDb(ctx context.Context, db SqlDatabase, flags branch_control.Permissions) error { 27 branchAwareSession := branch_control.GetBranchAwareSession(ctx) 28 // A nil session means we're not in the SQL context, so we allow all operations 29 if branchAwareSession == nil { 30 return nil 31 } 32 33 controller := branchAwareSession.GetController() 34 // Any context that has a non-nil session should always have a non-nil controller, so this is an error 35 if controller == nil { 36 return branch_control.ErrMissingController.New() 37 } 38 39 controller.Access.RWMutex.RLock() 40 defer controller.Access.RWMutex.RUnlock() 41 42 user := branchAwareSession.GetUser() 43 host := branchAwareSession.GetHost() 44 45 if db.RevisionType() != RevisionTypeBranch { 46 // not a branch db, no check necessary 47 return nil 48 } 49 50 dbName, branch := SplitRevisionDbName(db.RevisionQualifiedName()) 51 52 // Get the permissions for the branch, user, and host combination 53 _, perms := controller.Access.Match(dbName, branch, user, host) 54 // If either the flags match or the user is an admin for this branch, then we allow access 55 if (perms&flags == flags) || (perms&branch_control.Permissions_Admin == branch_control.Permissions_Admin) { 56 return nil 57 } 58 return branch_control.ErrIncorrectPermissions.New(user, host, branch) 59 }