From a95c0ed9b0239189cf618f842ce84ad617a763ab Mon Sep 17 00:00:00 2001 From: Donovan Date: Thu, 3 Oct 2024 15:37:23 -0500 Subject: [PATCH] refactor jwt secret --- core/jwt_claims.go | 18 +++++++++++++++++- secure_bytes.sh | 12 ++++++------ util/util.go | 10 ++++++++++ 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/core/jwt_claims.go b/core/jwt_claims.go index ba85d66..2dba3d2 100644 --- a/core/jwt_claims.go +++ b/core/jwt_claims.go @@ -4,6 +4,9 @@ import ( "errors" "fmt" "github.com/golang-jwt/jwt/v5" + "go-nkode/util" + "log" + "os" "time" ) @@ -23,7 +26,20 @@ const ( resetNKodeTokenExp = 5 * time.Minute ) -var secret = GetJwtSecret("./secrets.json") +var secret = getJwtSecret() + +func getJwtSecret() []byte { + jwtSecret := os.Getenv("JWT_SECRET") + if jwtSecret == "" { + log.Fatal("No JWT_SECRET found") + } + + jwtBytes, err := util.ParseHexString(jwtSecret) + if err != nil { + log.Fatalf("error parsing jwt secret %v", err) + } + return jwtBytes +} func NewAuthenticationTokens(username string, customerId CustomerId) (AuthenticationTokens, error) { accessClaims := NewAccessClaim(username, customerId) diff --git a/secure_bytes.sh b/secure_bytes.sh index 1a8bc4d..d9f7692 100644 --- a/secure_bytes.sh +++ b/secure_bytes.sh @@ -4,11 +4,11 @@ num_bytes=16 # Use dd to read cryptographically secure bytes from /dev/urandom -# and convert them to integers using od -secure_bytes=$(dd if=/dev/urandom bs=1 count=$num_bytes 2>/dev/null | od -An -tu1) +# and convert them to hexadecimal using od +secure_bytes=$(dd if=/dev/urandom bs=1 count=$num_bytes 2>/dev/null | od -An -tx1) -# Remove leading/trailing spaces and replace spaces with commas -secure_bytes=$(echo $secure_bytes | sed 's/ /,/g') +# Remove leading/trailing spaces and concatenate the hex bytes into a single string +secure_bytes=$(echo $secure_bytes | tr -d ' \n') -# Output the result as a comma-separated list of integers -echo "Cryptographically secure bytes (as integers): $secure_bytes" +# Output the result as a hexadecimal string +echo "Cryptographically secure bytes (as hex): $secure_bytes" diff --git a/util/util.go b/util/util.go index 78948b1..39dca6e 100644 --- a/util/util.go +++ b/util/util.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "encoding/base64" "encoding/binary" + "encoding/hex" "errors" "fmt" "go-nkode/hashset" @@ -261,3 +262,12 @@ func GenerateRandomString(length int) string { } return string(b) } + +func ParseHexString(hexStr string) ([]byte, error) { + // Decode the hex string into bytes + bytes, err := hex.DecodeString(hexStr) + if err != nil { + return nil, err + } + return bytes, nil +}