github.com/nicocha30/gvisor-ligolo@v0.0.0-20230726075806-989fa2c0a413/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/nicocha30/gvisor-ligolo/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  	// CtxThreadGroupID is the current thread group ID when a context represents
    29  	// a task context. The value is represented as an int32.
    30  	CtxThreadGroupID contextID = iota
    31  )
    32  
    33  // CredentialsFromContext returns a copy of the Credentials used by ctx, or a
    34  // set of Credentials with no capabilities if ctx does not have Credentials.
    35  func CredentialsFromContext(ctx context.Context) *Credentials {
    36  	if v := ctx.Value(CtxCredentials); v != nil {
    37  		return v.(*Credentials)
    38  	}
    39  	return NewAnonymousCredentials()
    40  }
    41  
    42  // ThreadGroupIDFromContext returns the current thread group ID when ctx
    43  // represents a task context.
    44  func ThreadGroupIDFromContext(ctx context.Context) (tgid int32, ok bool) {
    45  	if tgid := ctx.Value(CtxThreadGroupID); tgid != nil {
    46  		return tgid.(int32), true
    47  	}
    48  	return 0, false
    49  }
    50  
    51  // ContextWithCredentials returns a copy of ctx carrying creds.
    52  func ContextWithCredentials(ctx context.Context, creds *Credentials) context.Context {
    53  	return &authContext{ctx, creds}
    54  }
    55  
    56  type authContext struct {
    57  	context.Context
    58  	creds *Credentials
    59  }
    60  
    61  // Value implements context.Context.
    62  func (ac *authContext) Value(key any) any {
    63  	switch key {
    64  	case CtxCredentials:
    65  		return ac.creds
    66  	default:
    67  		return ac.Context.Value(key)
    68  	}
    69  }