2022-04-07 00:58:51 +00:00
package server
import (
"net"
2022-04-08 04:13:47 +00:00
"os"
"strconv"
2022-04-07 00:58:51 +00:00
"strings"
2022-04-08 04:13:47 +00:00
"time"
2022-04-07 00:58:51 +00:00
2022-04-08 04:13:47 +00:00
duoapi "github.com/duosecurity/duo_api_golang"
"github.com/fasthttp/router"
2022-04-07 00:58:51 +00:00
"github.com/valyala/fasthttp"
2022-04-08 04:13:47 +00:00
"github.com/valyala/fasthttp/expvarhandler"
"github.com/valyala/fasthttp/pprofhandler"
2022-04-07 00:58:51 +00:00
2022-04-08 04:13:47 +00:00
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/duo"
2022-04-07 00:58:51 +00:00
"github.com/authelia/authelia/v4/internal/handlers"
"github.com/authelia/authelia/v4/internal/logging"
2022-04-08 04:13:47 +00:00
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/oidc"
"github.com/authelia/authelia/v4/internal/utils"
2022-04-07 00:58:51 +00:00
)
// Replacement for the default error handler in fasthttp.
2022-04-08 04:13:47 +00:00
func handlerError ( ) func ( ctx * fasthttp . RequestCtx , err error ) {
2022-04-07 00:58:51 +00:00
logger := logging . Logger ( )
2022-04-08 04:13:47 +00:00
headerXForwardedFor := [ ] byte ( fasthttp . HeaderXForwardedFor )
getRemoteIP := func ( ctx * fasthttp . RequestCtx ) string {
if hdr := ctx . Request . Header . PeekBytes ( headerXForwardedFor ) ; hdr != nil {
ips := strings . Split ( string ( hdr ) , "," )
if len ( ips ) > 0 {
return strings . Trim ( ips [ 0 ] , " " )
}
}
return ctx . RemoteIP ( ) . String ( )
}
return func ( ctx * fasthttp . RequestCtx , err error ) {
switch e := err . ( type ) {
case * fasthttp . ErrSmallBuffer :
logger . Tracef ( "Request was too large to handle from client %s. Response Code %d." , getRemoteIP ( ctx ) , fasthttp . StatusRequestHeaderFieldsTooLarge )
ctx . Error ( "request header too large" , fasthttp . StatusRequestHeaderFieldsTooLarge )
case * net . OpError :
if e . Timeout ( ) {
logger . Tracef ( "Request timeout occurred while handling from client %s: %s. Response Code %d." , getRemoteIP ( ctx ) , ctx . RequestURI ( ) , fasthttp . StatusRequestTimeout )
ctx . Error ( "request timeout" , fasthttp . StatusRequestTimeout )
} else {
logger . Tracef ( "An unknown error occurred while handling a request from client %s: %s. Response Code %d." , getRemoteIP ( ctx ) , ctx . RequestURI ( ) , fasthttp . StatusBadRequest )
ctx . Error ( "error when parsing request" , fasthttp . StatusBadRequest )
}
default :
logger . Tracef ( "An unknown error occurred while handling a request from client %s: %s. Response Code %d." , getRemoteIP ( ctx ) , ctx . RequestURI ( ) , fasthttp . StatusBadRequest )
2022-04-07 00:58:51 +00:00
ctx . Error ( "error when parsing request" , fasthttp . StatusBadRequest )
}
}
}
func handlerNotFound ( next fasthttp . RequestHandler ) fasthttp . RequestHandler {
return func ( ctx * fasthttp . RequestCtx ) {
path := strings . ToLower ( string ( ctx . Path ( ) ) )
for i := 0 ; i < len ( httpServerDirs ) ; i ++ {
if path == httpServerDirs [ i ] . name || strings . HasPrefix ( path , httpServerDirs [ i ] . prefix ) {
handlers . SetStatusCodeResponse ( ctx , fasthttp . StatusNotFound )
return
}
}
next ( ctx )
}
}
func handlerMethodNotAllowed ( ctx * fasthttp . RequestCtx ) {
handlers . SetStatusCodeResponse ( ctx , fasthttp . StatusMethodNotAllowed )
}
2022-04-08 04:13:47 +00:00
func getHandler ( config schema . Configuration , providers middlewares . Providers ) fasthttp . RequestHandler {
rememberMe := strconv . FormatBool ( config . Session . RememberMeDuration != schema . RememberMeDisabled )
resetPassword := strconv . FormatBool ( ! config . AuthenticationBackend . DisableResetPassword )
resetPasswordCustomURL := config . AuthenticationBackend . PasswordReset . CustomURL . String ( )
duoSelfEnrollment := f
2022-04-15 23:34:26 +00:00
if ! config . DuoAPI . Disable {
2022-04-08 04:13:47 +00:00
duoSelfEnrollment = strconv . FormatBool ( config . DuoAPI . EnableSelfEnrollment )
}
https := config . Server . TLS . Key != "" && config . Server . TLS . Certificate != ""
serveIndexHandler := ServeTemplatedFile ( embeddedAssets , indexFile , config . Server . AssetPath , duoSelfEnrollment , rememberMe , resetPassword , resetPasswordCustomURL , config . Session . Name , config . Theme , https )
serveSwaggerHandler := ServeTemplatedFile ( swaggerAssets , indexFile , config . Server . AssetPath , duoSelfEnrollment , rememberMe , resetPassword , resetPasswordCustomURL , config . Session . Name , config . Theme , https )
serveSwaggerAPIHandler := ServeTemplatedFile ( swaggerAssets , apiFile , config . Server . AssetPath , duoSelfEnrollment , rememberMe , resetPassword , resetPasswordCustomURL , config . Session . Name , config . Theme , https )
handlerPublicHTML := newPublicHTMLEmbeddedHandler ( )
handlerLocales := newLocalesEmbeddedHandler ( )
2022-05-04 04:47:23 +00:00
middleware := middlewares . AutheliaMiddleware ( config , providers , middlewares . SecurityHeaders )
2022-04-08 04:13:47 +00:00
policyCORSPublicGET := middlewares . NewCORSPolicyBuilder ( ) .
WithAllowedMethods ( "OPTIONS" , "GET" ) .
WithAllowedOrigins ( "*" ) .
Build ( )
r := router . New ( )
// Static Assets.
r . GET ( "/" , middleware ( serveIndexHandler ) )
for _ , f := range rootFiles {
r . GET ( "/" + f , handlerPublicHTML )
}
2022-05-03 02:19:30 +00:00
r . GET ( "/favicon.ico" , middlewares . AssetOverride ( config . Server . AssetPath , 0 , handlerPublicHTML ) )
r . GET ( "/static/media/logo.png" , middlewares . AssetOverride ( config . Server . AssetPath , 2 , handlerPublicHTML ) )
2022-04-08 04:13:47 +00:00
r . GET ( "/static/{filepath:*}" , handlerPublicHTML )
// Locales.
2022-05-03 02:19:30 +00:00
r . GET ( "/locales/{language:[a-z]{1,3}}-{variant:[a-zA-Z0-9-]+}/{namespace:[a-z]+}.json" , middlewares . AssetOverride ( config . Server . AssetPath , 0 , handlerLocales ) )
r . GET ( "/locales/{language:[a-z]{1,3}}/{namespace:[a-z]+}.json" , middlewares . AssetOverride ( config . Server . AssetPath , 0 , handlerLocales ) )
2022-04-08 04:13:47 +00:00
// Swagger.
r . GET ( "/api/" , middleware ( serveSwaggerHandler ) )
r . OPTIONS ( "/api/" , policyCORSPublicGET . HandleOPTIONS )
r . GET ( "/api/" + apiFile , policyCORSPublicGET . Middleware ( middleware ( serveSwaggerAPIHandler ) ) )
r . OPTIONS ( "/api/" + apiFile , policyCORSPublicGET . HandleOPTIONS )
for _ , file := range swaggerFiles {
r . GET ( "/api/" + file , handlerPublicHTML )
}
2022-05-04 04:47:23 +00:00
middlewareAPI := middlewares . AutheliaMiddleware (
config , providers ,
middlewares . SecurityHeaders , middlewares . SecurityHeadersNoStore , middlewares . SecurityHeadersCSPNone ,
)
2022-04-08 04:13:47 +00:00
2022-05-04 04:47:23 +00:00
r . GET ( "/api/health" , middlewareAPI ( handlers . HealthGET ) )
r . GET ( "/api/state" , middlewareAPI ( handlers . StateGET ) )
2022-04-08 04:13:47 +00:00
2022-05-04 04:47:23 +00:00
r . GET ( "/api/configuration" , middlewareAPI ( middlewares . Require1FA ( handlers . ConfigurationGET ) ) )
2022-04-08 04:13:47 +00:00
2022-05-04 04:47:23 +00:00
r . GET ( "/api/configuration/password-policy" , middlewareAPI ( handlers . PasswordPolicyConfigurationGet ) )
2022-04-08 04:13:47 +00:00
2022-05-04 04:47:23 +00:00
r . GET ( "/api/verify" , middlewareAPI ( handlers . VerifyGET ( config . AuthenticationBackend ) ) )
r . HEAD ( "/api/verify" , middlewareAPI ( handlers . VerifyGET ( config . AuthenticationBackend ) ) )
r . POST ( "/api/checks/safe-redirection" , middlewareAPI ( handlers . CheckSafeRedirectionPOST ) )
2022-04-08 04:13:47 +00:00
delayFunc := middlewares . TimingAttackDelay ( 10 , 250 , 85 , time . Second )
2022-05-04 04:47:23 +00:00
r . POST ( "/api/firstfactor" , middlewareAPI ( handlers . FirstFactorPOST ( delayFunc ) ) )
r . POST ( "/api/logout" , middlewareAPI ( handlers . LogoutPOST ) )
2022-04-08 04:13:47 +00:00
// Only register endpoints if forgot password is not disabled.
if ! config . AuthenticationBackend . DisableResetPassword &&
config . AuthenticationBackend . PasswordReset . CustomURL . String ( ) == "" {
// Password reset related endpoints.
2022-05-04 04:47:23 +00:00
r . POST ( "/api/reset-password/identity/start" , middlewareAPI ( handlers . ResetPasswordIdentityStart ) )
r . POST ( "/api/reset-password/identity/finish" , middlewareAPI ( handlers . ResetPasswordIdentityFinish ) )
r . POST ( "/api/reset-password" , middlewareAPI ( handlers . ResetPasswordPOST ) )
2022-04-08 04:13:47 +00:00
}
// Information about the user.
2022-05-04 04:47:23 +00:00
r . GET ( "/api/user/info" , middlewareAPI ( middlewares . Require1FA ( handlers . UserInfoGET ) ) )
r . POST ( "/api/user/info" , middlewareAPI ( middlewares . Require1FA ( handlers . UserInfoPOST ) ) )
r . POST ( "/api/user/info/2fa_method" , middlewareAPI ( middlewares . Require1FA ( handlers . MethodPreferencePOST ) ) )
2022-04-08 04:13:47 +00:00
if ! config . TOTP . Disable {
// TOTP related endpoints.
2022-05-04 04:47:23 +00:00
r . GET ( "/api/user/info/totp" , middlewareAPI ( middlewares . Require1FA ( handlers . UserTOTPInfoGET ) ) )
r . POST ( "/api/secondfactor/totp/identity/start" , middlewareAPI ( middlewares . Require1FA ( handlers . TOTPIdentityStart ) ) )
r . POST ( "/api/secondfactor/totp/identity/finish" , middlewareAPI ( middlewares . Require1FA ( handlers . TOTPIdentityFinish ) ) )
r . POST ( "/api/secondfactor/totp" , middlewareAPI ( middlewares . Require1FA ( handlers . TimeBasedOneTimePasswordPOST ) ) )
2022-04-08 04:13:47 +00:00
}
if ! config . Webauthn . Disable {
// Webauthn Endpoints.
2022-05-04 04:47:23 +00:00
r . POST ( "/api/secondfactor/webauthn/identity/start" , middlewareAPI ( middlewares . Require1FA ( handlers . WebauthnIdentityStart ) ) )
r . POST ( "/api/secondfactor/webauthn/identity/finish" , middlewareAPI ( middlewares . Require1FA ( handlers . WebauthnIdentityFinish ) ) )
r . POST ( "/api/secondfactor/webauthn/attestation" , middlewareAPI ( middlewares . Require1FA ( handlers . WebauthnAttestationPOST ) ) )
2022-04-08 04:13:47 +00:00
2022-05-04 04:47:23 +00:00
r . GET ( "/api/secondfactor/webauthn/assertion" , middlewareAPI ( middlewares . Require1FA ( handlers . WebauthnAssertionGET ) ) )
r . POST ( "/api/secondfactor/webauthn/assertion" , middlewareAPI ( middlewares . Require1FA ( handlers . WebauthnAssertionPOST ) ) )
2022-04-08 04:13:47 +00:00
}
// Configure DUO api endpoint only if configuration exists.
2022-04-15 23:34:26 +00:00
if ! config . DuoAPI . Disable {
2022-04-08 04:13:47 +00:00
var duoAPI duo . API
if os . Getenv ( "ENVIRONMENT" ) == dev {
duoAPI = duo . NewDuoAPI ( duoapi . NewDuoApi (
config . DuoAPI . IntegrationKey ,
config . DuoAPI . SecretKey ,
config . DuoAPI . Hostname , "" , duoapi . SetInsecure ( ) ) )
} else {
duoAPI = duo . NewDuoAPI ( duoapi . NewDuoApi (
config . DuoAPI . IntegrationKey ,
config . DuoAPI . SecretKey ,
config . DuoAPI . Hostname , "" ) )
}
2022-05-04 04:47:23 +00:00
r . GET ( "/api/secondfactor/duo_devices" , middlewareAPI ( middlewares . Require1FA ( handlers . DuoDevicesGET ( duoAPI ) ) ) )
r . POST ( "/api/secondfactor/duo" , middlewareAPI ( middlewares . Require1FA ( handlers . DuoPOST ( duoAPI ) ) ) )
r . POST ( "/api/secondfactor/duo_device" , middlewareAPI ( middlewares . Require1FA ( handlers . DuoDevicePOST ) ) )
2022-04-08 04:13:47 +00:00
}
if config . Server . EnablePprof {
r . GET ( "/debug/pprof/{name?}" , pprofhandler . PprofHandler )
}
if config . Server . EnableExpvars {
r . GET ( "/debug/vars" , expvarhandler . ExpvarHandler )
}
if providers . OpenIDConnect . Fosite != nil {
2022-05-04 04:47:23 +00:00
r . GET ( "/api/oidc/consent" , middlewareAPI ( handlers . OpenIDConnectConsentGET ) )
r . POST ( "/api/oidc/consent" , middlewareAPI ( handlers . OpenIDConnectConsentPOST ) )
2022-04-08 04:13:47 +00:00
allowedOrigins := utils . StringSliceFromURLs ( config . IdentityProviders . OIDC . CORS . AllowedOrigins )
r . OPTIONS ( oidc . WellKnownOpenIDConfigurationPath , policyCORSPublicGET . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . GET ( oidc . WellKnownOpenIDConfigurationPath , policyCORSPublicGET . Middleware ( middlewareAPI ( handlers . OpenIDConnectConfigurationWellKnownGET ) ) )
2022-04-08 04:13:47 +00:00
r . OPTIONS ( oidc . WellKnownOAuthAuthorizationServerPath , policyCORSPublicGET . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . GET ( oidc . WellKnownOAuthAuthorizationServerPath , policyCORSPublicGET . Middleware ( middlewareAPI ( handlers . OAuthAuthorizationServerWellKnownGET ) ) )
2022-04-08 04:13:47 +00:00
r . OPTIONS ( oidc . JWKsPath , policyCORSPublicGET . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . GET ( oidc . JWKsPath , policyCORSPublicGET . Middleware ( middlewareAPI ( handlers . JSONWebKeySetGET ) ) )
2022-04-08 04:13:47 +00:00
// TODO (james-d-elliott): Remove in GA. This is a legacy implementation of the above endpoint.
r . OPTIONS ( "/api/oidc/jwks" , policyCORSPublicGET . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . GET ( "/api/oidc/jwks" , policyCORSPublicGET . Middleware ( middlewareAPI ( handlers . JSONWebKeySetGET ) ) )
2022-04-08 04:13:47 +00:00
policyCORSAuthorization := middlewares . NewCORSPolicyBuilder ( ) .
WithAllowedMethods ( "OPTIONS" , "GET" ) .
WithAllowedOrigins ( allowedOrigins ... ) .
WithEnabled ( utils . IsStringInSlice ( oidc . AuthorizationEndpoint , config . IdentityProviders . OIDC . CORS . Endpoints ) ) .
Build ( )
r . OPTIONS ( oidc . AuthorizationPath , policyCORSAuthorization . HandleOnlyOPTIONS )
2022-05-04 04:47:23 +00:00
r . GET ( oidc . AuthorizationPath , middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OpenIDConnectAuthorizationGET ) ) )
2022-04-08 04:13:47 +00:00
// TODO (james-d-elliott): Remove in GA. This is a legacy endpoint.
r . OPTIONS ( "/api/oidc/authorize" , policyCORSAuthorization . HandleOnlyOPTIONS )
2022-05-04 04:47:23 +00:00
r . GET ( "/api/oidc/authorize" , middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OpenIDConnectAuthorizationGET ) ) )
2022-04-08 04:13:47 +00:00
policyCORSToken := middlewares . NewCORSPolicyBuilder ( ) .
WithAllowCredentials ( true ) .
WithAllowedMethods ( "OPTIONS" , "POST" ) .
WithAllowedOrigins ( allowedOrigins ... ) .
WithEnabled ( utils . IsStringInSlice ( oidc . TokenEndpoint , config . IdentityProviders . OIDC . CORS . Endpoints ) ) .
Build ( )
r . OPTIONS ( oidc . TokenPath , policyCORSToken . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . POST ( oidc . TokenPath , policyCORSToken . Middleware ( middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OpenIDConnectTokenPOST ) ) ) )
2022-04-08 04:13:47 +00:00
policyCORSUserinfo := middlewares . NewCORSPolicyBuilder ( ) .
WithAllowCredentials ( true ) .
WithAllowedMethods ( "OPTIONS" , "GET" , "POST" ) .
WithAllowedOrigins ( allowedOrigins ... ) .
WithEnabled ( utils . IsStringInSlice ( oidc . UserinfoEndpoint , config . IdentityProviders . OIDC . CORS . Endpoints ) ) .
Build ( )
r . OPTIONS ( oidc . UserinfoPath , policyCORSUserinfo . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . GET ( oidc . UserinfoPath , policyCORSUserinfo . Middleware ( middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OpenIDConnectUserinfo ) ) ) )
r . POST ( oidc . UserinfoPath , policyCORSUserinfo . Middleware ( middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OpenIDConnectUserinfo ) ) ) )
2022-04-08 04:13:47 +00:00
policyCORSIntrospection := middlewares . NewCORSPolicyBuilder ( ) .
WithAllowCredentials ( true ) .
WithAllowedMethods ( "OPTIONS" , "POST" ) .
WithAllowedOrigins ( allowedOrigins ... ) .
WithEnabled ( utils . IsStringInSlice ( oidc . IntrospectionEndpoint , config . IdentityProviders . OIDC . CORS . Endpoints ) ) .
Build ( )
r . OPTIONS ( oidc . IntrospectionPath , policyCORSIntrospection . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . POST ( oidc . IntrospectionPath , policyCORSIntrospection . Middleware ( middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OAuthIntrospectionPOST ) ) ) )
2022-04-08 04:13:47 +00:00
// TODO (james-d-elliott): Remove in GA. This is a legacy implementation of the above endpoint.
r . OPTIONS ( "/api/oidc/introspect" , policyCORSIntrospection . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . POST ( "/api/oidc/introspect" , policyCORSIntrospection . Middleware ( middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OAuthIntrospectionPOST ) ) ) )
2022-04-08 04:13:47 +00:00
policyCORSRevocation := middlewares . NewCORSPolicyBuilder ( ) .
WithAllowCredentials ( true ) .
WithAllowedMethods ( "OPTIONS" , "POST" ) .
WithAllowedOrigins ( allowedOrigins ... ) .
WithEnabled ( utils . IsStringInSlice ( oidc . RevocationEndpoint , config . IdentityProviders . OIDC . CORS . Endpoints ) ) .
Build ( )
r . OPTIONS ( oidc . RevocationPath , policyCORSRevocation . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . POST ( oidc . RevocationPath , policyCORSRevocation . Middleware ( middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OAuthRevocationPOST ) ) ) )
2022-04-08 04:13:47 +00:00
// TODO (james-d-elliott): Remove in GA. This is a legacy implementation of the above endpoint.
r . OPTIONS ( "/api/oidc/revoke" , policyCORSRevocation . HandleOPTIONS )
2022-05-04 04:47:23 +00:00
r . POST ( "/api/oidc/revoke" , policyCORSRevocation . Middleware ( middlewareAPI ( middlewares . NewHTTPToAutheliaHandlerAdaptor ( handlers . OAuthRevocationPOST ) ) ) )
2022-04-08 04:13:47 +00:00
}
r . NotFound = handlerNotFound ( middleware ( serveIndexHandler ) )
r . HandleMethodNotAllowed = true
r . MethodNotAllowed = handlerMethodNotAllowed
if config . Server . Path != "" {
2022-05-04 04:47:23 +00:00
return middlewares . StripPath ( config . Server . Path ) ( middlewares . LogRequest ( r . Handler ) )
2022-04-08 04:13:47 +00:00
}
2022-05-04 04:47:23 +00:00
return middlewares . LogRequest ( r . Handler )
2022-04-08 04:13:47 +00:00
}