github.com/Racer159/helm-experiment@v0.0.0-20230822001441-1eb31183f614/src/root_unix_test.go (about)

     1  //go:build !windows
     2  
     3  /*
     4  Copyright The Helm Authors.
     5  
     6  Licensed under the Apache License, Version 2.0 (the "License");
     7  you may not use this file except in compliance with the License.
     8  You may obtain a copy of the License at
     9  
    10      http://www.apache.org/licenses/LICENSE-2.0
    11  
    12  Unless required by applicable law or agreed to in writing, software
    13  distributed under the License is distributed on an "AS IS" BASIS,
    14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15  See the License for the specific language governing permissions and
    16  limitations under the License.
    17  */
    18  
    19  package cmd
    20  
    21  import (
    22  	"bytes"
    23  	"io"
    24  	"os"
    25  	"path/filepath"
    26  	"strings"
    27  	"testing"
    28  )
    29  
    30  func checkPermsStderr() (string, error) {
    31  	r, w, err := os.Pipe()
    32  	if err != nil {
    33  		return "", err
    34  	}
    35  
    36  	stderr := os.Stderr
    37  	os.Stderr = w
    38  	defer func() {
    39  		os.Stderr = stderr
    40  	}()
    41  
    42  	checkPerms()
    43  	w.Close()
    44  
    45  	var text bytes.Buffer
    46  	io.Copy(&text, r)
    47  	return text.String(), nil
    48  }
    49  
    50  func TestCheckPerms(t *testing.T) {
    51  	tdir := t.TempDir()
    52  	tfile := filepath.Join(tdir, "testconfig")
    53  	fh, err := os.OpenFile(tfile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0440)
    54  	if err != nil {
    55  		t.Errorf("Failed to create temp file: %s", err)
    56  	}
    57  
    58  	tconfig := settings.KubeConfig
    59  	settings.KubeConfig = tfile
    60  	defer func() { settings.KubeConfig = tconfig }()
    61  
    62  	text, err := checkPermsStderr()
    63  	if err != nil {
    64  		t.Fatalf("could not read from stderr: %s", err)
    65  	}
    66  	expectPrefix := "WARNING: Kubernetes configuration file is group-readable. This is insecure. Location:"
    67  	if !strings.HasPrefix(text, expectPrefix) {
    68  		t.Errorf("Expected to get a warning for group perms. Got %q", text)
    69  	}
    70  
    71  	if err := fh.Chmod(0404); err != nil {
    72  		t.Errorf("Could not change mode on file: %s", err)
    73  	}
    74  	text, err = checkPermsStderr()
    75  	if err != nil {
    76  		t.Fatalf("could not read from stderr: %s", err)
    77  	}
    78  	expectPrefix = "WARNING: Kubernetes configuration file is world-readable. This is insecure. Location:"
    79  	if !strings.HasPrefix(text, expectPrefix) {
    80  		t.Errorf("Expected to get a warning for world perms. Got %q", text)
    81  	}
    82  }