github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/user.go (about) 1 /* 2 Copyright 2023 Gravitational, Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "os/user" 21 "time" 22 23 "github.com/gravitational/trace" 24 ) 25 26 const lookupTimeout = 10 * time.Second 27 28 type userGetter func() (*user.User, error) 29 30 type userResult struct { 31 user *user.User 32 err error 33 } 34 35 // CurrentUser is just like [user.Current], except an error is returned 36 // if the user lookup exceeds 10 seconds. This is because if 37 // [user.Current] is called on a domain joined host, the user lookup 38 // will contact potentially multiple domain controllers which can hang. 39 func CurrentUser() (*user.User, error) { 40 return currentUser(user.Current, lookupTimeout) 41 } 42 43 func currentUser(getUser userGetter, timeout time.Duration) (*user.User, error) { 44 result := make(chan userResult, 1) 45 go func() { 46 u, err := getUser() 47 result <- userResult{ 48 user: u, 49 err: err, 50 } 51 }() 52 53 timer := time.NewTimer(timeout) 54 defer timer.Stop() 55 56 select { 57 case u := <-result: 58 return u.user, trace.Wrap(u.err) 59 case <-timer.C: 60 return nil, trace.LimitExceeded( 61 "unexpected host user lookup timeout, please explicitly specify the Teleport user with \"--user\" and the host user \"--login\" to skip host user lookup", 62 ) 63 } 64 }