github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/kernel/auth/context.go (about) 1 // Copyright 2018 The gVisor Authors. 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 auth 16 17 import ( 18 "github.com/SagerNet/gvisor/pkg/context" 19 ) 20 21 // contextID is the auth package's type for context.Context.Value keys. 22 type contextID int 23 24 const ( 25 // CtxCredentials is a Context.Value key for Credentials. 26 CtxCredentials contextID = iota 27 ) 28 29 // CredentialsFromContext returns a copy of the Credentials used by ctx, or a 30 // set of Credentials with no capabilities if ctx does not have Credentials. 31 func CredentialsFromContext(ctx context.Context) *Credentials { 32 if v := ctx.Value(CtxCredentials); v != nil { 33 return v.(*Credentials) 34 } 35 return NewAnonymousCredentials() 36 } 37 38 // ContextWithCredentials returns a copy of ctx carrying creds. 39 func ContextWithCredentials(ctx context.Context, creds *Credentials) context.Context { 40 return &authContext{ctx, creds} 41 } 42 43 type authContext struct { 44 context.Context 45 creds *Credentials 46 } 47 48 // Value implements context.Context. 49 func (ac *authContext) Value(key interface{}) interface{} { 50 switch key { 51 case CtxCredentials: 52 return ac.creds 53 default: 54 return ac.Context.Value(key) 55 } 56 }