github.com/containerd/nerdctl/v2@v2.0.0-beta.5.0.20240520001846-b5758f54fa28/pkg/cmd/container/run_user.go (about)

     1  /*
     2     Copyright The containerd Authors.
     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 container
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"strconv"
    23  
    24  	"github.com/containerd/containerd/containers"
    25  	"github.com/containerd/containerd/oci"
    26  )
    27  
    28  func generateUserOpts(user string) ([]oci.SpecOpts, error) {
    29  	var opts []oci.SpecOpts
    30  	if user != "" {
    31  		opts = append(opts, oci.WithUser(user), withResetAdditionalGIDs(), oci.WithAdditionalGIDs(user))
    32  	}
    33  	return opts, nil
    34  }
    35  
    36  func generateUmaskOpts(umask string) ([]oci.SpecOpts, error) {
    37  	var opts []oci.SpecOpts
    38  
    39  	if umask != "" {
    40  		decVal, err := strconv.ParseUint(umask, 8, 32)
    41  		if err != nil {
    42  			return nil, fmt.Errorf("invalid Umask Value:%s", umask)
    43  		}
    44  		opts = append(opts, withAdditionalUmask(uint32(decVal)))
    45  	}
    46  	return opts, nil
    47  }
    48  
    49  func generateGroupsOpts(groups []string) ([]oci.SpecOpts, error) {
    50  	var opts []oci.SpecOpts
    51  
    52  	if len(groups) != 0 {
    53  		opts = append(opts, oci.WithAppendAdditionalGroups(groups...))
    54  	}
    55  	return opts, nil
    56  }
    57  
    58  func withResetAdditionalGIDs() oci.SpecOpts {
    59  	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *oci.Spec) error {
    60  		s.Process.User.AdditionalGids = nil
    61  		return nil
    62  	}
    63  }
    64  
    65  func withAdditionalUmask(umask uint32) oci.SpecOpts {
    66  	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *oci.Spec) error {
    67  		s.Process.User.Umask = &umask
    68  		return nil
    69  	}
    70  }