Skip to content
This repository was archived by the owner on Jan 22, 2025. It is now read-only.

Commit ff3920a

Browse files
committed
Add -v debug logs to kssh and make kssh silent otherwise
1 parent 0fa0c3c commit ff3920a

7 files changed

Lines changed: 68 additions & 21 deletions

File tree

src/cmd/kssh/kssh.go

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818
)
1919

2020
func main() {
21-
team, remainingArgs, action, err := handleArgs(os.Args[1:])
21+
team, remainingArgs, action, runtimeConfig, err := handleArgs(os.Args[1:])
2222
if err != nil {
2323
fmt.Printf("Failed to parse arguments: %v\n", err)
2424
os.Exit(1)
@@ -29,31 +29,32 @@ func main() {
2929
os.Exit(1)
3030
}
3131
if isValidCert(keyPath) {
32-
doAction(action, keyPath, remainingArgs)
32+
kssh.DebugLog(runtimeConfig, "Reusing unexpired certificate")
33+
doAction(runtimeConfig, action, keyPath, remainingArgs)
3334
}
3435
config, err := getConfig(team)
3536
if err != nil {
3637
fmt.Printf("%v\n", err)
3738
os.Exit(1)
3839
}
39-
err = provisionNewKey(config, keyPath)
40+
err = provisionNewKey(runtimeConfig, config, keyPath)
4041
if err != nil {
4142
fmt.Printf("%v\n", err)
4243
os.Exit(1)
4344
}
44-
doAction(action, keyPath, remainingArgs)
45+
doAction(runtimeConfig, action, keyPath, remainingArgs)
4546
}
4647

47-
func doAction(action Action, keyPath string, remainingArgs []string) {
48+
func doAction(runtimeConfig kssh.RuntimeConfig, action Action, keyPath string, remainingArgs []string) {
4849
if action == SSH {
49-
runSSHWithKey(keyPath, remainingArgs)
50+
runSSHWithKey(runtimeConfig, keyPath, remainingArgs)
5051
} else if action == Provision {
5152
err := kssh.AddKeyToSSHAgent(keyPath)
5253
if err != nil {
5354
fmt.Printf("%v\n", err)
5455
os.Exit(1)
5556
}
56-
fmt.Printf("Provisioned new SSH key at %s\n", keyPath)
57+
kssh.DebugLog(runtimeConfig, "Provisioned new SSH key at %s\n", keyPath)
5758
}
5859
}
5960

@@ -80,6 +81,7 @@ var cliArguments = []kssh.CLIArgument{
8081
{Name: "--set-default-user", HasArgument: true},
8182
{Name: "--clear-default-user", HasArgument: false},
8283
{Name: "--help", HasArgument: false},
84+
{Name: "-v", HasArgument: false, Preserve: true},
8385
}
8486

8587
func generateHelpPage() string {
@@ -93,7 +95,8 @@ VERSION:
9395
0.0.1
9496
9597
GLOBAL OPTIONS:
96-
--help, Show help
98+
--help Show help
99+
-v Enable kssh and ssh debug logs
97100
--provision Provision a new SSH key and add it to the ssh-agent. Useful if you need to run another
98101
program that uses SSH auth (eg scp, rsync, etc)
99102
--set-default-bot Set the default bot to be used for kssh. Not necessary if you are only in one team that
@@ -113,14 +116,15 @@ const (
113116
SSH
114117
)
115118

116-
// Returns botname, remaining arguments, action, error
119+
// Returns botname, remaining arguments, action, runtimeConfig, error
117120
// If the argument requires exiting after processing, it will call os.Exit
118-
func handleArgs(args []string) (string, []string, Action, error) {
121+
func handleArgs(args []string) (string, []string, Action, kssh.RuntimeConfig, error) {
119122
remaining, found, err := kssh.ParseArgs(args, cliArguments)
120123
if err != nil {
121-
return "", nil, 0, fmt.Errorf("Failed to parse provided arguments: %v", err)
124+
return "", nil, 0, kssh.RuntimeConfig{}, fmt.Errorf("Failed to parse provided arguments: %v", err)
122125
}
123126

127+
debug := false
124128
team := ""
125129
action := SSH
126130
for _, arg := range found {
@@ -171,8 +175,11 @@ func handleArgs(args []string) (string, []string, Action, error) {
171175
fmt.Println(generateHelpPage())
172176
os.Exit(0)
173177
}
178+
if arg.Argument.Name == "-v" {
179+
debug = true
180+
}
174181
}
175-
return team, remaining, action, nil
182+
return team, remaining, action, kssh.RuntimeConfig{Debug: debug}, nil
176183
}
177184

178185
// Get the kssh.ConfigFile. botname is the team specified via --bot if one was specified, otherwise the empty string
@@ -248,8 +255,8 @@ func isValidCert(keyPath string) bool {
248255
}
249256

250257
// Provision a new signed SSH key with the given config
251-
func provisionNewKey(config kssh.ConfigFile, keyPath string) error {
252-
fmt.Println("Generating a new SSH key...")
258+
func provisionNewKey(runtimeConfig kssh.RuntimeConfig, config kssh.ConfigFile, keyPath string) error {
259+
kssh.DebugLog(runtimeConfig, "Generating a new SSH key...")
253260
err := sshutils.GenerateNewSSHKey(keyPath, true, false)
254261
if err != nil {
255262
return fmt.Errorf("Failed to generate a new SSH key: %v", err)
@@ -264,13 +271,15 @@ func provisionNewKey(config kssh.ConfigFile, keyPath string) error {
264271
return fmt.Errorf("Failed to generate a new UUID for the SignatureRequest: %v", err)
265272
}
266273

274+
kssh.DebugLog(runtimeConfig, "Requesting signature from the CA....")
267275
resp, err := kssh.GetSignedKey(config, shared.SignatureRequest{
268276
UUID: randomUUID.String(),
269277
SSHPublicKey: string(pubKey),
270278
})
271279
if err != nil {
272280
return fmt.Errorf("Failed to get a signed key from the CA: %v", err)
273281
}
282+
kssh.DebugLog(runtimeConfig, "Received signature from the CA!")
274283

275284
err = ioutil.WriteFile(shared.KeyPathToCert(keyPath), []byte(resp.SignedKey), 0600)
276285
if err != nil {
@@ -281,7 +290,7 @@ func provisionNewKey(config kssh.ConfigFile, keyPath string) error {
281290
}
282291

283292
// Run SSH with the given key. Calls os.Exit and does not return.
284-
func runSSHWithKey(keyPath string, remainingArgs []string) {
293+
func runSSHWithKey(runtimeConfig kssh.RuntimeConfig, keyPath string, remainingArgs []string) {
285294
// Determine whether a default SSH user has been specified and configure it if so
286295
useConfig := false
287296
user, err := kssh.GetDefaultSSHUser()
@@ -305,13 +314,11 @@ func runSSHWithKey(keyPath string, remainingArgs []string) {
305314
os.Exit(1)
306315
}
307316

308-
// A new line to separate kssh output from ssh output
309-
fmt.Printf("\n")
310-
311317
argumentList := []string{"-i", keyPath, "-o", "IdentitiesOnly=yes"}
312318
checkAndWarnOnUnspecifiedBehavior(useConfig, remainingArgs)
313319
if useConfig {
314320
argumentList = append(argumentList, "-F", kssh.AlternateSSHConfigFile)
321+
kssh.DebugLog(runtimeConfig, "Using default ssh user %s", user)
315322
}
316323

317324
argumentList = append(argumentList, remainingArgs...)

src/kssh/bot.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ func GetSignedKey(config ConfigFile, request shared.SignatureRequest) (shared.Si
5151
}
5252
}()
5353

54-
fmt.Println("Requesting signature from the CA....")
5554
hasBeenAcked := false
5655
startTime := time.Now()
5756
for {
@@ -97,7 +96,6 @@ func GetSignedKey(config ConfigFile, request shared.SignatureRequest) (shared.Si
9796
// someone else's signature request
9897
continue
9998
}
100-
fmt.Println("Received signature from the CA!")
10199
return resp, nil
102100
}
103101
}

src/kssh/config.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,7 @@ func GetTeamFromBot(botname string) (string, error) {
227227
}
228228
return "", fmt.Errorf("did not find a client config file matching botname=%s (is the CA bot running and are you in the correct teams?)", botname)
229229
}
230+
231+
type RuntimeConfig struct {
232+
Debug bool
233+
}

src/kssh/debug.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package kssh
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
)
7+
8+
func DebugLog(runtimeConfig RuntimeConfig, fmtString string, a ...interface{}) {
9+
if runtimeConfig.Debug {
10+
str := "kssh: " + fmt.Sprintf(fmtString, a...)
11+
if !strings.HasSuffix(str, "\n") {
12+
str += "\n"
13+
}
14+
fmt.Print(str)
15+
}
16+
}

src/kssh/flags.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ import "fmt"
55
type CLIArgument struct {
66
Name string // eg "--foo"
77
HasArgument bool // true if an argument comes after it (eg "--foo bar") false if it is a boolean flag (eg "--help")
8+
Preserve bool // true if you wish to preserve this argument into the list of remaining arguments even if found
9+
// eg if your command takes in a `-v` flag and the subcommand also takes in a `-v` flag
10+
// incompatible with HasArgument: true
811
}
912

1013
type ParsedCLIArgument struct {
@@ -19,6 +22,12 @@ type ParsedCLIArgument struct {
1922
//
2023
// Returns: a list of the remaining unparsed arguments, a list of the parsed arguments, error
2124
func ParseArgs(args []string, cliArguments []CLIArgument) ([]string, []ParsedCLIArgument, error) {
25+
for _, cliArg := range cliArguments {
26+
if cliArg.Preserve && cliArg.HasArgument {
27+
return nil, nil, fmt.Errorf("cannot specify Preserve and HasArgument for argument %s", cliArg.Name)
28+
}
29+
}
30+
2231
remainingArguments := []string{}
2332
found := []ParsedCLIArgument{}
2433
OUTER:
@@ -36,6 +45,9 @@ OUTER:
3645
i++
3746
}
3847
found = append(found, parsed)
48+
if cliArg.Preserve {
49+
remainingArguments = append(remainingArguments, arg)
50+
}
3951
continue OUTER
4052
}
4153
}

src/kssh/flags_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ func TestParseArgs(t *testing.T) {
1919
{Name: "--arg-with-value", HasArgument: true},
2020
{Name: "--arg2-with-value", HasArgument: true},
2121
{Name: "--arg-without-value", HasArgument: false},
22+
{Name: "--preserved-flag", Preserve: true},
2223
}
2324
testCases := []testCase{
2425
// No arguments
@@ -71,6 +72,16 @@ func TestParseArgs(t *testing.T) {
7172
remaining: nil,
7273
found: nil,
7374
},
75+
// Preserve:true
76+
{
77+
args: []string{"--preserved-flag", "--arg-without-value", "unused"},
78+
err: nil,
79+
remaining: []string{"--preserved-flag", "unused"},
80+
found: []ParsedCLIArgument{
81+
{Argument: CLIArgument{Name: "--preserved-flag", HasArgument: false, Preserve: true}, Value: ""},
82+
{Argument: CLIArgument{Name: "--arg-without-value", HasArgument: false}, Value: ""},
83+
},
84+
},
7485
}
7586

7687
for i, testCase := range testCases {

src/kssh/ssh.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@ func CreateDefaultUserConfigFile(keyPath string) error {
6161
if err != nil {
6262
return err
6363
}
64-
fmt.Printf("Using default ssh user %s\n", user)
6564
return nil
6665
}
6766

0 commit comments

Comments
 (0)