-
Notifications
You must be signed in to change notification settings - Fork 276
feat: generate jwt tokens from signing key #3969
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
sweatybridge
wants to merge
5
commits into
develop
Choose a base branch
from
push-key
base: develop
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.
+318
−71
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4360a47
feat: push signing keys to remote
sweatybridge dcf9c82
chore: disable signing key update for now
sweatybridge 7e68a15
feat: asymmetric signed api keys
cemalkilic 980b370
chore: scope down key generation to validate method
sweatybridge 2ed57b5
chore: conditionally validate jwt secret
sweatybridge 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
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 |
---|---|---|
@@ -0,0 +1,169 @@ | ||
package config | ||
|
||
import ( | ||
"crypto" | ||
"crypto/ecdsa" | ||
"crypto/elliptic" | ||
"crypto/rsa" | ||
"encoding/base64" | ||
"math/big" | ||
"time" | ||
|
||
"github.com/go-errors/errors" | ||
"github.com/golang-jwt/jwt/v5" | ||
"github.com/google/uuid" | ||
) | ||
|
||
// generateAPIKeys generates JWT tokens using the appropriate signing method | ||
func (a *auth) generateAPIKeys() error { | ||
// Generate anon key if not provided | ||
if len(a.AnonKey.Value) == 0 { | ||
signed, err := a.generateJWT("anon") | ||
if err != nil { | ||
return err | ||
} | ||
a.AnonKey.Value = signed | ||
} | ||
// Generate service_role key if not provided | ||
if len(a.ServiceRoleKey.Value) == 0 { | ||
signed, err := a.generateJWT("service_role") | ||
if err != nil { | ||
return err | ||
} | ||
a.ServiceRoleKey.Value = signed | ||
} | ||
return nil | ||
} | ||
|
||
func (a auth) generateJWT(role string) (string, error) { | ||
claims := CustomClaims{Issuer: "supabase-demo", Role: role} | ||
if len(a.SigningKeys) > 0 { | ||
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Hour * 24 * 365 * 10)) // 10 years | ||
return generateAsymmetricJWT(a.SigningKeys[0], claims) | ||
} | ||
// Fallback to generating symmetric keys | ||
if len(a.JwtSecret.Value) < 16 { | ||
return "", errors.Errorf("Invalid config for auth.jwt_secret. Must be at least 16 characters") | ||
} | ||
signed, err := claims.NewToken().SignedString([]byte(a.JwtSecret.Value)) | ||
if err != nil { | ||
return "", errors.Errorf("failed to generate JWT: %w", err) | ||
} | ||
return signed, nil | ||
} | ||
|
||
// generateAsymmetricJWT generates a JWT token signed with the provided JWK private key | ||
func generateAsymmetricJWT(jwk JWK, claims CustomClaims) (string, error) { | ||
privateKey, err := jwkToPrivateKey(jwk) | ||
if err != nil { | ||
return "", errors.Errorf("failed to convert JWK to private key: %w", err) | ||
} | ||
|
||
// Determine signing method based on algorithm | ||
var token *jwt.Token | ||
switch jwk.Algorithm { | ||
case AlgRS256: | ||
token = jwt.NewWithClaims(jwt.SigningMethodRS256, claims) | ||
case AlgES256: | ||
token = jwt.NewWithClaims(jwt.SigningMethodES256, claims) | ||
default: | ||
return "", errors.Errorf("unsupported algorithm: %s", jwk.Algorithm) | ||
} | ||
|
||
if jwk.KeyID != uuid.Nil { | ||
token.Header["kid"] = jwk.KeyID.String() | ||
} | ||
|
||
tokenString, err := token.SignedString(privateKey) | ||
if err != nil { | ||
return "", errors.Errorf("failed to sign JWT: %w", err) | ||
} | ||
|
||
return tokenString, nil | ||
} | ||
|
||
// jwkToPrivateKey converts a JWK to a crypto.PrivateKey | ||
func jwkToPrivateKey(jwk JWK) (crypto.PrivateKey, error) { | ||
switch jwk.KeyType { | ||
case "RSA": | ||
return jwkToRSAPrivateKey(jwk) | ||
case "EC": | ||
return jwkToECDSAPrivateKey(jwk) | ||
default: | ||
return nil, errors.Errorf("unsupported key type: %s", jwk.KeyType) | ||
} | ||
} | ||
|
||
// jwkToRSAPrivateKey converts a JWK to an RSA private key | ||
func jwkToRSAPrivateKey(jwk JWK) (*rsa.PrivateKey, error) { | ||
nBytes, err := base64.RawURLEncoding.DecodeString(jwk.Modulus) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode modulus: %w", err) | ||
} | ||
n := new(big.Int).SetBytes(nBytes) | ||
|
||
eBytes, err := base64.RawURLEncoding.DecodeString(jwk.Exponent) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode exponent: %w", err) | ||
} | ||
e := int(new(big.Int).SetBytes(eBytes).Int64()) | ||
|
||
dBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExponent) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode private exponent: %w", err) | ||
} | ||
d := new(big.Int).SetBytes(dBytes) | ||
|
||
pBytes, err := base64.RawURLEncoding.DecodeString(jwk.FirstPrimeFactor) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode first prime factor: %w", err) | ||
} | ||
p := new(big.Int).SetBytes(pBytes) | ||
|
||
qBytes, err := base64.RawURLEncoding.DecodeString(jwk.SecondPrimeFactor) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode second prime factor: %w", err) | ||
} | ||
q := new(big.Int).SetBytes(qBytes) | ||
|
||
return &rsa.PrivateKey{ | ||
PublicKey: rsa.PublicKey{N: n, E: e}, | ||
D: d, | ||
Primes: []*big.Int{p, q}, | ||
}, nil | ||
} | ||
|
||
// jwkToECDSAPrivateKey converts a JWK to an ECDSA private key | ||
func jwkToECDSAPrivateKey(jwk JWK) (*ecdsa.PrivateKey, error) { | ||
// Only support P-256 curve for ES256 | ||
if jwk.Curve != "P-256" { | ||
return nil, errors.Errorf("unsupported curve: %s", jwk.Curve) | ||
} | ||
|
||
xBytes, err := base64.RawURLEncoding.DecodeString(jwk.X) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode x coordinate: %w", err) | ||
} | ||
x := new(big.Int).SetBytes(xBytes) | ||
|
||
yBytes, err := base64.RawURLEncoding.DecodeString(jwk.Y) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode y coordinate: %w", err) | ||
} | ||
y := new(big.Int).SetBytes(yBytes) | ||
|
||
dBytes, err := base64.RawURLEncoding.DecodeString(jwk.PrivateExponent) | ||
if err != nil { | ||
return nil, errors.Errorf("failed to decode private key: %w", err) | ||
} | ||
d := new(big.Int).SetBytes(dBytes) | ||
|
||
return &ecdsa.PrivateKey{ | ||
PublicKey: ecdsa.PublicKey{ | ||
Curve: elliptic.P256(), | ||
X: x, | ||
Y: y, | ||
}, | ||
D: d, | ||
}, nil | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.