[CI] Add goconst linter (#961)

* [CI] Add goconst linter

* Implement goconst recommendations

* Rename defaultPolicy to denyPolicy

* Change order for test constants

Co-authored-by: Clément Michaud <clement.michaud34@gmail.com>
pull/962/head
Amir Zarrinkafsh 2020-05-03 02:20:40 +10:00 committed by GitHub
parent 310c5dc09b
commit be0cc72473
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 160 additions and 113 deletions

View File

@ -2,6 +2,9 @@ run:
timeout: 3m
linters-settings:
goconst:
min-len: 2
min-occurrences: 2
gocyclo:
min-complexity: 15
godot:
@ -11,6 +14,7 @@ linters-settings:
linters:
enable:
- goconst
- gocyclo
- godot
- gofmt

View File

@ -25,7 +25,7 @@ func buildAutheliaBinary() {
func buildFrontend() {
// Install npm dependencies.
cmd := utils.CommandWithStdout("yarn", "install")
cmd.Dir = "web"
cmd.Dir = webDirectory
if err := cmd.Run(); err != nil {
log.Fatal(err)
@ -33,7 +33,7 @@ func buildFrontend() {
// Then build the frontend.
cmd = utils.CommandWithStdout("yarn", "build")
cmd.Dir = "web"
cmd.Dir = webDirectory
cmd.Env = append(os.Environ(), "INLINE_RUNTIME_CHUNK=false")
if err := cmd.Run(); err != nil {

View File

@ -53,7 +53,7 @@ func dockerBuildOfficialImage(arch string) error {
}
if arch == "arm32v7" {
if buildkiteQEMU != "true" {
if buildkiteQEMU != stringTrue {
err := utils.CommandWithStdout("docker", "run", "--rm", "--privileged", "multiarch/qemu-user-static", "--reset", "-p", "yes").Run()
if err != nil {
panic(err)
@ -66,7 +66,7 @@ func dockerBuildOfficialImage(arch string) error {
panic(err)
}
} else if arch == "arm64v8" {
if buildkiteQEMU != "true" {
if buildkiteQEMU != stringTrue {
err := utils.CommandWithStdout("docker", "run", "--rm", "--privileged", "multiarch/qemu-user-static", "--reset", "-p", "yes").Run()
if err != nil {
panic(err)
@ -83,7 +83,7 @@ func dockerBuildOfficialImage(arch string) error {
gitTag := ciTag
if gitTag == "" {
// If commit is not tagged, mark the build has having master tag.
gitTag = "master"
gitTag = masterTag
}
cmd := utils.Shell("git rev-parse HEAD")
@ -213,13 +213,13 @@ func publishDockerImage(arch string) {
} else {
log.Fatal("Docker image will not be published, the specified tag does not conform to the standard")
}
} else if ciBranch != "master" && !publicRepo.MatchString(ciBranch) {
} else if ciBranch != masterTag && !publicRepo.MatchString(ciBranch) {
login(docker)
deploy(docker, ciBranch+"-"+arch)
} else if ciBranch != "master" && publicRepo.MatchString(ciBranch) {
} else if ciBranch != masterTag && publicRepo.MatchString(ciBranch) {
login(docker)
deploy(docker, "PR"+ciPullRequest+"-"+arch)
} else if ciBranch == "master" && ciPullRequest == "false" {
} else if ciBranch == masterTag && ciPullRequest == stringFalse {
login(docker)
deploy(docker, "master-"+arch)
} else {
@ -248,13 +248,13 @@ func publishDockerManifest() {
} else {
log.Fatal("Docker manifest will not be published, the specified tag does not conform to the standard")
}
} else if ciBranch != "master" && !publicRepo.MatchString(ciBranch) {
} else if ciBranch != masterTag && !publicRepo.MatchString(ciBranch) {
login(docker)
deployManifest(docker, ciBranch, ciBranch+"-amd64", ciBranch+"-arm32v7", ciBranch+"-arm64v8")
} else if ciBranch != "master" && publicRepo.MatchString(ciBranch) {
} else if ciBranch != masterTag && publicRepo.MatchString(ciBranch) {
login(docker)
deployManifest(docker, "PR"+ciPullRequest, "PR"+ciPullRequest+"-amd64", "PR"+ciPullRequest+"-arm32v7", "PR"+ciPullRequest+"-arm64v8")
} else if ciBranch == "master" && ciPullRequest == "false" {
} else if ciBranch == masterTag && ciPullRequest == stringFalse {
login(docker)
deployManifest(docker, "master", "master-amd64", "master-arm32v7", "master-arm64v8")
publishDockerReadme(docker)

View File

@ -17,7 +17,7 @@ func RunUnitTest(cobraCmd *cobra.Command, args []string) {
}
cmd := utils.Shell("yarn test")
cmd.Dir = "web"
cmd.Dir = webDirectory
cmd.Env = append(os.Environ(), "CI=true")
if err := cmd.Run(); err != nil {
log.Fatal(err)

View File

@ -8,3 +8,8 @@ var DockerImageName = "authelia/authelia"
// IntermediateDockerImageName local name of the docker image.
var IntermediateDockerImageName = "authelia:dist"
const masterTag = "master"
const stringFalse = "false"
const stringTrue = "true"
const webDirectory = "web"

View File

@ -43,3 +43,7 @@ const (
// HashingPossibleSaltCharacters represents valid hashing runes.
var HashingPossibleSaltCharacters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/")
const sha512 = "sha512"
const testPassword = "my;secure*password"

View File

@ -54,7 +54,7 @@ func NewFileUserProvider(configuration *schema.FileAuthenticationBackendConfigur
// TODO: Remove this. This is only here to temporarily fix the username enumeration security flaw in #949.
// This generates a hash that should be usable to do a fake CheckUserPassword
algorithm := configuration.Password.Algorithm
if configuration.Password.Algorithm == "sha512" {
if configuration.Password.Algorithm == sha512 {
algorithm = HashingAlgorithmSHA512
}
settings := getCryptSettings(utils.RandomString(configuration.Password.SaltLength, HashingPossibleSaltCharacters),
@ -143,7 +143,7 @@ func (p *FileUserProvider) UpdatePassword(username string, newPassword string) e
var algorithm string
if p.configuration.Password.Algorithm == "argon2id" {
algorithm = HashingAlgorithmArgon2id
} else if p.configuration.Password.Algorithm == "sha512" {
} else if p.configuration.Password.Algorithm == sha512 {
algorithm = HashingAlgorithmSHA512
} else {
return errors.New("Invalid algorithm in configuration. It should be `argon2id` or `sha512`")

View File

@ -299,7 +299,7 @@ func TestNumberOfRoundsNotInt(t *testing.T) {
}
func TestShouldCheckPasswordArgon2idHashedWithAuthelia(t *testing.T) {
password := "my;secure*password"
password := testPassword
hash, err := HashPassword(password, "", HashingAlgorithmArgon2id, schema.DefaultCIPasswordConfiguration.Iterations,
schema.DefaultCIPasswordConfiguration.Memory*1024, schema.DefaultCIPasswordConfiguration.Parallelism,
schema.DefaultCIPasswordConfiguration.KeyLength, schema.DefaultCIPasswordConfiguration.SaltLength)
@ -313,7 +313,7 @@ func TestShouldCheckPasswordArgon2idHashedWithAuthelia(t *testing.T) {
}
func TestShouldCheckPasswordSHA512HashedWithAuthelia(t *testing.T) {
password := "my;secure*password"
password := testPassword
hash, err := HashPassword(password, "", HashingAlgorithmSHA512, schema.DefaultPasswordSHA512Configuration.Iterations,
0, 0, 0, schema.DefaultPasswordSHA512Configuration.SaltLength)

View File

@ -17,7 +17,7 @@ type ACLRule struct {
// IsPolicyValid check if policy is valid.
func IsPolicyValid(policy string) bool {
return policy == "deny" || policy == "one_factor" || policy == "two_factor" || policy == "bypass"
return policy == denyPolicy || policy == "one_factor" || policy == "two_factor" || policy == "bypass"
}
// IsSubjectValid check if a subject is valid.
@ -63,7 +63,7 @@ type AccessControlConfiguration struct {
// Validate validate the access control configuration.
func (acc *AccessControlConfiguration) Validate(validator *StructValidator) {
if acc.DefaultPolicy == "" {
acc.DefaultPolicy = "deny"
acc.DefaultPolicy = denyPolicy
}
if !IsPolicyValid(acc.DefaultPolicy) {

View File

@ -0,0 +1,3 @@
package schema
const denyPolicy = "deny"

View File

@ -22,14 +22,14 @@ func validateFileAuthenticationBackend(configuration *schema.FileAuthenticationB
configuration.Password.Algorithm = schema.DefaultPasswordConfiguration.Algorithm
} else {
configuration.Password.Algorithm = strings.ToLower(configuration.Password.Algorithm)
if configuration.Password.Algorithm != "argon2id" && configuration.Password.Algorithm != "sha512" {
if configuration.Password.Algorithm != argon2id && configuration.Password.Algorithm != sha512 {
validator.Push(fmt.Errorf("Unknown hashing algorithm supplied, valid values are argon2id and sha512, you configured '%s'", configuration.Password.Algorithm))
}
}
// Iterations (time)
if configuration.Password.Iterations == 0 {
if configuration.Password.Algorithm == "argon2id" {
if configuration.Password.Algorithm == argon2id {
configuration.Password.Iterations = schema.DefaultPasswordConfiguration.Iterations
} else {
configuration.Password.Iterations = schema.DefaultPasswordSHA512Configuration.Iterations
@ -47,7 +47,7 @@ func validateFileAuthenticationBackend(configuration *schema.FileAuthenticationB
validator.Push(fmt.Errorf("The salt length must be 16 or less, you configured %d", configuration.Password.SaltLength))
}
if configuration.Password.Algorithm == "argon2id" {
if configuration.Password.Algorithm == argon2id {
// Parallelism
if configuration.Password.Parallelism == 0 {
configuration.Password.Parallelism = schema.DefaultPasswordConfiguration.Parallelism
@ -80,14 +80,14 @@ func validateLdapURL(ldapURL string, validator *schema.StructValidator) string {
return ""
}
if !(u.Scheme == "ldap" || u.Scheme == "ldaps") {
if !(u.Scheme == schemeLDAP || u.Scheme == schemeLDAPS) {
validator.Push(errors.New("Unknown scheme for ldap url, should be ldap:// or ldaps://"))
return ""
}
if u.Scheme == "ldap" && u.Port() == "" {
if u.Scheme == schemeLDAP && u.Port() == "" {
u.Host += ":389"
} else if u.Scheme == "ldaps" && u.Port() == "" {
} else if u.Scheme == schemeLDAPS && u.Port() == "" {
u.Host += ":636"
}

View File

@ -14,7 +14,7 @@ func newDefaultConfig() schema.Configuration {
config.Host = "127.0.0.1"
config.Port = 9090
config.LogLevel = "info"
config.JWTSecret = "a_secret"
config.JWTSecret = testJWTSecret
config.AuthenticationBackend.File = new(schema.FileAuthenticationBackendConfiguration)
config.AuthenticationBackend.File.Path = "/a/path"
config.Session = schema.SessionConfiguration{
@ -104,7 +104,7 @@ func TestShouldAddDefaultAccessControl(t *testing.T) {
func TestShouldRaiseErrorWhenTLSCertWithoutKeyIsProvided(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.TLSCert = "/tmp/cert.pem"
config.TLSCert = testTLSCert
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 1)
@ -114,7 +114,7 @@ func TestShouldRaiseErrorWhenTLSCertWithoutKeyIsProvided(t *testing.T) {
func TestShouldRaiseErrorWhenTLSKeyWithoutCertIsProvided(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.TLSKey = "/tmp/key.pem"
config.TLSKey = testTLSKey
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 1)
@ -124,8 +124,8 @@ func TestShouldRaiseErrorWhenTLSKeyWithoutCertIsProvided(t *testing.T) {
func TestShouldNotRaiseErrorWhenBothTLSCertificateAndKeyAreProvided(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultConfig()
config.TLSCert = "/tmp/cert.pem"
config.TLSKey = "/tmp/key.pem"
config.TLSCert = testTLSCert
config.TLSKey = testTLSKey
ValidateConfiguration(&config, validator)
require.Len(t, validator.Errors(), 0)

View File

@ -150,3 +150,15 @@ var specificErrorKeys = map[string]string{
"authentication_backend.file.hashing.memory": "config key incorrect: authentication_backend.file.hashing should be authentication_backend.file.password",
"authentication_backend.file.hashing.parallelism": "config key incorrect: authentication_backend.file.hashing should be authentication_backend.file.password",
}
const argon2id = "argon2id"
const sha512 = "sha512"
const schemeLDAP = "ldap"
const schemeLDAPS = "ldaps"
const testBadTimer = "-1"
const testModeDisabled = "disable"
const testJWTSecret = "a_secret"
const testTLSCert = "/tmp/cert.pem"
const testTLSKey = "/tmp/key.pem"

View File

@ -10,7 +10,7 @@ import (
func newDefaultSessionConfig() schema.SessionConfiguration {
config := schema.SessionConfiguration{}
config.Secret = "a_secret"
config.Secret = testJWTSecret
config.Domain = "example.com"
return config
}
@ -78,8 +78,8 @@ func TestShouldRaiseErrorWhenDomainNotSet(t *testing.T) {
func TestShouldRaiseErrorWhenBadInactivityAndExpirationSet(t *testing.T) {
validator := schema.NewStructValidator()
config := newDefaultSessionConfig()
config.Inactivity = "-1"
config.Expiration = "-1"
config.Inactivity = testBadTimer
config.Expiration = testBadTimer
ValidateSession(&config, validator)

View File

@ -35,10 +35,10 @@ func validatePostgreSQLConfiguration(configuration *schema.PostgreSQLStorageConf
validateSQLConfiguration(&configuration.SQLStorageConfiguration, validator)
if configuration.SSLMode == "" {
configuration.SSLMode = "disable"
configuration.SSLMode = testModeDisabled
}
if !(configuration.SSLMode == "disable" || configuration.SSLMode == "require" ||
if !(configuration.SSLMode == testModeDisabled || configuration.SSLMode == "require" ||
configuration.SSLMode == "verify-ca" || configuration.SSLMode == "verify-full") {
validator.Push(errors.New("SSL mode must be 'disable', 'require', 'verify-ca', or 'verify-full'"))
}

View File

@ -34,3 +34,9 @@ const unableToRegisterOneTimePasswordMessage = "Unable to set up one-time passwo
const unableToRegisterSecurityKeyMessage = "Unable to register your security key."
const unableToResetPasswordMessage = "Unable to reset your password."
const mfaValidationFailedMessage = "Authentication failed, please retry later."
const testGATrackingID = "ABC"
const testInactivity = "10"
const testRedirectionURL = "http://redirection.local"
const testResultAllow = "allow"
const testUsername = "john"

View File

@ -25,7 +25,7 @@ func (s *ConfigurationSuite) TearDownTest() {
}
func (s *ConfigurationSuite) TestShouldReturnConfiguredGATrackingID() {
GATrackingID := "ABC"
GATrackingID := testGATrackingID
s.mock.Ctx.Configuration.GoogleAnalyticsTrackingID = GATrackingID
s.mock.Ctx.Configuration.Session.RememberMeDuration = schema.DefaultSessionConfiguration.RememberMeDuration
@ -40,7 +40,7 @@ func (s *ConfigurationSuite) TestShouldReturnConfiguredGATrackingID() {
}
func (s *ConfigurationSuite) TestShouldDisableRememberMe() {
GATrackingID := "ABC"
GATrackingID := testGATrackingID
s.mock.Ctx.Configuration.GoogleAnalyticsTrackingID = GATrackingID
s.mock.Ctx.Configuration.Session.RememberMeDuration = "0"
s.mock.Ctx.Providers.SessionProvider = session.NewProvider(
@ -56,7 +56,7 @@ func (s *ConfigurationSuite) TestShouldDisableRememberMe() {
}
func (s *ConfigurationSuite) TestShouldDisableResetPassword() {
GATrackingID := "ABC"
GATrackingID := testGATrackingID
s.mock.Ctx.Configuration.GoogleAnalyticsTrackingID = GATrackingID
s.mock.Ctx.Configuration.AuthenticationBackend.DisableResetPassword = true
expectedBody := ConfigurationBody{

View File

@ -19,7 +19,7 @@ type LogoutSuite struct {
func (s *LogoutSuite) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
userSession := s.mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
}

View File

@ -24,7 +24,7 @@ func (s *HandlerRegisterU2FStep1Suite) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
userSession := s.mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
}

View File

@ -52,7 +52,7 @@ func SecondFactorDuoPost(duoAPI duo.API) middlewares.RequestHandler {
}
}
if duoResponse.Response.Result != "allow" {
if duoResponse.Response.Result != testResultAllow {
ctx.ReplyUnauthorized()
return
}

View File

@ -24,7 +24,7 @@ type SecondFactorDuoPostSuite struct {
func (s *SecondFactorDuoPostSuite) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
userSession := s.mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
}
@ -43,7 +43,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldCallDuoAPIAndAllowAccess() {
values.Set("pushinfo", "target%20url=https://target.example.com")
response := duo.Response{}
response.Response.Result = "allow"
response.Response.Result = testResultAllow
duoMock.EXPECT().Call(gomock.Eq(values), s.mock.Ctx).Return(&response, nil)
@ -99,11 +99,11 @@ func (s *SecondFactorDuoPostSuite) TestShouldRedirectUserToDefaultURL() {
duoMock := mocks.NewMockAPI(s.mock.Ctrl)
response := duo.Response{}
response.Response.Result = "allow"
response.Response.Result = testResultAllow
duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil)
s.mock.Ctx.Configuration.DefaultRedirectionURL = "http://redirection.local"
s.mock.Ctx.Configuration.DefaultRedirectionURL = testRedirectionURL
bodyBytes, err := json.Marshal(signDuoRequestBody{})
s.Require().NoError(err)
@ -111,7 +111,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldRedirectUserToDefaultURL() {
SecondFactorDuoPost(duoMock)(s.mock.Ctx)
s.mock.Assert200OK(s.T(), redirectResponse{
Redirect: "http://redirection.local",
Redirect: testRedirectionURL,
})
}
@ -119,7 +119,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldNotReturnRedirectURL() {
duoMock := mocks.NewMockAPI(s.mock.Ctrl)
response := duo.Response{}
response.Response.Result = "allow"
response.Response.Result = testResultAllow
duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil)
@ -135,7 +135,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldRedirectUserToSafeTargetURL() {
duoMock := mocks.NewMockAPI(s.mock.Ctrl)
response := duo.Response{}
response.Response.Result = "allow"
response.Response.Result = testResultAllow
duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil)
@ -155,7 +155,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldNotRedirectToUnsafeURL() {
duoMock := mocks.NewMockAPI(s.mock.Ctrl)
response := duo.Response{}
response.Response.Result = "allow"
response.Response.Result = testResultAllow
duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil)
@ -173,7 +173,7 @@ func (s *SecondFactorDuoPostSuite) TestShouldRegenerateSessionForPreventingSessi
duoMock := mocks.NewMockAPI(s.mock.Ctrl)
response := duo.Response{}
response.Response.Result = "allow"
response.Response.Result = testResultAllow
duoMock.EXPECT().Call(gomock.Any(), s.mock.Ctx).Return(&response, nil)

View File

@ -22,7 +22,7 @@ type HandlerSignTOTPSuite struct {
func (s *HandlerSignTOTPSuite) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
userSession := s.mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.U2FChallenge = &u2f.Challenge{}
userSession.U2FRegistration = &session.U2FRegistration{}
s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -43,7 +43,7 @@ func (s *HandlerSignTOTPSuite) TestShouldRedirectUserToDefaultURL() {
Verify(gomock.Eq("abc"), gomock.Eq("secret")).
Return(true, nil)
s.mock.Ctx.Configuration.DefaultRedirectionURL = "http://redirection.local"
s.mock.Ctx.Configuration.DefaultRedirectionURL = testRedirectionURL
bodyBytes, err := json.Marshal(signTOTPRequestBody{
Token: "abc",
@ -53,7 +53,7 @@ func (s *HandlerSignTOTPSuite) TestShouldRedirectUserToDefaultURL() {
SecondFactorTOTPPost(verifier)(s.mock.Ctx)
s.mock.Assert200OK(s.T(), redirectResponse{
Redirect: "http://redirection.local",
Redirect: testRedirectionURL,
})
}

View File

@ -22,7 +22,7 @@ type HandlerSignU2FStep2Suite struct {
func (s *HandlerSignU2FStep2Suite) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
userSession := s.mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.U2FChallenge = &u2f.Challenge{}
userSession.U2FRegistration = &session.U2FRegistration{}
s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -39,7 +39,7 @@ func (s *HandlerSignU2FStep2Suite) TestShouldRedirectUserToDefaultURL() {
Verify(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
Return(nil)
s.mock.Ctx.Configuration.DefaultRedirectionURL = "http://redirection.local"
s.mock.Ctx.Configuration.DefaultRedirectionURL = testRedirectionURL
bodyBytes, err := json.Marshal(signU2FRequestBody{
SignResponse: u2f.SignResponse{},
@ -49,7 +49,7 @@ func (s *HandlerSignU2FStep2Suite) TestShouldRedirectUserToDefaultURL() {
SecondFactorU2FSignPost(u2fVerifier)(s.mock.Ctx)
s.mock.Assert200OK(s.T(), redirectResponse{
Redirect: "http://redirection.local",
Redirect: testRedirectionURL,
})
}

View File

@ -22,7 +22,7 @@ func (s *FetchSuite) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
// Set the initial user session.
userSession := s.mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = 1
s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
}
@ -90,7 +90,7 @@ func TestMethodSetToU2F(t *testing.T) {
mock := mocks.NewMockAutheliaCtx(t)
// Set the initial user session.
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = 1
mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -168,7 +168,7 @@ func (s *SaveSuite) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
// Set the initial user session.
userSession := s.mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = 1
s.mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
}

View File

@ -176,7 +176,7 @@ func TestShouldCheckAuthorizationMatching(t *testing.T) {
username := ""
if rule.AuthLevel > authentication.NotAuthenticated {
username = "john"
username = testUsername
}
matching := isTargetURLAuthorized(authorizer, *url, username, []string{}, net.ParseIP("127.0.0.1"), rule.AuthLevel)
@ -472,13 +472,13 @@ func TestShouldDestroySessionWhenInactiveForTooLong(t *testing.T) {
clock.Set(time.Now())
past := clock.Now().Add(-1 * time.Hour)
mock.Ctx.Configuration.Session.Inactivity = "10"
mock.Ctx.Configuration.Session.Inactivity = testInactivity
// Reload the session provider since the configuration is indirect.
mock.Ctx.Providers.SessionProvider = session.NewProvider(mock.Ctx.Configuration.Session)
assert.Equal(t, time.Second*10, mock.Ctx.Providers.SessionProvider.Inactivity)
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = authentication.TwoFactor
userSession.LastActivity = past.Unix()
mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -509,7 +509,7 @@ func TestShouldDestroySessionWhenInactiveForTooLongUsingDurationNotation(t *test
assert.Equal(t, time.Second*10, mock.Ctx.Providers.SessionProvider.Inactivity)
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = authentication.TwoFactor
userSession.LastActivity = clock.Now().Add(-1 * time.Hour).Unix()
mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -531,10 +531,10 @@ func TestShouldKeepSessionWhenUserCheckedRememberMeAndIsInactiveForTooLong(t *te
clock := mocks.TestingClock{}
clock.Set(time.Now())
mock.Ctx.Configuration.Session.Inactivity = "10"
mock.Ctx.Configuration.Session.Inactivity = testInactivity
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = authentication.TwoFactor
userSession.LastActivity = 0
userSession.KeepMeLoggedIn = true
@ -560,12 +560,12 @@ func TestShouldKeepSessionWhenInactivityTimeoutHasNotBeenExceeded(t *testing.T)
clock := mocks.TestingClock{}
clock.Set(time.Now())
mock.Ctx.Configuration.Session.Inactivity = "10"
mock.Ctx.Configuration.Session.Inactivity = testInactivity
past := clock.Now().Add(-1 * time.Hour)
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = authentication.TwoFactor
userSession.LastActivity = past.Unix()
mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -592,7 +592,7 @@ func TestShouldRedirectWhenSessionInactiveForTooLongAndRDParamProvided(t *testin
clock := mocks.TestingClock{}
clock.Set(time.Now())
mock.Ctx.Configuration.Session.Inactivity = "10"
mock.Ctx.Configuration.Session.Inactivity = testInactivity
// Reload the session provider since the configuration is indirect.
mock.Ctx.Providers.SessionProvider = session.NewProvider(mock.Ctx.Configuration.Session)
assert.Equal(t, time.Second*10, mock.Ctx.Providers.SessionProvider.Inactivity)
@ -600,7 +600,7 @@ func TestShouldRedirectWhenSessionInactiveForTooLongAndRDParamProvided(t *testin
past := clock.Now().Add(-1 * time.Hour)
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = authentication.TwoFactor
userSession.LastActivity = past.Unix()
mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -626,12 +626,12 @@ func TestShouldUpdateInactivityTimestampEvenWhenHittingForbiddenResources(t *tes
clock := mocks.TestingClock{}
clock.Set(time.Now())
mock.Ctx.Configuration.Session.Inactivity = "10"
mock.Ctx.Configuration.Session.Inactivity = testInactivity
past := clock.Now().Add(-1 * time.Hour)
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = authentication.TwoFactor
userSession.LastActivity = past.Unix()
mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.
@ -653,7 +653,7 @@ func TestShouldURLEncodeRedirectionURLParameter(t *testing.T) {
defer mock.Close()
userSession := mock.Ctx.GetSession()
userSession.Username = "john"
userSession.Username = testUsername
userSession.AuthenticationLevel = authentication.NotAuthenticated
mock.Ctx.SaveSession(userSession) //nolint:errcheck // TODO: Legacy code, consider refactoring time permitting.

View File

@ -1,6 +1,5 @@
package middlewares
// JWTIssuer is.
const jwtIssuer = "Authelia"
const xForwardedProtoHeader = "X-Forwarded-Proto"

View File

@ -15,6 +15,8 @@ import (
"github.com/authelia/authelia/internal/session"
)
const testJWTSecret = "abc"
func newArgs(retriever func(ctx *middlewares.AutheliaCtx) (*session.Identity, error)) middlewares.IdentityVerificationStartArgs {
return middlewares.IdentityVerificationStartArgs{
ActionClaim: "Claim",
@ -50,7 +52,7 @@ func TestShouldFailIfJWTCannotBeSaved(t *testing.T) {
mock := mocks.NewMockAutheliaCtx(t)
defer mock.Close()
mock.Ctx.Configuration.JWTSecret = "abc"
mock.Ctx.Configuration.JWTSecret = testJWTSecret
mock.StorageProviderMock.EXPECT().
SaveIdentityVerificationToken(gomock.Any()).
@ -67,7 +69,7 @@ func TestShouldFailSendingAnEmail(t *testing.T) {
mock := mocks.NewMockAutheliaCtx(t)
defer mock.Close()
mock.Ctx.Configuration.JWTSecret = "abc"
mock.Ctx.Configuration.JWTSecret = testJWTSecret
mock.Ctx.Request.Header.Add("X-Forwarded-Proto", "http")
mock.Ctx.Request.Header.Add("X-Forwarded-Host", "host")
@ -90,7 +92,7 @@ func TestShouldFailWhenXForwardedProtoHeaderIsMissing(t *testing.T) {
mock := mocks.NewMockAutheliaCtx(t)
defer mock.Close()
mock.Ctx.Configuration.JWTSecret = "abc"
mock.Ctx.Configuration.JWTSecret = testJWTSecret
mock.Ctx.Request.Header.Add("X-Forwarded-Host", "host")
mock.StorageProviderMock.EXPECT().
@ -108,7 +110,7 @@ func TestShouldFailWhenXForwardedHostHeaderIsMissing(t *testing.T) {
mock := mocks.NewMockAutheliaCtx(t)
defer mock.Close()
mock.Ctx.Configuration.JWTSecret = "abc"
mock.Ctx.Configuration.JWTSecret = testJWTSecret
mock.Ctx.Request.Header.Add("X-Forwarded-Proto", "http")
mock.StorageProviderMock.EXPECT().
@ -126,7 +128,7 @@ func TestShouldSucceedIdentityVerificationStartProcess(t *testing.T) {
mock := mocks.NewMockAutheliaCtx(t)
defer mock.Close()
mock.Ctx.Configuration.JWTSecret = "abc"
mock.Ctx.Configuration.JWTSecret = testJWTSecret
mock.Ctx.Request.Header.Add("X-Forwarded-Proto", "http")
mock.Ctx.Request.Header.Add("X-Forwarded-Host", "host")
@ -154,7 +156,7 @@ type IdentityVerificationFinishProcess struct {
func (s *IdentityVerificationFinishProcess) SetupTest() {
s.mock = mocks.NewMockAutheliaCtx(s.T())
s.mock.Ctx.Configuration.JWTSecret = "abc"
s.mock.Ctx.Configuration.JWTSecret = testJWTSecret
}
func (s *IdentityVerificationFinishProcess) TearDownTest() {

View File

@ -1,3 +1,8 @@
package session
const userSessionStorerKey = "UserSession"
const testDomain = "example.com"
const testExpiration = "40"
const testName = "my_session"
const testUsername = "john"

View File

@ -18,13 +18,13 @@ import (
func TestShouldCreateInMemorySessionProvider(t *testing.T) {
// The redis configuration is not provided so we create a in-memory provider.
configuration := schema.SessionConfiguration{}
configuration.Domain = "example.com"
configuration.Name = "my_session"
configuration.Expiration = "40"
configuration.Domain = testDomain
configuration.Name = testName
configuration.Expiration = testExpiration
providerConfig := NewProviderConfig(configuration)
assert.Equal(t, "my_session", providerConfig.config.CookieName)
assert.Equal(t, "example.com", providerConfig.config.Domain)
assert.Equal(t, testDomain, providerConfig.config.Domain)
assert.Equal(t, true, providerConfig.config.Secure)
assert.Equal(t, time.Duration(40)*time.Second, providerConfig.config.Expires)
assert.True(t, providerConfig.config.IsSecureFunc(nil))
@ -36,9 +36,9 @@ func TestShouldCreateInMemorySessionProvider(t *testing.T) {
func TestShouldCreateRedisSessionProvider(t *testing.T) {
// The redis configuration is not provided so we create a in-memory provider.
configuration := schema.SessionConfiguration{}
configuration.Domain = "example.com"
configuration.Name = "my_session"
configuration.Expiration = "40"
configuration.Domain = testDomain
configuration.Name = testName
configuration.Expiration = testExpiration
configuration.Redis = &schema.RedisSessionConfiguration{
Host: "redis.example.com",
Port: 6379,
@ -47,7 +47,7 @@ func TestShouldCreateRedisSessionProvider(t *testing.T) {
providerConfig := NewProviderConfig(configuration)
assert.Equal(t, "my_session", providerConfig.config.CookieName)
assert.Equal(t, "example.com", providerConfig.config.Domain)
assert.Equal(t, testDomain, providerConfig.config.Domain)
assert.Equal(t, true, providerConfig.config.Secure)
assert.Equal(t, time.Duration(40)*time.Second, providerConfig.config.Expires)
assert.True(t, providerConfig.config.IsSecureFunc(nil))
@ -65,9 +65,9 @@ func TestShouldCreateRedisSessionProvider(t *testing.T) {
func TestShouldSetDbNumber(t *testing.T) {
configuration := schema.SessionConfiguration{}
configuration.Domain = "example.com"
configuration.Name = "my_session"
configuration.Expiration = "40"
configuration.Domain = testDomain
configuration.Name = testName
configuration.Expiration = testExpiration
configuration.Redis = &schema.RedisSessionConfiguration{
Host: "redis.example.com",
Port: 6379,

View File

@ -14,9 +14,9 @@ import (
func TestShouldInitializerSession(t *testing.T) {
ctx := &fasthttp.RequestCtx{}
configuration := schema.SessionConfiguration{}
configuration.Domain = "example.com"
configuration.Name = "my_session"
configuration.Expiration = "40"
configuration.Domain = testDomain
configuration.Name = testName
configuration.Expiration = testExpiration
provider := NewProvider(configuration)
session, err := provider.GetSession(ctx)
@ -28,14 +28,14 @@ func TestShouldInitializerSession(t *testing.T) {
func TestShouldUpdateSession(t *testing.T) {
ctx := &fasthttp.RequestCtx{}
configuration := schema.SessionConfiguration{}
configuration.Domain = "example.com"
configuration.Name = "my_session"
configuration.Expiration = "40"
configuration.Domain = testDomain
configuration.Name = testName
configuration.Expiration = testExpiration
provider := NewProvider(configuration)
session, _ := provider.GetSession(ctx)
session.Username = "john"
session.Username = testUsername
session.AuthenticationLevel = authentication.TwoFactor
err := provider.SaveSession(ctx, session)
@ -45,7 +45,7 @@ func TestShouldUpdateSession(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, UserSession{
Username: "john",
Username: testUsername,
AuthenticationLevel: authentication.TwoFactor,
}, session)
}
@ -53,15 +53,15 @@ func TestShouldUpdateSession(t *testing.T) {
func TestShouldDestroySessionAndWipeSessionData(t *testing.T) {
ctx := &fasthttp.RequestCtx{}
configuration := schema.SessionConfiguration{}
configuration.Domain = "example.com"
configuration.Name = "my_session"
configuration.Expiration = "40"
configuration.Domain = testDomain
configuration.Name = testName
configuration.Expiration = testExpiration
provider := NewProvider(configuration)
session, err := provider.GetSession(ctx)
require.NoError(t, err)
session.Username = "john"
session.Username = testUsername
session.AuthenticationLevel = authentication.TwoFactor
err = provider.SaveSession(ctx, session)
@ -69,7 +69,7 @@ func TestShouldDestroySessionAndWipeSessionData(t *testing.T) {
newUserSession, err := provider.GetSession(ctx)
require.NoError(t, err)
assert.Equal(t, "john", newUserSession.Username)
assert.Equal(t, testUsername, newUserSession.Username)
assert.Equal(t, authentication.TwoFactor, newUserSession.AuthenticationLevel)
err = provider.DestroySession(ctx)

View File

@ -40,3 +40,8 @@ var DuoBaseURL = "https://duo.example.com"
// AutheliaBaseURL the base URL of Authelia service.
var AutheliaBaseURL = "https://authelia.example.com:9091"
const stringTrue = "true"
const testUsername = "john"
const testPassword = "password"

View File

@ -18,7 +18,7 @@ type DockerEnvironment struct {
// NewDockerEnvironment create a new docker environment.
func NewDockerEnvironment(files []string) *DockerEnvironment {
if os.Getenv("CI") == "true" {
if os.Getenv("CI") == stringTrue {
for i := range files {
files[i] = strings.ReplaceAll(files[i], "{}", "dist")
}

View File

@ -63,7 +63,7 @@ func waitUntilAutheliaIsReady(dockerEnvironment *DockerEnvironment) error {
return err
}
if os.Getenv("CI") != "true" {
if os.Getenv("CI") != stringTrue {
if err := waitUntilAutheliaFrontendIsReady(dockerEnvironment); err != nil {
return err
}

View File

@ -51,8 +51,8 @@ func (s *TwoFactorSuite) TestShouldAuthorizeSecretAfterTwoFactor() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
username := "john"
password := "password"
username := testUsername
password := testPassword
// Login one factor
s.doLoginOneFactor(ctx, s.T(), username, password, false, "")
@ -68,7 +68,7 @@ func (s *TwoFactorSuite) TestShouldAuthorizeSecretAfterTwoFactor() {
// Login again with 1FA & 2FA
targetURL := fmt.Sprintf("%s/secret.html", AdminBaseURL)
s.doLoginTwoFactor(ctx, s.T(), "john", "password", false, secret, targetURL)
s.doLoginTwoFactor(ctx, s.T(), testUsername, testPassword, false, secret, targetURL)
// And check if the user is redirected to the secret.
s.verifySecretAuthorized(ctx, s.T())
@ -87,10 +87,10 @@ func (s *TwoFactorSuite) TestShouldFailTwoFactor() {
defer cancel()
// Register TOTP secret and logout.
s.doRegisterThenLogout(ctx, s.T(), "john", "password")
s.doRegisterThenLogout(ctx, s.T(), testUsername, testPassword)
wrongPasscode := "123456"
s.doLoginOneFactor(ctx, s.T(), "john", "password", false, "")
s.doLoginOneFactor(ctx, s.T(), testUsername, testPassword, false, "")
s.verifyIsSecondFactorPage(ctx, s.T())
s.doEnterOTP(ctx, s.T(), wrongPasscode)

View File

@ -44,7 +44,7 @@ func init() {
}
log.Debug("Building authelia:dist image or use cache if already built...")
if os.Getenv("CI") != "true" {
if os.Getenv("CI") != stringTrue {
if err := utils.Shell("authelia-scripts docker build").Run(); err != nil {
return err
}

View File

@ -24,3 +24,5 @@ const Year = Day * 365
// Month is an int based representation of the time unit.
const Month = Year / 12
const testStringInput = "abcdefghijkl"

View File

@ -7,7 +7,7 @@ import (
)
func TestShouldSplitIntoEvenStringsOfFour(t *testing.T) {
input := "abcdefghijkl"
input := testStringInput
arrayOfStrings := SliceString(input, 4)
assert.Equal(t, len(arrayOfStrings), 3)
assert.Equal(t, "abcd", arrayOfStrings[0])
@ -16,7 +16,7 @@ func TestShouldSplitIntoEvenStringsOfFour(t *testing.T) {
}
func TestShouldSplitIntoEvenStringsOfOne(t *testing.T) {
input := "abcdefghijkl"
input := testStringInput
arrayOfStrings := SliceString(input, 1)
assert.Equal(t, 12, len(arrayOfStrings))
assert.Equal(t, "a", arrayOfStrings[0])
@ -27,7 +27,7 @@ func TestShouldSplitIntoEvenStringsOfOne(t *testing.T) {
}
func TestShouldSplitIntoUnevenStringsOfFour(t *testing.T) {
input := "abcdefghijklm"
input := testStringInput + "m"
arrayOfStrings := SliceString(input, 4)
assert.Equal(t, len(arrayOfStrings), 4)
assert.Equal(t, "abcd", arrayOfStrings[0])