Skip to content

Commit

Permalink
[MISC] Implement golint recommendations (#885)
Browse files Browse the repository at this point in the history
Co-authored-by: Clément Michaud <clement.michaud34@gmail.com>
  • Loading branch information
nightah and clems4ever committed Apr 20, 2020
1 parent a6b7a86 commit 2e78408
Show file tree
Hide file tree
Showing 31 changed files with 111 additions and 70 deletions.
3 changes: 3 additions & 0 deletions cmd/authelia/constants.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
package main

// BuildTag tag used to bootstrap Authelia binary.
var BuildTag = "__BUILD_TAG__"

// BuildCommit commit used to bootstrap Authelia binary.
var BuildCommit = "__BUILD_COMMIT__"
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ require (
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/kr/pty v1.1.8 // indirect
github.com/lib/pq v1.3.0
github.com/mattn/go-sqlite3 v1.13.0
github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/ogier/pflag v0.0.1 // indirect
github.com/onsi/ginkgo v1.10.3 // indirect
github.com/onsi/gomega v1.7.1 // indirect
Expand All @@ -32,7 +32,7 @@ require (
github.com/stretchr/testify v1.5.1
github.com/tebeka/selenium v0.9.9
github.com/tstranex/u2f v1.0.0
github.com/valyala/fasthttp v1.10.0
github.com/valyala/fasthttp v1.11.0
github.com/xdg/stringprep v1.0.0 // indirect
go.mongodb.org/mongo-driver v1.3.2
google.golang.org/appengine v1.6.5 // indirect
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-redis/redis v6.15.2+incompatible h1:9SpNVG76gr6InJGxoZ6IuuxaCOQwDAhzyXg+Bs+0Sb4=
github.com/go-redis/redis v6.15.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-redis/redis/v7 v7.2.0 h1:CrCexy/jYWZjW0AyVoHlcJUeZN19VWlbepTh1Vq6dJs=
github.com/go-redis/redis/v7 v7.2.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
Expand Down Expand Up @@ -212,6 +213,7 @@ github.com/mattn/go-sqlite3 v1.11.0 h1:LDdKkqtYlom37fkvqs8rMPFKAMe8+SgjbwZ6ex1/A
github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c=
github.com/mattn/go-sqlite3 v1.13.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U=
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
Expand Down Expand Up @@ -447,6 +449,7 @@ golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191010194322-b09406accb47 h1:/XfQ9z7ib8eEJX2hdgFTZJ/ntt0swNk5oYBziWeTCvY=
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
Expand Down
23 changes: 12 additions & 11 deletions internal/authentication/const.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,38 @@
package authentication

// Level is the type representing a level of authentication
// Level is the type representing a level of authentication.
type Level int

const (
// NotAuthenticated if the user is not authenticated yet
// NotAuthenticated if the user is not authenticated yet.
NotAuthenticated Level = iota
// OneFactor if the user has passed first factor only
// OneFactor if the user has passed first factor only.
OneFactor Level = iota
// TwoFactor if the user has passed two factors
// TwoFactor if the user has passed two factors.
TwoFactor Level = iota
)

const (
// TOTP Method using Time-Based One-Time Password applications like Google Authenticator
// TOTP Method using Time-Based One-Time Password applications like Google Authenticator.
TOTP = "totp"
// U2F Method using U2F devices like Yubikeys
// U2F Method using U2F devices like Yubikeys.
U2F = "u2f"
// Push Method using Duo application to receive push notifications
// Push Method using Duo application to receive push notifications.
Push = "mobile_push"
)

// PossibleMethods is the set of all possible 2FA methods
var PossibleMethods = []string{TOTP, U2F, Push}

const (
//Argon2id Hash Identifier
// HashingAlgorithmArgon2id Argon2id hash identifier.
HashingAlgorithmArgon2id = "argon2id"
//SHA512 Hash Identifier
// HashingAlgorithmSHA512 SHA512 hash identifier.
HashingAlgorithmSHA512 = "6"
)

// These are the default values from the upstream crypt module, we use them to for GetInt, and they need to be checked when updating github.com/simia-tech/crypt
// These are the default values from the upstream crypt module we use them to for GetInt
// and they need to be checked when updating github.com/simia-tech/crypt.
const (
HashingDefaultArgon2idTime = 1
HashingDefaultArgon2idMemory = 32 * 1024
Expand All @@ -40,5 +41,5 @@ const (
HashingDefaultSHA512Iterations = 5000
)

// HashingPossibleSaltCharacters represents valid hashing runes
// HashingPossibleSaltCharacters represents valid hashing runes.
var HashingPossibleSaltCharacters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/")
12 changes: 8 additions & 4 deletions internal/authentication/ldap_connection_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,35 +17,39 @@ type LDAPConnection interface {
Modify(modifyRequest *ldap.ModifyRequest) error
}

// LDAPConnectionImpl the production implementation of an ldap connection
// LDAPConnectionImpl the production implementation of an ldap connection.
type LDAPConnectionImpl struct {
conn *ldap.Conn
}

// NewLDAPConnectionImpl create a new ldap connection
// NewLDAPConnectionImpl create a new ldap connection.
func NewLDAPConnectionImpl(conn *ldap.Conn) *LDAPConnectionImpl {
return &LDAPConnectionImpl{conn}
}

// Bind binds ldap connection to a username/password.
func (lc *LDAPConnectionImpl) Bind(username, password string) error {
return lc.conn.Bind(username, password)
}

// Close closes a ldap connection.
func (lc *LDAPConnectionImpl) Close() {
lc.conn.Close()
}

// Search searches a ldap server.
func (lc *LDAPConnectionImpl) Search(searchRequest *ldap.SearchRequest) (*ldap.SearchResult, error) {
return lc.conn.Search(searchRequest)
}

// Modify modifies an ldap object.
func (lc *LDAPConnectionImpl) Modify(modifyRequest *ldap.ModifyRequest) error {
return lc.conn.Modify(modifyRequest)
}

// ********************* FACTORY ***********************

// LDAPConnectionFactory an interface of factory of ldap connections
// LDAPConnectionFactory an interface of factory of ldap connections.
type LDAPConnectionFactory interface {
DialTLS(network, addr string, config *tls.Config) (LDAPConnection, error)
Dial(network, addr string) (LDAPConnection, error)
Expand All @@ -54,7 +58,7 @@ type LDAPConnectionFactory interface {
// LDAPConnectionFactoryImpl the production implementation of an ldap connection factory.
type LDAPConnectionFactoryImpl struct{}

// NewLDAPConnectionFactoryImpl create a concrete ldap connection factory
// NewLDAPConnectionFactoryImpl create a concrete ldap connection factory.
func NewLDAPConnectionFactoryImpl() *LDAPConnectionFactoryImpl {
return &LDAPConnectionFactoryImpl{}
}
Expand Down
15 changes: 8 additions & 7 deletions internal/authentication/ldap_user_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func NewLDAPUserProvider(configuration schema.LDAPAuthenticationBackendConfigura
}
}

// NewLDAPUserProviderWithFactory creates a new instance of LDAPUserProvider with existing factory.
func NewLDAPUserProviderWithFactory(configuration schema.LDAPAuthenticationBackendConfiguration,
connectionFactory LDAPConnectionFactory) *LDAPUserProvider {
return &LDAPUserProvider{
Expand Down Expand Up @@ -90,7 +91,7 @@ func (p *LDAPUserProvider) CheckUserPassword(inputUsername string, password stri
return true, nil
}

// OWASP recommends to escape some special characters
// OWASP recommends to escape some special characters.
// https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.md
const specialLDAPRunes = ",#+<>;\"="

Expand All @@ -111,7 +112,7 @@ type ldapUserProfile struct {
func (p *LDAPUserProvider) resolveUsersFilter(userFilter string, inputUsername string) string {
inputUsername = p.ldapEscape(inputUsername)

// We temporarily keep placeholder {0} for backward compatibility
// We temporarily keep placeholder {0} for backward compatibility.
userFilter = strings.ReplaceAll(userFilter, "{0}", inputUsername)

// The {username} placeholder is equivalent to {0}, it's the new way, a named placeholder.
Expand All @@ -137,7 +138,7 @@ func (p *LDAPUserProvider) getUserProfile(conn LDAPConnection, inputUsername str
p.configuration.MailAttribute,
p.configuration.UsernameAttribute}

// Search for the given username
// Search for the given username.
searchRequest := ldap.NewSearchRequest(
baseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
1, 0, false, userFilter, attributes, nil,
Expand Down Expand Up @@ -182,11 +183,11 @@ func (p *LDAPUserProvider) getUserProfile(conn LDAPConnection, inputUsername str
func (p *LDAPUserProvider) resolveGroupsFilter(inputUsername string, profile *ldapUserProfile) (string, error) { //nolint:unparam
inputUsername = p.ldapEscape(inputUsername)

// We temporarily keep placeholder {0} for backward compatibility
// We temporarily keep placeholder {0} for backward compatibility.
groupFilter := strings.ReplaceAll(p.configuration.GroupsFilter, "{0}", inputUsername)
groupFilter = strings.ReplaceAll(groupFilter, "{input}", inputUsername)
if profile != nil {
// We temporarily keep placeholder {1} for backward compatibility
// We temporarily keep placeholder {1} for backward compatibility.
groupFilter = strings.ReplaceAll(groupFilter, "{1}", ldap.EscapeFilter(profile.Username))
groupFilter = strings.ReplaceAll(groupFilter, "{username}", ldap.EscapeFilter(profile.Username))
groupFilter = strings.ReplaceAll(groupFilter, "{dn}", ldap.EscapeFilter(profile.DN))
Expand Down Expand Up @@ -219,7 +220,7 @@ func (p *LDAPUserProvider) GetDetails(inputUsername string) (*UserDetails, error
groupBaseDN = p.configuration.AdditionalGroupsDN + "," + groupBaseDN
}

// Search for the given username
// Search for the given username.
searchGroupRequest := ldap.NewSearchRequest(
groupBaseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases,
0, 0, false, groupsFilter, []string{p.configuration.GroupNameAttribute}, nil,
Expand All @@ -237,7 +238,7 @@ func (p *LDAPUserProvider) GetDetails(inputUsername string) (*UserDetails, error
logging.Logger().Warningf("No groups retrieved from LDAP for user %s", inputUsername)
break
}
// append all values of the document. Normally there should be only one per document.
// Append all values of the document. Normally there should be only one per document.
groups = append(groups, res.Attributes[0].Values...)
}

Expand Down
1 change: 1 addition & 0 deletions internal/authorization/authorizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ func selectMatchingRules(rules []schema.ACLRule, subject Subject, object Object)
return selectMatchingObjectRules(matchingRules, object)
}

// PolicyToLevel converts a string policy to int authorization level.
func PolicyToLevel(policy string) Level {
switch policy {
case "bypass":
Expand Down
2 changes: 2 additions & 0 deletions internal/commands/certificates.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,13 @@ func generateSelfSignedCertificate(cmd *cobra.Command, args []string) {
log.Printf("wrote %s\n", keyPath)
}

// CertificatesCmd certificate helper command.
var CertificatesCmd = &cobra.Command{
Use: "certificates",
Short: "Commands related to certificate generation",
}

// CertificatesGenerateCmd certificate generation command.
var CertificatesGenerateCmd = &cobra.Command{
Use: "generate",
Short: "Generate a self-signed certificate",
Expand Down
1 change: 1 addition & 0 deletions internal/commands/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func init() {
HashPasswordCmd.Flags().IntP("salt-length", "l", schema.DefaultPasswordConfiguration.SaltLength, "set the auto-generated salt length")
}

// HashPasswordCmd password hashing command.
var HashPasswordCmd = &cobra.Command{
Use: "hash-password [password]",
Short: "Hash a password to be used in file-based users database. Default algorithm is argon2id.",
Expand Down
9 changes: 5 additions & 4 deletions internal/commands/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/authelia/authelia/internal/storage"
)

// MigrateCmd migration helper command.
var MigrateCmd *cobra.Command

func init() {
Expand All @@ -20,15 +21,15 @@ func init() {
MigrateCmd.AddCommand(MigrateLocalCmd, MigrateMongoCmd)
}

// TOTPSecretsV3 one entry of TOTP secrets in v3
// TOTPSecretsV3 one entry of TOTP secrets in v3.
type TOTPSecretsV3 struct {
UserID string `json:"userId"`
Secret struct {
Base32 string `json:"base32"`
} `json:"secret"`
}

// U2FDeviceHandleV3 one entry of U2F device handle in v3
// U2FDeviceHandleV3 one entry of U2F device handle in v3.
type U2FDeviceHandleV3 struct {
UserID string `json:"userId"`
Registration struct {
Expand All @@ -37,13 +38,13 @@ type U2FDeviceHandleV3 struct {
} `json:"registration"`
}

// PreferencesV3 one entry of preferences in v3
// PreferencesV3 one entry of preferences in v3.
type PreferencesV3 struct {
UserID string `json:"userId"`
Method string `json:"method"`
}

// AuthenticationTraceV3 one authentication trace in v3
// AuthenticationTraceV3 one authentication trace in v3.
type AuthenticationTraceV3 struct {
UserID string `json:"userId"`
Successful bool `json:"isAuthenticationSuccessful"`
Expand Down
4 changes: 2 additions & 2 deletions internal/commands/migration_local.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
var configurationPath string
var localDatabasePath string

// MigrateLocalCmd migration command
// MigrateLocalCmd migration command.
var MigrateLocalCmd = &cobra.Command{
Use: "localdb",
Short: "Migrate data from v3 local database into database configured in v4 configuration file",
Expand All @@ -32,7 +32,7 @@ func init() {
MigrateLocalCmd.MarkPersistentFlagRequired("config")
}

// migrateLocal data from v3 to v4
// migrateLocal data from v3 to v4.
func migrateLocal(cmd *cobra.Command, args []string) {
dbProvider := createDBProvider(configurationPath)

Expand Down
2 changes: 1 addition & 1 deletion internal/commands/migration_mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
var mongoURL string
var mongoDatabase string

// MigrateMongoCmd migration command
// MigrateMongoCmd migration command.
var MigrateMongoCmd = &cobra.Command{
Use: "mongo",
Short: "Migrate data from v3 mongo database into database configured in v4 configuration file",
Expand Down
14 changes: 6 additions & 8 deletions internal/configuration/schema/access_control.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import (
"strings"
)

// ACLRule represent one ACL rule
// "weak" coerces a single value into string slice
// ACLRule represent one ACL rule "weak" coerces a single value into string slice.
type ACLRule struct {
Domains []string `mapstructure:"domain,weak"`
Policy string `mapstructure:"policy"`
Expand All @@ -16,25 +15,24 @@ type ACLRule struct {
Resources []string `mapstructure:"resources"`
}

// IsPolicyValid check if policy is valid
// IsPolicyValid check if policy is valid.
func IsPolicyValid(policy string) bool {
return policy == "deny" || policy == "one_factor" || policy == "two_factor" || policy == "bypass"
}

// IsSubjectValid check if a subject is valid
// IsSubjectValid check if a subject is valid.
func IsSubjectValid(subject string) bool {
return subject == "" || strings.HasPrefix(subject, "user:") || strings.HasPrefix(subject, "group:")
}

// IsNetworkValid check if a network is valid
// IsNetworkValid check if a network is valid.
func IsNetworkValid(network string) bool {
_, _, err := net.ParseCIDR(network)
return err == nil
}

// Validate validate an ACL Rule
// Validate validate an ACL Rule.
func (r *ACLRule) Validate(validator *StructValidator) {

if len(r.Domains) == 0 {
validator.Push(fmt.Errorf("Domain must be provided"))
}
Expand Down Expand Up @@ -62,7 +60,7 @@ type AccessControlConfiguration struct {
Rules []ACLRule `mapstructure:"rules"`
}

// Validate validate the access control configuration
// Validate validate the access control configuration.
func (acc *AccessControlConfiguration) Validate(validator *StructValidator) {
if acc.DefaultPolicy == "" {
acc.DefaultPolicy = "deny"
Expand Down

0 comments on commit 2e78408

Please sign in to comment.