mirror of
				https://github.com/steveiliop56/tinyauth.git
				synced 2025-10-30 21:55:43 +00:00 
			
		
		
		
	Compare commits
	
		
			4 Commits
		
	
	
		
			3960d89788
			...
			refactor/a
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | 59e997da26 | ||
|   | 9014be90aa | ||
|   | f978ae155a | ||
|   | 0227af6d2b | 
							
								
								
									
										11
									
								
								cmd/root.go
									
									
									
									
									
								
							
							
						
						
									
										11
									
								
								cmd/root.go
									
									
									
									
									
								
							| @@ -1,6 +1,7 @@ | |||||||
| package cmd | package cmd | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
|  | 	"os" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"tinyauth/internal/bootstrap" | 	"tinyauth/internal/bootstrap" | ||||||
| 	"tinyauth/internal/config" | 	"tinyauth/internal/config" | ||||||
| @@ -16,13 +17,14 @@ import ( | |||||||
| type rootCmd struct { | type rootCmd struct { | ||||||
| 	root     *cobra.Command | 	root     *cobra.Command | ||||||
| 	cmd      *cobra.Command | 	cmd      *cobra.Command | ||||||
|  |  | ||||||
| 	viper    *viper.Viper | 	viper    *viper.Viper | ||||||
|  | 	aclFlags map[string]string | ||||||
| } | } | ||||||
|  |  | ||||||
| func newRootCmd() *rootCmd { | func newRootCmd() *rootCmd { | ||||||
| 	return &rootCmd{ | 	return &rootCmd{ | ||||||
| 		viper:    viper.New(), | 		viper:    viper.New(), | ||||||
|  | 		aclFlags: make(map[string]string), | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -32,6 +34,9 @@ func (c *rootCmd) Register() { | |||||||
| 		Short: "The simplest way to protect your apps with a login screen", | 		Short: "The simplest way to protect your apps with a login screen", | ||||||
| 		Long:  `Tinyauth is a simple authentication middleware that adds a simple login screen or OAuth with Google, Github or any other provider to all of your docker apps.`, | 		Long:  `Tinyauth is a simple authentication middleware that adds a simple login screen or OAuth with Google, Github or any other provider to all of your docker apps.`, | ||||||
| 		Run:   c.run, | 		Run:   c.run, | ||||||
|  | 		FParseErrWhitelist: cobra.FParseErrWhitelist{ | ||||||
|  | 			UnknownFlags: true, | ||||||
|  | 		}, | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	c.viper.AutomaticEnv() | 	c.viper.AutomaticEnv() | ||||||
| @@ -116,7 +121,7 @@ func (c *rootCmd) run(cmd *cobra.Command, args []string) { | |||||||
| 		log.Warn().Msg("Log level set to trace, this will log sensitive information!") | 		log.Warn().Msg("Log level set to trace, this will log sensitive information!") | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	app := bootstrap.NewBootstrapApp(conf) | 	app := bootstrap.NewBootstrapApp(conf, c.aclFlags) | ||||||
|  |  | ||||||
| 	err = app.Setup() | 	err = app.Setup() | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| @@ -126,6 +131,8 @@ func (c *rootCmd) run(cmd *cobra.Command, args []string) { | |||||||
|  |  | ||||||
| func Run() { | func Run() { | ||||||
| 	rootCmd := newRootCmd() | 	rootCmd := newRootCmd() | ||||||
|  | 	rootCmd.aclFlags = utils.ExtractACLFlags(os.Args[1:]) | ||||||
|  |  | ||||||
| 	rootCmd.Register() | 	rootCmd.Register() | ||||||
| 	root := rootCmd.GetCmd() | 	root := rootCmd.GetCmd() | ||||||
|  |  | ||||||
|   | |||||||
							
								
								
									
										1
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										1
									
								
								go.mod
									
									
									
									
									
								
							| @@ -47,6 +47,7 @@ require ( | |||||||
| 	github.com/quic-go/qpack v0.5.1 // indirect | 	github.com/quic-go/qpack v0.5.1 // indirect | ||||||
| 	github.com/quic-go/quic-go v0.54.1 // indirect | 	github.com/quic-go/quic-go v0.54.1 // indirect | ||||||
| 	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect | 	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect | ||||||
|  | 	github.com/stoewer/go-strcase v1.3.1 // indirect | ||||||
| 	github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect | 	github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect | ||||||
| 	go.opentelemetry.io/auto/sdk v1.1.0 // indirect | 	go.opentelemetry.io/auto/sdk v1.1.0 // indirect | ||||||
| 	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.34.0 // indirect | 	go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.34.0 // indirect | ||||||
|   | |||||||
							
								
								
									
										2
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										2
									
								
								go.sum
									
									
									
									
									
								
							| @@ -259,6 +259,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= | |||||||
| github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= | github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= | ||||||
| github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= | github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= | ||||||
| github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= | github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= | ||||||
|  | github.com/stoewer/go-strcase v1.3.1 h1:iS0MdW+kVTxgMoE1LAZyMiYJFKlOzLooE4MxjirtkAs= | ||||||
|  | github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo= | ||||||
| github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= | ||||||
| github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= | ||||||
| github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= | ||||||
|   | |||||||
| @@ -38,12 +38,14 @@ type Service interface { | |||||||
|  |  | ||||||
| type BootstrapApp struct { | type BootstrapApp struct { | ||||||
| 	config   config.Config | 	config   config.Config | ||||||
|  | 	aclFlags map[string]string | ||||||
| 	uuid     string | 	uuid     string | ||||||
| } | } | ||||||
|  |  | ||||||
| func NewBootstrapApp(config config.Config) *BootstrapApp { | func NewBootstrapApp(config config.Config, aclFlags map[string]string) *BootstrapApp { | ||||||
| 	return &BootstrapApp{ | 	return &BootstrapApp{ | ||||||
| 		config:   config, | 		config:   config, | ||||||
|  | 		aclFlags: aclFlags, | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
| @@ -140,6 +142,7 @@ func (app *BootstrapApp) Setup() error { | |||||||
| 	// Create services | 	// Create services | ||||||
| 	dockerService := service.NewDockerService() | 	dockerService := service.NewDockerService() | ||||||
| 	aclsService := service.NewAccessControlsService(dockerService) | 	aclsService := service.NewAccessControlsService(dockerService) | ||||||
|  | 	aclsService.SetACLFlags(app.aclFlags) | ||||||
| 	authService := service.NewAuthService(authConfig, dockerService, ldapService, database) | 	authService := service.NewAuthService(authConfig, dockerService, ldapService, database) | ||||||
| 	oauthBrokerService := service.NewOAuthBrokerService(oauthProviders) | 	oauthBrokerService := service.NewOAuthBrokerService(oauthProviders) | ||||||
|  |  | ||||||
|   | |||||||
| @@ -53,16 +53,16 @@ type Claims struct { | |||||||
| } | } | ||||||
|  |  | ||||||
| type OAuthServiceConfig struct { | type OAuthServiceConfig struct { | ||||||
| 	ClientID           string   `key:"client-id"` | 	ClientID           string `field:"client-id"` | ||||||
| 	ClientSecret       string   `key:"client-secret"` | 	ClientSecret       string | ||||||
| 	ClientSecretFile   string   `key:"client-secret-file"` | 	ClientSecretFile   string | ||||||
| 	Scopes             []string `key:"scopes"` | 	Scopes             []string | ||||||
| 	RedirectURL        string   `key:"redirect-url"` | 	RedirectURL        string `field:"redirect-url"` | ||||||
| 	AuthURL            string   `key:"auth-url"` | 	AuthURL            string `field:"auth-url"` | ||||||
| 	TokenURL           string   `key:"token-url"` | 	TokenURL           string `field:"token-url"` | ||||||
| 	UserinfoURL        string   `key:"user-info-url"` | 	UserinfoURL        string `field:"user-info-url"` | ||||||
| 	InsecureSkipVerify bool     `key:"insecure-skip-verify"` | 	InsecureSkipVerify bool | ||||||
| 	Name               string   `key:"name"` | 	Name               string | ||||||
| } | } | ||||||
|  |  | ||||||
| var OverrideProviders = map[string]string{ | var OverrideProviders = map[string]string{ | ||||||
|   | |||||||
| @@ -4,7 +4,7 @@ import ( | |||||||
| 	"os" | 	"os" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"tinyauth/internal/config" | 	"tinyauth/internal/config" | ||||||
| 	"tinyauth/internal/utils/decoders" | 	"tinyauth/internal/utils" | ||||||
|  |  | ||||||
| 	"github.com/rs/zerolog/log" | 	"github.com/rs/zerolog/log" | ||||||
| ) | ) | ||||||
| @@ -12,62 +12,31 @@ import ( | |||||||
| type AccessControlsService struct { | type AccessControlsService struct { | ||||||
| 	docker   *DockerService | 	docker   *DockerService | ||||||
| 	envACLs  config.Apps | 	envACLs  config.Apps | ||||||
|  | 	aclFlags map[string]string | ||||||
| } | } | ||||||
|  |  | ||||||
| func NewAccessControlsService(docker *DockerService) *AccessControlsService { | func NewAccessControlsService(docker *DockerService) *AccessControlsService { | ||||||
| 	return &AccessControlsService{ | 	return &AccessControlsService{ | ||||||
| 		docker:   docker, | 		docker:   docker, | ||||||
|  | 		aclFlags: make(map[string]string), | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func (acls *AccessControlsService) SetACLFlags(flags map[string]string) { | ||||||
|  | 	acls.aclFlags = flags | ||||||
|  | } | ||||||
|  |  | ||||||
| func (acls *AccessControlsService) Init() error { | func (acls *AccessControlsService) Init() error { | ||||||
| 	acls.envACLs = config.Apps{} |  | ||||||
| 	env := os.Environ() | 	env := os.Environ() | ||||||
| 	appEnvVars := []string{} |  | ||||||
|  |  | ||||||
| 	for _, e := range env { | 	apps, err := utils.GetACLsConfig(env, acls.aclFlags) | ||||||
| 		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 { | 	if err != nil { | ||||||
| 		return err | 		return err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	acls.envACLs = apps | 	acls.envACLs = apps | ||||||
|  |  | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
|   | |||||||
| @@ -147,7 +147,7 @@ func GetOAuthProvidersConfig(env []string, args []string, appUrl string) (map[st | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	envProviders, err := decoders.DecodeEnv(envMap) | 	envProviders, err := decoders.DecodeEnv[config.Providers, config.OAuthServiceConfig](envMap, "providers") | ||||||
|  |  | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| @@ -167,7 +167,7 @@ func GetOAuthProvidersConfig(env []string, args []string, appUrl string) (map[st | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	flagProviders, err := decoders.DecodeFlags(flagsMap) | 	flagProviders, err := decoders.DecodeFlags[config.Providers, config.OAuthServiceConfig](flagsMap, "providers") | ||||||
|  |  | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return nil, err | 		return nil, err | ||||||
| @@ -208,3 +208,53 @@ func GetOAuthProvidersConfig(env []string, args []string, appUrl string) (map[st | |||||||
| 	// Return combined providers | 	// Return combined providers | ||||||
| 	return providers, nil | 	return providers, nil | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func GetACLsConfig(env []string, flagsMap map[string]string) (config.Apps, error) { | ||||||
|  | 	apps := config.Apps{Apps: make(map[string]config.App)} | ||||||
|  |  | ||||||
|  | 	envMap := make(map[string]string) | ||||||
|  |  | ||||||
|  | 	for _, e := range env { | ||||||
|  | 		pair := strings.SplitN(e, "=", 2) | ||||||
|  | 		if len(pair) == 2 { | ||||||
|  | 			envMap[pair[0]] = pair[1] | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	envApps, err := decoders.DecodeACLEnv[config.Apps](envMap, "apps") | ||||||
|  |  | ||||||
|  | 	if err != nil { | ||||||
|  | 		return config.Apps{}, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if envApps.Apps != nil { | ||||||
|  | 		maps.Copy(apps.Apps, envApps.Apps) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	flagApps, err := decoders.DecodeACLFlags[config.Apps](flagsMap, "apps") | ||||||
|  |  | ||||||
|  | 	if err != nil { | ||||||
|  | 		return config.Apps{}, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if flagApps.Apps != nil { | ||||||
|  | 		maps.Copy(apps.Apps, flagApps.Apps) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return apps, nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func ExtractACLFlags(args []string) map[string]string { | ||||||
|  | 	aclFlags := make(map[string]string) | ||||||
|  |  | ||||||
|  | 	for _, arg := range args { | ||||||
|  | 		if strings.HasPrefix(arg, "--apps-") || strings.HasPrefix(arg, "--tinyauth-apps-") { | ||||||
|  | 			pair := strings.SplitN(arg[2:], "=", 2) | ||||||
|  | 			if len(pair) == 2 { | ||||||
|  | 				aclFlags[pair[0]] = pair[1] | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return aclFlags | ||||||
|  | } | ||||||
|   | |||||||
| @@ -3,29 +3,89 @@ package decoders | |||||||
| import ( | import ( | ||||||
| 	"reflect" | 	"reflect" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"tinyauth/internal/config" |  | ||||||
|  | 	"github.com/stoewer/go-strcase" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| func NormalizeKeys(keys map[string]string, rootName string, sep string) map[string]string { | func ParsePath(parts []string, idx int, t reflect.Type) []string { | ||||||
| 	normalized := make(map[string]string) | 	if idx >= len(parts) { | ||||||
| 	knownKeys := getKnownKeys() | 		return []string{} | ||||||
|  |  | ||||||
| 	for k, v := range keys { |  | ||||||
| 		var finalKey []string |  | ||||||
| 		var suffix string |  | ||||||
| 		var camelClientName string |  | ||||||
| 		var camelField string |  | ||||||
|  |  | ||||||
| 		finalKey = append(finalKey, rootName) |  | ||||||
| 		finalKey = append(finalKey, "providers") |  | ||||||
| 		lowerKey := strings.ToLower(k) |  | ||||||
|  |  | ||||||
| 		if !strings.HasPrefix(lowerKey, "providers"+sep) { |  | ||||||
| 			continue |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	if t.Kind() == reflect.Map { | ||||||
|  |  | ||||||
|  | 		if idx >= len(parts) { | ||||||
|  | 			return []string{} | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		elemType := t.Elem() | ||||||
|  | 		keyEndIdx := idx + 1 | ||||||
|  |  | ||||||
|  | 		if elemType.Kind() == reflect.Struct { | ||||||
|  | 			for i := idx + 1; i < len(parts); i++ { | ||||||
|  | 				found := false | ||||||
|  |  | ||||||
|  | 				for j := 0; j < elemType.NumField(); j++ { | ||||||
|  | 					field := elemType.Field(j) | ||||||
|  | 					if strings.EqualFold(parts[i], field.Name) { | ||||||
|  | 						keyEndIdx = i | ||||||
|  | 						found = true | ||||||
|  | 						break | ||||||
|  | 					} | ||||||
|  | 				} | ||||||
|  |  | ||||||
|  | 				if found { | ||||||
|  | 					break | ||||||
|  | 				} | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		keyParts := parts[idx:keyEndIdx] | ||||||
|  | 		keyName := strings.ToLower(strings.Join(keyParts, "_")) | ||||||
|  |  | ||||||
|  | 		rest := ParsePath(parts, keyEndIdx, elemType) | ||||||
|  | 		result := append([]string{keyName}, rest...) | ||||||
|  | 		return result | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if t.Kind() == reflect.Struct { | ||||||
|  | 		for i := 0; i < t.NumField(); i++ { | ||||||
|  | 			field := t.Field(i) | ||||||
|  | 			if field.Type.Kind() == reflect.Map { | ||||||
|  | 				rest := ParsePath(parts, idx, field.Type) | ||||||
|  | 				if len(rest) > 0 { | ||||||
|  | 					return rest | ||||||
|  | 				} | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		for i := 0; i < t.NumField(); i++ { | ||||||
|  | 			field := t.Field(i) | ||||||
|  | 			if strings.EqualFold(parts[idx], field.Name) { | ||||||
|  | 				rest := ParsePath(parts, idx+1, field.Type) | ||||||
|  | 				result := append([]string{strings.ToLower(field.Name)}, rest...) | ||||||
|  | 				return result | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return []string{} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func normalizeKeys[T any](input map[string]string, root string, sep string) map[string]string { | ||||||
|  | 	knownKeys := getKnownKeys[T]() | ||||||
|  | 	normalized := make(map[string]string) | ||||||
|  |  | ||||||
|  | 	for k, v := range input { | ||||||
|  | 		parts := []string{"tinyauth"} | ||||||
|  |  | ||||||
|  | 		key := strings.ToLower(k) | ||||||
|  | 		key = strings.ReplaceAll(key, sep, "-") | ||||||
|  |  | ||||||
|  | 		suffix := "" | ||||||
|  |  | ||||||
| 		for _, known := range knownKeys { | 		for _, known := range knownKeys { | ||||||
| 			if strings.HasSuffix(lowerKey, strings.ReplaceAll(known, "-", sep)) { | 			if strings.HasSuffix(key, known) { | ||||||
| 				suffix = known | 				suffix = known | ||||||
| 				break | 				break | ||||||
| 			} | 			} | ||||||
| @@ -35,55 +95,101 @@ func NormalizeKeys(keys map[string]string, rootName string, sep string) map[stri | |||||||
| 			continue | 			continue | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(lowerKey, "providers"+sep), strings.ReplaceAll(suffix, "-", sep))) == "" { | 		parts = append(parts, root) | ||||||
|  |  | ||||||
|  | 		id := strings.TrimPrefix(key, root+"-") | ||||||
|  | 		id = strings.TrimSuffix(id, "-"+suffix) | ||||||
|  |  | ||||||
|  | 		if id == "" { | ||||||
| 			continue | 			continue | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		clientNameParts := strings.Split(strings.TrimPrefix(strings.TrimSuffix(lowerKey, sep+strings.ReplaceAll(suffix, "-", sep)), "providers"+sep), sep) | 		parts = append(parts, id) | ||||||
|  | 		parts = append(parts, suffix) | ||||||
|  |  | ||||||
| 		for i, p := range clientNameParts { | 		final := "" | ||||||
| 			if i == 0 { |  | ||||||
| 				camelClientName += p | 		for i, part := range parts { | ||||||
| 				continue | 			if i > 0 { | ||||||
|  | 				final += "." | ||||||
| 			} | 			} | ||||||
| 			if p == "" { | 			final += strcase.LowerCamelCase(part) | ||||||
| 				continue |  | ||||||
| 			} |  | ||||||
| 			camelClientName += strings.ToUpper(string([]rune(p)[0])) + string([]rune(p)[1:]) |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		finalKey = append(finalKey, camelClientName) | 		normalized[final] = v | ||||||
|  |  | ||||||
| 		fieldParts := strings.Split(suffix, "-") |  | ||||||
|  |  | ||||||
| 		for i, p := range fieldParts { |  | ||||||
| 			if i == 0 { |  | ||||||
| 				camelField += p |  | ||||||
| 				continue |  | ||||||
| 			} |  | ||||||
| 			if p == "" { |  | ||||||
| 				continue |  | ||||||
| 			} |  | ||||||
| 			camelField += strings.ToUpper(string([]rune(p)[0])) + string([]rune(p)[1:]) |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		finalKey = append(finalKey, camelField) |  | ||||||
| 		normalized[strings.Join(finalKey, ".")] = v |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return normalized | 	return normalized | ||||||
| } | } | ||||||
|  |  | ||||||
| func getKnownKeys() []string { | func getKnownKeys[T any]() []string { | ||||||
| 	var known []string | 	var keys []string | ||||||
|  | 	var t T | ||||||
|  |  | ||||||
| 	p := config.OAuthServiceConfig{} | 	v := reflect.ValueOf(t) | ||||||
| 	v := reflect.ValueOf(p) | 	typeOfT := v.Type() | ||||||
| 	typeOfP := v.Type() |  | ||||||
|  |  | ||||||
| 	for field := range typeOfP.NumField() { | 	for field := range typeOfT.NumField() { | ||||||
| 		known = append(known, typeOfP.Field(field).Tag.Get("key")) | 		if typeOfT.Field(field).Tag.Get("field") != "" { | ||||||
|  | 			keys = append(keys, typeOfT.Field(field).Tag.Get("field")) | ||||||
|  | 			continue | ||||||
|  | 		} | ||||||
|  | 		keys = append(keys, strcase.KebabCase(typeOfT.Field(field).Name)) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return known | 	return keys | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func normalizeACLKeys[T any](input map[string]string, root string, sep string) map[string]string { | ||||||
|  | 	normalized := make(map[string]string) | ||||||
|  | 	var t T | ||||||
|  | 	rootType := reflect.TypeOf(t) | ||||||
|  |  | ||||||
|  | 	for k, v := range input { | ||||||
|  | 		parts := strings.Split(strings.ToLower(k), sep) | ||||||
|  |  | ||||||
|  | 		if len(parts) < 2 { | ||||||
|  | 			continue | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// Two cases: | ||||||
|  | 		// 1. Keys starting with "tinyauth" (env vars): tinyauth_apps_... | ||||||
|  | 		// 2. Keys starting with root directly (flags): apps-... | ||||||
|  | 		startIdx := 0 | ||||||
|  | 		if parts[0] == "tinyauth" { | ||||||
|  | 			if len(parts) < 3 { | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
|  | 			if parts[1] != root { | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
|  | 			startIdx = 2 // Skip "tinyauth" and root | ||||||
|  | 		} else if parts[0] == root { | ||||||
|  | 			startIdx = 1 // Skip root only | ||||||
|  | 		} else { | ||||||
|  | 			continue | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		if startIdx < len(parts) { | ||||||
|  | 			parsedParts := ParsePath(parts[startIdx:], 0, rootType) | ||||||
|  |  | ||||||
|  | 			if len(parsedParts) == 0 { | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
|  |  | ||||||
|  | 			final := "tinyauth." + root | ||||||
|  |  | ||||||
|  | 			for _, part := range parsedParts { | ||||||
|  | 				if strings.Contains(part, "_") { | ||||||
|  | 					final += "." + part | ||||||
|  | 				} else { | ||||||
|  | 					final += "." + strcase.LowerCamelCase(part) | ||||||
|  | 				} | ||||||
|  | 			} | ||||||
|  |  | ||||||
|  | 			normalized[final] = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return normalized | ||||||
| } | } | ||||||
|   | |||||||
| @@ -1,49 +0,0 @@ | |||||||
| package decoders_test |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"testing" |  | ||||||
| 	"tinyauth/internal/utils/decoders" |  | ||||||
|  |  | ||||||
| 	"gotest.tools/v3/assert" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| func TestNormalizeKeys(t *testing.T) { |  | ||||||
| 	// Test with env |  | ||||||
| 	test := map[string]string{ |  | ||||||
| 		"PROVIDERS_CLIENT1_CLIENT_ID":                    "my-client-id", |  | ||||||
| 		"PROVIDERS_CLIENT1_CLIENT_SECRET":                "my-client-secret", |  | ||||||
| 		"PROVIDERS_MY_AWESOME_CLIENT_CLIENT_ID":          "my-awesome-client-id", |  | ||||||
| 		"PROVIDERS_MY_AWESOME_CLIENT_CLIENT_SECRET_FILE": "/path/to/secret", |  | ||||||
| 		"I_LOOK_LIKE_A_KEY_CLIENT_ID":                    "should-not-appear", |  | ||||||
| 		"PROVIDERS_CLIENT_ID":                            "should-not-appear", |  | ||||||
| 	} |  | ||||||
| 	expected := map[string]string{ |  | ||||||
| 		"tinyauth.providers.client1.clientId":                 "my-client-id", |  | ||||||
| 		"tinyauth.providers.client1.clientSecret":             "my-client-secret", |  | ||||||
| 		"tinyauth.providers.myAwesomeClient.clientId":         "my-awesome-client-id", |  | ||||||
| 		"tinyauth.providers.myAwesomeClient.clientSecretFile": "/path/to/secret", |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	normalized := decoders.NormalizeKeys(test, "tinyauth", "_") |  | ||||||
| 	assert.DeepEqual(t, normalized, expected) |  | ||||||
|  |  | ||||||
| 	// Test with flags (assume -- is already stripped) |  | ||||||
| 	test = map[string]string{ |  | ||||||
| 		"providers-client1-client-id":                    "my-client-id", |  | ||||||
| 		"providers-client1-client-secret":                "my-client-secret", |  | ||||||
| 		"providers-my-awesome-client-client-id":          "my-awesome-client-id", |  | ||||||
| 		"providers-my-awesome-client-client-secret-file": "/path/to/secret", |  | ||||||
| 		"providers-should-not-appear-client":             "should-not-appear", |  | ||||||
| 		"i-look-like-a-key-client-id":                    "should-not-appear", |  | ||||||
| 		"providers-client-id":                            "should-not-appear", |  | ||||||
| 	} |  | ||||||
| 	expected = map[string]string{ |  | ||||||
| 		"tinyauth.providers.client1.clientId":                 "my-client-id", |  | ||||||
| 		"tinyauth.providers.client1.clientSecret":             "my-client-secret", |  | ||||||
| 		"tinyauth.providers.myAwesomeClient.clientId":         "my-awesome-client-id", |  | ||||||
| 		"tinyauth.providers.myAwesomeClient.clientSecretFile": "/path/to/secret", |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	normalized = decoders.NormalizeKeys(test, "tinyauth", "-") |  | ||||||
| 	assert.DeepEqual(t, normalized, expected) |  | ||||||
| } |  | ||||||
| @@ -1,20 +1,33 @@ | |||||||
| package decoders | package decoders | ||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"tinyauth/internal/config" |  | ||||||
|  |  | ||||||
| 	"github.com/traefik/paerser/parser" | 	"github.com/traefik/paerser/parser" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| func DecodeEnv(env map[string]string) (config.Providers, error) { | func DecodeEnv[T any, C any](env map[string]string, subName string) (T, error) { | ||||||
| 	normalized := NormalizeKeys(env, "tinyauth", "_") | 	var result T | ||||||
| 	var providers config.Providers |  | ||||||
|  |  | ||||||
| 	err := parser.Decode(normalized, &providers, "tinyauth", "tinyauth.providers") | 	normalized := normalizeKeys[C](env, subName, "_") | ||||||
|  |  | ||||||
|  | 	err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName) | ||||||
|  |  | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return config.Providers{}, err | 		return result, err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return providers, nil | 	return result, nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func DecodeACLEnv[T any](env map[string]string, subName string) (T, error) { | ||||||
|  | 	var result T | ||||||
|  |  | ||||||
|  | 	normalized := normalizeACLKeys[T](env, subName, "_") | ||||||
|  |  | ||||||
|  | 	err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName) | ||||||
|  |  | ||||||
|  | 	if err != nil { | ||||||
|  | 		return result, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return result, nil | ||||||
| } | } | ||||||
|   | |||||||
| @@ -9,52 +9,29 @@ import ( | |||||||
| ) | ) | ||||||
|  |  | ||||||
| func TestDecodeEnv(t *testing.T) { | func TestDecodeEnv(t *testing.T) { | ||||||
| 	// Variables | 	// Setup | ||||||
| 	expected := config.Providers{ | 	env := map[string]string{ | ||||||
| 		Providers: map[string]config.OAuthServiceConfig{ | 		"PROVIDERS_GOOGLE_CLIENT_ID":        "google-client-id", | ||||||
| 			"client1": { | 		"PROVIDERS_GOOGLE_CLIENT_SECRET":    "google-client-secret", | ||||||
| 				ClientID:           "client1-id", | 		"PROVIDERS_MY_GITHUB_CLIENT_ID":     "github-client-id", | ||||||
| 				ClientSecret:       "client1-secret", | 		"PROVIDERS_MY_GITHUB_CLIENT_SECRET": "github-client-secret", | ||||||
| 				Scopes:             []string{"client1-scope1", "client1-scope2"}, |  | ||||||
| 				RedirectURL:        "client1-redirect-url", |  | ||||||
| 				AuthURL:            "client1-auth-url", |  | ||||||
| 				UserinfoURL:        "client1-user-info-url", |  | ||||||
| 				Name:               "Client1", |  | ||||||
| 				InsecureSkipVerify: false, |  | ||||||
| 			}, |  | ||||||
| 			"client2": { |  | ||||||
| 				ClientID:           "client2-id", |  | ||||||
| 				ClientSecret:       "client2-secret", |  | ||||||
| 				Scopes:             []string{"client2-scope1", "client2-scope2"}, |  | ||||||
| 				RedirectURL:        "client2-redirect-url", |  | ||||||
| 				AuthURL:            "client2-auth-url", |  | ||||||
| 				UserinfoURL:        "client2-user-info-url", |  | ||||||
| 				Name:               "My Awesome Client2", |  | ||||||
| 				InsecureSkipVerify: false, |  | ||||||
| 			}, |  | ||||||
| 		}, |  | ||||||
| 	} |  | ||||||
| 	test := map[string]string{ |  | ||||||
| 		"PROVIDERS_CLIENT1_CLIENT_ID":            "client1-id", |  | ||||||
| 		"PROVIDERS_CLIENT1_CLIENT_SECRET":        "client1-secret", |  | ||||||
| 		"PROVIDERS_CLIENT1_SCOPES":               "client1-scope1,client1-scope2", |  | ||||||
| 		"PROVIDERS_CLIENT1_REDIRECT_URL":         "client1-redirect-url", |  | ||||||
| 		"PROVIDERS_CLIENT1_AUTH_URL":             "client1-auth-url", |  | ||||||
| 		"PROVIDERS_CLIENT1_USER_INFO_URL":        "client1-user-info-url", |  | ||||||
| 		"PROVIDERS_CLIENT1_NAME":                 "Client1", |  | ||||||
| 		"PROVIDERS_CLIENT1_INSECURE_SKIP_VERIFY": "false", |  | ||||||
| 		"PROVIDERS_CLIENT2_CLIENT_ID":            "client2-id", |  | ||||||
| 		"PROVIDERS_CLIENT2_CLIENT_SECRET":        "client2-secret", |  | ||||||
| 		"PROVIDERS_CLIENT2_SCOPES":               "client2-scope1,client2-scope2", |  | ||||||
| 		"PROVIDERS_CLIENT2_REDIRECT_URL":         "client2-redirect-url", |  | ||||||
| 		"PROVIDERS_CLIENT2_AUTH_URL":             "client2-auth-url", |  | ||||||
| 		"PROVIDERS_CLIENT2_USER_INFO_URL":        "client2-user-info-url", |  | ||||||
| 		"PROVIDERS_CLIENT2_NAME":                 "My Awesome Client2", |  | ||||||
| 		"PROVIDERS_CLIENT2_INSECURE_SKIP_VERIFY": "false", |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// Test | 	expected := config.Providers{ | ||||||
| 	res, err := decoders.DecodeEnv(test) | 		Providers: map[string]config.OAuthServiceConfig{ | ||||||
|  | 			"google": { | ||||||
|  | 				ClientID:     "google-client-id", | ||||||
|  | 				ClientSecret: "google-client-secret", | ||||||
|  | 			}, | ||||||
|  | 			"myGithub": { | ||||||
|  | 				ClientID:     "github-client-id", | ||||||
|  | 				ClientSecret: "github-client-secret", | ||||||
|  | 			}, | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// Execute | ||||||
|  | 	result, err := decoders.DecodeEnv[config.Providers, config.OAuthServiceConfig](env, "providers") | ||||||
| 	assert.NilError(t, err) | 	assert.NilError(t, err) | ||||||
| 	assert.DeepEqual(t, expected, res) | 	assert.DeepEqual(t, result, expected) | ||||||
| } | } | ||||||
|   | |||||||
| @@ -2,23 +2,38 @@ package decoders | |||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"tinyauth/internal/config" |  | ||||||
|  |  | ||||||
| 	"github.com/traefik/paerser/parser" | 	"github.com/traefik/paerser/parser" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| func DecodeFlags(flags map[string]string) (config.Providers, error) { | func DecodeFlags[T any, C any](flags map[string]string, subName string) (T, error) { | ||||||
| 	filtered := filterFlags(flags) | 	var result T | ||||||
| 	normalized := NormalizeKeys(filtered, "tinyauth", "-") |  | ||||||
| 	var providers config.Providers |  | ||||||
|  |  | ||||||
| 	err := parser.Decode(normalized, &providers, "tinyauth", "tinyauth.providers") | 	filtered := filterFlags(flags) | ||||||
|  | 	normalized := normalizeKeys[C](filtered, subName, "_") | ||||||
|  |  | ||||||
|  | 	err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName) | ||||||
|  |  | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		return config.Providers{}, err | 		return result, err | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return providers, nil | 	return result, nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func DecodeACLFlags[T any](flags map[string]string, subName string) (T, error) { | ||||||
|  | 	var result T | ||||||
|  |  | ||||||
|  | 	filtered := filterFlags(flags) | ||||||
|  | 	normalized := normalizeACLKeys[T](filtered, subName, "-") | ||||||
|  |  | ||||||
|  | 	err := parser.Decode(normalized, &result, "tinyauth", "tinyauth."+subName) | ||||||
|  |  | ||||||
|  | 	if err != nil { | ||||||
|  | 		return result, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return result, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func filterFlags(flags map[string]string) map[string]string { | func filterFlags(flags map[string]string) map[string]string { | ||||||
|   | |||||||
| @@ -9,52 +9,29 @@ import ( | |||||||
| ) | ) | ||||||
|  |  | ||||||
| func TestDecodeFlags(t *testing.T) { | func TestDecodeFlags(t *testing.T) { | ||||||
| 	// Variables | 	// Setup | ||||||
| 	expected := config.Providers{ | 	flags := map[string]string{ | ||||||
| 		Providers: map[string]config.OAuthServiceConfig{ | 		"--providers-google-client-id":        "google-client-id", | ||||||
| 			"client1": { | 		"--providers-google-client-secret":    "google-client-secret", | ||||||
| 				ClientID:           "client1-id", | 		"--providers-my-github-client-id":     "github-client-id", | ||||||
| 				ClientSecret:       "client1-secret", | 		"--providers-my-github-client-secret": "github-client-secret", | ||||||
| 				Scopes:             []string{"client1-scope1", "client1-scope2"}, |  | ||||||
| 				RedirectURL:        "client1-redirect-url", |  | ||||||
| 				AuthURL:            "client1-auth-url", |  | ||||||
| 				UserinfoURL:        "client1-user-info-url", |  | ||||||
| 				Name:               "Client1", |  | ||||||
| 				InsecureSkipVerify: false, |  | ||||||
| 			}, |  | ||||||
| 			"client2": { |  | ||||||
| 				ClientID:           "client2-id", |  | ||||||
| 				ClientSecret:       "client2-secret", |  | ||||||
| 				Scopes:             []string{"client2-scope1", "client2-scope2"}, |  | ||||||
| 				RedirectURL:        "client2-redirect-url", |  | ||||||
| 				AuthURL:            "client2-auth-url", |  | ||||||
| 				UserinfoURL:        "client2-user-info-url", |  | ||||||
| 				Name:               "My Awesome Client2", |  | ||||||
| 				InsecureSkipVerify: false, |  | ||||||
| 			}, |  | ||||||
| 		}, |  | ||||||
| 	} |  | ||||||
| 	test := map[string]string{ |  | ||||||
| 		"--providers-client1-client-id":            "client1-id", |  | ||||||
| 		"--providers-client1-client-secret":        "client1-secret", |  | ||||||
| 		"--providers-client1-scopes":               "client1-scope1,client1-scope2", |  | ||||||
| 		"--providers-client1-redirect-url":         "client1-redirect-url", |  | ||||||
| 		"--providers-client1-auth-url":             "client1-auth-url", |  | ||||||
| 		"--providers-client1-user-info-url":        "client1-user-info-url", |  | ||||||
| 		"--providers-client1-name":                 "Client1", |  | ||||||
| 		"--providers-client1-insecure-skip-verify": "false", |  | ||||||
| 		"--providers-client2-client-id":            "client2-id", |  | ||||||
| 		"--providers-client2-client-secret":        "client2-secret", |  | ||||||
| 		"--providers-client2-scopes":               "client2-scope1,client2-scope2", |  | ||||||
| 		"--providers-client2-redirect-url":         "client2-redirect-url", |  | ||||||
| 		"--providers-client2-auth-url":             "client2-auth-url", |  | ||||||
| 		"--providers-client2-user-info-url":        "client2-user-info-url", |  | ||||||
| 		"--providers-client2-name":                 "My Awesome Client2", |  | ||||||
| 		"--providers-client2-insecure-skip-verify": "false", |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	// Test | 	expected := config.Providers{ | ||||||
| 	res, err := decoders.DecodeFlags(test) | 		Providers: map[string]config.OAuthServiceConfig{ | ||||||
|  | 			"google": { | ||||||
|  | 				ClientID:     "google-client-id", | ||||||
|  | 				ClientSecret: "google-client-secret", | ||||||
|  | 			}, | ||||||
|  | 			"myGithub": { | ||||||
|  | 				ClientID:     "github-client-id", | ||||||
|  | 				ClientSecret: "github-client-secret", | ||||||
|  | 			}, | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// Execute | ||||||
|  | 	result, err := decoders.DecodeFlags[config.Providers, config.OAuthServiceConfig](flags, "providers") | ||||||
| 	assert.NilError(t, err) | 	assert.NilError(t, err) | ||||||
| 	assert.DeepEqual(t, expected, res) | 	assert.DeepEqual(t, result, expected) | ||||||
| } | } | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user