chore: remove meaningless comments

This commit is contained in:
Stavros
2025-07-12 13:17:06 +03:00
parent e742603c15
commit 8ebed0ac9a
24 changed files with 81 additions and 876 deletions

View File

@@ -24,168 +24,118 @@ import (
func ParseUsers(users string) (types.Users, error) {
log.Debug().Msg("Parsing users")
// Create a new users struct
var usersParsed types.Users
// Split the users by comma
userList := strings.Split(users, ",")
// Check if there are any users
if len(userList) == 0 {
return types.Users{}, errors.New("invalid user format")
}
// Loop through the users and split them by colon
for _, user := range userList {
parsed, err := ParseUser(user)
// Check if there was an error
if err != nil {
return types.Users{}, err
}
// Append the user to the users struct
usersParsed = append(usersParsed, parsed)
}
log.Debug().Msg("Parsed users")
// Return the users struct
return usersParsed, nil
}
// Get upper domain parses a hostname and returns the upper domain (e.g. sub1.sub2.domain.com -> sub2.domain.com)
func GetUpperDomain(urlSrc string) (string, error) {
// Make sure the url is valid
urlParsed, err := url.Parse(urlSrc)
// Check if there was an error
if err != nil {
return "", err
}
// Split the hostname by period
urlSplitted := strings.Split(urlParsed.Hostname(), ".")
// Get the last part of the url
urlFinal := strings.Join(urlSplitted[1:], ".")
// Return the root domain
return urlFinal, nil
}
// Reads a file and returns the contents
func ReadFile(file string) (string, error) {
// Check if the file exists
_, err := os.Stat(file)
// Check if there was an error
if err != nil {
return "", err
}
// Read the file
data, err := os.ReadFile(file)
// Check if there was an error
if err != nil {
return "", err
}
// Return the file contents
return string(data), nil
}
// Parses a file into a comma separated list of users
func ParseFileToLine(content string) string {
// Split the content by newline
lines := strings.Split(content, "\n")
// Create a list of users
users := make([]string, 0)
// Loop through the lines, trimming the whitespace and appending to the users list
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
users = append(users, strings.TrimSpace(line))
}
// Return the users as a comma separated string
return strings.Join(users, ",")
}
// Get the secret from the config or file
func GetSecret(conf string, file string) string {
// If neither the config or file is set, return an empty string
if conf == "" && file == "" {
return ""
}
// If the config is set, return the config (environment variable)
if conf != "" {
return conf
}
// If the file is set, read the file
contents, err := ReadFile(file)
// Check if there was an error
if err != nil {
return ""
}
// Return the contents of the file
return ParseSecretFile(contents)
}
// Get the users from the config or file
func GetUsers(conf string, file string) (types.Users, error) {
// Create a string to store the users
var users string
// If neither the config or file is set, return an empty users struct
if conf == "" && file == "" {
return types.Users{}, nil
}
// If the config (environment) is set, append the users to the users string
if conf != "" {
log.Debug().Msg("Using users from config")
users += conf
}
// If the file is set, read the file and append the users to the users string
if file != "" {
// Read the file
contents, err := ReadFile(file)
// If there isn't an error we can append the users to the users string
if err == nil {
log.Debug().Msg("Using users from file")
// Append the users to the users string
if users != "" {
users += ","
}
// Parse the file contents into a comma separated list of users
users += ParseFileToLine(contents)
}
}
// Return the parsed users
return ParseUsers(users)
}
// Parse the headers in a map[string]string format
func ParseHeaders(headers []string) map[string]string {
// Create a map to store the headers
headerMap := make(map[string]string)
// Loop through the headers
for _, header := range headers {
split := strings.SplitN(header, "=", 2)
if len(split) != 2 || strings.TrimSpace(split[0]) == "" || strings.TrimSpace(split[1]) == "" {
@@ -197,25 +147,19 @@ func ParseHeaders(headers []string) map[string]string {
headerMap[key] = value
}
// Return the header map
return headerMap
}
// Get labels parses a map of labels into a struct with only the needed labels
func GetLabels(labels map[string]string) (types.Labels, error) {
// Create a new labels struct
var labelsParsed types.Labels
// Decode the labels into the labels struct
err := parser.Decode(labels, &labelsParsed, "tinyauth", "tinyauth.users", "tinyauth.allowed", "tinyauth.headers", "tinyauth.domain", "tinyauth.basic", "tinyauth.oauth", "tinyauth.ip")
// Check if there was an error
if err != nil {
log.Error().Err(err).Msg("Error parsing labels")
return types.Labels{}, err
}
// Return the labels struct
return labelsParsed, nil
}
@@ -236,27 +180,22 @@ func Filter[T any](slice []T, test func(T) bool) (res []T) {
// Parse user
func ParseUser(user string) (types.User, error) {
// Check if the user is escaped
if strings.Contains(user, "$$") {
user = strings.ReplaceAll(user, "$$", "$")
}
// Split the user by colon
userSplit := strings.Split(user, ":")
// Check if the user is in the correct format
if len(userSplit) < 2 || len(userSplit) > 3 {
return types.User{}, errors.New("invalid user format")
}
// Check for empty strings
for _, userPart := range userSplit {
if strings.TrimSpace(userPart) == "" {
return types.User{}, errors.New("invalid user format")
}
}
// Check if the user has a totp secret
if len(userSplit) == 2 {
return types.User{
Username: strings.TrimSpace(userSplit[0]),
@@ -264,7 +203,6 @@ func ParseUser(user string) (types.User, error) {
}, nil
}
// Return the user struct
return types.User{
Username: strings.TrimSpace(userSplit[0]),
Password: strings.TrimSpace(userSplit[1]),
@@ -274,60 +212,44 @@ func ParseUser(user string) (types.User, error) {
// Parse secret file
func ParseSecretFile(contents string) string {
// Split to lines
lines := strings.Split(contents, "\n")
// Loop through the lines
for _, line := range lines {
// Check if the line is empty
if strings.TrimSpace(line) == "" {
continue
}
// Return the line
return strings.TrimSpace(line)
}
// Return an empty string
return ""
}
// Check if a string matches a regex or if it is included in a comma separated list
func CheckFilter(filter string, str string) bool {
// Check if the filter is empty
if len(strings.TrimSpace(filter)) == 0 {
return true
}
// Check if the filter is a regex
if strings.HasPrefix(filter, "/") && strings.HasSuffix(filter, "/") {
// Create regex
re, err := regexp.Compile(filter[1 : len(filter)-1])
// Check if there was an error
if err != nil {
log.Error().Err(err).Msg("Error compiling regex")
return false
}
// Check if the string matches the regex
if re.MatchString(str) {
return true
}
}
// Split the filter by comma
filterSplit := strings.Split(filter, ",")
// Loop through the filter items
for _, item := range filterSplit {
// Check if the item matches with the string
if strings.TrimSpace(item) == str {
return true
}
}
// Return false if no match was found
return false
}
@@ -352,89 +274,56 @@ func SanitizeHeader(header string) string {
// Generate a static identifier from a string
func GenerateIdentifier(str string) string {
// Create a new UUID
uuid := uuid.NewSHA1(uuid.NameSpaceURL, []byte(str))
// Convert the UUID to a string
uuidString := uuid.String()
// Show the UUID
log.Debug().Str("uuid", uuidString).Msg("Generated UUID")
// Convert the UUID to a string
return strings.Split(uuidString, "-")[0]
}
// Get a basic auth header from a username and password
func GetBasicAuth(username string, password string) string {
// Create the auth string
auth := username + ":" + password
// Encode the auth string to base64
return base64.StdEncoding.EncodeToString([]byte(auth))
}
// Check if an IP is contained in a CIDR range/matches a single IP
func FilterIP(filter string, ip string) (bool, error) {
// Convert the check IP to an IP instance
ipAddr := net.ParseIP(ip)
// Check if the filter is a CIDR range
if strings.Contains(filter, "/") {
// Parse the CIDR range
_, cidr, err := net.ParseCIDR(filter)
// Check if there was an error
if err != nil {
return false, err
}
// Check if the IP is in the CIDR range
return cidr.Contains(ipAddr), nil
}
// Parse the filter as a single IP
ipFilter := net.ParseIP(filter)
// Check if the IP is valid
if ipFilter == nil {
return false, errors.New("invalid IP address in filter")
}
// Check if the IP matches the filter
if ipFilter.Equal(ipAddr) {
return true, nil
}
// If the filter is not a CIDR range or a single IP, return false
return false, nil
}
func DeriveKey(secret string, info string) (string, error) {
// Create hashing function
hash := sha256.New
// Create a new key using the secret and info
hkdf := hkdf.New(hash, []byte(secret), nil, []byte(info)) // I am not using a salt because I just want two different keys from one secret, maybe bad practice
// Create a new key
key := make([]byte, 24)
// Read the key from the HKDF
_, err := io.ReadFull(hkdf, key)
if err != nil {
return "", err
}
// Verify the key is not empty
if bytes.Equal(key, make([]byte, 24)) {
return "", errors.New("derived key is empty")
}
// Encode the key to base64
encodedKey := base64.StdEncoding.EncodeToString(key)
// Return the key as a base64 encoded string
return encodedKey, nil
}

View File

@@ -9,11 +9,9 @@ import (
"tinyauth/internal/utils"
)
// Test the parse users function
func TestParseUsers(t *testing.T) {
t.Log("Testing parse users with a valid string")
// Test the parse users function with a valid string
users := "user1:pass1,user2:pass2"
expected := types.Users{
{
@@ -27,154 +25,116 @@ func TestParseUsers(t *testing.T) {
}
result, err := utils.ParseUsers(users)
// Check if there was an error
if err != nil {
t.Fatalf("Error parsing users: %v", err)
}
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test the get upper domain function
func TestGetUpperDomain(t *testing.T) {
t.Log("Testing get upper domain with a valid url")
// Test the get upper domain function with a valid url
url := "https://sub1.sub2.domain.com:8080"
expected := "sub2.domain.com"
result, err := utils.GetUpperDomain(url)
// Check if there was an error
if err != nil {
t.Fatalf("Error getting root url: %v", err)
}
// Check if the result is equal to the expected
if expected != result {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test the read file function
func TestReadFile(t *testing.T) {
t.Log("Creating a test file")
// Create a test file
err := os.WriteFile("/tmp/test.txt", []byte("test"), 0644)
// Check if there was an error
if err != nil {
t.Fatalf("Error creating test file: %v", err)
}
// Test the read file function
t.Log("Testing read file with a valid file")
data, err := utils.ReadFile("/tmp/test.txt")
// Check if there was an error
if err != nil {
t.Fatalf("Error reading file: %v", err)
}
// Check if the data is equal to the expected
if data != "test" {
t.Fatalf("Expected test, got %v", data)
}
// Cleanup the test file
t.Log("Cleaning up test file")
err = os.Remove("/tmp/test.txt")
// Check if there was an error
if err != nil {
t.Fatalf("Error cleaning up test file: %v", err)
}
}
// Test the parse file to line function
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 := "\nuser1:pass1\nuser2:pass2\n"
expected := "user1:pass1,user2:pass2"
result := utils.ParseFileToLine(content)
// Check if the result is equal to the expected
if expected != result {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test the get secret function
func TestGetSecret(t *testing.T) {
t.Log("Testing get secret with an empty config and file")
// Test the get secret function with an empty config and file
conf := ""
file := "/tmp/test.txt"
expected := "test"
// Create file
err := os.WriteFile(file, []byte(fmt.Sprintf("\n\n \n\n\n %s \n\n \n ", expected)), 0644)
// Check if there was an error
if err != nil {
t.Fatalf("Error creating test file: %v", err)
}
// Test
result := utils.GetSecret(conf, file)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing get secret with an empty file and a valid config")
// Test the get secret function with an empty file and a valid config
result = utils.GetSecret(expected, "")
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing get secret with both a valid config and file")
// Test the get secret function with both a valid config and file
result = utils.GetSecret(expected, file)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
// Cleanup the test file
t.Log("Cleaning up test file")
err = os.Remove(file)
// Check if there was an error
if err != nil {
t.Fatalf("Error cleaning up test file: %v", err)
}
}
// Test the get users function
func TestGetUsers(t *testing.T) {
t.Log("Testing get users with a config and no file")
// Test the get users function with a config and no file
conf := "user1:pass1,user2:pass2"
file := ""
expected := types.Users{
@@ -189,20 +149,16 @@ func TestGetUsers(t *testing.T) {
}
result, err := utils.GetUsers(conf, file)
// Check if there was an error
if err != nil {
t.Fatalf("Error getting users: %v", err)
}
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing get users with a file and no config")
// Test the get users function with a file and no config
conf = ""
file = "/tmp/test.txt"
expected = types.Users{
@@ -216,28 +172,20 @@ func TestGetUsers(t *testing.T) {
},
}
// Create file
err = os.WriteFile(file, []byte("user1:pass1\nuser2:pass2"), 0644)
// Check if there was an error
if err != nil {
t.Fatalf("Error creating test file: %v", err)
}
// Test
result, err = utils.GetUsers(conf, file)
// Check if there was an error
if err != nil {
t.Fatalf("Error getting users: %v", err)
}
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
// Test the get users function with both a config and file
t.Log("Testing get users with both a config and file")
conf = "user3:pass3"
@@ -257,33 +205,25 @@ func TestGetUsers(t *testing.T) {
}
result, err = utils.GetUsers(conf, file)
// Check if there was an error
if err != nil {
t.Fatalf("Error getting users: %v", err)
}
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
// Cleanup the test file
t.Log("Cleaning up test file")
err = os.Remove(file)
// Check if there was an error
if err != nil {
t.Fatalf("Error cleaning up test file: %v", err)
}
}
// Test the get labels function
func TestGetLabels(t *testing.T) {
t.Log("Testing get labels with a valid map")
// Test the get tinyauth labels function with a valid map
labels := map[string]string{
"tinyauth.users": "user1,user2",
"tinyauth.oauth.whitelist": "/regex/",
@@ -303,23 +243,18 @@ func TestGetLabels(t *testing.T) {
}
result, err := utils.GetLabels(labels)
// Check if there was an error
if err != nil {
t.Fatalf("Error getting labels: %v", err)
}
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test parse user
func TestParseUser(t *testing.T) {
t.Log("Testing parse user with a valid user")
// Create variables
user := "user:pass:secret"
expected := types.User{
Username: "user",
@@ -327,22 +262,17 @@ func TestParseUser(t *testing.T) {
TotpSecret: "secret",
}
// Test the parse user function
result, err := utils.ParseUser(user)
// Check if there was an error
if err != nil {
t.Fatalf("Error parsing user: %v", err)
}
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing parse user with an escaped user")
// Create variables
user = "user:p$$ass$$:secret"
expected = types.User{
Username: "user",
@@ -350,304 +280,233 @@ func TestParseUser(t *testing.T) {
TotpSecret: "secret",
}
// Test the parse user function
result, err = utils.ParseUser(user)
// Check if there was an error
if err != nil {
t.Fatalf("Error parsing user: %v", err)
}
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing parse user with an invalid user")
// Create variables
user = "user::pass"
// Test the parse user function
_, err = utils.ParseUser(user)
// Check if there was an error
if err == nil {
t.Fatalf("Expected error parsing user")
}
}
// Test the check filter function
func TestCheckFilter(t *testing.T) {
t.Log("Testing check filter with a comma separated list")
// Create variables
filter := "user1,user2,user3"
str := "user1"
expected := true
// Test the check filter function
result := utils.CheckFilter(filter, str)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing check filter with a regex filter")
// Create variables
filter = "/^user[0-9]+$/"
str = "user1"
expected = true
// Test the check filter function
result = utils.CheckFilter(filter, str)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing check filter with an empty filter")
// Create variables
filter = ""
str = "user1"
expected = true
// Test the check filter function
result = utils.CheckFilter(filter, str)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing check filter with an invalid regex filter")
// Create variables
filter = "/^user[0-9+$/"
str = "user1"
expected = false
// Test the check filter function
result = utils.CheckFilter(filter, str)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing check filter with a non matching list")
// Create variables
filter = "user1,user2,user3"
str = "user4"
expected = false
// Test the check filter function
result = utils.CheckFilter(filter, str)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test the header sanitizer
func TestSanitizeHeader(t *testing.T) {
t.Log("Testing sanitize header with a valid string")
// Create variables
str := "X-Header=value"
expected := "X-Header=value"
// Test the sanitize header function
result := utils.SanitizeHeader(str)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing sanitize header with an invalid string")
// Create variables
str = "X-Header=val\nue"
expected = "X-Header=value"
// Test the sanitize header function
result = utils.SanitizeHeader(str)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test the parse headers function
func TestParseHeaders(t *testing.T) {
t.Log("Testing parse headers with a valid string")
// Create variables
headers := []string{"X-Hea\x00der1=value1", "X-Header2=value\n2"}
expected := map[string]string{
"X-Header1": "value1",
"X-Header2": "value2",
}
// Test the parse headers function
result := utils.ParseHeaders(headers)
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing parse headers with an invalid string")
// Create variables
headers = []string{"X-Header1=", "X-Header2", "=value", "X-Header3=value3"}
expected = map[string]string{"X-Header3": "value3"}
// Test the parse headers function
result = utils.ParseHeaders(headers)
// Check if the result is equal to the expected
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test the parse secret file function
func TestParseSecretFile(t *testing.T) {
t.Log("Testing parse secret file with a valid file")
// Create variables
content := "\n\n \n\n\n secret \n\n \n "
expected := "secret"
// Test the parse secret file function
result := utils.ParseSecretFile(content)
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
}
// Test the filter IP function
func TestFilterIP(t *testing.T) {
t.Log("Testing filter IP with an IP and a valid CIDR")
// Create variables
ip := "10.10.10.10"
filter := "10.10.10.0/24"
expected := true
// Test the filter IP function
result, err := utils.FilterIP(filter, ip)
// Check if there was an error
if err != nil {
t.Fatalf("Error filtering IP: %v", err)
}
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing filter IP with an IP and a valid IP")
// Create variables
filter = "10.10.10.10"
expected = true
// Test the filter IP function
result, err = utils.FilterIP(filter, ip)
// Check if there was an error
if err != nil {
t.Fatalf("Error filtering IP: %v", err)
}
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing filter IP with an IP and an non matching CIDR")
// Create variables
filter = "10.10.15.0/24"
expected = false
// Test the filter IP function
result, err = utils.FilterIP(filter, ip)
// Check if there was an error
if err != nil {
t.Fatalf("Error filtering IP: %v", err)
}
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing filter IP with a non matching IP and a valid CIDR")
// Create variables
filter = "10.10.10.11"
expected = false
// Test the filter IP function
result, err = utils.FilterIP(filter, ip)
// Check if there was an error
if err != nil {
t.Fatalf("Error filtering IP: %v", err)
}
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}
t.Log("Testing filter IP with an IP and an invalid CIDR")
// Create variables
filter = "10.../83"
// Test the filter IP function
_, err = utils.FilterIP(filter, ip)
// Check if there was an error
if err == nil {
t.Fatalf("Expected error filtering IP")
}
}
// Test the derive key function
func TestDeriveKey(t *testing.T) {
t.Log("Testing the derive key function")
// Create variables
master := "master"
info := "info"
expected := "gdrdU/fXzclYjiSXRexEatVgV13qQmKl"
// Test the derive key function
result, err := utils.DeriveKey(master, info)
// Check if there was an error
if err != nil {
t.Fatalf("Error deriving key: %v", err)
}
// Check if the result is equal to the expected
if result != expected {
t.Fatalf("Expected %v, got %v", expected, result)
}