refactor: make error handling simpler (#55)

This commit is contained in:
Stavros
2025-03-19 16:41:19 +02:00
committed by GitHub
parent f3471880ee
commit 3ccc831a1f
15 changed files with 145 additions and 139 deletions

View File

@@ -53,11 +53,11 @@ func getAPI(t *testing.T) *api.API {
docker := docker.NewDocker()
// Initialize docker
dockerErr := docker.Init()
err := docker.Init()
// Check if there was an error
if dockerErr != nil {
t.Fatalf("Failed to initialize docker: %v", dockerErr)
if err != nil {
t.Fatalf("Failed to initialize docker: %v", err)
}
// Create auth service
@@ -167,21 +167,21 @@ func TestAppContext(t *testing.T) {
assert.Equal(t, recorder.Code, http.StatusOK)
// Read the body of the response
body, bodyErr := io.ReadAll(recorder.Body)
body, err := io.ReadAll(recorder.Body)
// Check if there was an error
if bodyErr != nil {
t.Fatalf("Error getting body: %v", bodyErr)
if err != nil {
t.Fatalf("Error getting body: %v", err)
}
// Unmarshal the body into the user struct
var app types.AppContext
jsonErr := json.Unmarshal(body, &app)
err = json.Unmarshal(body, &app)
// Check if there was an error
if jsonErr != nil {
t.Fatalf("Error unmarshalling body: %v", jsonErr)
if err != nil {
t.Fatalf("Error unmarshalling body: %v", err)
}
// Create tests values
@@ -231,11 +231,11 @@ func TestUserContext(t *testing.T) {
assert.Equal(t, recorder.Code, http.StatusOK)
// Read the body of the response
body, bodyErr := io.ReadAll(recorder.Body)
body, err := io.ReadAll(recorder.Body)
// Check if there was an error
if bodyErr != nil {
t.Fatalf("Error getting body: %v", bodyErr)
if err != nil {
t.Fatalf("Error getting body: %v", err)
}
// Unmarshal the body into the user struct
@@ -245,11 +245,11 @@ func TestUserContext(t *testing.T) {
var user User
jsonErr := json.Unmarshal(body, &user)
err = json.Unmarshal(body, &user)
// Check if there was an error
if jsonErr != nil {
t.Fatalf("Error unmarshalling body: %v", jsonErr)
if err != nil {
t.Fatalf("Error unmarshalling body: %v", err)
}
// We should get the username back

View File

@@ -160,7 +160,7 @@ func (auth *Auth) ResourceAllowed(c *gin.Context, context types.UserContext) (bo
appId := strings.Split(host, ".")[0]
// Check if resource is allowed
allowed, allowedErr := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
allowed, err := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
// If the container has an oauth whitelist, check if the user is in it
if context.OAuth {
if len(labels.OAuthWhitelist) == 0 {
@@ -187,9 +187,9 @@ func (auth *Auth) ResourceAllowed(c *gin.Context, context types.UserContext) (bo
})
// If there is an error, return false
if allowedErr != nil {
log.Error().Err(allowedErr).Msg("Error checking if resource is allowed")
return false, allowedErr
if err != nil {
log.Error().Err(err).Msg("Error checking if resource is allowed")
return false, err
}
// Return if the resource is allowed
@@ -205,7 +205,7 @@ func (auth *Auth) AuthEnabled(c *gin.Context) (bool, error) {
appId := strings.Split(host, ".")[0]
// Check if auth is enabled
enabled, enabledErr := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
enabled, err := auth.Docker.ContainerAction(appId, func(labels types.TinyauthLabels) (bool, error) {
// Check if the allowed label is empty
if labels.Allowed == "" {
// Auth enabled
@@ -213,12 +213,12 @@ func (auth *Auth) AuthEnabled(c *gin.Context) (bool, error) {
}
// Compile regex
regex, regexErr := regexp.Compile(labels.Allowed)
regex, err := regexp.Compile(labels.Allowed)
// If there is an error, invalid regex, auth enabled
if regexErr != nil {
log.Warn().Err(regexErr).Msg("Invalid regex")
return true, regexErr
if err != nil {
log.Warn().Err(err).Msg("Invalid regex")
return true, err
}
// Check if the uri matches the regex
@@ -232,9 +232,9 @@ func (auth *Auth) AuthEnabled(c *gin.Context) (bool, error) {
})
// If there is an error, auth enabled
if enabledErr != nil {
log.Error().Err(enabledErr).Msg("Error checking if auth is enabled")
return true, enabledErr
if err != nil {
log.Error().Err(err).Msg("Error checking if auth is enabled")
return true, err
}
return enabled, nil

View File

@@ -23,7 +23,7 @@ type Docker struct {
func (docker *Docker) Init() error {
// Create a new docker client
apiClient, err := client.NewClientWithOpts(client.FromEnv)
client, err := client.NewClientWithOpts(client.FromEnv)
// Check if there was an error
if err != nil {
@@ -32,7 +32,7 @@ func (docker *Docker) Init() error {
// Set the context and api client
docker.Context = context.Background()
docker.Client = apiClient
docker.Client = client
// Done
return nil
@@ -81,11 +81,11 @@ func (docker *Docker) ContainerAction(appId string, runCheck func(labels appType
}
// Get the containers
containers, containersErr := docker.GetContainers()
containers, err := docker.GetContainers()
// If there is an error, return false
if containersErr != nil {
return false, containersErr
if err != nil {
return false, err
}
log.Debug().Msg("Got containers")
@@ -93,11 +93,11 @@ func (docker *Docker) ContainerAction(appId string, runCheck func(labels appType
// Loop through the containers
for _, container := range containers {
// Inspect the container
inspect, inspectErr := docker.InspectContainer(container.ID)
inspect, err := docker.InspectContainer(container.ID)
// If there is an error, return false
if inspectErr != nil {
return false, inspectErr
if err != nil {
return false, err
}
// Get the container name (for some reason it is /name)

View File

@@ -144,7 +144,7 @@ func (h *Handlers) AuthHandler(c *gin.Context) {
// Handle error (no need to check for nginx/headers since we are sure we are using caddy/traefik)
if err != nil {
log.Error().Err(err).Msg("Failed to build query")
log.Error().Err(err).Msg("Failed to build queries")
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
return
}
@@ -184,7 +184,7 @@ func (h *Handlers) AuthHandler(c *gin.Context) {
})
if err != nil {
log.Error().Err(err).Msg("Failed to build query")
log.Error().Err(err).Msg("Failed to build queries")
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
return
}
@@ -323,10 +323,10 @@ func (h *Handlers) TotpHandler(c *gin.Context) {
}
// Check if totp is correct
totpOk := totp.Validate(totpReq.Code, user.TotpSecret)
ok := totp.Validate(totpReq.Code, user.TotpSecret)
// TOTP is incorrect
if !totpOk {
if !ok {
log.Debug().Msg("Totp incorrect")
c.JSON(401, gin.H{
"status": 401,
@@ -473,13 +473,13 @@ func (h *Handlers) OauthUrlHandler(c *gin.Context) {
// Tailscale does not have an auth url so we create a random code (does not need to be secure) to avoid caching and send it
if request.Provider == "tailscale" {
// Build tailscale query
tailscaleQuery, err := query.Values(types.TailscaleQuery{
queries, err := query.Values(types.TailscaleQuery{
Code: (1000 + rand.IntN(9000)),
})
// Handle error
if err != nil {
log.Error().Err(err).Msg("Failed to build query")
log.Error().Err(err).Msg("Failed to build queries")
c.JSON(500, gin.H{
"status": 500,
"message": "Internal Server Error",
@@ -491,7 +491,7 @@ func (h *Handlers) OauthUrlHandler(c *gin.Context) {
c.JSON(200, gin.H{
"status": 200,
"message": "OK",
"url": fmt.Sprintf("%s/api/oauth/callback/tailscale?%s", h.Config.AppURL, tailscaleQuery.Encode()),
"url": fmt.Sprintf("%s/api/oauth/callback/tailscale?%s", h.Config.AppURL, queries.Encode()),
})
return
}
@@ -572,19 +572,19 @@ func (h *Handlers) OauthCallbackHandler(c *gin.Context) {
log.Warn().Str("email", email).Msg("Email not whitelisted")
// Build query
unauthorizedQuery, err := query.Values(types.UnauthorizedQuery{
queries, err := query.Values(types.UnauthorizedQuery{
Username: email,
})
// Handle error
if err != nil {
log.Error().Msg("Failed to build query")
log.Error().Msg("Failed to build queries")
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
return
}
// Redirect to unauthorized
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/unauthorized?%s", h.Config.AppURL, unauthorizedQuery.Encode()))
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/unauthorized?%s", h.Config.AppURL, queries.Encode()))
}
log.Debug().Msg("Email whitelisted")
@@ -596,10 +596,10 @@ func (h *Handlers) OauthCallbackHandler(c *gin.Context) {
})
// Get redirect URI
redirectURI, redirectURIErr := c.Cookie("tinyauth_redirect_uri")
redirectURI, err := c.Cookie("tinyauth_redirect_uri")
// If it is empty it means that no redirect_uri was provided to the login screen so we just log in
if redirectURIErr != nil {
if err != nil {
c.Redirect(http.StatusPermanentRedirect, h.Config.AppURL)
}
@@ -609,7 +609,7 @@ func (h *Handlers) OauthCallbackHandler(c *gin.Context) {
c.SetCookie("tinyauth_redirect_uri", "", -1, "/", h.Config.Domain, h.Config.CookieSecure, true)
// Build query
redirectQuery, err := query.Values(types.LoginQuery{
queries, err := query.Values(types.LoginQuery{
RedirectURI: redirectURI,
})
@@ -617,13 +617,13 @@ func (h *Handlers) OauthCallbackHandler(c *gin.Context) {
// Handle error
if err != nil {
log.Error().Msg("Failed to build query")
log.Error().Msg("Failed to build queries")
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/error", h.Config.AppURL))
return
}
// Redirect to continue with the redirect URI
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/continue?%s", h.Config.AppURL, redirectQuery.Encode()))
c.Redirect(http.StatusPermanentRedirect, fmt.Sprintf("%s/continue?%s", h.Config.AppURL, queries.Encode()))
}
func (h *Handlers) HealthcheckHandler(c *gin.Context) {

View File

@@ -15,21 +15,21 @@ type GenericUserInfoResponse struct {
func GetGenericEmail(client *http.Client, url string) (string, error) {
// Using the oauth client get the user info url
res, resErr := client.Get(url)
res, err := client.Get(url)
// Check if there was an error
if resErr != nil {
return "", resErr
if err != nil {
return "", err
}
log.Debug().Msg("Got response from generic provider")
// Read the body of the response
body, bodyErr := io.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
// Check if there was an error
if bodyErr != nil {
return "", bodyErr
if err != nil {
return "", err
}
log.Debug().Msg("Read body from generic provider")
@@ -38,11 +38,11 @@ func GetGenericEmail(client *http.Client, url string) (string, error) {
var user GenericUserInfoResponse
// Unmarshal the body into the user struct
jsonErr := json.Unmarshal(body, &user)
err = json.Unmarshal(body, &user)
// Check if there was an error
if jsonErr != nil {
return "", jsonErr
if err != nil {
return "", err
}
log.Debug().Msg("Parsed user from generic provider")

View File

@@ -22,21 +22,21 @@ func GithubScopes() []string {
func GetGithubEmail(client *http.Client) (string, error) {
// Get the user emails from github using the oauth http client
res, resErr := client.Get("https://api.github.com/user/emails")
res, err := client.Get("https://api.github.com/user/emails")
// Check if there was an error
if resErr != nil {
return "", resErr
if err != nil {
return "", err
}
log.Debug().Msg("Got response from github")
// Read the body of the response
body, bodyErr := io.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
// Check if there was an error
if bodyErr != nil {
return "", bodyErr
if err != nil {
return "", err
}
log.Debug().Msg("Read body from github")
@@ -45,11 +45,11 @@ func GetGithubEmail(client *http.Client) (string, error) {
var emails GithubUserInfoResponse
// Unmarshal the body into the user struct
jsonErr := json.Unmarshal(body, &emails)
err = json.Unmarshal(body, &emails)
// Check if there was an error
if jsonErr != nil {
return "", jsonErr
if err != nil {
return "", err
}
log.Debug().Msg("Parsed emails from github")

View File

@@ -20,21 +20,21 @@ func GoogleScopes() []string {
func GetGoogleEmail(client *http.Client) (string, error) {
// Get the user info from google using the oauth http client
res, resErr := client.Get("https://www.googleapis.com/userinfo/v2/me")
res, err := client.Get("https://www.googleapis.com/userinfo/v2/me")
// Check if there was an error
if resErr != nil {
return "", resErr
if err != nil {
return "", err
}
log.Debug().Msg("Got response from google")
// Read the body of the response
body, bodyErr := io.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
// Check if there was an error
if bodyErr != nil {
return "", bodyErr
if err != nil {
return "", err
}
log.Debug().Msg("Read body from google")
@@ -43,11 +43,11 @@ func GetGoogleEmail(client *http.Client) (string, error) {
var user GoogleUserInfoResponse
// Unmarshal the body into the user struct
jsonErr := json.Unmarshal(body, &user)
err = json.Unmarshal(body, &user)
// Check if there was an error
if jsonErr != nil {
return "", jsonErr
if err != nil {
return "", err
}
log.Debug().Msg("Parsed user from google")

View File

@@ -128,11 +128,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
log.Debug().Msg("Got client from github")
// Get the email from the github provider
email, emailErr := GetGithubEmail(client)
email, err := GetGithubEmail(client)
// Check if there was an error
if emailErr != nil {
return "", emailErr
if err != nil {
return "", err
}
log.Debug().Msg("Got email from github")
@@ -152,11 +152,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
log.Debug().Msg("Got client from google")
// Get the email from the google provider
email, emailErr := GetGoogleEmail(client)
email, err := GetGoogleEmail(client)
// Check if there was an error
if emailErr != nil {
return "", emailErr
if err != nil {
return "", err
}
log.Debug().Msg("Got email from google")
@@ -176,11 +176,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
log.Debug().Msg("Got client from tailscale")
// Get the email from the tailscale provider
email, emailErr := GetTailscaleEmail(client)
email, err := GetTailscaleEmail(client)
// Check if there was an error
if emailErr != nil {
return "", emailErr
if err != nil {
return "", err
}
log.Debug().Msg("Got email from tailscale")
@@ -200,11 +200,11 @@ func (providers *Providers) GetUser(provider string) (string, error) {
log.Debug().Msg("Got client from generic")
// Get the email from the generic provider
email, emailErr := GetGenericEmail(client, providers.Config.GenericUserURL)
email, err := GetGenericEmail(client, providers.Config.GenericUserURL)
// Check if there was an error
if emailErr != nil {
return "", emailErr
if err != nil {
return "", err
}
log.Debug().Msg("Got email from generic")

View File

@@ -31,21 +31,21 @@ var TailscaleEndpoint = oauth2.Endpoint{
func GetTailscaleEmail(client *http.Client) (string, error) {
// Get the user info from tailscale using the oauth http client
res, resErr := client.Get("https://api.tailscale.com/api/v2/tailnet/-/users")
res, err := client.Get("https://api.tailscale.com/api/v2/tailnet/-/users")
// Check if there was an error
if resErr != nil {
return "", resErr
if err != nil {
return "", err
}
log.Debug().Msg("Got response from tailscale")
// Read the body of the response
body, bodyErr := io.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
// Check if there was an error
if bodyErr != nil {
return "", bodyErr
if err != nil {
return "", err
}
log.Debug().Msg("Read body from tailscale")
@@ -54,11 +54,11 @@ func GetTailscaleEmail(client *http.Client) (string, error) {
var users TailscaleUserInfoResponse
// Unmarshal the body into the user struct
jsonErr := json.Unmarshal(body, &users)
err = json.Unmarshal(body, &users)
// Check if there was an error
if jsonErr != nil {
return "", jsonErr
if err != nil {
return "", err
}
log.Debug().Msg("Parsed users from tailscale")

View File

@@ -29,11 +29,11 @@ func ParseUsers(users string) (types.Users, error) {
// Loop through the users and split them by colon
for _, user := range userList {
parsed, parseErr := ParseUser(user)
parsed, err := ParseUser(user)
// Check if there was an error
if parseErr != nil {
return types.Users{}, parseErr
if err != nil {
return types.Users{}, err
}
// Append the user to the users struct
@@ -69,19 +69,19 @@ func GetUpperDomain(urlSrc string) (string, error) {
// Reads a file and returns the contents
func ReadFile(file string) (string, error) {
// Check if the file exists
_, statErr := os.Stat(file)
_, err := os.Stat(file)
// Check if there was an error
if statErr != nil {
return "", statErr
if err != nil {
return "", err
}
// Read the file
data, readErr := os.ReadFile(file)
data, err := os.ReadFile(file)
// Check if there was an error
if readErr != nil {
return "", readErr
if err != nil {
return "", err
}
// Return the file contents
@@ -152,10 +152,10 @@ func GetUsers(conf string, file string) (types.Users, error) {
// If the file is set, read the file and append the users to the users string
if file != "" {
// Read the file
fileContents, fileErr := ReadFile(file)
contents, err := ReadFile(file)
// If there isn't an error we can append the users to the users string
if fileErr == nil {
if err == nil {
log.Debug().Msg("Using users from file")
// Append the users to the users string
@@ -164,7 +164,7 @@ func GetUsers(conf string, file string) (types.Users, error) {
}
// Parse the file contents into a comma separated list of users
users += ParseFileToLine(fileContents)
users += ParseFileToLine(contents)
}
}

View File

@@ -102,7 +102,7 @@ func TestParseFileToLine(t *testing.T) {
t.Log("Testing parse file to line with a valid string")
// Test the parse file to line function with a valid string
content := "user1:pass1\nuser2:pass2"
content := "\nuser1:pass1\nuser2:pass2\n"
expected := "user1:pass1,user2:pass2"
result := utils.ParseFileToLine(content)