Skip to content

Commit

Permalink
golang-ci: Enable lll (long lines) linter and fix issues
Browse files Browse the repository at this point in the history
Set the long lines linter to block lines longer than 120 chars an fix
the cases in which we were not respecting this limit.

This was somewhat mentioned during the sprint, and I wanted to finally
tackle it :)
  • Loading branch information
3v1n0 committed Nov 5, 2024
1 parent ab5a98a commit 39dfb18
Show file tree
Hide file tree
Showing 58 changed files with 1,149 additions and 465 deletions.
5 changes: 5 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ linters:
- godot
- gofmt
- gosec
- lll
- misspell
- nakedret
- nolintlint
Expand Down Expand Up @@ -61,3 +62,7 @@ linters-settings:
# Never have naked return ever
nakedret:
max-func-lines: 1

lll:
line-length: 120
tab-width: 4
6 changes: 4 additions & 2 deletions cmd/authd/daemon/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ func initViperConfig(name string, cmd *cobra.Command, vip *viper.Viper) (err err
vip.AddConfigPath("/etc/authd/")
// Add the executable path to the config search path.
if binPath, err := os.Executable(); err != nil {
log.Warningf(context.Background(), "Failed to get current executable path, not adding it as a config dir: %v", err)
log.Warningf(context.Background(),
"Failed to get current executable path, not adding it as a config dir: %v", err)
} else {
vip.AddConfigPath(filepath.Dir(binPath))
}
Expand All @@ -49,7 +50,8 @@ func initViperConfig(name string, cmd *cobra.Command, vip *viper.Viper) (err err
if err := vip.ReadInConfig(); err != nil {
var e viper.ConfigFileNotFoundError
if errors.As(err, &e) {
log.Infof(context.Background(), "No configuration file: %v.\nWe will only use the defaults, env variables or flags.", e)
log.Infof(context.Background(),
"No configuration file: %v.\nWe will only use the defaults, env variables or flags.", e)
} else {
return fmt.Errorf("invalid configuration file: %w", err)
}
Expand Down
12 changes: 8 additions & 4 deletions cmd/authd/daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ type daemonConfig struct {
func New() *App {
a := App{ready: make(chan struct{})}
a.rootCmd = cobra.Command{
Use: fmt.Sprintf("%s COMMAND", cmdName),
Use: fmt.Sprintf("%s COMMAND", cmdName),

Short:/*i18n.G(*/ "Authentication daemon", /*)*/
Long:/*i18n.G(*/ "Authentication daemon bridging the system with external brokers.", /*)*/
Args: cobra.NoArgs,
Expand Down Expand Up @@ -138,7 +139,8 @@ func (a *App) serve(config daemonConfig) error {

// installVerbosityFlag adds the -v and -vv options and returns the reference to it.
func installVerbosityFlag(cmd *cobra.Command, viper *viper.Viper) *int {
r := cmd.PersistentFlags().CountP("verbosity", "v" /*i18n.G(*/, "issue INFO (-v), DEBUG (-vv) or DEBUG with caller (-vvv) output") //)
r := cmd.PersistentFlags().CountP("verbosity", "v", /*i18n.G(*/
"issue INFO (-v), DEBUG (-vv) or DEBUG with caller (-vvv) output") //)
decorate.LogOnError(viper.BindPFlag("verbosity", cmd.PersistentFlags().Lookup("verbosity")))
return r
}
Expand Down Expand Up @@ -171,12 +173,14 @@ func (a *App) Quit() {
}

// WaitReady signals when the daemon is ready
// Note: we need to use a pointer to not copy the App object before the daemon is ready, and thus, creates a data race.
// Note: we need to use a pointer to not copy the App object before the daemon is ready,
// and thus, creates a data race.
func (a *App) WaitReady() {
<-a.ready
}

// RootCmd returns a copy of the root command for the app. Shouldn't be in general necessary apart when running generators.
// RootCmd returns a copy of the root command for the app.
// Shouldn't be in general necessary apart when running generators.
func (a App) RootCmd() cobra.Command {
return a.rootCmd
}
5 changes: 3 additions & 2 deletions cmd/authd/daemon/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ func (a *App) installVersion() {
cmd := &cobra.Command{
Use: "version",
Short:/*i18n.G(*/ "Returns version of daemon and exits", /*)*/
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { return getVersion() },

Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { return getVersion() },
}
a.rootCmd.AddCommand(cmd)
}
Expand Down
32 changes: 21 additions & 11 deletions examplebroker/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ func New(name string) (b *Broker, fullName, brandIcon string) {
}

// NewSession creates a new session for the specified user.
func (b *Broker) NewSession(ctx context.Context, username, lang, mode string) (sessionID, encryptionKey string, err error) {
func (b *Broker) NewSession(ctx context.Context, username, lang, mode string) (
sessionID, encryptionKey string, err error) {
sessionID = uuid.New().String()
info := sessionInfo{
username: username,
Expand Down Expand Up @@ -214,8 +215,10 @@ func (b *Broker) NewSession(ctx context.Context, username, lang, mode string) (s
return sessionID, base64.StdEncoding.EncodeToString(pubASN1), nil
}

// GetAuthenticationModes returns the list of supported authentication modes for the selected broker depending on session info.
func (b *Broker) GetAuthenticationModes(ctx context.Context, sessionID string, supportedUILayouts []map[string]string) (authenticationModes []map[string]string, err error) {
// GetAuthenticationModes returns the list of supported authentication modes
// for the selected broker depending on session info.
func (b *Broker) GetAuthenticationModes(ctx context.Context, sessionID string, supportedUILayouts []map[string]string) (
authenticationModes []map[string]string, err error) {
sessionInfo, err := b.sessionInfo(sessionID)
if err != nil {
return nil, err
Expand Down Expand Up @@ -312,8 +315,9 @@ func getSupportedModes(sessionInfo sessionInfo, supportedUILayouts []map[string]
"selection_label": fmt.Sprintf("Send URL to %[email protected]", sessionInfo.username),
"email": fmt.Sprintf("%[email protected]", sessionInfo.username),
"ui": mapToJSON(map[string]string{
"type": "form",
"label": fmt.Sprintf("Click on the link received at %[email protected] or enter the code:", sessionInfo.username),
"type": "form",
"label": fmt.Sprintf("Click on the link received at %[email protected] or enter the code:",
sessionInfo.username),
"entry": "chars",
"wait": "true",
}),
Expand Down Expand Up @@ -463,7 +467,8 @@ func qrcodeData(sessionInfo *sessionInfo) (content string, code string) {
}

// SelectAuthenticationMode returns the UI layout information for the selected authentication mode.
func (b *Broker) SelectAuthenticationMode(ctx context.Context, sessionID, authenticationModeName string) (uiLayoutInfo map[string]string, err error) {
func (b *Broker) SelectAuthenticationMode(ctx context.Context, sessionID, authenticationModeName string) (
uiLayoutInfo map[string]string, err error) {
// Ensure session ID is an active one.
sessionInfo, err := b.sessionInfo(sessionID)
if err != nil {
Expand Down Expand Up @@ -513,7 +518,8 @@ func (b *Broker) SelectAuthenticationMode(ctx context.Context, sessionID, authen
}

// IsAuthenticated evaluates the provided authenticationData and returns the authentication status for the user.
func (b *Broker) IsAuthenticated(ctx context.Context, sessionID, authenticationData string) (access, data string, err error) {
func (b *Broker) IsAuthenticated(ctx context.Context, sessionID, authenticationData string) (
access, data string, err error) {
sessionInfo, err := b.sessionInfo(sessionID)
if err != nil {
return "", "", err
Expand Down Expand Up @@ -574,7 +580,8 @@ func (b *Broker) sleepDuration(in time.Duration) time.Duration {
return time.Duration(math.Round(float64(in) * b.sleepMultiplier))
}

func (b *Broker) handleIsAuthenticated(ctx context.Context, sessionInfo sessionInfo, authData map[string]string) (access, data string) {
func (b *Broker) handleIsAuthenticated(ctx context.Context, sessionInfo sessionInfo, authData map[string]string) (
access, data string) {
// Decrypt challenge if present.
challenge, err := decodeRawChallenge(b.privateKey, authData["challenge"])
if err != nil {
Expand All @@ -597,7 +604,8 @@ func (b *Broker) handleIsAuthenticated(ctx context.Context, sessionInfo sessionI
expectedChallenge := user.Password

if challenge != expectedChallenge {
return AuthRetry, fmt.Sprintf(`{"message": "invalid password '%s', should be '%s'"}`, challenge, expectedChallenge)
return AuthRetry, fmt.Sprintf(`{"message": "invalid password '%s', should be '%s'"}`,
challenge, expectedChallenge)
}

case "pincode":
Expand Down Expand Up @@ -650,7 +658,8 @@ func (b *Broker) handleIsAuthenticated(ctx context.Context, sessionInfo sessionI

case "qrcodewithtypo", "qrcodeandcodewithtypo":
if authData["wait"] != "true" {
return AuthDenied, fmt.Sprintf(`{"message": "%s should have wait set to true"}`, sessionInfo.currentAuthMode)
return AuthDenied, fmt.Sprintf(`{"message": "%s should have wait set to true"}`,
sessionInfo.currentAuthMode)
}
// Simulate connexion with remote server to check that the correct code was entered
select {
Expand All @@ -673,7 +682,8 @@ func (b *Broker) handleIsAuthenticated(ctx context.Context, sessionInfo sessionI
}

if challenge != expectedChallenge {
return AuthRetry, fmt.Sprintf(`{"message": "new password does not match criteria: must be '%s'"}`, expectedChallenge)
return AuthRetry, fmt.Sprintf(`{"message": "new password does not match criteria: must be '%s'"}`,
expectedChallenge)
}
exampleUsersMu.Lock()
exampleUsers[sessionInfo.username] = userInfoBroker{Password: challenge}
Expand Down
27 changes: 18 additions & 9 deletions examplebroker/dbus.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ dbus_object = %s
return conn, nil
}

// NewSession is the method through which the broker and the daemon will communicate once dbusInterface.NewSession is called.
// NewSession is the method through which the broker and the daemon will communicate once
// dbusInterface.NewSession is called.
func (b *Bus) NewSession(username, lang, mode string) (sessionID, encryptionKey string, dbusErr *dbus.Error) {
sessionID, encryptionKey, err := b.broker.NewSession(context.Background(), username, lang, mode)
if err != nil {
Expand All @@ -84,25 +85,30 @@ func (b *Bus) NewSession(username, lang, mode string) (sessionID, encryptionKey
return sessionID, encryptionKey, nil
}

// GetAuthenticationModes is the method through which the broker and the daemon will communicate once dbusInterface.GetAuthenticationModes is called.
func (b *Bus) GetAuthenticationModes(sessionID string, supportedUILayouts []map[string]string) (authenticationModes []map[string]string, dbusErr *dbus.Error) {
// GetAuthenticationModes is the method through which the broker and the daemon will communicate once
// dbusInterface.GetAuthenticationModes is called.
func (b *Bus) GetAuthenticationModes(sessionID string, supportedUILayouts []map[string]string) (
authenticationModes []map[string]string, dbusErr *dbus.Error) {
authenticationModes, err := b.broker.GetAuthenticationModes(context.Background(), sessionID, supportedUILayouts)
if err != nil {
return nil, dbus.MakeFailedError(err)
}
return authenticationModes, nil
}

// SelectAuthenticationMode is the method through which the broker and the daemon will communicate once dbusInterface.SelectAuthenticationMode is called.
func (b *Bus) SelectAuthenticationMode(sessionID, authenticationModeName string) (uiLayoutInfo map[string]string, dbusErr *dbus.Error) {
// SelectAuthenticationMode is the method through which the broker and the daemon will communicate once
// dbusInterface.SelectAuthenticationMode is called.
func (b *Bus) SelectAuthenticationMode(sessionID, authenticationModeName string) (
uiLayoutInfo map[string]string, dbusErr *dbus.Error) {
uiLayoutInfo, err := b.broker.SelectAuthenticationMode(context.Background(), sessionID, authenticationModeName)
if err != nil {
return nil, dbus.MakeFailedError(err)
}
return uiLayoutInfo, nil
}

// IsAuthenticated is the method through which the broker and the daemon will communicate once dbusInterface.IsAuthenticated is called.
// IsAuthenticated is the method through which the broker and the daemon will communicate once
// dbusInterface.IsAuthenticated is called.
func (b *Bus) IsAuthenticated(sessionID, authenticationData string) (access, data string, dbusErr *dbus.Error) {
access, data, err := b.broker.IsAuthenticated(context.Background(), sessionID, authenticationData)
if err != nil {
Expand All @@ -111,7 +117,8 @@ func (b *Bus) IsAuthenticated(sessionID, authenticationData string) (access, dat
return access, data, nil
}

// EndSession is the method through which the broker and the daemon will communicate once dbusInterface.EndSession is called.
// EndSession is the method through which the broker and the daemon will communicate once
// dbusInterface.EndSession is called.
func (b *Bus) EndSession(sessionID string) (dbusErr *dbus.Error) {
err := b.broker.EndSession(context.Background(), sessionID)
if err != nil {
Expand All @@ -120,13 +127,15 @@ func (b *Bus) EndSession(sessionID string) (dbusErr *dbus.Error) {
return nil
}

// CancelIsAuthenticated is the method through which the broker and the daemon will communicate once dbusInterface.CancelIsAuthenticated is called.
// CancelIsAuthenticated is the method through which the broker and the daemon will communicate once
// dbusInterface.CancelIsAuthenticated is called.
func (b *Bus) CancelIsAuthenticated(sessionID string) (dbusErr *dbus.Error) {
b.broker.CancelIsAuthenticated(context.Background(), sessionID)
return nil
}

// UserPreCheck is the method through which the broker and the daemon will communicate once dbusInterface.UserPreCheck is called.
// UserPreCheck is the method through which the broker and the daemon will communicate once
// dbusInterface.UserPreCheck is called.
func (b *Bus) UserPreCheck(username string) (userinfo string, dbusErr *dbus.Error) {
userinfo, err := b.broker.UserPreCheck(context.Background(), username)
if err != nil {
Expand Down
36 changes: 24 additions & 12 deletions internal/brokers/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,14 @@ const (
var AuthReplies = []string{AuthGranted, AuthDenied, AuthCancelled, AuthRetry, AuthNext}

type brokerer interface {
NewSession(ctx context.Context, username, lang, mode string) (sessionID, encryptionKey string, err error)
GetAuthenticationModes(ctx context.Context, sessionID string, supportedUILayouts []map[string]string) (authenticationModes []map[string]string, err error)
SelectAuthenticationMode(ctx context.Context, sessionID, authenticationModeName string) (uiLayoutInfo map[string]string, err error)
IsAuthenticated(ctx context.Context, sessionID, authenticationData string) (access, data string, err error)
NewSession(ctx context.Context, username, lang, mode string) (
sessionID, encryptionKey string, err error)
GetAuthenticationModes(ctx context.Context, sessionID string, supportedUILayouts []map[string]string) (
authenticationModes []map[string]string, err error)
SelectAuthenticationMode(ctx context.Context, sessionID, authenticationModeName string) (
uiLayoutInfo map[string]string, err error)
IsAuthenticated(ctx context.Context, sessionID, authenticationData string) (
access, data string, err error)
EndSession(ctx context.Context, sessionID string) (err error)
CancelIsAuthenticated(ctx context.Context, sessionID string)

Expand Down Expand Up @@ -101,7 +105,8 @@ func newBroker(ctx context.Context, configFile string, bus *dbus.Conn) (b Broker
}

// newSession calls the broker corresponding method, expanding sessionID with the broker ID prefix.
func (b Broker) newSession(ctx context.Context, username, lang, mode string) (sessionID, encryptionKey string, err error) {
func (b Broker) newSession(ctx context.Context, username, lang, mode string) (
sessionID, encryptionKey string, err error) {
sessionID, encryptionKey, err = b.brokerer.NewSession(ctx, username, lang, mode)
if err != nil {
return "", "", err
Expand All @@ -119,7 +124,8 @@ func (b Broker) newSession(ctx context.Context, username, lang, mode string) (se
}

// GetAuthenticationModes calls the broker corresponding method, stripping broker ID prefix from sessionID.
func (b *Broker) GetAuthenticationModes(ctx context.Context, sessionID string, supportedUILayouts []map[string]string) (authenticationModes []map[string]string, err error) {
func (b *Broker) GetAuthenticationModes(ctx context.Context, sessionID string,
supportedUILayouts []map[string]string) (authenticationModes []map[string]string, err error) {
sessionID = b.parseSessionID(sessionID)

b.layoutValidatorsMu.Lock()
Expand All @@ -143,7 +149,8 @@ func (b *Broker) GetAuthenticationModes(ctx context.Context, sessionID string, s
}

// SelectAuthenticationMode calls the broker corresponding method, stripping broker ID prefix from sessionID.
func (b Broker) SelectAuthenticationMode(ctx context.Context, sessionID, authenticationModeName string) (uiLayoutInfo map[string]string, err error) {
func (b Broker) SelectAuthenticationMode(ctx context.Context, sessionID, authenticationModeName string) (
uiLayoutInfo map[string]string, err error) {
sessionID = b.parseSessionID(sessionID)
uiLayoutInfo, err = b.brokerer.SelectAuthenticationMode(ctx, sessionID, authenticationModeName)
if err != nil {
Expand All @@ -153,7 +160,8 @@ func (b Broker) SelectAuthenticationMode(ctx context.Context, sessionID, authent
}

// IsAuthenticated calls the broker corresponding method, stripping broker ID prefix from sessionID.
func (b Broker) IsAuthenticated(ctx context.Context, sessionID, authenticationData string) (access string, data string, err error) {
func (b Broker) IsAuthenticated(ctx context.Context, sessionID, authenticationData string) (
access string, data string, err error) {
sessionID = b.parseSessionID(sessionID)

// monitor ctx in goroutine to call cancel
Expand Down Expand Up @@ -254,11 +262,13 @@ func (b Broker) UserPreCheck(ctx context.Context, username string) (userinfo str
// }
// }
// }
func generateValidators(ctx context.Context, sessionID string, supportedUILayouts []map[string]string) map[string]layoutValidator {
func generateValidators(ctx context.Context, sessionID string,
supportedUILayouts []map[string]string) map[string]layoutValidator {
validators := make(map[string]layoutValidator)
for _, layout := range supportedUILayouts {
if _, exists := layout["type"]; !exists {
log.Errorf(ctx, "layout %v provided with missing type for session %s, it will be ignored", layout, sessionID)
log.Errorf(ctx, "layout %v provided with missing type for session %s, it will be ignored",
layout, sessionID)
continue
}

Expand Down Expand Up @@ -326,7 +336,8 @@ func (b Broker) validateUILayout(sessionID string, layout map[string]string) (r
continue
}
if validator.supportedValues != nil && !slices.Contains(validator.supportedValues, value) {
return nil, fmt.Errorf("field %q has invalid value %q, expected one of %s", key, value, strings.Join(validator.supportedValues, ","))
return nil, fmt.Errorf("field %q has invalid value %q, expected one of %s",
key, value, strings.Join(validator.supportedValues, ","))
}
}
return layout, nil
Expand Down Expand Up @@ -389,7 +400,8 @@ func validateUserInfo(uInfo userInfo) (err error) {
func unmarshalAndGetKey(data, key string) (json.RawMessage, error) {
var returnedData map[string]json.RawMessage
if err := json.Unmarshal([]byte(data), &returnedData); err != nil {
return nil, fmt.Errorf("response returned by the broker is not a valid json: %v\nBroker returned: %v", err, data)
return nil, fmt.Errorf("response returned by the broker is not a valid json: %v\nBroker returned: %v",
err, data)
}

rawMsg, ok := returnedData[key]
Expand Down
Loading

0 comments on commit 39dfb18

Please sign in to comment.