Skip to content

Commit

Permalink
WIP: Add user flag and log executed commands
Browse files Browse the repository at this point in the history
  • Loading branch information
spowelljr committed Jan 14, 2021
1 parent 857e0a2 commit ca1fe41
Show file tree
Hide file tree
Showing 37 changed files with 326 additions and 7 deletions.
5 changes: 5 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,6 +32,7 @@ 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"
Expand Down Expand Up @@ -68,6 +70,8 @@ var RootCmd = &cobra.Command{
// 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 +174,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.User, "", "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
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -986,8 +986,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok=
github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8=
github.com/ulikunitz/xz v0.5.8 h1:ERv8V6GKqVi23rgu5cj9pVfVzJbOqAY2Ntl88O6c2nQ=
github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ultraware/funlen v0.0.1/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA=
Expand Down
57 changes: 57 additions & 0 deletions pkg/minikube/audit/audit.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 (
"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.User)
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 {
if len(os.Args) < 3 {
return ""
}
return strings.Join(os.Args[2:], " ")
}

// Log details about the executed command.
func Log(startTime time.Time) {
e := newEntry(os.Args[1], args(), username(), startTime, time.Now())
if err := appendToLog(e); err != nil {
klog.Error(err)
}
}
83 changes: 83 additions & 0 deletions pkg/minikube/audit/audit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
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("UsernameSetFlag", func(t *testing.T) {
want := "test123"
viper.Set(config.User, want)

got := username()

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

t.Run("UsernameOS", func(t *testing.T) {
viper.Set(config.User, "")

u, err := user.Current()
if err != nil {
t.Fatal(err)
}
want := u.Username

got := username()

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

t.Run("ArgsNone", func(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"minikube", "start"}

want := ""

got := args()

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

t.Run("Args", func(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"minikube", "start", "--user", "test123"}

want := "--user test123"

got := args()

if got != want {
t.Errorf("args() = %q; want %q", got, want)
}
})
}
42 changes: 42 additions & 0 deletions pkg/minikube/audit/entry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
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"

// 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.String(),
"startTime": startTime.String(),
"user": user,
},
}
}
72 changes: 72 additions & 0 deletions pkg/minikube/audit/logFile.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
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"
)

var (
file *os.File
logPath string
)

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

// createLogFile creates the file used for logging audits.
func createLogFile() error {
f, err := os.Create(logPath)
if err != nil {
return fmt.Errorf("unable to create file %s: %v", logPath, err)
}
file = f
return nil
}

// appendToLog appends the audit entry to the log file.
func appendToLog(entry *entry) error {
if file == 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 := file.WriteString(string(bs) + "\n"); err != nil {
return fmt.Errorf("unable to write to %s: %v", logPath, err)
}
return nil
}
2 changes: 2 additions & 0 deletions pkg/minikube/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ const (
ShowDriverDeprecationNotification = "ShowDriverDeprecationNotification"
// ShowBootstrapperDeprecationNotification is the key for ShowBootstrapperDeprecationNotification
ShowBootstrapperDeprecationNotification = "ShowBootstrapperDeprecationNotification"
// User represents the key for the global user parameter
User = "user"
)

var (
Expand Down
5 changes: 5 additions & 0 deletions pkg/minikube/localpath/localpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ func EventLog(name string) string {
return filepath.Join(Profile(name), "events.json")
}

// AuditLog returns the path to the audit log.
func AuditLog() string {
return filepath.Join(MiniPath(), "logs", "audit.json")
}

// ClientCert returns client certificate path, used by kubeconfig
func ClientCert(name string) string {
new := filepath.Join(Profile(name), "client.crt")
Expand Down
10 changes: 5 additions & 5 deletions pkg/minikube/out/register/cloud_events.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ func SetEventLogPath(path string) {
eventFile = f
}

// cloudEvent creates a CloudEvent from a log object & associated data
func cloudEvent(log Log, data map[string]string) cloudevents.Event {
// CloudEvent creates a CloudEvent from a log object & associated data
func CloudEvent(log Log, data map[string]string) cloudevents.Event {
event := cloudevents.NewEvent()
event.SetSource("https://minikube.sigs.k8s.io/")
event.SetType(log.Type())
Expand All @@ -78,7 +78,7 @@ func cloudEvent(log Log, data map[string]string) cloudevents.Event {

// print JSON output to configured writer
func printAsCloudEvent(log Log, data map[string]string) {
event := cloudEvent(log, data)
event := CloudEvent(log, data)

bs, err := event.MarshalJSON()
if err != nil {
Expand All @@ -90,7 +90,7 @@ func printAsCloudEvent(log Log, data map[string]string) {

// print JSON output to configured writer, and record it to disk
func printAndRecordCloudEvent(log Log, data map[string]string) {
event := cloudEvent(log, data)
event := CloudEvent(log, data)

bs, err := event.MarshalJSON()
if err != nil {
Expand Down Expand Up @@ -118,7 +118,7 @@ func recordCloudEvent(log Log, data map[string]string) {
}

go func() {
event := cloudEvent(log, data)
event := CloudEvent(log, data)
bs, err := event.MarshalJSON()
if err != nil {
klog.Errorf("error marshalling event: %v", err)
Expand Down
Loading

0 comments on commit ca1fe41

Please sign in to comment.