Skip to content

Commit

Permalink
refactor(log): replace panics with log fatal or log panic functions
Browse files Browse the repository at this point in the history
Signed-off-by: Laurentiu Niculae <[email protected]>
  • Loading branch information
laurentiuNiculae committed Aug 25, 2023
1 parent 289acfa commit f20e20d
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 41 deletions.
41 changes: 24 additions & 17 deletions pkg/api/authn.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,11 @@ const (
type AuthnMiddleware struct {
credMap map[string]string
ldapClient *LDAPClient
log log.Logger
}

func AuthHandler(ctlr *Controller) mux.MiddlewareFunc {
authnMiddleware := &AuthnMiddleware{}
authnMiddleware := &AuthnMiddleware{log: ctlr.Log}

if ctlr.Config.IsBearerAuthEnabled() {
return bearerAuthHandler(ctlr)
Expand Down Expand Up @@ -245,14 +246,14 @@ func (amw *AuthnMiddleware) TryAuthnHandlers(ctlr *Controller) mux.MiddlewareFun

cookieStoreHashKey := securecookie.GenerateRandomKey(64)
if cookieStoreHashKey == nil {
panic(zerr.ErrHashKeyNotCreated)
amw.log.Fatal().Err(zerr.ErrHashKeyNotCreated).Msg("failed to generate random key")
}

// if storage is filesystem then use zot's rootDir to store sessions
if ctlr.Config.Storage.StorageDriver == nil {
sessionsDir := path.Join(ctlr.Config.Storage.RootDirectory, "_sessions")
if err := os.MkdirAll(sessionsDir, storageConstants.DefaultDirPerms); err != nil {
panic(err)
amw.log.Fatal().Err(err).Str("session-dir", sessionsDir).Msg("failed to create session dir")
}

cookieStore := sessions.NewFilesystemStore(sessionsDir, cookieStoreHashKey)
Expand Down Expand Up @@ -291,21 +292,24 @@ func (amw *AuthnMiddleware) TryAuthnHandlers(ctlr *Controller) mux.MiddlewareFun
if ctlr.Config.HTTP.Auth.LDAP.CACert != "" {
caCert, err := os.ReadFile(ctlr.Config.HTTP.Auth.LDAP.CACert)
if err != nil {
panic(err)
amw.log.Fatal().Err(err).Str("caCert", ctlr.Config.HTTP.Auth.LDAP.CACert).
Msg("failed to read caCert")
}

caCertPool := x509.NewCertPool()

if !caCertPool.AppendCertsFromPEM(caCert) {
panic(zerr.ErrBadCACert)
amw.log.Fatal().Err(zerr.ErrBadCACert).Str("caCert", ctlr.Config.HTTP.Auth.LDAP.CACert).
Msg("failed to read caCert")
}

amw.ldapClient.ClientCAs = caCertPool
} else {
// default to system cert pool
caCertPool, err := x509.SystemCertPool()
if err != nil {
panic(zerr.ErrBadCACert)
amw.log.Fatal().Err(zerr.ErrBadCACert).Str("caCert", ctlr.Config.HTTP.Auth.LDAP.CACert).
Msg("failed to get system cert pool")
}

amw.ldapClient.ClientCAs = caCertPool
Expand All @@ -315,7 +319,8 @@ func (amw *AuthnMiddleware) TryAuthnHandlers(ctlr *Controller) mux.MiddlewareFun
if ctlr.Config.IsHtpasswdAuthEnabled() {
credsFile, err := os.Open(ctlr.Config.HTTP.Auth.HTPasswd.Path)
if err != nil {
panic(err)
amw.log.Fatal().Err(err).Str("credsFile", ctlr.Config.HTTP.Auth.HTPasswd.Path).
Msg("failed to open creds-file")
}
defer credsFile.Close()

Expand All @@ -336,10 +341,10 @@ func (amw *AuthnMiddleware) TryAuthnHandlers(ctlr *Controller) mux.MiddlewareFun

for provider := range ctlr.Config.HTTP.Auth.OpenID.Providers {
if config.IsOpenIDSupported(provider) {
rp := NewRelyingPartyOIDC(ctlr.Config, provider)
rp := NewRelyingPartyOIDC(ctlr.Config, provider, ctlr.Log)
ctlr.RelyingParties[provider] = rp
} else if config.IsOauth2Supported(provider) {
rp := NewRelyingPartyGithub(ctlr.Config, provider)
rp := NewRelyingPartyGithub(ctlr.Config, provider, ctlr.Log)
ctlr.RelyingParties[provider] = rp
}
}
Expand Down Expand Up @@ -548,19 +553,20 @@ func (rh *RouteHandler) AuthURLHandler() http.HandlerFunc {
}
}

func NewRelyingPartyOIDC(config *config.Config, provider string) rp.RelyingParty {
issuer, clientID, clientSecret, redirectURI, scopes, options := getRelyingPartyArgs(config, provider)
func NewRelyingPartyOIDC(config *config.Config, provider string, log log.Logger) rp.RelyingParty {
issuer, clientID, clientSecret, redirectURI, scopes, options := getRelyingPartyArgs(config, provider, log)

relyingParty, err := rp.NewRelyingPartyOIDC(issuer, clientID, clientSecret, redirectURI, scopes, options...)
if err != nil {
panic(err)
log.Panic().Err(err).Str("issuer", issuer).Str("redirectURI", redirectURI).Strs("scopes", scopes).
Msg("failed to get new rekying party oicd")
}

return relyingParty
}

func NewRelyingPartyGithub(config *config.Config, provider string) rp.RelyingParty {
_, clientID, clientSecret, redirectURI, scopes, options := getRelyingPartyArgs(config, provider)
func NewRelyingPartyGithub(config *config.Config, provider string, log log.Logger) rp.RelyingParty {
_, clientID, clientSecret, redirectURI, scopes, options := getRelyingPartyArgs(config, provider, log)

rpConfig := &oauth2.Config{
ClientID: clientID,
Expand All @@ -572,17 +578,18 @@ func NewRelyingPartyGithub(config *config.Config, provider string) rp.RelyingPar

relyingParty, err := rp.NewRelyingPartyOAuth(rpConfig, options...)
if err != nil {
panic(err)
log.Panic().Err(err).Str("redirectURI", redirectURI).Strs("scopes", scopes).
Msg("failed to get new rekying party oauth")
}

return relyingParty
}

func getRelyingPartyArgs(cfg *config.Config, provider string) (
func getRelyingPartyArgs(cfg *config.Config, provider string, log log.Logger) (
string, string, string, string, []string, []rp.Option,
) {
if _, ok := cfg.HTTP.Auth.OpenID.Providers[provider]; !ok {
panic(zerr.ErrOpenIDProviderDoesNotExist)
log.Panic().Err(zerr.ErrOpenIDProviderDoesNotExist).Str("provider", provider).Msg("")
}

clientID := cfg.HTTP.Auth.OpenID.Providers[provider].ClientID
Expand Down
4 changes: 2 additions & 2 deletions pkg/api/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,13 @@ func (c *Controller) Run(reloadCtx context.Context) error {

caCert, err := os.ReadFile(c.Config.HTTP.TLS.CACert)
if err != nil {
panic(err)
c.Log.Fatal().Err(err).Str("caCert", c.Config.HTTP.TLS.CACert).Msg("failed to read file")
}

caCertPool := x509.NewCertPool()

if !caCertPool.AppendCertsFromPEM(caCert) {
panic(errors.ErrBadCACert)
c.Log.Panic().Err(errors.ErrBadCACert).Msg("failed to append cherts from pem")
}

server.TLSConfig.ClientAuth = clientAuth
Expand Down
10 changes: 5 additions & 5 deletions pkg/api/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2547,15 +2547,15 @@ func TestNewRelyingPartyOIDC(t *testing.T) {
}

Convey("provider not found in config", func() {
So(func() { _ = api.NewRelyingPartyOIDC(conf, "notDex") }, ShouldPanic)
So(func() { _ = api.NewRelyingPartyOIDC(conf, "notDex", log.NewLogger("debug", "")) }, ShouldPanic)
})

Convey("key path not found on disk", func() {
oidcProviderCfg := conf.HTTP.Auth.OpenID.Providers["oidc"]
oidcProviderCfg.KeyPath = "path/to/file"
conf.HTTP.Auth.OpenID.Providers["oidc"] = oidcProviderCfg

So(func() { _ = api.NewRelyingPartyOIDC(conf, "oidc") }, ShouldPanic)
So(func() { _ = api.NewRelyingPartyOIDC(conf, "oidc", log.NewLogger("debug", "")) }, ShouldPanic)
})

Convey("https callback", func() {
Expand All @@ -2564,7 +2564,7 @@ func TestNewRelyingPartyOIDC(t *testing.T) {
Key: ServerKey,
}

rp := api.NewRelyingPartyOIDC(conf, "oidc")
rp := api.NewRelyingPartyOIDC(conf, "oidc", log.NewLogger("debug", ""))
So(rp, ShouldNotBeNil)
})

Expand All @@ -2573,7 +2573,7 @@ func TestNewRelyingPartyOIDC(t *testing.T) {
oidcProvider.ClientSecret = ""
conf.HTTP.Auth.OpenID.Providers["oidc"] = oidcProvider

rp := api.NewRelyingPartyOIDC(conf, "oidc")
rp := api.NewRelyingPartyOIDC(conf, "oidc", log.NewLogger("debug", ""))
So(rp, ShouldNotBeNil)
})

Expand All @@ -2582,7 +2582,7 @@ func TestNewRelyingPartyOIDC(t *testing.T) {
oidcProvider.Issuer = ""
conf.HTTP.Auth.OpenID.Providers["oidc"] = oidcProvider

So(func() { _ = api.NewRelyingPartyOIDC(conf, "oidc") }, ShouldPanic)
So(func() { _ = api.NewRelyingPartyOIDC(conf, "oidc", log.NewLogger("debug", "")) }, ShouldPanic)
})
})
}
Expand Down
6 changes: 2 additions & 4 deletions pkg/cli/config_reloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,13 @@ func (hr *HotReloader) Start() context.Context {
}
// watch for errors
case err := <-hr.watcher.Errors:
log.Error().Err(err).Str("config", hr.filePath).Msg("fsnotfy error while watching config")
panic(err)
log.Panic().Err(err).Str("config", hr.filePath).Msg("fsnotfy error while watching config")
}
}
}()

if err := hr.watcher.Add(hr.filePath); err != nil {
log.Error().Err(err).Str("config", hr.filePath).Msg("error adding config file to FsNotify watcher")
panic(err)
log.Panic().Err(err).Str("config", hr.filePath).Msg("error adding config file to FsNotify watcher")
}

<-done
Expand Down
2 changes: 1 addition & 1 deletion pkg/compliance/v1_0_0/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func CheckWorkflows(t *testing.T, config *compliance.Config) {
t.Helper()

if config == nil || config.Address == "" || config.Port == "" {
panic("insufficient config")
t.Fatal("insufficient config")
}

if config.OutputJSON {
Expand Down
9 changes: 3 additions & 6 deletions pkg/exporter/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,15 @@ func loadConfiguration(config *api.Config, configPath string) {
viper.SetConfigFile(configPath)

if err := viper.ReadInConfig(); err != nil {
log.Error().Err(err).Msg("Error while reading configuration")
panic(err)
log.Panic().Err(err).Msg("Error while reading configuration")
}

metaData := &mapstructure.Metadata{}
if err := viper.Unmarshal(&config, metadataConfig(metaData)); err != nil {
log.Error().Err(err).Msg("Error while unmarshalling new config")
panic(err)
log.Panic().Err(err).Msg("Error while unmarshalling new config")
}

if len(metaData.Keys) == 0 || len(metaData.Unused) > 0 {
log.Error().Err(errors.ErrBadConfig).Msg("Bad configuration, retry writing it")
panic(errors.ErrBadConfig)
log.Panic().Err(errors.ErrBadConfig).Msg("Bad configuration, retry writing it")
}
}
8 changes: 4 additions & 4 deletions pkg/meta/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func Create(dbtype string, dbDriver, parameters interface{}, log log.Logger, //n
{
properDriver, ok := dbDriver.(*bbolt.DB)
if !ok {
panic("failed type assertion")
log.Panic().Msg("failed type assertion")
}

return boltdb.New(properDriver, log)
Expand All @@ -58,12 +58,12 @@ func Create(dbtype string, dbDriver, parameters interface{}, log log.Logger, //n
{
properDriver, ok := dbDriver.(*dynamodb.Client)
if !ok {
panic("failed type assertion")
log.Panic().Msg("failed type assertion")
}

properParameters, ok := parameters.(mdynamodb.DBDriverParameters)
if !ok {
panic("failed type assertion")
log.Panic().Msg("failed type assertion")
}

return mdynamodb.New(properDriver, properParameters, log)
Expand Down Expand Up @@ -103,7 +103,7 @@ func getDynamoParams(cacheDriverConfig map[string]interface{}, log log.Logger) m
allParametersOk = allParametersOk && ok

if !allParametersOk {
panic("dynamo parameters are not specified correctly, can't proceede")
log.Panic().Msg("dynamo parameters are not specified correctly, can't proceede")
}

return mdynamodb.DBDriverParameters{
Expand Down
2 changes: 1 addition & 1 deletion pkg/storage/cache/boltdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type BoltDBDriverParameters struct {
func NewBoltDBCache(parameters interface{}, log zlog.Logger) Cache {
properParameters, ok := parameters.(BoltDBDriverParameters)
if !ok {
panic("Failed type assertion")
log.Panic().Msg("Failed type assertion")
}

err := os.MkdirAll(properParameters.RootDir, constants.DefaultDirPerms)
Expand Down
2 changes: 1 addition & 1 deletion pkg/storage/cache/dynamodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (d *DynamoDBDriver) NewTable(tableName string) error {
func NewDynamoDBCache(parameters interface{}, log zlog.Logger) Cache {
properParameters, ok := parameters.(DynamoDBDriverParameters)
if !ok {
panic("Failed type assertion!")
log.Panic().Msg("Failed type assertion")
}

// custom endpoint resolver to point to localhost
Expand Down

0 comments on commit f20e20d

Please sign in to comment.