Skip to content

Commit 2ee4ddf

Browse files
committed
Add user flag and log executed commands
1 parent 857e0a2 commit 2ee4ddf

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+488
-8
lines changed

cmd/minikube/cmd/.start_flags.go.swp

16 KB
Binary file not shown.

cmd/minikube/cmd/root.go

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import (
2323
"path/filepath"
2424
"runtime"
2525
"strings"
26+
"time"
2627

2728
"github.com/spf13/cobra"
2829
"github.com/spf13/pflag"
@@ -31,6 +32,7 @@ import (
3132
"k8s.io/kubectl/pkg/util/templates"
3233
configCmd "k8s.io/minikube/cmd/minikube/cmd/config"
3334
"k8s.io/minikube/pkg/drivers/kic/oci"
35+
"k8s.io/minikube/pkg/minikube/audit"
3436
"k8s.io/minikube/pkg/minikube/config"
3537
"k8s.io/minikube/pkg/minikube/constants"
3638
"k8s.io/minikube/pkg/minikube/exit"
@@ -68,6 +70,8 @@ var RootCmd = &cobra.Command{
6870
// Execute adds all child commands to the root command sets flags appropriately.
6971
// This is called by main.main(). It only needs to happen once to the rootCmd.
7072
func Execute() {
73+
defer audit.Log(time.Now())
74+
7175
_, callingCmd := filepath.Split(os.Args[0])
7276

7377
if callingCmd == "kubectl" {
@@ -170,6 +174,7 @@ func init() {
170174

171175
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.`)
172176
RootCmd.PersistentFlags().StringP(configCmd.Bootstrapper, "b", "kubeadm", "The name of the cluster bootstrapper that will set up the Kubernetes cluster.")
177+
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.")
173178

174179
groups := templates.CommandGroups{
175180
{

go.sum

-2
Original file line numberDiff line numberDiff line change
@@ -986,8 +986,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1
986986
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
987987
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
988988
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
989-
github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok=
990-
github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8=
991989
github.com/ulikunitz/xz v0.5.8 h1:ERv8V6GKqVi23rgu5cj9pVfVzJbOqAY2Ntl88O6c2nQ=
992990
github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
993991
github.com/ultraware/funlen v0.0.1/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA=

pkg/minikube/audit/audit.go

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
Copyright 2020 The Kubernetes Authors All rights reserved.
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 audit
18+
19+
import (
20+
"os"
21+
"os/user"
22+
"strings"
23+
"time"
24+
25+
"github.com/spf13/viper"
26+
"k8s.io/klog"
27+
"k8s.io/minikube/pkg/minikube/config"
28+
)
29+
30+
// username pulls the user flag, if empty gets the os username.
31+
func username() string {
32+
u := viper.GetString(config.User)
33+
if u != "" {
34+
return u
35+
}
36+
osUser, err := user.Current()
37+
if err != nil {
38+
return "UNKNOWN"
39+
}
40+
return osUser.Username
41+
}
42+
43+
// args concats the args into space delimited string.
44+
func args() string {
45+
// first arg is binary and second is command, anything beyond is a minikube arg
46+
if len(os.Args) < 3 {
47+
return ""
48+
}
49+
return strings.Join(os.Args[2:], " ")
50+
}
51+
52+
// Log details about the executed command.
53+
func Log(startTime time.Time) {
54+
if !shouldLog() {
55+
return
56+
}
57+
e := newEntry(os.Args[1], args(), username(), startTime, time.Now())
58+
if err := appendToLog(e); err != nil {
59+
klog.Error(err)
60+
}
61+
}
62+
63+
// shouldLog returns if the command should be logged.
64+
func shouldLog() bool {
65+
// commands that should not be logged.
66+
no := []string{"status", "version"}
67+
a := os.Args[1]
68+
for _, c := range no {
69+
if a == c {
70+
return false
71+
}
72+
}
73+
return true
74+
}

pkg/minikube/audit/audit_test.go

+125
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/*
2+
Copyright 2020 The Kubernetes Authors All rights reserved.
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 audit
18+
19+
import (
20+
"os"
21+
"os/user"
22+
"testing"
23+
24+
"github.com/spf13/viper"
25+
"k8s.io/minikube/pkg/minikube/config"
26+
)
27+
28+
func TestAudit(t *testing.T) {
29+
t.Run("Username", func(t *testing.T) {
30+
u, err := user.Current()
31+
if err != nil {
32+
t.Fatal(err)
33+
}
34+
35+
tests := []struct {
36+
userFlag string
37+
want string
38+
}{
39+
{
40+
"test123",
41+
"test123",
42+
},
43+
{
44+
"",
45+
u.Username,
46+
},
47+
}
48+
49+
for _, test := range tests {
50+
viper.Set(config.User, test.userFlag)
51+
52+
got := username()
53+
54+
if got != test.want {
55+
t.Errorf("userFlag = %q; username() = %q; want %q", test.userFlag, got, test.want)
56+
}
57+
}
58+
})
59+
60+
t.Run("Args", func(t *testing.T) {
61+
oldArgs := os.Args
62+
defer func() { os.Args = oldArgs }()
63+
64+
tests := []struct {
65+
args []string
66+
want string
67+
}{
68+
{
69+
[]string{"minikube", "start"},
70+
"",
71+
},
72+
{
73+
[]string{"minikube", "start", "--user", "test123"},
74+
"--user test123",
75+
},
76+
}
77+
78+
for _, test := range tests {
79+
os.Args = test.args
80+
81+
got := args()
82+
83+
if got != test.want {
84+
t.Errorf("os.Args = %q; args() = %q; want %q", os.Args, got, test.want)
85+
}
86+
}
87+
})
88+
89+
t.Run("ShouldLog", func(t *testing.T) {
90+
oldArgs := os.Args
91+
defer func() { os.Args = oldArgs }()
92+
93+
tests := []struct {
94+
args []string
95+
want bool
96+
}{
97+
{
98+
[]string{"minikube", "start"},
99+
true,
100+
},
101+
{
102+
[]string{"minikube", "delete"},
103+
true,
104+
},
105+
{
106+
[]string{"minikube", "status"},
107+
false,
108+
},
109+
{
110+
[]string{"minikube", "version"},
111+
false,
112+
},
113+
}
114+
115+
for _, test := range tests {
116+
os.Args = test.args
117+
118+
got := shouldLog()
119+
120+
if got != test.want {
121+
t.Errorf("os.Args = %q; shouldLog() = %t; want %t", os.Args, got, test.want)
122+
}
123+
}
124+
})
125+
}

pkg/minikube/audit/entry.go

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Copyright 2020 The Kubernetes Authors All rights reserved.
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 audit
18+
19+
import (
20+
"time"
21+
22+
"github.com/spf13/viper"
23+
"k8s.io/minikube/pkg/minikube/config"
24+
"k8s.io/minikube/pkg/minikube/constants"
25+
)
26+
27+
// entry represents the execution of a command.
28+
type entry struct {
29+
data map[string]string
30+
}
31+
32+
// Type returns the cloud events compatible type of this struct.
33+
func (e *entry) Type() string {
34+
return "io.k8s.sigs.minikube.audit"
35+
}
36+
37+
// newEntry returns a new audit type.
38+
func newEntry(command string, args string, user string, startTime time.Time, endTime time.Time) *entry {
39+
return &entry{
40+
map[string]string{
41+
"args": args,
42+
"command": command,
43+
"endTime": endTime.Format(constants.TimeFormat),
44+
"profile": viper.GetString(config.ProfileName),
45+
"startTime": startTime.Format(constants.TimeFormat),
46+
"user": user,
47+
},
48+
}
49+
}

pkg/minikube/audit/logFile.go

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Copyright 2020 The Kubernetes Authors All rights reserved.
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 audit
18+
19+
import (
20+
"fmt"
21+
"os"
22+
23+
"k8s.io/minikube/pkg/minikube/localpath"
24+
"k8s.io/minikube/pkg/minikube/out/register"
25+
)
26+
27+
// currentLogFile the file that's used to store audit logs
28+
var currentLogFile *os.File
29+
30+
// setLogFile sets the logPath and creates the log file if it doesn't exist.
31+
func setLogFile() error {
32+
lp := localpath.AuditLog()
33+
f, err := os.OpenFile(lp, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
34+
if err != nil {
35+
return fmt.Errorf("unable to open %s: %v", lp, err)
36+
}
37+
currentLogFile = f
38+
return nil
39+
}
40+
41+
// appendToLog appends the audit entry to the log file.
42+
func appendToLog(entry *entry) error {
43+
if currentLogFile == nil {
44+
if err := setLogFile(); err != nil {
45+
return err
46+
}
47+
}
48+
e := register.CloudEvent(entry, entry.data)
49+
bs, err := e.MarshalJSON()
50+
if err != nil {
51+
return fmt.Errorf("error marshalling event: %v", err)
52+
}
53+
if _, err := currentLogFile.WriteString(string(bs) + "\n"); err != nil {
54+
return fmt.Errorf("unable to write to audit log: %v", err)
55+
}
56+
return nil
57+
}

0 commit comments

Comments
 (0)