Skip to content

Commit 7296178

Browse files
authored
Merge 7a5f6f8 into 6cc2538
2 parents 6cc2538 + 7a5f6f8 commit 7296178

File tree

70 files changed

+2432
-1598
lines changed

Some content is hidden

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

70 files changed

+2432
-1598
lines changed

CHANGELOG.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,23 @@
1+
# v1.7.0
2+
3+
## Features
4+
5+
### CLI
6+
7+
- `stores import csv`: supports interactive credential input, as well as input via flags and environmental
8+
variables. [docs](docs/kfutil_stores_import_csv.md)
9+
10+
## Fixes
11+
12+
### CLI
13+
14+
- `stores import csv`: providing a `Password(/StorePassword)` does not crash CLI.
15+
- `stores import csv`: results CSV retains input header ordering.
16+
- `stores import csv`: Handle `BOM` characters in an input CSV file.
17+
- `store-types create`: URL encode `-b` parameter when passed.
18+
- `store-types create`: Initialize logger before fetching store-type definitions.
19+
- `stores rot`: Re-enabled and improved logging.
20+
121
# v1.6.2
222

323
## Fixes

cmd/constants.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,14 @@ const (
3030
FlagGitRef = "git-ref"
3131
FlagGitRepo = "repo"
3232
FlagFromFile = "from-file"
33-
DebugFuncEnter = "entered: %s"
34-
DebugFuncExit = "exiting: %s"
35-
DebugFuncCall = "calling: %s"
33+
DebugFuncEnter = "entered:"
34+
DebugFuncExit = "exiting:"
35+
DebugFuncCall = "calling:"
3636
MinHttpTimeout = 3
37+
38+
EnvStoresImportCSVServerUsername = "KFUTIL_CSV_SERVER_USERNAME"
39+
EnvStoresImportCSVServerPassword = "KFUTIL_CSV_SERVER_PASSWORD"
40+
EnvStoresImportCSVStorePassword = "KFUTIL_CSV_STORE_PASSWORD"
3741
)
3842

3943
var ProviderTypeChoices = []string{

cmd/helpers.go

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@ import (
2323
"net/http"
2424
"os"
2525
"path/filepath"
26+
"slices"
2627
"strconv"
2728
"time"
2829

2930
"github.com/google/uuid"
3031
"github.com/rs/zerolog"
3132
"github.com/rs/zerolog/log"
3233
"github.com/spf13/cobra"
33-
34-
stdlog "log"
34+
//stdlog "log"
3535
)
3636

3737
func boolToPointer(b bool) *bool {
@@ -132,7 +132,7 @@ func csvToMap(filename string) ([]map[string]string, error) {
132132

133133
// Populate the map with data from the row
134134
for i, column := range header {
135-
rowMap[column] = row[i]
135+
rowMap[column] = stripAllBOMs(row[i])
136136
}
137137

138138
// Append the map to the data slice
@@ -190,12 +190,23 @@ func informDebug(debugFlag bool) {
190190
}
191191

192192
func initLogger() {
193-
stdlog.SetOutput(io.Discard)
194-
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
195-
zerolog.SetGlobalLevel(zerolog.Disabled) // default to disabled
196-
log.Logger = log.With().Caller().Logger()
193+
// Configure zerolog to include caller information
194+
log.Logger = log.With().Caller().Logger().Output(
195+
zerolog.ConsoleWriter{
196+
Out: os.Stdout,
197+
TimeFormat: time.RFC3339,
198+
FormatCaller: func(caller interface{}) string {
199+
if c, ok := caller.(string); ok {
200+
return c // This will include the full file path and line number
201+
}
202+
return ""
203+
},
204+
},
205+
)
197206
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339})
198207

208+
initStdLogger()
209+
199210
}
200211

201212
func intToPointer(i int) *int {
@@ -282,27 +293,32 @@ func logGlobals() {
282293

283294
}
284295

285-
func mapToCSV(data []map[string]string, filename string) error {
286-
file, err := os.Create(filename)
287-
if err != nil {
288-
return err
296+
func mapToCSV(data []map[string]string, filename string, inputHeader []string) error {
297+
file, fErr := os.Create(filename)
298+
if fErr != nil {
299+
return fErr
289300
}
290301
defer file.Close()
291302

292303
writer := csv.NewWriter(file)
293304
defer writer.Flush()
294305

295306
// Write the header using keys from the first map
296-
var header []string
297-
if len(data) > 0 {
307+
var header = inputHeader
308+
if len(header) <= 0 && len(data) > 0 {
298309
for key := range data[0] {
299-
header = append(header, key)
300-
}
301-
if err := writer.Write(header); err != nil {
302-
return err
310+
header = append(header, stripAllBOMs(key))
303311
}
304312
}
305313

314+
errorColFound := slices.Contains(header, "Errors")
315+
if !errorColFound {
316+
header = append(header, "Errors")
317+
}
318+
if hErr := writer.Write(header); hErr != nil {
319+
return hErr
320+
}
321+
306322
// Write map data to CSV
307323
for _, row := range data {
308324
var record []string

cmd/logging.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package cmd
2+
3+
import (
4+
"strings"
5+
6+
"github.com/rs/zerolog/log"
7+
)
8+
9+
// zerologWriter implements io.Writer and forwards standard log output to zerolog
10+
type zerologWriter struct{}
11+
12+
func (w zerologWriter) Write(p []byte) (n int, err error) {
13+
// Clean up the log message (remove timestamp, etc.)
14+
msg := string(p)
15+
msg = strings.TrimSpace(msg)
16+
17+
// Check if it's a debug message
18+
if strings.Contains(msg, "[DEBUG]") {
19+
msg = strings.Replace(msg, "[DEBUG]", "", 1)
20+
log.Debug().Msg(strings.TrimSpace(msg))
21+
} else if strings.Contains(msg, "[ERROR]") {
22+
msg = strings.Replace(msg, "[ERROR]", "", 1)
23+
log.Error().Msg(strings.TrimSpace(msg))
24+
} else if strings.Contains(msg, "[INFO]") {
25+
msg = strings.Replace(msg, "[INFO]", "", 1)
26+
log.Info().Msg(strings.TrimSpace(msg))
27+
28+
} else if strings.Contains(msg, "[WARN]") {
29+
msg = strings.Replace(msg, "[WARN]", "", 1)
30+
log.Warn().Msg(strings.TrimSpace(msg))
31+
32+
} else if strings.Contains(msg, "[FATAL]") {
33+
msg = strings.Replace(msg, "[FATAL]", "", 1)
34+
log.Fatal().Msg(strings.TrimSpace(msg))
35+
36+
} else if strings.Contains(msg, "[TRACE]") {
37+
msg = strings.Replace(msg, "[TRACE]", "", 1)
38+
log.Debug().Msg(strings.TrimSpace(msg)) // Converting TRACE to DEBUG for zerolog
39+
} else {
40+
// Default to info level
41+
log.Info().Msg(msg)
42+
}
43+
44+
return len(p), nil
45+
}

cmd/login.go

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@ package cmd
1717
import (
1818
"bufio"
1919
"fmt"
20-
"io"
21-
stdlog "log"
2220
"os"
2321
"path"
2422
"strings"
@@ -70,7 +68,7 @@ WARNING: This will write the environmental credentials to disk and will be store
7068
if debugErr != nil {
7169
return debugErr
7270
}
73-
stdlog.SetOutput(io.Discard)
71+
//stdlog.SetOutput(io.Discard)
7472
informDebug(debugFlag)
7573
logGlobals()
7674

@@ -237,14 +235,32 @@ WARNING: This will write the environmental credentials to disk and will be store
237235
}
238236

239237
if authType == "oauth" {
240-
log.Debug().Msg("attempting to authenticate via OAuth")
238+
log.Debug().
239+
Str("profile", profile).
240+
Str("configFile", configFile).
241+
Str("host", outputServer.Host).
242+
Str("authType", authType).
243+
Str("accessToken", hashSecretValue(kfcOAuth.AccessToken)).
244+
Str("clientID", kfcOAuth.ClientID).
245+
Str("clientSecret", hashSecretValue(kfcOAuth.ClientSecret)).
246+
Str("apiPath", kfcOAuth.CommandAPIPath).
247+
Msg("attempting to authenticate via OAuth")
241248
aErr := kfcOAuth.Authenticate()
242249
if aErr != nil {
243250
log.Error().Err(aErr)
244251
return aErr
245252
}
246253
} else if authType == "basic" {
247-
log.Debug().Msg("attempting to authenticate via Basic Auth")
254+
log.Debug().
255+
Str("profile", profile).
256+
Str("configFile", configFile).
257+
Str("host", outputServer.Host).
258+
Str("authType", authType).
259+
Str("username", kfcBasicAuth.Username).
260+
Str("domain", kfcBasicAuth.Domain).
261+
Str("password", hashSecretValue(kfcBasicAuth.Password)).
262+
Str("apiPath", kfcBasicAuth.CommandAPIPath).
263+
Msg("attempting to authenticate via Basic Auth")
248264
aErr := kfcBasicAuth.Authenticate()
249265
if aErr != nil {
250266
log.Error().Err(aErr)

cmd/logout.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ package cmd
1616

1717
import (
1818
"fmt"
19-
"io"
20-
stdlog "log"
2119
"os"
2220

2321
"github.com/Keyfactor/keyfactor-auth-client-go/auth_providers"
@@ -39,7 +37,7 @@ var logoutCmd = &cobra.Command{
3937
if debugErr != nil {
4038
return debugErr
4139
}
42-
stdlog.SetOutput(io.Discard)
40+
//stdlog.SetOutput(io.Discard)
4341
informDebug(debugFlag)
4442

4543
logGlobals()

cmd/root.go

Lines changed: 68 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ package cmd
1717
import (
1818
_ "embed"
1919
"fmt"
20-
"io"
2120
stdlog "log"
2221
"os"
2322
"strings"
@@ -135,6 +134,13 @@ func getServerConfigFromEnv() (*auth_providers.Server, error) {
135134
apiPath, aOk := os.LookupEnv(auth_providers.EnvKeyfactorAPIPath)
136135
clientId, cOk := os.LookupEnv(auth_providers.EnvKeyfactorClientID)
137136
clientSecret, csOk := os.LookupEnv(auth_providers.EnvKeyfactorClientSecret)
137+
audience, _ := os.LookupEnv(auth_providers.EnvKeyfactorAuthAudience)
138+
scopesCSV, _ := os.LookupEnv(auth_providers.EnvKeyfactorAuthScopes)
139+
var scopes []string
140+
if scopesCSV != "" {
141+
scopes = strings.Split(scopesCSV, ",")
142+
}
143+
138144
tokenUrl, tOk := os.LookupEnv(auth_providers.EnvKeyfactorAuthTokenURL)
139145
skipVerify, svOk := os.LookupEnv(auth_providers.EnvKeyfactorSkipVerify)
140146
var skipVerifyBool bool
@@ -161,24 +167,44 @@ func getServerConfigFromEnv() (*auth_providers.Server, error) {
161167
}
162168

163169
if isBasicAuth {
164-
log.Debug().
165-
Str("username", username).
166-
Str("password", hashSecretValue(password)).
167-
Str("domain", domain).
168-
Str("hostname", hostname).
170+
171+
log.Debug().Str("hostname", hostname).
169172
Str("apiPath", apiPath).
170173
Bool("skipVerify", skipVerifyBool).
171-
Msg("call: basicAuthNoParamsConfig.Authenticate()")
174+
Msg("setting up basic auth client base configuration")
172175
basicAuthNoParamsConfig.WithCommandHostName(hostname).
173176
WithCommandAPIPath(apiPath).
174177
WithSkipVerify(skipVerifyBool)
175178

176-
bErr := basicAuthNoParamsConfig.
179+
log.Debug().
180+
Str("username", username).
181+
Str("password", hashSecretValue(password)).
182+
Str("domain", domain).
183+
Msg("setting up basic auth configuration")
184+
_ = basicAuthNoParamsConfig.
177185
WithUsername(username).
178186
WithPassword(password).
179-
WithDomain(domain).
180-
Authenticate()
181-
log.Debug().Msg("complete: basicAuthNoParamsConfig.Authenticate()")
187+
WithDomain(domain)
188+
189+
log.Debug().
190+
Str("username", basicAuthNoParamsConfig.Username).
191+
Str("password", hashSecretValue(password)).
192+
Str("domain", basicAuthNoParamsConfig.Domain).
193+
Str("hostname", basicAuthNoParamsConfig.CommandHostName).
194+
Str("apiPath", basicAuthNoParamsConfig.CommandAPIPath).
195+
Bool("skipVerify", basicAuthNoParamsConfig.CommandAuthConfig.SkipVerify).
196+
Msg(fmt.Sprintf("%s basicAuthNoParamsConfig.Authenticate()", DebugFuncCall))
197+
198+
bErr := basicAuthNoParamsConfig.Authenticate()
199+
log.Debug().
200+
Str("username", basicAuthNoParamsConfig.Username).
201+
Str("password", hashSecretValue(password)).
202+
Str("domain", basicAuthNoParamsConfig.Domain).
203+
Str("hostname", basicAuthNoParamsConfig.CommandHostName).
204+
Str("apiPath", basicAuthNoParamsConfig.CommandAPIPath).
205+
Bool("skipVerify", basicAuthNoParamsConfig.CommandAuthConfig.SkipVerify).
206+
Msg("complete: basicAuthNoParamsConfig.Authenticate()")
207+
182208
if bErr != nil {
183209
log.Error().Err(bErr).Msg("unable to authenticate with provided credentials")
184210
return nil, bErr
@@ -187,16 +213,36 @@ func getServerConfigFromEnv() (*auth_providers.Server, error) {
187213
return basicAuthNoParamsConfig.GetServerConfig(), nil
188214
} else if isOAuth {
189215
log.Debug().
190-
Str("clientId", clientId).
191-
Str("clientSecret", hashSecretValue(clientSecret)).
192-
Str("tokenUrl", tokenUrl).
193216
Str("hostname", hostname).
194217
Str("apiPath", apiPath).
195218
Bool("skipVerify", skipVerifyBool).
196-
Msg("call: oAuthNoParamsConfig.Authenticate()")
219+
Msg("setting up oAuth client base configuration")
197220
_ = oAuthNoParamsConfig.CommandAuthConfig.WithCommandHostName(hostname).
198221
WithCommandAPIPath(apiPath).
199222
WithSkipVerify(skipVerifyBool)
223+
224+
log.Debug().
225+
Str("clientId", clientId).
226+
Str("clientSecret", hashSecretValue(clientSecret)).
227+
Str("tokenUrl", tokenUrl).
228+
Str("audience", audience).
229+
Strs("scopes", scopes).
230+
Msg("setting up oAuth configuration")
231+
_ = oAuthNoParamsConfig.WithClientId(clientId).
232+
WithClientSecret(clientSecret).
233+
WithTokenUrl(tokenUrl).
234+
WithAudience(audience).
235+
WithScopes(scopes)
236+
237+
log.Debug().
238+
Str("clientId", oAuthNoParamsConfig.ClientID).
239+
Str("clientSecret", hashSecretValue(oAuthNoParamsConfig.ClientSecret)).
240+
Str("tokenUrl", oAuthNoParamsConfig.TokenURL).
241+
Str("hostname", oAuthNoParamsConfig.CommandHostName).
242+
Str("apiPath", oAuthNoParamsConfig.CommandAPIPath).
243+
Bool("skipVerify", oAuthNoParamsConfig.SkipVerify).
244+
Str("caCert", oAuthNoParamsConfig.CommandCACert).
245+
Msg(fmt.Sprintf("%s oAuthNoParamsConfig.Authenticate()", DebugFuncCall))
200246
oErr := oAuthNoParamsConfig.Authenticate()
201247
log.Debug().Msg("complete: oAuthNoParamsConfig.Authenticate()")
202248
if oErr != nil {
@@ -738,7 +784,7 @@ var RootCmd = &cobra.Command{
738784
// Execute adds all child commands to the root command and sets flags appropriately.
739785
// This is called by main.main(). It only needs to happen once to the rootCmd.
740786
func Execute() {
741-
stdlog.SetOutput(io.Discard)
787+
//stdlog.SetOutput(io.Discard)
742788
err := RootCmd.Execute()
743789
if err != nil {
744790
os.Exit(1)
@@ -881,3 +927,9 @@ func init() {
881927

882928
RootCmd.AddCommand(makeDocsCmd)
883929
}
930+
931+
func initStdLogger() {
932+
// Redirect standard library's log to zerolog
933+
stdlog.SetOutput(zerologWriter{})
934+
stdlog.SetFlags(0) // Remove timestamp from standard logger
935+
}

0 commit comments

Comments
 (0)