-
Notifications
You must be signed in to change notification settings - Fork 12
fix: generate strong unique JWT key #1071
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
graikhel-intel
wants to merge
2
commits into
main
Choose a base branch
from
jwtkey
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+428
−18
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,15 @@ | ||
| package config | ||
|
|
||
| import ( | ||
| "crypto/rand" | ||
| "encoding/hex" | ||
| "errors" | ||
| "flag" | ||
| "log" | ||
| "net" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/ilyakaznacheev/cleanenv" | ||
|
|
@@ -17,7 +21,15 @@ var ConsoleConfig *Config | |
| // TrayMode indicates whether to run with system tray UI. | ||
| var TrayMode bool | ||
|
|
||
| const defaultHost = "localhost" | ||
| const ( | ||
| defaultHost = "localhost" | ||
| hs256RecommendedMinKeyBytes = 32 | ||
| ) | ||
|
|
||
| // ErrEmptyJWTKeyEnv is returned when AUTH_JWT_KEY is set in the environment but | ||
| // has an empty or whitespace-only value. Operators must either provide a non-empty | ||
| // key or leave the variable unset so Console can auto-generate one. | ||
| var ErrEmptyJWTKeyEnv = errors.New("AUTH_JWT_KEY is set but empty; provide a non-empty key or unset the variable to auto-generate") | ||
|
|
||
| type ( | ||
| // Config -. | ||
|
|
@@ -94,7 +106,7 @@ type ( | |
| Disabled bool `yaml:"disabled" env:"AUTH_DISABLED"` | ||
| AdminUsername string `yaml:"adminUsername" env:"AUTH_ADMIN_USERNAME"` | ||
| AdminPassword string `yaml:"adminPassword" env:"AUTH_ADMIN_PASSWORD"` | ||
| JWTKey string `env-required:"true" yaml:"jwtKey" env:"AUTH_JWT_KEY"` | ||
| JWTKey string `yaml:"jwtKey" env:"AUTH_JWT_KEY"` | ||
| JWTExpiration time.Duration `yaml:"jwtExpiration" env:"AUTH_JWT_EXPIRATION"` | ||
| RedirectionJWTExpiration time.Duration `yaml:"redirectionJWTExpiration" env:"AUTH_REDIRECTION_JWT_EXPIRATION"` | ||
| ClientID string `yaml:"clientId" env:"AUTH_CLIENT_ID"` | ||
|
|
@@ -187,7 +199,7 @@ func defaultConfig() *Config { | |
| Auth: Auth{ | ||
| AdminUsername: "standalone", | ||
| AdminPassword: "", // Generated and stored in config on first run if not provided | ||
| JWTKey: "your_secret_jwt_key", | ||
| JWTKey: "", // Generated and stored in config on first run if not provided | ||
| JWTExpiration: 24 * time.Hour, | ||
| RedirectionJWTExpiration: 5 * time.Minute, | ||
| // OAUTH CONFIG, if provided will not use basic auth | ||
|
|
@@ -236,17 +248,42 @@ func resolveConfigPath(configPathFlag string) (string, error) { | |
| func readOrInitConfig(configPath string, cfg *Config) error { | ||
| err := cleanenv.ReadConfig(configPath, cfg) | ||
| if err == nil { | ||
| return nil | ||
| if cfg.JWTKey != "" { | ||
| return nil | ||
| } | ||
|
|
||
| if hasNonEmptyJWTKeyEnv() { | ||
| return nil | ||
| } | ||
|
|
||
| jwtKey, genErr := generateAndSetJWTKey(cfg) | ||
| if genErr != nil { | ||
| return genErr | ||
| } | ||
|
|
||
| return saveJWTKey(configPath, jwtKey) | ||
| } | ||
|
|
||
| var pathErr *os.PathError | ||
| if errors.As(err, &pathErr) { | ||
| if !hasNonEmptyJWTKeyEnv() { | ||
| if _, genErr := generateAndSetJWTKey(cfg); genErr != nil { | ||
| return genErr | ||
| } | ||
| } | ||
|
|
||
| return writeConfig(configPath, cfg) | ||
| } | ||
|
|
||
| return err | ||
| } | ||
|
|
||
| func hasNonEmptyJWTKeyEnv() bool { | ||
| jwtKeyEnv, isSetByEnv := os.LookupEnv("AUTH_JWT_KEY") | ||
|
|
||
| return isSetByEnv && strings.TrimSpace(jwtKeyEnv) != "" | ||
| } | ||
|
|
||
| // writeConfig serializes cfg to configPath, creating the parent directory if needed. | ||
| func writeConfig(configPath string, cfg *Config) error { | ||
| configDir := filepath.Dir(configPath) | ||
|
|
@@ -296,6 +333,69 @@ func SaveAdminPassword(adminPassword string) error { | |
| return writeConfig(configPath, fileCfg) | ||
| } | ||
|
|
||
| func saveJWTKey(configPath, jwtKey string) error { | ||
| data, err := os.ReadFile(configPath) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| fileCfg := defaultConfig() | ||
| if err := yaml.Unmarshal(data, fileCfg); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| fileCfg.JWTKey = jwtKey | ||
|
|
||
| return writeConfig(configPath, fileCfg) | ||
| } | ||
|
|
||
| func generateJWTKey() (string, error) { | ||
| b := make([]byte, hs256RecommendedMinKeyBytes) | ||
| if _, err := rand.Read(b); err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| return hex.EncodeToString(b), nil | ||
| } | ||
|
|
||
| func generateAndSetJWTKey(cfg *Config) (string, error) { | ||
| jwtKey, err := generateJWTKey() | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| cfg.JWTKey = jwtKey | ||
|
|
||
| return jwtKey, nil | ||
| } | ||
|
|
||
| func warnIfWeakJWTKey(cfg *Config) { | ||
| keyLen := len([]byte(cfg.JWTKey)) | ||
| if keyLen < hs256RecommendedMinKeyBytes { | ||
| log.Printf("WARNING: auth.jwtKey looks too short (%d bytes). Please use at least %d bytes for a strong key.", keyLen, hs256RecommendedMinKeyBytes) | ||
| } | ||
| } | ||
|
|
||
| func ensureJWTKeyNotEmpty(cfg *Config, configPath string) error { | ||
| if strings.TrimSpace(cfg.JWTKey) != "" { | ||
| return nil | ||
| } | ||
|
|
||
| // If AUTH_JWT_KEY is explicitly set in the environment but empty, fail fast. | ||
| // Operators who opt in to env-driven config must supply a valid value. | ||
| jwtKeyEnv, isSetByEnv := os.LookupEnv("AUTH_JWT_KEY") | ||
| if isSetByEnv && strings.TrimSpace(jwtKeyEnv) == "" { | ||
| return ErrEmptyJWTKeyEnv | ||
| } | ||
|
|
||
| jwtKey, err := generateAndSetJWTKey(cfg) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return saveJWTKey(configPath, jwtKey) | ||
| } | ||
|
|
||
| // NewConfig returns app config. | ||
| func NewConfig() (*Config, error) { | ||
| // set defaults | ||
|
|
@@ -329,5 +429,11 @@ func NewConfig() (*Config, error) { | |
| return nil, err | ||
| } | ||
|
|
||
| if err := ensureJWTKeyNotEmpty(ConsoleConfig, configPath); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| warnIfWeakJWTKey(ConsoleConfig) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we not exit if the key length is < 32 than instead of logging a warning. |
||
|
|
||
| return ConsoleConfig, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
use log.Errorf or log.Faralf() to exit.
another way is possible warn and replace smaller key with 32 or more secure jwt key.