* feat(oidc): oauth2 discovery and endpoint rename
This implements the oauth2 authorization server discovery document, adds tests to the discovery documents, implements an efficiency upgrade to these docs, and renames some endpoints to be uniform.
This implements Webauthn. Old devices can be used to authenticate via the appid compatibility layer which should be automatic. New devices will be registered via Webauthn, and devices which do not support FIDO2 will no longer be able to be registered. At this time it does not fully support multiple devices (backend does, frontend doesn't allow registration of additional devices). Does not support passwordless.
This enhances the existing time.Duration parser to allow multiple units, and implements a decode hook which can be used by koanf to decode string/integers into time.Durations as applicable.
Implements Proof Key for Code Exchange for OpenID Connect Authorization Code Flow. By default this is enabled for the public client type and requires the S256 challenge method.
Closes#2921
This adds an access-control command that checks the policy enforcement for a given criteria using a configuration file and refactors the configuration validation command to include all configuration sources.
This unifies the methods to obtain the X-Forwarded-* header values and provides logical fallbacks. In addition, so we can ensure this functionality extends to the templated files we've converted the ServeTemplatedFile method into a function that operates as a middlewares.RequestHandler.
Fixes#2765
This adds a smart delay on reset password attempts to prevent username enumeration. Additionally utilizes crypto rand instead of math rand. It also moves the timing delay functionality into its own handler func.
Adds encryption to the U2F public keys. While the public keys cannot be used to authenticate, only to validate someone is authenticated, if a rogue operator changed these in the database they may be able to bypass 2FA. This prevents that.
* change all instances (file names and docs) of "config.template.yml" to "configuration.template.yml" so its consistent with the expectations of the Dockerfile
* Keep config.template.yml named as is
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
* Update index.html
* revert filename changes and add a note about docker
* refactor: apply suggestions from code review
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
This replaces the standard duo_devices upsert with a PostgreSQL specific one and ensures the u2f_devices upsert uses the new unique key for the ON CONFLICT check.
This utilizes the referrer query parameters instead of current request query parameters for logging the requested URI and method. Minor performance improvements to header peek/sets.
This is a fix to the authentication_logs schema that prevents the VARCHAR from being insufficient for HTTP request methods such as PATCH, DELETE, OPTIONS, CONNECT.
Allow users to configure the TOTP Algorithm and Digits. This should be used with caution as many TOTP applications do not support it. Some will also fail to notify the user that there is an issue. i.e. if the algorithm in the QR code is sha512, they continue to generate one time passwords with sha1. In addition this drastically refactors TOTP in general to be more user friendly by not forcing them to register a new device if the administrator changes the period (or algorithm).
Fixes#1226.
Allow users to select and save the preferred duo device and method, depending on availability in the duo account. A default enrollment URL is provided and adjusted if returned by the duo API. This allows auto-enrollment if enabled by the administrator.
Closes#594. Closes#1039.
This change addresses an issue with the usage of the full sender configuration option in the MAIL FROM SMTP command. If a user includes a name in the sender this shouldn't be sent in the MAIL FROM command, instead we should extract it and use just the email portion.
Fixes#2571
This change makes it so only metadata about tokens is stored. Tokens can still be resigned due to conversion methods that convert from the JWT type to the database type. This should be more efficient and should mean we don't have to encrypt tokens or token info in the database at least for now.
This adds additional logging to the authentication logs such as type, remote IP, request method, redirect URL, and if the attempt was done during a ban. This also means we log attempts that occur when the attempt was blocked by the regulator for record keeping purposes, as well as record 2FA attempts which can be used to inform admins and later to regulate based on other factors.
Fixes#116, Fixes#1293.
This adds an AES-GCM 256bit encryption layer for storage for sensitive items. This is only TOTP secrets for the time being but this may be expanded later. This will require a configuration change as per https://www.authelia.com/docs/configuration/migration.html#4330.
Closes#682
This is a massive overhaul to the SQL Storage for Authelia. It facilitates a whole heap of utility commands to help manage the database, primary keys, ensures all database requests use a context for cancellations, and paves the way for a few other PR's which improve the database.
Fixes#1337
* feat: customizable static assets
This change provides the means to override specific assets from the embedded Go FS with files situated on disk.
We only allow overriding the following files currently:
* favicon.ico
* logo.png
* refactor(server): make logo string a const
* refactor(suites): override favicon and use ntp3 in traefik2 suite
* test(suites): test logo override in traefik2 suite
* test(suites): test asset override fallback in traefik suite
Closes#1630.
This adjusts the session ID generator making it use it's own random function rather than using one from the utils lib. This allows us to utilize crypto/rand or math/rand interchangeably. Additionally refactor the utils.RandomString func.
* refactor(suites): replace selenium with go-rod
This change replaces [tebeka/selenium](https://github.com/tebeka/selenium) with [go-rod](https://github.com/go-rod/rod).
We no longer have a chromedriver/external driver dependency to utilise Selenium as we instead utilise the Chrome Dev Protocol to communicate with the browser.
Rod [documents](https://go-rod.github.io/#/why-rod) benefits of choosing the library as opposed to the available alternatives.
This changes the validation of salts for sha512 to be done by the upstream API rather than locally. This allows the salts used in Linux to be utilized with Authelia provided the hash is a sha512 hash.
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
* feat(web): replace cra with vite
* fix: add istanbul
* fix: add jest
* fix: inject env vars
* fix: replicate cra output directories
* fix: post-frontend build for go templating
* fix: dynamic publicpath
* fix(web): import resolution with aliases for .module.css files
* refactor(server): baseurl var
* refactor(web): drop babel-jest for esbuild-jest
* refactor(web): add inline sourcemap for coverage bundle
* build(deps): update web deps
* build(deps): downgrade vite-plugin-istanbul to 2.2.0
98bf77dbaa is a breaking change that means production mode builds can no longer be instrumented.
* refactor(web): match frontend name and version
* refactor(web): drop cra readme
* ci(codecov): utilise new codecov uploader for coverage
The codecov bash uploader is being [deprecated](https://docs.codecov.com/docs/about-the-codecov-bash-uploader).
This utilises the new uploader which is recommended.
* ci(codecov): adjust file search path and name uploads
* fix(suites): coverage paths for codecov
* refactor: replace sqlite library with the original cgo variant
This change reverts our SQLite library back to the original for compatibility and performance reasons now that we always package with CGO.
* fix: cgo and build flags
* fix: gcc requirement
* fix: gcc in dev workflow too
* Check for pnpm in authelia-scripts
* Improve husky hooks to check for required apps
* Use pnpm in coverage dockerfile
* Use pnpm in dev workflow
* Stop buildx log truncation
* Ignore pnpm lockfile in yamllint
* Update versions required for docker and docker-compose in contributing docs
* refactor(handlers): lower case error messages
also refactor verifyAuth function to detect malicious activity both with session
cookie and authorization header.
* refacto(handlers): simplify error construction
* fix(handlers): check prefix in authorization header to determine auth method
* fix(handlers): determining the method should be done with headers instead of query arg
* refacto(handlers): rollback changes of verifyAuth
* don't lowercase log messages
* Apply suggestions from code review
Make sure logger errors are not lowercased.
* fix: uppercase logger errors and remove unused param
* Do not lowercase logger errors
* Remove unused param targetURL
* Rename url variable to not conflict with imported package
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
This adds method to validate the system clock is synchronized on startup. Configuration allows adjusting the server address, enabled state, desync limit, and if the error is fatal.
Co-authored-by: James Elliott <james-d-elliott@users.noreply.github.com>
Given the fact that many Linux OSes are defaulting to CGroups v2 and also Authelia changing the default memory config for argon2id this warning is now obselete.
This change implements a --config flag for the hash-password which parses the config and validates it just as it would at run-time. The values specified in the config replace those specified as parameters.
* feat(cmd): add config flag to hash-password tool
* fix(cmd): fix linting issue
Closes: #1709.
* fix: oidc issuer path and strip path middleware
This ensures the server.path requests append the base_url to the oidc well-known issuer information and adjusts server.path configuration to only strip the configured path instead of the first level entirely regardless of its content.
* fix: only log the token error and general refactoring
* refactor: factorize base_url functions
* refactor(server): include all paths in startup logging
* refactor: factorize
* refactor: GetExternalRootURL -> ExternalRootURL
Co-authored-by: James Elliott <james-d-elliott@users.noreply.github.com>
This is so an unexpected error doesn't occur when someone uses the new ldap timeout key which we missed adding to the list of valid keys in b2a49e1780.
The changes in the koanf commit a7e867a699 introduced a regression in the startup procedure that prevented the option to disable the startup check from having an effect. This ensures the startup check is not performed if it is disabled as it was intended.
This implements both a connection timeout for LDAP connections, and makes it configurable by administrators. The default is 5s. The reason for this commit is currently if a connection to an LDAP server cannot be established it does not timeout in a reasonable period.
This change means we only check the filters for the existence of placeholders that cannot be replaced at startup. We then utilized cached results of that lookup for subsequent replacements.
This commit replaces github.com/spf13/viper with github.com/knadh/koanf. Koanf is very similar library to viper, with less dependencies and several quality of life differences. This also allows most config options to be defined by ENV. Lastly it also enables the use of split configuration files which can be configured by setting the --config flag multiple times.
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
This change adjusts several global options moving them into the server block. It additionally notes other breaking changes in the configuration.
BREAKING CHANGE: Several configuration options have been changed and moved into other sections. Migration instructions are documented here: https://authelia.com/docs/configuration/migration.html#4.30.0
This implements the public option for clients which allows using Authelia as an OpenID Connect Provider for cli applications and SPA's where the client secret cannot be considered secure.
This adds a performance change to the default Active Directory users filter. Basically as per TechNet the (sAMAccountType=805306368) filter is the same as (&(objectCategory=person)(objectClass=user)) except the performance is better.
The recent ldap changes in cb71df5 left a connection to the LDAP server open at startup. This resolves this which prevents an ugly log message and unnecessary open sockets.
This is a required endpoint for OIDC and is one we missed in our initial implementation. Also adds some rudamentary documentaiton about the implemented endpoints.
This is so on startup administrators who have a LDAP server implementation that may not support password hashing by default are clearly warned. This only triggers if the disable password reset option is not enabled, we cannot find the extension OID for the Extended Password Modify Operation, and the implementation is not Active Directory. Active Directory has it's own method for this which doesn't advertise an OID.
* This gives admins more control over their OIDC installation exposing options that had defaults before. Things like lifespans for authorize codes, access tokens, id tokens, refresh tokens, a option to enable the debug client messages, minimum parameter entropy. It also allows admins to configure the response modes.
* Additionally this records specific values about a users session indicating when they performed a specific authz factor so this is represented in the token accurately.
* Lastly we also implemented a OIDC key manager which calculates the kid for jwk's using the SHA1 digest instead of being static, or more specifically the first 7 chars. As per https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key#section-8.1.1 the kid should not exceed 8 chars. While it's allowed to exceed 8 chars, it must only be done so with a compelling reason, which we do not have.
* feat(authentiation): check ldap server on startup
This PR adds a startup check to the LDAP authentication backend. It additionally adds support for checking supportedExtension OIDs, currently only checking passwdModifyOID (1.3.6.1.4.1.4203.1.11.3). This can relatively easily be enhanced to add detection for other rootDSE capabilities like supportedControl and supportedCapabilities as necessary.
* test(authentication): add unit tests for new feature
* refactor(authentication): factorize ldap user provider newup
* refactor: minor adjustments
#2101 introduced a minor regression when using the authelia scripts suite for developing.
The following issues occurred:
```
[00] # runtime/cgo
[00] cgo: exec gcc: exec: "gcc": executable file not found in $PATH
```
Adding the CGO_ENABLED=0 before the dlv build command in the run-backend-dev.sh fixed the issue.
* refactor: drop cgo requirement for sqlite
Replace github.com/mattn/go-sqlite3 with modernc.org/sqlite which drops our CGO requirement.
* refactor: newline for consistency with dockerfiles
This commit adjusts the build flags to include version information in the LDFLAGS using the -X options. Additionally this makes the information recorded at build time more comprehensive. All build information can now be obtained via the `authelia build` command, and the `authelia version` command is now `authelia --version`. Lastly this adjusts the Dockerfile to utilize docker cache more effectively.
This replaces github.com/dgrijalva/jwt-go and github.com/form3tech-oss/jwt-go with github.com/golang-jwt/jwt which will be the maintained package going forward.
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
* Implement an automatic theme
The "auto" theme will automatically switch between "dark" and "light"
depending on user preference. This allows for automatic dark mode.
* fix(configuration): allow the "auto" theme when validating
The new theme "auto" was not allowed to be used in a configuration file.
* docs: clarify what critera controls the automatic theme
How the "auto" theme functioned was unclear.
* docs: typeset themes as code
* fix(web): apply useEffector to media query watch
* docs: add technical details
* fix(configuration): resolve merge conflicts
* refactor: logging config key to log
This refactors the recent pre-release change adding log options to their own configuration section in favor of a log section (from logging).
* docs: add step to getting started to get the latest tagged commit
This is so we avoid issues with changes on master having differences that don't work on the latest docker tag.
* test: adjust tests
* docs: adjust doc strings
This is so levels like warn and error can be used to exclude info or warn messages. Additionally there is a reasonable refactoring of logging moving the log config options to the logging key because there are a significant number of log options now. This also decouples the expvars and pprof handlers from the log level, and they are now configured by server.enable_expvars and server.enable_pprof at any logging level.
Currently if a `log_file_path` is defined Authelia will redirect all logging from standard output to said defined location. This change allows users to keep standard output logging along with a defined `log_file_path`.
This aligns all response status codes on the /api/verify endpoint when an error occurs, making it impossible to determine the actual reason for the failure.
This change will ensure that if the curl command for the cleaning of Docker tags on DockerHub fails it will be reattempted up to 2 more times (total of 3) with a 10 second sleep between each attempt.
The clean tag logic itself within curl attempts to execute the http request upto 3 times so this will ensure a maximum of 9 attempts.
OpenID connect has become a standard when it comes to authentication and
in order to fix a security concern around forwarding authentication and authorization information
it has been decided to add support for it.
This feature is in beta version and only enabled when there is a configuration for it.
Before enabling it in production, please consider that it's in beta with potential bugs and that there
are several production critical features still missing such as all OIDC related data is stored in
configuration or memory. This means you are potentially going to experience issues with HA
deployments, or when restarting a single instance specifically related to OIDC.
We are still working on adding the remaining set of features before making it GA as soon as possible.
Related to #189
Co-authored-by: Clement Michaud <clement.michaud34@gmail.com>
This implements a change to the default behaviour of the cookies generated by the sessions package. The old behaviour was to set the SameSite=None, this changes it to SameSite=Lax. Additionally this puts the option in the hands of the end-user so they can decide for themselves what the best option is.
This removes the deprecated options from 4.25. This includes the LDAP filters which allow {0} or {1} placeholders. The new aliases are documented. Additionally it refactors the keys validator to use uniform messages for most replaced keys.
This fixes misleading errors for ACL rules with an empty list of domains. This also enables admins to have a default policy with zero ACL rules as long as the default policy is not deny or bypass. It also adds a rule number to all ACL rule related log messages which is the position in the YAML list plus 1. Lastly it adds comprehensive per rule HIT/MISS logging when Authelia trace logging is enabled. This trace logging includes the rule number.
This logs the baseDN for user and group searching on startup as well as the users filter (with just input remaining). Additionally refactors the location of a few log messages, and exposes the logger to the provider to reduce calls to logging.Logger().
Updated all links to use https://www.authelia.com/docs/.
Removed all comment sections from documented configuration on the documentation site and replaced them with their own sections.
Made all documentation inside config.template.yml double hashes, and made all commented configuration sections single quoted.
Added .yamllint.yaml to express our desired YAML styles.
Added a style guide.
Refactored many documentation areas to be 120 char widths where possible. It's by no means exhaustive but is a large start.
Added a statelessness guide for the pending Kubernetes chart introduction.
Added labels to configuration documentation and made many areas uniform.
This change implements yamllint and adjusts all yaml files to abide by our linting setup. This excludes config.template.yml as this will be done in an alternate commit.
Attempting to run Authelia with least privilege principle as the `nobody` user and a file based notifier will cause issues during start up as the user cannot remove the notification file.
Given that ioutil.WriteFile truncates the file before writing the removal should not be necessary.
Fixes#1846.
* fix: redis sentinel secret missing
* refactor: use consts for authentication_backend.file.password errs
* fix: unit test for new default port
* test: cover additional misses
* test: fix windows/linux specific test error
* test: more windows specific tests
* test: remove superfluous url.IsAbs
* test: validator 100% coverage
This PR changes the suites tests so if go test -short is used, they are skipped per go standards and a message is displayed. Additionally removed some redundant types from suite_high_availability_test.go and adjusted a warning about a nil req var.
Returns a 404 instead of 405 on bad API endpoints. The original issue was resolved in 3487fd392e however this resolves another issue that's related. Additionally this ensures the behavior is tested.
Co-authored-by: Clément Michaud <clement.michaud34@gmail.com>
Fixes#1520Closes#1534
* refactor(authentication): use crypto constant time compare
Improve security with usage of the crypto/subtle ConstantTimeCompare() method for hash comparison.
Fixes#1799
* docs: add explicit labels for chat types
* fix(configuration): lower argon2id default memory requirements
The current default hashing value of 1024MB (1GB) is far too aggressive to cover all use cases.
Reducing this number and encouraging users to to read the documentation and tune will result in less issues and a better user experience.
* test: fix broken tests
* [FEATURE] Add auth query param to /api/verify (#1353)
When `/api/verify` is called with `?auth=basic`, use the standard
Authorization header instead of Proxy-Authorization.
* [FIX] Better basic auth error reporting
* [FIX] Return 401 when using basic auth instead of redirecting
* [TESTS] Add tests for auth=basic query param
* [DOCS] Mention auth=basic argument and provide nginx example
* docs: add/adjust basic auth query arg docs for proxies
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
* feat: go:embed static assets
Go 1.16 introduced the ability to embed files within a generated binary directly with the go tool chain. This simplifies our dependencies and the significantly improves the development workflow for future developers.
Key points to note:
Due to the inability to embed files that do not reside within the local package we need to duplicate our `config.template.yml` within `internal/configuration`.
To avoid issues with the development workflow empty mock files have been included within `internal/server/public_html`. These are substituted with the respective generated files during the CI/CD and build workflows.
* fix(suites): increase ldap suite test timeout
* fix(server): fix swagger asset CSP
* fix(handlers): refresh user details on all domains
* previously sessions only got checked for updated details if the domain had group subjects attached
* this meant disabled or deleted accounts did not get detected until the session expired or the user visited a domain protected by a group subject
* this patch fixes this issue and simplifies some logic surrounding the check
* add tests
simplify IsStringSlicesDifferent so it only iterates once
* add another test for IsStringSlicesDifferent
This PR achieves the following goals:
* Utilise upstream version of kind instead of a patched version which allows binding to networks other than the default "kind"
* Utilises the registry cache which is setup one level above the kind cluster
The former point was required to successfully run our integration tests in a Kubernetes environment, however this is now possible without running a patched version of kind.
The second point is because DockerHub has introduced rate limiting for container downloads. If there are a large number of CI jobs nodes may occasionally be rejected due to the Kubernetes suite not pulling down from the registry cache.
When authelia.yml got renamed to openapi.yml in 3487fd392e the embedded fs was not updated with a openapi.yml which in turn causes the dev workflow to no longer work.
* [FEATURE] Add theme support
This change allows users to select a theme for Authelia on start-up.
The default will continue to be the existing theme which is known as `light`.
Three new options are now also provided:
* `dark`
* `grey`
* `custom`
The `custom` theme allows users to specify a primary and secondary hex color code to be utilised to style the portal.
Co-authored-by: BankaiNoJutsu <lbegert@gmail.com>
* Add themes to integration tests
* Remove custom theme
* Fix linting issue in access_control_test.go
Co-authored-by: BankaiNoJutsu <lbegert@gmail.com>
* [MISC] Add missing CLI suite test
* Add missing test for `authelia version` command in CLI suite.
* Standardise logger calls and swap CSP switch order
This change adds a new integration testing suite "CLI".
The intent of this suite is to test, validate and capture coverage for Authelia's commands via the CLI.
* [MISC] Validate all sections of ACLs on startup
This change ensure that all sections of the `access_control` key are validated on startup.
* Change error format to clearly identify values
In some scenarios if a user has a `log_file_path` specified and a TTY seems to be detected this causes terminal coloring outputs to be written to the file. This in turn will cause issues when attempting to utilise the log with the provided fail2ban regexes.
We now override any TTY detection/logging treatments and disable coloring/removal of the timestamp when a user is utilising the text based logger to a file.
* add .crt to the PEM extensions scanned for
* fix documentation on the extensions allowed
* add trace logging to the loading process to help debug in the future
* add new directive in the global scope `certificates_directory` which is used to bulk load certs and trust them in Authelia
* this is in ADDITION to system certs and are trusted by both LDAP and SMTP
* added a shared TLSConfig struct to be used by both SMTP and LDAP, and anything else in the future that requires tuning the TLS
* remove usage of deprecated LDAP funcs Dial and DialTLS in favor of DialURL which is also easier to use
* use the server name from LDAP URL or SMTP host when validating the certificate unless otherwise defined in the TLS section
* added temporary translations from the old names to the new ones for all deprecated options
* added docs
* updated example configuration
* final deprecations to be done in 4.28.0
* doc updates
* fix misc linting issues
* uniform deprecation notices for ease of final removal
* added additional tests covering previously uncovered areas and the new configuration options
* add non-fatal to certificate loading when system certs could not be loaded
* adjust timeout of Suite ShortTimeouts
* add warnings pusher for the StructValidator
* make the schema suites uninform
* utilize the warnings in the StructValidator
* fix test suite usage for skip_verify
* extract LDAP filter parsing into it's own function to make it possible to test
* test LDAP filter parsing
* update ErrorContainer interface
* add tests to the StructValidator
* add NewTLSConfig test
* move baseDN for users/groups into parsed values
* add tests to cover many of the outstanding areas in LDAP
* add explicit deferred LDAP conn close to UpdatePassword
* add some basic testing to SMTP notifier
* suggestions from code review
* [FEATURE] Add API docs and swagger-ui
This change will serve out swagger-ui at the `/api/` root path.
* Update descriptions and summaries in API spec
* Utilise frontend assets from unit testing for Docker build steps
* Fix tag for /api/user/* endpoints
* Fix response schema for /api/user/info/2fa_method
* Template and inject the session name during runtime into swagger-ui
This change also factorises and renames index.go into template.go, this can now be generically utilised to template any file.
* Fix integration tests
* Add U2F endpoints
* Change swagger directory to api
This change is to more closely conform to the golang-standards project layout.
* Add authentication for u2f endpoints
* Modify u2f endpoint descriptions
* Rename and fix u2f 2fa sign endpoints
* Fix request body for /api/secondfactor/u2f/sign endpoint
Co-authored-by: James Elliott <james-d-elliott@users.noreply.github.com>
* This change provides the TOTP secret which allows users to copy and utilise for password managers and other applications.
* Hide TextField if secret isn't present
* This ensure that the TextField is removed on a page or if there is no secret present.
* Add multiple buttons and set default value to OTP URL
* Remove inline icon and add icons under text field which allow copying of the secret key and the whole OTP URL.
* Fix integration tests
* Add notifications on click for secret buttons
* Also remove autoFocus on TextField so a user can identify that the full OTP URL is in focus.
* [BUGFIX] Static Session Expiration Key
* keys for session expiration are random for each instance of Authelia
* this is caused by upstream setting it to a random value
* using a temporary bugfix fork of github.com/fasthttp/session to resolve locally
* add some misc doc additions
* [MISC] Refactor and address most errcheck linter ignores
This is mostly a quality of life change.
When we first implemented the errcheck linter we ignored a number of items in our legacy codebase with intent to revisit down the track.
* Handle errors for regulation marks and remove unnecessary logging
* [MISC] Catch OpenLDAP ppolicy error
Further to the discussion over at #361, this change now ensures that OpenLDAP password complexity errors are caught and appropriately handled.
This change also includes the PasswordComplexity test suite in the LDAP integration suite. This is because a ppolicy has been setup and enforced.
* Remove password history for integration tests
* Adjust max failures due to regulation trigger
* Fix error handling for password resets
* Refactor and include code suggestions
* add start_tls config option
* add StartTLS method to the LDAP conn factory and the mock
* implemented use of the StartTLS method when the config is set to true
* add mock unit tests
* add docs
* add TLS min version support
* add tests to tls version method
* fix lint issues
* minor adjustments
* remove SSL3.0
* add tls consts
* deprecate old filter placeholders
* remove redundant fake hashing in file auth provider (to delay username enumeration, was replaced by #993
* make suite ActiveDirectory use StartTLS
* misc adjustments to docs
* suggested changes from code review
* deprecation notice conformity
* add mock test for LDAPS plus StartTLS
* Adding the Session-Username header to the /api/verify endpoint when using cookie auth will check the value stored in the session store for the username and the header value are the same.
* use strings.EqualFold to compare case insensitively
* add docs
* add unit tests
* invalidate session if it is theoretically hijacked and log it as a warning (can only be determined if the header doesn't match the cookie)
* add example PAM script
* go mod tidy
* go mod bump to 1.15
This change aims to factorize code introduced in #1467 for webdriver port customisation within the suites.
Co-authored-by: James Elliott <james-d-elliott@users.noreply.github.com>
* [BUGFIX] Make username_attribute a mandatory placeholder in users_filter
Not including the `username_attribute` in the `users_filter` will cause issues with the LDAP session refresh and will result in session resets when the refresh interval has expired.
This change makes said attribute mandatory for the `users_filter`.
* Update version referenced in docs for fix
* Added `ActiveDirectory` suite for integration tests with Samba AD
* Updated documentation
* Minor styling refactor to suites
* Clean up LDAP user provisioning
* Fix Authelia home splash to reference correct link for webmail
* Add notification message for password complexity errors
* Add password complexity integration test
* Rename implementation default from rfc to custom
* add specific defaults for LDAP (activedirectory implementation)
* add docs to show the new defaults
* add docs explaining the importance of users filter
* add tests
* update instances of LDAP implementation names to use the new consts where applicable
* made the 'custom' case in the UpdatePassword method for the implementation switch the default case instead
* update config examples due to the new defaults
* apply changes from code review
* replace schema default name from MSAD to ActiveDirectory for consistency
* fix missing default for username_attribute
* replace test raising on empty username attribute with not raising on empty
Co-authored-by: James Elliott <james-d-elliott@users.noreply.github.com>
This change adds the ability to format Authelia's log output as JSON.
Example below:
```
{"level":"info","msg":"Logging severity set to info","time":"2020-01-01T00:00:00+11:00"}
{"level":"info","msg":"Authelia is listening for non-TLS connections on 0.0.0.0:9091","time":"2020-01-01T00:00:00+11:00"}
```
This change points the Docker containers healthcheck to the dedicated `/api/health` endpoint and also includes support for Authelia running with a path prefix.
This change aims to utilise the correct logging interface consistently.
The only instances where stdlib log is utilised is for tests and when commands that Authelia supports; for example certificate generation, password hashing and config validation.
This change will allow us to collect frontend code coverage from our Selenium based integration tests.
Given that the frontend is embedded into the Go binary and the integration tests run with a compiled binary in Docker this poses some issues with the instrumented code and the ability for it to run in this manner. To fix this we need to relax Authelia's CSP for the integration tests. This is achieved by setting the env variable `ENVIRONMENT` to `dev`.
* [BUGFIX] Prevent crash when email has not been set
a83ccd7188 introduced a regression where if a misconfigured deployment presented an empty emails array setting `Remote-*` headers would fail.
If the emails array is empty we now set the `Remote-Email` header to an empty string.
* Add additional case for unit tests
The development workflow expects chromedriver to be run on the host on port 4444.
There is currently no mechanism to modify this behaviour at runtime, so if another service is running on 4444 tests will just fail silently.
This change introduces the `CHROMEDRIVER_PORT` environment variable which can be utilised to set a custom port.
* [MISC] Append log file instead of overwriting
If Authelia is restarted when a `log_file_path` is defined upon restart the log file is overwritten as opposed to appending the existing file.
This change ensures that the log file will be appended to, users will need to ensure that they rotate/truncate this over time especially if running in `debug` or `trace`.
* Amend documentation for log_file_path
* [MISC] (deps): Bump haproxy in /internal/suites/example/compose/haproxy
Bumps haproxy from 2.2.4-alpine to 2.3.0-alpine.
Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
* Fix HAProxy suite
Looks like the new version of HAProxy has config validation which expects a newline at the bottom of `haproxy.cfg`.
CI was failing with the following error:
[NOTICE] 313/021816 (1) : haproxy version is 2.3.0-1c0a722
[ALERT] 313/021816 (1) : parsing [/usr/local/etc/haproxy/haproxy.cfg:80]: Missing LF on last line, file might have been truncated at position 42.
[ALERT] 313/021816 (1) : Error(s) found in configuration file : /usr/local/etc/haproxy/haproxy.cfg
[ALERT] 313/021816 (1) : Fatal errors found in configuration.
Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
The warnings are currently limited to Linux based deployments, however this covers both container and host (static binary) based deployments.
We could potentially look to expand this to FreeBSD in future too.
* [FEATURE] Support updated haproxy-auth-request
This version removes the dependency of lua-socket which seemed to result in many unsupported and broken BSD/Pfsense deployments.
* Fix docs indentation
* Add haproxy-lua-http to TLS enabled configuration
* add a plain text email template
* use plain text email template for file based emails
* add config option to SMTP emails named disable_html_emails
* config option is a boolean that when set to true will only send plain text emails
* add docs for more complex SMTP notifier options
* update template
* add rfc1341 multipart logic to notifier
* check for errors after identity_verification
* * fix nil ptr
* go mod tidy
* remove needless checks
* * use multipart/atlernative instead
* * add rfc5322 compliant date header
* * fix linting issues
* [MISC] Storage Schema Versioning Model
* fixup go.sum
* remove pq
* fix int to text issue
* fix incorrect SQL text
* use key_name vs key
* use transactions for all queries during upgrades
* fix missing parenthesis
* move upgrades to their own file
* add provider name for future usage in upgrades
* fix missing create config table values
* fix using the const instead of the provider SQL
* import logging once and reuse
* update docs
* remove db at suite teardown
* apply suggestions from code review
* fix mysql
* make errors more uniform
* style changes
* remove commented code sections
* remove commented code sections
* add schema version type
* add sql mock unit tests
* go mod tidy
* test blank row situations
* [MISC] Template global config and refactor some /api endpoints
* /api/configuration has been removed in favour of templating said global config
* /api/configuration/extended has been renamed to /api/configuration and display_name has been removed
* /api/user/info has been modified to include display_name
Co-authored-by: Clement Michaud <clement.michaud34@gmail.com>
* [FEATURE] Add configurable display name to frontend
This feature allows users with a LDAP backend to specify an attribute (default is "displayname") to retrieve a users name for the portal greeting.
Similarly for the file based backend a new required key "name" has been introduced.
This can also be used down the line with OIDC as a separate scope.
* Update references from Name to DisplayName
* Update compose bundles to include displayname refs
* Update LDAP automatic profile refresh
* Ensure display name is updated
* Fix bug which prevented trace logging for profile refresh to not trigger
* [FEATURE] Docker simplification and configuration generation
The Authelia binary now will attempt to generate configuration based on the latest template assuming that the config location specified on startup does not exist. If a file based backend is selected and the backend cannot be found similarly it will generate a `user_database.yml` based a template.
This will allow more seamless bootstrapping of an environment no matter the deployment method.
We have also squashed the Docker volume requirement down to just `/config` thus removing the requirement for `/var/lib/authelia` this is primarily in attempts to simplify the Docker deployment.
Users with the old volume mappings have two options:
1. Change their mappings to conform to `/config`
2. Change the container entrypoint from `authelia --config /config/configuration.yml` to their old mapping
* Adjust paths relative to `/etc/authelia` and simplify to single volume for compose
* Add generation for file backend based user database
* Refactor Docker volumes and paths to /config
* Refactor Docker WORKDIR to /app
* Fix integration tests
* Update BREAKING.md for v4.20.0
* Run go mod tidy
* Fix log_file_path in miscellaneous.md docs
* Generate config and userdb with 0600 permissions
* Fix log_file_path in config.template.yml
If the configuration yaml is poorly indented or special values are not appropriately escaped Authelia attempts to load said configuration and fails.
This attempts to unmarshal the config into an empty interface to catch and warn on malformed yaml.
Using the example from issue https://github.com/authelia/authelia/issues/1053#issuecomment-634791662
```yaml
host: 0.0.0.0
port: 9091
log_level: debug
jwt_secret: RUtG9TnbXrOl1XLLmDgySw1DGgx9QcrtepIf1uDDBlBVKFZxkVBruYKBi32PvaU
default_redirection_url: example.com
totp:
issuer: example.com
period: 30
skew: 1
authentication_backend:
file:
path: /etc/authelia/users_database.yml
access_control:
default_policy: deny
rules:
- domain: example.com
policy: bypass
- domain: "*.example.com"
policy: one_factor
session:
name: authelia_session
secret: TVPMIcDFbBwhnW3kLJzKhdjeHhtqisr7m28FgRY8oLh2A4lwuV2jV2ZGdGbh4aa
expiration: 3600
inactivity: 300
domain: example.com
regulation:
max_retries: 3
find_time: 120
ban_time: 300
storage:
mysql:
host: example.com
port: 3306
database: authelia
username: authelia
password: example.com
notifier:
smtp:
username: example.com
password: example.com
host: smtp.gmail.com
port: 465
sender: example.com
```
We would actually get a more meaningful error which helps pinpoint the issue:
`Error malformed yaml: line 23: did not find expected alphabetic or numeric character`
* [CI] Add Codecov support
* [CI] Capture backend coverage from integration tests
* [CI] Remove unnecessary artifacts for coverage build
* [CI] Only run coverage elements where necessary
* [CI] Simplify post-command hook
* Fix yarn dependencies and collect coverage
* [CI] Include cmd/authelia/ path in coverage
* [CI] Exclude internal/suites/ in coverage
Closes#1061.
Due to a [change in net/url](https://golang.org/doc/go1.14#net/url) tests need to be adjusted:
When parsing of a URL fails (for example by Parse or ParseRequestURI), the resulting Error message will now quote the unparsable URL. This provides clearer structure and consistency with other parsing errors.
* [DEV] Debug authelia when running a suite.
This runs dlv debugger within authelia backend container so that an IDE can remote
debug the application using port 2345.
* Apply suggestions from code review
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
Add a suite for testing the PathPrefix feature implemented earlier to serve authelia under a multi-purpose domain.
Co-authored-by: Clément Michaud <clement.michaud34@gmail.com>
* [MISC] Remove executable permission of nginx backend files.
* Set permissions to 644 on k8s tar'd files
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
* [DEV] Fix permission issue with dev workflow.
nginx backend was facing permission denied errors because the permissions of the html
files were too restricted. Moreover those files were added to the docker image while they
could just be mounted as other services.
* Fix Kubernetes integration test
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
This will need to be revisited to re-introduce trusted-types when we have a clear handle on all the libraries and their implementation to support this.
* [FEATURE] Allow Authelia to listen on a specified path
* Fix linting and add a couple typescript types
* Template index.html to support base_url
* Update docs and configuration template
* Access base path from body attribute.
* Update CSP
* Fix unit test
Also remove check for body as this will never get triggered, react itself is loaded inside the body so this has to always be successful.
* Template index.html with ${PUBLIC_URL}
* Define PUBLIC_URL in .env(s)
* Add docs clarification
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
Co-authored-by: Clement Michaud <clement.michaud34@gmail.com>
* adaptively delay 1FA by the actual execution time of authentication
* should grow and shrink over time as successful attempts are made
* uses the average of the last 10 successful attempts to calculate
* starts at an average of 1000ms
* minimum is 250ms
* a random delay is added to the largest of avg or minimum
* the random delay is between 0ms and 85ms
* bump LDAP suite to 80s timeout
* bump regulation scenario to 45s
* add mutex locking
* amend logging
* add docs
* add tests
Co-authored-by: Clément Michaud <clement.michaud34@gmail.com>
* [FEATURE] Bump to fasthttp/session/v2 to support redis unix socket.
* Fix lint issues.
* Remove v1 import and fix double import.
* [DOCS] Document use of redis unix socket.
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
* it doesn't work with our current CSP
* it's probably not used by anyone
* it isn't in harmony with our security purposes
* literally removes all use of it
* suggestions from code review
* remove useless test.
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
Co-authored-by: Clement Michaud <clement.michaud34@gmail.com>
* using authelia hash-password if you provide a salt it doesn't encode it as a base64 string
* this causes invalid salts to be stored if a user manually provided one instead of reliance on the automatic generation
* additionally bumped the minimum required salt length to 8 as per reference spec
* additionally removed the maximum salt length as per reference spec (actually 2^32-1 per int32)
* see docs:
* https://tools.ietf.org/html/draft-irtf-cfrg-argon2-10
* https://github.com/P-H-C/phc-winner-argon2
* https://github.com/P-H-C/phc-string-format
* encode all salts
* fix edge case of false positive in CheckPassword
* bump crypt version and fix tests
* only do salt validation in validate salt
* fix tests
* remove panic(err.Error())
* use file mode const
* do hash cleanup on file read instead of check password
* design ConfigAlgoToCryptoAlgo and implement it
* split HashPassword func into functional chunks that could theoretically be reused
* Fix dev workflow.
* Fix dev workflow.
* Cover Remote-User and Remote-Groups using Traefik.
* Cover Remote-User and Remote-Groups using HAProxy.
* Fix redirection after unauthorized response when using HAProxy.
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
* [FIX] Send correct HTTP status codes for 1FA
* use harmonious func to handle all 1FA attempt errors
* use same harmonious func to handle 2FA attempt errors
* always send a 401 which is correct according to https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401
* fix tests
* refactor isTargetURLAuthorized
* fix padding and imports
* harmonize remaining return messages
* fixup docs and layout of verifySessionHasUpToDateProfile
* [FIX] LDAP Not Checking for Updated Groups
* refactor handlers verifyFromSessionCookie
* refactor authorizer selectMatchingObjectRules
* refactor authorizer isDomainMatching
* add authorizer URLHasGroupSubjects method
* add user provider ProviderType method
* update tests
* check for new LDAP groups and update session when:
* user provider type is LDAP
* authorization is forbidden
* URL has rule with group subjects
* Implement Refresh Interval
* add default values for LDAP user provider
* add default for refresh interval
* add schema validator for refresh interval
* add various tests
* rename hasUserBeenInactiveLongEnough to hasUserBeenInactiveTooLong
* use Authelia ctx clock
* add check to determine if user is deleted, if so destroy the
* make ldap user not found error a const
* implement GetRefreshSettings in mock
* Use user not found const with FileProvider
* comment exports
* use ctx.Clock instead of time pkg
* add debug logging
* use ptr to reference userSession so we don't have to retrieve it again
* add documenation
* add check for 0 refresh interval to reduce CPU cost
* remove badly copied debug msg
* add group change delta message
* add SliceStringDelta
* refactor ldap refresh to use the new func
* improve delta add/remove log message
* fix incorrect logic in SliceStringDelta
* add tests to SliceStringDelta
* add always config option
* add tests for always config option
* update docs
* apply suggestions from code review
Co-Authored-By: Amir Zarrinkafsh <nightah@me.com>
* complete mocks and fix an old one
* show warning when LDAP details failed to update for an unknown reason
* golint fix
* actually fix existing mocks
* use mocks for LDAP refresh testing
* use mocks for LDAP refresh testing for both added and removed groups
* use test mock to verify disabled refresh behaviour
* add information to threat model
* add time const for default Unix() value
* misc adjustments to mocks
* Suggestions from code review
* requested changes
* update emails
* docs updates
* test updates
* misc
* golint fix
* set debug for dev testing
* misc docs and logging updates
* misc grammar/spelling
* use built function for VerifyGet
* fix reviewdog suggestions
* requested changes
* Apply suggestions from code review
Co-authored-by: Amir Zarrinkafsh <nightah@me.com>
Co-authored-by: Clément Michaud <clement.michaud34@gmail.com>
* [MISC] Introduce CryptAlgo type.
It helps distinguish between the configuration representation of an algorithm
and the crypt representation (6 and argon2id vs sha512 vs argon2id).
* Add a description to CryptAlgo.
* use const
Co-authored-by: James Elliott <james-d-elliott@users.noreply.github.com>
* [HOTFIX] Prevent Username Enumeration
* thanks to TheHllm for identifying the bug: https://github.com/TheHllm
* temporarily prevents username enumeration with file auth
* proper calculated and very slightly random fix to come
* closely replicate behaviour
* allow error to bubble up
* Synchronize security documentation.
Co-authored-by: Clement Michaud <clement.michaud34@gmail.com>
* [FEATURE] Embed static assets in Go binary
* Refactor/consolidate code and specify public_html via configuration
* Update docs and config template for assets
* Update AUR package pre-requisites and systemd unit
* Include static assets as Buildkite and GitHub artifacts
* Remove references to PUBLIC_DIR
* Only serve assets via embedded filesystem and remove configuration references
* Update authelia-scripts helper to build the embedded filesystem
* Mock the embedded filesystem for unit tests
Add to gitignore to ensure this isn't overwritten.
* Move go:generate to satisfy linter
* This affects primarily Authelia instances running behind Traefik or
nginx ingress controllers within Kubernetes because those proxies
require that Authelia returns 302 instead of 401 after the session
has been inactive for too long.
* fixes#909
* fixed activity timestamp not being updated when accessing forbidden resources.
* fix inactivity not updated when user was inactive for too long.
* cover inactivity timeout updates with unit tests.
* [FIX] File Notifier Default Permissions
* set to 0600 for security
* recreate file if it exists with correct perms
* remove named return vars from notifier
* [FEATURE] Config Validation
* check configuration for invalid keys on startup
* allow users to manually trigger all configuration validation on a file using a cmd
* setup all defaults in config template and run tests against it to prevent accidents
* use tests to check bad configuration values are caught
* use tests to check old configuration values are caught
* add tests for specific key errors
* resolve merge conflicts
* nolint prealloc for test
* [FEATURE] File Secret Loading
* add a validator for secrets
* run the secrets validator before the main config validator
* only allow a secret to be defined in one of: config, env, file env
* remove LF if found in file
* update configuration before main config validation
* fix unit tests
* implement secret testing
* refactor the secrets validator
* make check os agnostic
* update docs
* add warning when user attempts to use ENV instead of ENV file
* discourage ENV in docs
* update config template
* oxford comma
* apply suggestions from code review
* rename Validate to ValidateConfiguration
* add k8s example
* add deprecation notice in docs and warning
* style changes
* [DEPRECATE] Remove migration tools from latest version of Authelia
Also update references to point to container version 4.14.2 for any of the migration examples.
* [DOCS] Remove v4 release statement in README.md
* [MISC] Ignore errcheck recommendations for legacy code
Some of this is likely intended to stay how it is, some could use refactoring, for now we will mark is and ignore it from the linter to be potentially addressed in the future.
* [MISC] Ensure files are gofmt-ed