mirror of
				https://github.com/steveiliop56/tinyauth.git
				synced 2025-10-30 21:55:43 +00:00 
			
		
		
		
	Compare commits
	
		
			1 Commits
		
	
	
		
			dependabot
			...
			l10n_main
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | 8aacadbb25 | 
| @@ -1,5 +1,5 @@ | ||||
| # Site builder | ||||
| FROM oven/bun:1.3.1-alpine AS frontend-builder | ||||
| FROM oven/bun:1.3.0-alpine AS frontend-builder | ||||
|  | ||||
| WORKDIR /frontend | ||||
|  | ||||
|   | ||||
| @@ -1,5 +1,5 @@ | ||||
| # Site builder | ||||
| FROM oven/bun:1.3.1-alpine AS frontend-builder | ||||
| FROM oven/bun:1.3.0-alpine AS frontend-builder | ||||
|  | ||||
| WORKDIR /frontend | ||||
|  | ||||
|   | ||||
| @@ -1,62 +1,62 @@ | ||||
| { | ||||
|     "loginTitle": "Welcome back, login with", | ||||
|     "loginTitleSimple": "Welcome back, please login", | ||||
|     "loginDivider": "Or", | ||||
|     "loginUsername": "Username", | ||||
|     "loginPassword": "Password", | ||||
|     "loginSubmit": "Login", | ||||
|     "loginFailTitle": "Failed to log in", | ||||
|     "loginFailSubtitle": "Please check your username and password", | ||||
|     "loginFailRateLimit": "You failed to login too many times. Please try again later", | ||||
|     "loginSuccessTitle": "Logged in", | ||||
|     "loginSuccessSubtitle": "Welcome back!", | ||||
|     "loginOauthFailTitle": "An error occurred", | ||||
|     "loginOauthFailSubtitle": "Failed to get OAuth URL", | ||||
|     "loginOauthSuccessTitle": "Redirecting", | ||||
|     "loginOauthSuccessSubtitle": "Redirecting to your OAuth provider", | ||||
|     "loginOauthAutoRedirectTitle": "OAuth Auto Redirect", | ||||
|     "loginOauthAutoRedirectSubtitle": "You will be automatically redirected to your OAuth provider to authenticate.", | ||||
|     "loginOauthAutoRedirectButton": "Redirect now", | ||||
|     "continueTitle": "Continue", | ||||
|     "continueRedirectingTitle": "Redirecting...", | ||||
|     "continueRedirectingSubtitle": "You should be redirected to the app soon", | ||||
|     "continueRedirectManually": "Redirect me manually", | ||||
|     "continueInsecureRedirectTitle": "Insecure redirect", | ||||
|     "continueInsecureRedirectSubtitle": "You are trying to redirect from <code>https</code> to <code>http</code> which is not secure. Are you sure you want to continue?", | ||||
|     "continueUntrustedRedirectTitle": "Untrusted redirect", | ||||
|     "continueUntrustedRedirectSubtitle": "You are trying to redirect to a domain that does not match your configured domain (<code>{{cookieDomain}}</code>). Are you sure you want to continue?", | ||||
|     "logoutFailTitle": "Failed to log out", | ||||
|     "logoutFailSubtitle": "Please try again", | ||||
|     "logoutSuccessTitle": "Logged out", | ||||
|     "logoutSuccessSubtitle": "You have been logged out", | ||||
|     "logoutTitle": "Logout", | ||||
|     "logoutUsernameSubtitle": "You are currently logged in as <code>{{username}}</code>. Click the button below to logout.", | ||||
|     "logoutOauthSubtitle": "You are currently logged in as <code>{{username}}</code> using the {{provider}} OAuth provider. Click the button below to logout.", | ||||
|     "notFoundTitle": "Page not found", | ||||
|     "notFoundSubtitle": "The page you are looking for does not exist.", | ||||
|     "notFoundButton": "Go home", | ||||
|     "totpFailTitle": "Failed to verify code", | ||||
|     "totpFailSubtitle": "Please check your code and try again", | ||||
|     "totpSuccessTitle": "Verified", | ||||
|     "totpSuccessSubtitle": "Redirecting to your app", | ||||
|     "totpTitle": "Enter your TOTP code", | ||||
|     "totpSubtitle": "Please enter the code from your authenticator app.", | ||||
|     "unauthorizedTitle": "Unauthorized", | ||||
|     "unauthorizedResourceSubtitle": "The user with username <code>{{username}}</code> is not authorized to access the resource <code>{{resource}}</code>.", | ||||
|     "unauthorizedLoginSubtitle": "The user with username <code>{{username}}</code> is not authorized to login.", | ||||
|     "unauthorizedGroupsSubtitle": "The user with username <code>{{username}}</code> is not in the groups required by the resource <code>{{resource}}</code>.", | ||||
|     "unauthorizedIpSubtitle": "Your IP address <code>{{ip}}</code> is not authorized to access the resource <code>{{resource}}</code>.", | ||||
|     "unauthorizedButton": "Try again", | ||||
|     "cancelTitle": "Cancel", | ||||
|     "forgotPasswordTitle": "Forgot your password?", | ||||
|     "failedToFetchProvidersTitle": "Failed to load authentication providers. Please check your configuration.", | ||||
|     "errorTitle": "An error occurred", | ||||
|     "errorSubtitle": "An error occurred while trying to perform this action. Please check the console for more information.", | ||||
|     "forgotPasswordMessage": "You can reset your password by changing the `USERS` environment variable.", | ||||
|     "fieldRequired": "This field is required", | ||||
|     "invalidInput": "Invalid input", | ||||
|     "domainWarningTitle": "Invalid Domain", | ||||
|     "domainWarningSubtitle": "This instance is configured to be accessed from <code>{{appUrl}}</code>, but <code>{{currentUrl}}</code> is being used. If you proceed, you may encounter issues with authentication.", | ||||
|     "ignoreTitle": "Ignore", | ||||
|     "goToCorrectDomainTitle": "Go to correct domain" | ||||
|     "loginTitle": "Tervetuloa takaisin, kirjaudu sisään käyttäen", | ||||
|     "loginTitleSimple": "Tervetuloa takaisin, ole hyvä ja kirjaudu", | ||||
|     "loginDivider": "Tai", | ||||
|     "loginUsername": "Käyttäjätunnus", | ||||
|     "loginPassword": "Salasana", | ||||
|     "loginSubmit": "Kirjaudu", | ||||
|     "loginFailTitle": "Kirjautuminen epäonnistui", | ||||
|     "loginFailSubtitle": "Tarkista käyttäjätunnuksesi ja salasanasi", | ||||
|     "loginFailRateLimit": "Kirjautuminen epäonnistui liian monta kertaa. Yritä myöhemmin uudelleen", | ||||
|     "loginSuccessTitle": "Olet kirjautunut sisään", | ||||
|     "loginSuccessSubtitle": "Tervetuloa takaisin!", | ||||
|     "loginOauthFailTitle": "Tapahtui virhe", | ||||
|     "loginOauthFailSubtitle": "OAuthin URL-osoitteen haku epäonnistui", | ||||
|     "loginOauthSuccessTitle": "Uudelleenohjataan", | ||||
|     "loginOauthSuccessSubtitle": "Uudelleenohjaus OAuth -palveluntarjoajallesi", | ||||
|     "loginOauthAutoRedirectTitle": "Automaattinen OAuth -uudelleenohjaus", | ||||
|     "loginOauthAutoRedirectSubtitle": "Sinut ohjataan automaattisesti OAuth -palveluntarjoajallesi todentamista varten.", | ||||
|     "loginOauthAutoRedirectButton": "Siirry nyt", | ||||
|     "continueTitle": "Jatka", | ||||
|     "continueRedirectingTitle": "Uudelleenohjataan...", | ||||
|     "continueRedirectingSubtitle": "Sinun pitäisi ohjautua sovellukseen pian", | ||||
|     "continueRedirectManually": "Siirrä minut manuaalisesti", | ||||
|     "continueInsecureRedirectTitle": "Turvaton uudelleenohjaus", | ||||
|     "continueInsecureRedirectSubtitle": "Yrität siirtyä suojatusta <code>https</code> -sivusta suojaamattomalle <code>http</code> -sivulle. Oletko varma, että haluat jatkaa?", | ||||
|     "continueUntrustedRedirectTitle": "Ei-luotettu uudelleenohjaus", | ||||
|     "continueUntrustedRedirectSubtitle": "Yrität uudelleenohjata domainiin, joka ei vastaa määritettyä verkkotunnusta (<code>{{cookieDomain}}</code>). Oletko varma, että haluat jatkaa?", | ||||
|     "logoutFailTitle": "Uloskirjautuminen epäonnistui", | ||||
|     "logoutFailSubtitle": "Ole hyvä ja yritä uudelleen", | ||||
|     "logoutSuccessTitle": "Kirjauduttu ulos", | ||||
|     "logoutSuccessSubtitle": "Sinut on kirjattu ulos", | ||||
|     "logoutTitle": "Kirjaudu ulos", | ||||
|     "logoutUsernameSubtitle": "Olet kirjautuneena sisään tunnuksella <code>{{username}}</code>. Kirjaudu ulos alla olevasta painikkeesta.", | ||||
|     "logoutOauthSubtitle": "Olet kirjautuneena sisään tunnuksella <code>{{username}}</code> OAuth palvelun {{provider}} kautta. Kirjaudu ulos alla olevasta painikkeesta.", | ||||
|     "notFoundTitle": "Sivua ei löydy", | ||||
|     "notFoundSubtitle": "Sivua, jota etsit ei ole olemassa.", | ||||
|     "notFoundButton": "Palaa kotinäkymään", | ||||
|     "totpFailTitle": "Koodin vahvistus epäonnistui", | ||||
|     "totpFailSubtitle": "Tarkista koodisi ja yritä uudelleen", | ||||
|     "totpSuccessTitle": "Vahvistettu", | ||||
|     "totpSuccessSubtitle": "Uudelleenohjataan sovelluksellesi", | ||||
|     "totpTitle": "Syötä TOTP -koodisi", | ||||
|     "totpSubtitle": "Ole hyvä ja syötä koodi todennussovelluksestasi.", | ||||
|     "unauthorizedTitle": "Ei sallittu", | ||||
|     "unauthorizedResourceSubtitle": "Käyttäjällä <code>{{username}}</code> ei ole pääsyä kohteeseen <code>{{resource}}</code>.", | ||||
|     "unauthorizedLoginSubtitle": "Käyttäjällä <code>{{username}}</code> ei ole lupaa kirjautua.", | ||||
|     "unauthorizedGroupsSubtitle": "Käyttäjä <code>{{username}}</code> ei ole ryhmässä, joka vaaditaan pääsyyn kohteeseen <code>{{resource}}</code>.", | ||||
|     "unauthorizedIpSubtitle": "IP osoitteestasi <code>{{ip}}</code> ei ole pääsyä kohteeseen <code>{{resource}}</code>.", | ||||
|     "unauthorizedButton": "Yritä uudelleen", | ||||
|     "cancelTitle": "Peruuta", | ||||
|     "forgotPasswordTitle": "Unohditko salasanasi?", | ||||
|     "failedToFetchProvidersTitle": "Todennuspalvelujen tarjoajien lataaminen epäonnistui. Tarkista määrityksesi.", | ||||
|     "errorTitle": "Tapahtui virhe", | ||||
|     "errorSubtitle": "Tapahtui virhe yritettäessä suorittaa tämä toiminto. Ole hyvä ja tarkista konsoli saadaksesi lisätietoja.", | ||||
|     "forgotPasswordMessage": "Voit nollata salasanasi vaihtamalla ympäristömuuttujan `USERS`.", | ||||
|     "fieldRequired": "Tämä kenttä on pakollinen", | ||||
|     "invalidInput": "Virheellinen syöte", | ||||
|     "domainWarningTitle": "Virheellinen verkkotunnus", | ||||
|     "domainWarningSubtitle": "Tämä instanssi on määritelty käyttämään osoitetta <code>{{appUrl}}</code>, mutta nykyinen osoite on <code>{{currentUrl}}</code>. Jos jatkat, saatat törmätä ongelmiin autentikoinnissa.", | ||||
|     "ignoreTitle": "Jätä huomiotta", | ||||
|     "goToCorrectDomainTitle": "Siirry oikeaan verkkotunnukseen" | ||||
| } | ||||
| @@ -2,7 +2,6 @@ package bootstrap | ||||
|  | ||||
| import ( | ||||
| 	"bytes" | ||||
| 	"context" | ||||
| 	"encoding/json" | ||||
| 	"fmt" | ||||
| 	"net/http" | ||||
| @@ -14,13 +13,11 @@ import ( | ||||
| 	"tinyauth/internal/config" | ||||
| 	"tinyauth/internal/controller" | ||||
| 	"tinyauth/internal/middleware" | ||||
| 	"tinyauth/internal/model" | ||||
| 	"tinyauth/internal/service" | ||||
| 	"tinyauth/internal/utils" | ||||
|  | ||||
| 	"github.com/gin-gonic/gin" | ||||
| 	"github.com/rs/zerolog/log" | ||||
| 	"gorm.io/gorm" | ||||
| ) | ||||
|  | ||||
| type Controller interface { | ||||
| @@ -139,14 +136,12 @@ func (app *BootstrapApp) Setup() error { | ||||
|  | ||||
| 	// Create services | ||||
| 	dockerService := service.NewDockerService() | ||||
| 	aclsService := service.NewAccessControlsService(dockerService) | ||||
| 	authService := service.NewAuthService(authConfig, dockerService, ldapService, database) | ||||
| 	oauthBrokerService := service.NewOAuthBrokerService(oauthProviders) | ||||
|  | ||||
| 	// Initialize services (order matters) | ||||
| 	// Initialize services | ||||
| 	services := []Service{ | ||||
| 		dockerService, | ||||
| 		aclsService, | ||||
| 		authService, | ||||
| 		oauthBrokerService, | ||||
| 	} | ||||
| @@ -248,7 +243,7 @@ func (app *BootstrapApp) Setup() error { | ||||
|  | ||||
| 	proxyController := controller.NewProxyController(controller.ProxyControllerConfig{ | ||||
| 		AppURL: app.config.AppURL, | ||||
| 	}, apiRouter, aclsService, authService) | ||||
| 	}, apiRouter, dockerService, authService) | ||||
|  | ||||
| 	userController := controller.NewUserController(controller.UserControllerConfig{ | ||||
| 		CookieDomain: cookieDomain, | ||||
| @@ -282,10 +277,6 @@ func (app *BootstrapApp) Setup() error { | ||||
| 		go app.heartbeat() | ||||
| 	} | ||||
|  | ||||
| 	// Start DB cleanup routine | ||||
| 	log.Debug().Msg("Starting database cleanup routine") | ||||
| 	go app.dbCleanup(database) | ||||
|  | ||||
| 	// Start server | ||||
| 	address := fmt.Sprintf("%s:%d", app.config.Address, app.config.Port) | ||||
| 	log.Info().Msgf("Starting server on %s", address) | ||||
| @@ -347,17 +338,3 @@ func (app *BootstrapApp) heartbeat() { | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (app *BootstrapApp) dbCleanup(db *gorm.DB) { | ||||
| 	ticker := time.NewTicker(time.Duration(30) * time.Minute) | ||||
| 	defer ticker.Stop() | ||||
| 	ctx := context.Background() | ||||
|  | ||||
| 	for ; true; <-ticker.C { | ||||
| 		log.Debug().Msg("Cleaning up old database sessions") | ||||
| 		_, err := gorm.G[model.Session](db).Where("expiry < ?", time.Now().UnixMilli()).Delete(ctx) | ||||
| 		if err != nil { | ||||
| 			log.Error().Err(err).Msg("Failed to cleanup old sessions") | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
|   | ||||
| @@ -72,7 +72,6 @@ func (controller *OAuthController) oauthURLHandler(c *gin.Context) { | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	service.GenerateVerifier() | ||||
| 	state := service.GenerateState() | ||||
| 	authURL := service.GetAuthURL(state) | ||||
| 	c.SetCookie(controller.config.CSRFCookieName, state, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true) | ||||
|   | ||||
| @@ -24,15 +24,15 @@ type ProxyControllerConfig struct { | ||||
| type ProxyController struct { | ||||
| 	config ProxyControllerConfig | ||||
| 	router *gin.RouterGroup | ||||
| 	acls   *service.AccessControlsService | ||||
| 	docker *service.DockerService | ||||
| 	auth   *service.AuthService | ||||
| } | ||||
|  | ||||
| func NewProxyController(config ProxyControllerConfig, router *gin.RouterGroup, acls *service.AccessControlsService, auth *service.AuthService) *ProxyController { | ||||
| func NewProxyController(config ProxyControllerConfig, router *gin.RouterGroup, docker *service.DockerService, auth *service.AuthService) *ProxyController { | ||||
| 	return &ProxyController{ | ||||
| 		config: config, | ||||
| 		router: router, | ||||
| 		acls:   acls, | ||||
| 		docker: docker, | ||||
| 		auth:   auth, | ||||
| 	} | ||||
| } | ||||
| @@ -76,21 +76,20 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 	proto := c.Request.Header.Get("X-Forwarded-Proto") | ||||
| 	host := c.Request.Header.Get("X-Forwarded-Host") | ||||
|  | ||||
| 	// Get acls | ||||
| 	acls, err := controller.acls.GetAccessControls(host) | ||||
| 	labels, err := controller.docker.GetLabels(host) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to get access controls for resource") | ||||
| 		log.Error().Err(err).Msg("Failed to get labels from Docker") | ||||
| 		controller.handleError(c, req, isBrowser) | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	log.Trace().Interface("acls", acls).Msg("ACLs for resource") | ||||
| 	log.Trace().Interface("labels", labels).Msg("Labels for resource") | ||||
|  | ||||
| 	clientIP := c.ClientIP() | ||||
|  | ||||
| 	if controller.auth.IsBypassedIP(acls.IP, clientIP) { | ||||
| 		controller.setHeaders(c, acls) | ||||
| 	if controller.auth.IsBypassedIP(labels.IP, clientIP) { | ||||
| 		controller.setHeaders(c, labels) | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| 			"message": "Authenticated", | ||||
| @@ -98,7 +97,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	authEnabled, err := controller.auth.IsAuthEnabled(uri, acls.Path) | ||||
| 	authEnabled, err := controller.auth.IsAuthEnabled(uri, labels.Path) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		log.Error().Err(err).Msg("Failed to check if auth is enabled for resource") | ||||
| @@ -108,7 +107,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
|  | ||||
| 	if !authEnabled { | ||||
| 		log.Debug().Msg("Authentication disabled for resource, allowing access") | ||||
| 		controller.setHeaders(c, acls) | ||||
| 		controller.setHeaders(c, labels) | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| 			"message": "Authenticated", | ||||
| @@ -116,7 +115,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		return | ||||
| 	} | ||||
|  | ||||
| 	if !controller.auth.CheckIP(acls.IP, clientIP) { | ||||
| 	if !controller.auth.CheckIP(labels.IP, clientIP) { | ||||
| 		if req.Proxy == "nginx" || !isBrowser { | ||||
| 			c.JSON(401, gin.H{ | ||||
| 				"status":  401, | ||||
| @@ -161,7 +160,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 	} | ||||
|  | ||||
| 	if userContext.IsLoggedIn { | ||||
| 		appAllowed := controller.auth.IsResourceAllowed(c, userContext, acls) | ||||
| 		appAllowed := controller.auth.IsResourceAllowed(c, userContext, labels) | ||||
|  | ||||
| 		if !appAllowed { | ||||
| 			log.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User not allowed to access resource") | ||||
| @@ -195,7 +194,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		} | ||||
|  | ||||
| 		if userContext.OAuth { | ||||
| 			groupOK := controller.auth.IsInOAuthGroup(c, userContext, acls.OAuth.Groups) | ||||
| 			groupOK := controller.auth.IsInOAuthGroup(c, userContext, labels.OAuth.Groups) | ||||
|  | ||||
| 			if !groupOK { | ||||
| 				log.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User OAuth groups do not match resource requirements") | ||||
| @@ -235,7 +234,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 		c.Header("Remote-Email", utils.SanitizeHeader(userContext.Email)) | ||||
| 		c.Header("Remote-Groups", utils.SanitizeHeader(userContext.OAuthGroups)) | ||||
|  | ||||
| 		controller.setHeaders(c, acls) | ||||
| 		controller.setHeaders(c, labels) | ||||
|  | ||||
| 		c.JSON(200, gin.H{ | ||||
| 			"status":  200, | ||||
| @@ -265,21 +264,21 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) { | ||||
| 	c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?%s", controller.config.AppURL, queries.Encode())) | ||||
| } | ||||
|  | ||||
| func (controller *ProxyController) setHeaders(c *gin.Context, acls config.App) { | ||||
| func (controller *ProxyController) setHeaders(c *gin.Context, labels config.App) { | ||||
| 	c.Header("Authorization", c.Request.Header.Get("Authorization")) | ||||
|  | ||||
| 	headers := utils.ParseHeaders(acls.Response.Headers) | ||||
| 	headers := utils.ParseHeaders(labels.Response.Headers) | ||||
|  | ||||
| 	for key, value := range headers { | ||||
| 		log.Debug().Str("header", key).Msg("Setting header") | ||||
| 		c.Header(key, value) | ||||
| 	} | ||||
|  | ||||
| 	basicPassword := utils.GetSecret(acls.Response.BasicAuth.Password, acls.Response.BasicAuth.PasswordFile) | ||||
| 	basicPassword := utils.GetSecret(labels.Response.BasicAuth.Password, labels.Response.BasicAuth.PasswordFile) | ||||
|  | ||||
| 	if acls.Response.BasicAuth.Username != "" && basicPassword != "" { | ||||
| 		log.Debug().Str("username", acls.Response.BasicAuth.Username).Msg("Setting basic auth header") | ||||
| 		c.Header("Authorization", fmt.Sprintf("Basic %s", utils.GetBasicAuth(acls.Response.BasicAuth.Username, basicPassword))) | ||||
| 	if labels.Response.BasicAuth.Username != "" && basicPassword != "" { | ||||
| 		log.Debug().Str("username", labels.Response.BasicAuth.Username).Msg("Setting basic auth header") | ||||
| 		c.Header("Authorization", fmt.Sprintf("Basic %s", utils.GetBasicAuth(labels.Response.BasicAuth.Username, basicPassword))) | ||||
| 	} | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -39,11 +39,6 @@ func setupProxyController(t *testing.T, middlewares *[]gin.HandlerFunc) (*gin.En | ||||
|  | ||||
| 	assert.NilError(t, dockerService.Init()) | ||||
|  | ||||
| 	// Access controls | ||||
| 	accessControlsService := service.NewAccessControlsService(dockerService) | ||||
|  | ||||
| 	assert.NilError(t, accessControlsService.Init()) | ||||
|  | ||||
| 	// Auth service | ||||
| 	authService := service.NewAuthService(service.AuthServiceConfig{ | ||||
| 		Users: []config.User{ | ||||
| @@ -64,7 +59,7 @@ func setupProxyController(t *testing.T, middlewares *[]gin.HandlerFunc) (*gin.En | ||||
| 	// Controller | ||||
| 	ctrl := controller.NewProxyController(controller.ProxyControllerConfig{ | ||||
| 		AppURL: "http://localhost:8080", | ||||
| 	}, group, accessControlsService, authService) | ||||
| 	}, group, dockerService, authService) | ||||
| 	ctrl.SetupRoutes() | ||||
|  | ||||
| 	return router, recorder, authService | ||||
|   | ||||
| @@ -1,103 +0,0 @@ | ||||
| package service | ||||
|  | ||||
| import ( | ||||
| 	"os" | ||||
| 	"strings" | ||||
| 	"tinyauth/internal/config" | ||||
| 	"tinyauth/internal/utils/decoders" | ||||
|  | ||||
| 	"github.com/rs/zerolog/log" | ||||
| ) | ||||
|  | ||||
| type AccessControlsService struct { | ||||
| 	docker  *DockerService | ||||
| 	envACLs config.Apps | ||||
| } | ||||
|  | ||||
| func NewAccessControlsService(docker *DockerService) *AccessControlsService { | ||||
| 	return &AccessControlsService{ | ||||
| 		docker: docker, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (acls *AccessControlsService) Init() error { | ||||
| 	acls.envACLs = config.Apps{} | ||||
| 	env := os.Environ() | ||||
| 	appEnvVars := []string{} | ||||
|  | ||||
| 	for _, e := range env { | ||||
| 		if strings.HasPrefix(e, "TINYAUTH_APPS_") { | ||||
| 			appEnvVars = append(appEnvVars, e) | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	err := acls.loadEnvACLs(appEnvVars) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| func (acls *AccessControlsService) loadEnvACLs(appEnvVars []string) error { | ||||
| 	if len(appEnvVars) == 0 { | ||||
| 		return nil | ||||
| 	} | ||||
|  | ||||
| 	envAcls := map[string]string{} | ||||
|  | ||||
| 	for _, e := range appEnvVars { | ||||
| 		parts := strings.SplitN(e, "=", 2) | ||||
| 		if len(parts) != 2 { | ||||
| 			continue | ||||
| 		} | ||||
|  | ||||
| 		// Normalize key, this should use the same normalization logic as in utils/decoders/decoders.go | ||||
| 		key := parts[0] | ||||
| 		key = strings.ToLower(key) | ||||
| 		key = strings.ReplaceAll(key, "_", ".") | ||||
| 		value := parts[1] | ||||
| 		envAcls[key] = value | ||||
| 	} | ||||
|  | ||||
| 	apps, err := decoders.DecodeLabels(envAcls) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	acls.envACLs = apps | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| func (acls *AccessControlsService) lookupEnvACLs(appDomain string) *config.App { | ||||
| 	if len(acls.envACLs.Apps) == 0 { | ||||
| 		return nil | ||||
| 	} | ||||
|  | ||||
| 	for appName, appACLs := range acls.envACLs.Apps { | ||||
| 		if appACLs.Config.Domain == appDomain { | ||||
| 			return &appACLs | ||||
| 		} | ||||
|  | ||||
| 		if strings.SplitN(appDomain, ".", 2)[0] == appName { | ||||
| 			return &appACLs | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| func (acls *AccessControlsService) GetAccessControls(appDomain string) (config.App, error) { | ||||
| 	// First check environment variables | ||||
| 	envACLs := acls.lookupEnvACLs(appDomain) | ||||
|  | ||||
| 	if envACLs != nil { | ||||
| 		log.Debug().Str("domain", appDomain).Msg("Found matching access controls in environment variables") | ||||
| 		return *envACLs, nil | ||||
| 	} | ||||
|  | ||||
| 	// Fallback to Docker labels | ||||
| 	return acls.docker.GetLabels(appDomain) | ||||
| } | ||||
| @@ -1,8 +1,6 @@ | ||||
| package service | ||||
|  | ||||
| import ( | ||||
| 	"context" | ||||
| 	"errors" | ||||
| 	"fmt" | ||||
| 	"regexp" | ||||
| 	"strings" | ||||
| @@ -43,7 +41,6 @@ type AuthService struct { | ||||
| 	loginMutex    sync.RWMutex | ||||
| 	ldap          *LdapService | ||||
| 	database      *gorm.DB | ||||
| 	ctx           context.Context | ||||
| } | ||||
|  | ||||
| func NewAuthService(config AuthServiceConfig, docker *DockerService, ldap *LdapService, database *gorm.DB) *AuthService { | ||||
| @@ -57,7 +54,6 @@ func NewAuthService(config AuthServiceConfig, docker *DockerService, ldap *LdapS | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) Init() error { | ||||
| 	auth.ctx = context.Background() | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -217,7 +213,7 @@ func (auth *AuthService) CreateSessionCookie(c *gin.Context, data *config.Sessio | ||||
| 		OAuthName:   data.OAuthName, | ||||
| 	} | ||||
|  | ||||
| 	err = gorm.G[model.Session](auth.database).Create(auth.ctx, &session) | ||||
| 	err = auth.database.Create(&session).Error | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| @@ -235,10 +231,10 @@ func (auth *AuthService) DeleteSessionCookie(c *gin.Context) error { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	_, err = gorm.G[model.Session](auth.database).Where("uuid = ?", cookie).Delete(auth.ctx) | ||||
| 	res := auth.database.Unscoped().Where("uuid = ?", cookie).Delete(&model.Session{}) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	if res.Error != nil { | ||||
| 		return res.Error | ||||
| 	} | ||||
|  | ||||
| 	c.SetCookie(auth.config.SessionCookieName, "", -1, "/", fmt.Sprintf(".%s", auth.config.CookieDomain), auth.config.SecureCookie, true) | ||||
| @@ -253,13 +249,15 @@ func (auth *AuthService) GetSessionCookie(c *gin.Context) (config.SessionCookie, | ||||
| 		return config.SessionCookie{}, err | ||||
| 	} | ||||
|  | ||||
| 	session, err := gorm.G[model.Session](auth.database).Where("uuid = ?", cookie).First(auth.ctx) | ||||
| 	var session model.Session | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return config.SessionCookie{}, err | ||||
| 	res := auth.database.Unscoped().Where("uuid = ?", cookie).First(&session) | ||||
|  | ||||
| 	if res.Error != nil { | ||||
| 		return config.SessionCookie{}, res.Error | ||||
| 	} | ||||
|  | ||||
| 	if errors.Is(err, gorm.ErrRecordNotFound) { | ||||
| 	if res.RowsAffected == 0 { | ||||
| 		return config.SessionCookie{}, fmt.Errorf("session not found") | ||||
| 	} | ||||
|  | ||||
| @@ -289,21 +287,21 @@ func (auth *AuthService) UserAuthConfigured() bool { | ||||
| 	return len(auth.config.Users) > 0 || auth.ldap != nil | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) IsResourceAllowed(c *gin.Context, context config.UserContext, acls config.App) bool { | ||||
| func (auth *AuthService) IsResourceAllowed(c *gin.Context, context config.UserContext, labels config.App) bool { | ||||
| 	if context.OAuth { | ||||
| 		log.Debug().Msg("Checking OAuth whitelist") | ||||
| 		return utils.CheckFilter(acls.OAuth.Whitelist, context.Email) | ||||
| 		return utils.CheckFilter(labels.OAuth.Whitelist, context.Email) | ||||
| 	} | ||||
|  | ||||
| 	if acls.Users.Block != "" { | ||||
| 	if labels.Users.Block != "" { | ||||
| 		log.Debug().Msg("Checking blocked users") | ||||
| 		if utils.CheckFilter(acls.Users.Block, context.Username) { | ||||
| 		if utils.CheckFilter(labels.Users.Block, context.Username) { | ||||
| 			return false | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	log.Debug().Msg("Checking users") | ||||
| 	return utils.CheckFilter(acls.Users.Allow, context.Username) | ||||
| 	return utils.CheckFilter(labels.Users.Allow, context.Username) | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) IsInOAuthGroup(c *gin.Context, context config.UserContext, requiredGroups string) bool { | ||||
| @@ -371,8 +369,8 @@ func (auth *AuthService) GetBasicAuth(c *gin.Context) *config.User { | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) CheckIP(acls config.AppIP, ip string) bool { | ||||
| 	for _, blocked := range acls.Block { | ||||
| func (auth *AuthService) CheckIP(labels config.AppIP, ip string) bool { | ||||
| 	for _, blocked := range labels.Block { | ||||
| 		res, err := utils.FilterIP(blocked, ip) | ||||
| 		if err != nil { | ||||
| 			log.Warn().Err(err).Str("item", blocked).Msg("Invalid IP/CIDR in block list") | ||||
| @@ -384,7 +382,7 @@ func (auth *AuthService) CheckIP(acls config.AppIP, ip string) bool { | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	for _, allowed := range acls.Allow { | ||||
| 	for _, allowed := range labels.Allow { | ||||
| 		res, err := utils.FilterIP(allowed, ip) | ||||
| 		if err != nil { | ||||
| 			log.Warn().Err(err).Str("item", allowed).Msg("Invalid IP/CIDR in allow list") | ||||
| @@ -396,7 +394,7 @@ func (auth *AuthService) CheckIP(acls config.AppIP, ip string) bool { | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if len(acls.Allow) > 0 { | ||||
| 	if len(labels.Allow) > 0 { | ||||
| 		log.Debug().Str("ip", ip).Msg("IP not in allow list, denying access") | ||||
| 		return false | ||||
| 	} | ||||
| @@ -405,8 +403,8 @@ func (auth *AuthService) CheckIP(acls config.AppIP, ip string) bool { | ||||
| 	return true | ||||
| } | ||||
|  | ||||
| func (auth *AuthService) IsBypassedIP(acls config.AppIP, ip string) bool { | ||||
| 	for _, bypassed := range acls.Bypass { | ||||
| func (auth *AuthService) IsBypassedIP(labels config.AppIP, ip string) bool { | ||||
| 	for _, bypassed := range labels.Bypass { | ||||
| 		res, err := utils.FilterIP(bypassed, ip) | ||||
| 		if err != nil { | ||||
| 			log.Warn().Err(err).Str("item", bypassed).Msg("Invalid IP/CIDR in bypass list") | ||||
|   | ||||
| @@ -59,8 +59,10 @@ func (generic *GenericOAuthService) Init() error { | ||||
| 	ctx := context.Background() | ||||
|  | ||||
| 	ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
|  | ||||
| 	generic.context = ctx | ||||
| 	generic.verifier = verifier | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -74,12 +76,6 @@ func (generic *GenericOAuthService) GenerateState() string { | ||||
| 	return state | ||||
| } | ||||
|  | ||||
| func (generic *GenericOAuthService) GenerateVerifier() string { | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
| 	generic.verifier = verifier | ||||
| 	return verifier | ||||
| } | ||||
|  | ||||
| func (generic *GenericOAuthService) GetAuthURL(state string) string { | ||||
| 	return generic.config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(generic.verifier)) | ||||
| } | ||||
|   | ||||
| @@ -53,7 +53,10 @@ func (github *GithubOAuthService) Init() error { | ||||
| 	httpClient := &http.Client{} | ||||
| 	ctx := context.Background() | ||||
| 	ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
|  | ||||
| 	github.context = ctx | ||||
| 	github.verifier = verifier | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -67,12 +70,6 @@ func (github *GithubOAuthService) GenerateState() string { | ||||
| 	return state | ||||
| } | ||||
|  | ||||
| func (github *GithubOAuthService) GenerateVerifier() string { | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
| 	github.verifier = verifier | ||||
| 	return verifier | ||||
| } | ||||
|  | ||||
| func (github *GithubOAuthService) GetAuthURL(state string) string { | ||||
| 	return github.config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(github.verifier)) | ||||
| } | ||||
|   | ||||
| @@ -48,7 +48,10 @@ func (google *GoogleOAuthService) Init() error { | ||||
| 	httpClient := &http.Client{} | ||||
| 	ctx := context.Background() | ||||
| 	ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
|  | ||||
| 	google.context = ctx | ||||
| 	google.verifier = verifier | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @@ -62,12 +65,6 @@ func (oauth *GoogleOAuthService) GenerateState() string { | ||||
| 	return state | ||||
| } | ||||
|  | ||||
| func (google *GoogleOAuthService) GenerateVerifier() string { | ||||
| 	verifier := oauth2.GenerateVerifier() | ||||
| 	google.verifier = verifier | ||||
| 	return verifier | ||||
| } | ||||
|  | ||||
| func (google *GoogleOAuthService) GetAuthURL(state string) string { | ||||
| 	return google.config.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(google.verifier)) | ||||
| } | ||||
|   | ||||
| @@ -11,7 +11,6 @@ import ( | ||||
| type OAuthService interface { | ||||
| 	Init() error | ||||
| 	GenerateState() string | ||||
| 	GenerateVerifier() string | ||||
| 	GetAuthURL(state string) string | ||||
| 	VerifyCode(code string) error | ||||
| 	Userinfo() (config.Claims, error) | ||||
|   | ||||
		Reference in New Issue
	
	Block a user