Skip to content

Commit

Permalink
Merge pull request #10106 from spowelljr/userFlag
Browse files Browse the repository at this point in the history
Add new flag --user and to log executed commands
  • Loading branch information
medyagh authored Jan 26, 2021
2 parents c636bfe + 44e3aed commit 597091d
Show file tree
Hide file tree
Showing 41 changed files with 506 additions and 6 deletions.
15 changes: 15 additions & 0 deletions cmd/minikube/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"path/filepath"
"runtime"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand All @@ -31,10 +32,12 @@ import (
"k8s.io/kubectl/pkg/util/templates"
configCmd "k8s.io/minikube/cmd/minikube/cmd/config"
"k8s.io/minikube/pkg/drivers/kic/oci"
"k8s.io/minikube/pkg/minikube/audit"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/exit"
"k8s.io/minikube/pkg/minikube/localpath"
"k8s.io/minikube/pkg/minikube/out"
"k8s.io/minikube/pkg/minikube/reason"
"k8s.io/minikube/pkg/minikube/translate"
)
Expand Down Expand Up @@ -62,12 +65,19 @@ var RootCmd = &cobra.Command{
exit.Error(reason.HostHomeMkdir, "Error creating minikube directory", err)
}
}
userName := viper.GetString(config.UserFlag)
if !validateUsername(userName) {
out.WarningT("User name '{{.username}}' is not valid", out.V{"username": userName})
exit.Message(reason.Usage, "User name must be 60 chars or less.")
}
},
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
defer audit.Log(time.Now())

_, callingCmd := filepath.Split(os.Args[0])

if callingCmd == "kubectl" {
Expand Down Expand Up @@ -170,6 +180,7 @@ func init() {

RootCmd.PersistentFlags().StringP(config.ProfileName, "p", constants.DefaultClusterName, `The name of the minikube VM being used. This can be set to allow having multiple instances of minikube independently.`)
RootCmd.PersistentFlags().StringP(configCmd.Bootstrapper, "b", "kubeadm", "The name of the cluster bootstrapper that will set up the Kubernetes cluster.")
RootCmd.PersistentFlags().String(config.UserFlag, "", "Specifies the user executing the operation. Useful for auditing operations executed by 3rd party tools. Defaults to the operating system username.")

groups := templates.CommandGroups{
{
Expand Down Expand Up @@ -280,3 +291,7 @@ func addToPath(dir string) {
klog.Infof("Updating PATH: %s", dir)
os.Setenv("PATH", new)
}

func validateUsername(name string) bool {
return len(name) <= 60
}
78 changes: 78 additions & 0 deletions pkg/minikube/audit/audit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
Copyright 2020 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package audit

import (
"os"
"os/user"
"strings"
"time"

"github.com/spf13/viper"
"k8s.io/klog"
"k8s.io/minikube/pkg/minikube/config"
)

// userName pulls the user flag, if empty gets the os username.
func userName() string {
u := viper.GetString(config.UserFlag)
if u != "" {
return u
}
osUser, err := user.Current()
if err != nil {
return "UNKNOWN"
}
return osUser.Username
}

// args concats the args into space delimited string.
func args() string {
// first arg is binary and second is command, anything beyond is a minikube arg
if len(os.Args) < 3 {
return ""
}
return strings.Join(os.Args[2:], " ")
}

// Log details about the executed command.
func Log(startTime time.Time) {
if !shouldLog() {
return
}
e := newEntry(os.Args[1], args(), userName(), startTime, time.Now())
if err := appendToLog(e); err != nil {
klog.Error(err)
}
}

// shouldLog returns if the command should be logged.
func shouldLog() bool {
// commands that should not be logged.
no := []string{"status", "version"}
// in rare chance we get here without a command, don't log
if len(os.Args) < 2 {
return false
}
a := os.Args[1]
for _, c := range no {
if a == c {
return false
}
}
return true
}
129 changes: 129 additions & 0 deletions pkg/minikube/audit/audit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
Copyright 2020 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package audit

import (
"os"
"os/user"
"testing"

"github.com/spf13/viper"
"k8s.io/minikube/pkg/minikube/config"
)

func TestAudit(t *testing.T) {
t.Run("Username", func(t *testing.T) {
u, err := user.Current()
if err != nil {
t.Fatal(err)
}

tests := []struct {
userFlag string
want string
}{
{
"testUser",
"testUser",
},
{
"",
u.Username,
},
}

for _, test := range tests {
viper.Set(config.UserFlag, test.userFlag)

got := userName()

if got != test.want {
t.Errorf("userFlag = %q; username() = %q; want %q", test.userFlag, got, test.want)
}
}
})

t.Run("Args", func(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()

tests := []struct {
args []string
want string
}{
{
[]string{"minikube", "start"},
"",
},
{
[]string{"minikube", "start", "--user", "testUser"},
"--user testUser",
},
}

for _, test := range tests {
os.Args = test.args

got := args()

if got != test.want {
t.Errorf("os.Args = %q; args() = %q; want %q", os.Args, got, test.want)
}
}
})

t.Run("ShouldLog", func(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()

tests := []struct {
args []string
want bool
}{
{
[]string{"minikube", "start"},
true,
},
{
[]string{"minikube", "delete"},
true,
},
{
[]string{"minikube", "status"},
false,
},
{
[]string{"minikube", "version"},
false,
},
{
[]string{"minikube"},
false,
},
}

for _, test := range tests {
os.Args = test.args

got := shouldLog()

if got != test.want {
t.Errorf("os.Args = %q; shouldLog() = %t; want %t", os.Args, got, test.want)
}
}
})
}
49 changes: 49 additions & 0 deletions pkg/minikube/audit/entry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
Copyright 2020 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package audit

import (
"time"

"github.com/spf13/viper"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants"
)

// entry represents the execution of a command.
type entry struct {
data map[string]string
}

// Type returns the cloud events compatible type of this struct.
func (e *entry) Type() string {
return "io.k8s.sigs.minikube.audit"
}

// newEntry returns a new audit type.
func newEntry(command string, args string, user string, startTime time.Time, endTime time.Time) *entry {
return &entry{
map[string]string{
"args": args,
"command": command,
"endTime": endTime.Format(constants.TimeFormat),
"profile": viper.GetString(config.ProfileName),
"startTime": startTime.Format(constants.TimeFormat),
"user": user,
},
}
}
57 changes: 57 additions & 0 deletions pkg/minikube/audit/logFile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
Copyright 2020 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package audit

import (
"fmt"
"os"

"k8s.io/minikube/pkg/minikube/localpath"
"k8s.io/minikube/pkg/minikube/out/register"
)

// currentLogFile the file that's used to store audit logs
var currentLogFile *os.File

// setLogFile sets the logPath and creates the log file if it doesn't exist.
func setLogFile() error {
lp := localpath.AuditLog()
f, err := os.OpenFile(lp, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("unable to open %s: %v", lp, err)
}
currentLogFile = f
return nil
}

// appendToLog appends the audit entry to the log file.
func appendToLog(entry *entry) error {
if currentLogFile == nil {
if err := setLogFile(); err != nil {
return err
}
}
e := register.CloudEvent(entry, entry.data)
bs, err := e.MarshalJSON()
if err != nil {
return fmt.Errorf("error marshalling event: %v", err)
}
if _, err := currentLogFile.WriteString(string(bs) + "\n"); err != nil {
return fmt.Errorf("unable to write to audit log: %v", err)
}
return nil
}
Loading

0 comments on commit 597091d

Please sign in to comment.