tokens.go94 lines, 2.8 KB
| 1 | package auth |
| 2 | |
| 3 | import ( |
| 4 | "crypto/ed25519" |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "crypto/x509" |
| 8 | "encoding/base64" |
| 9 | "encoding/pem" |
| 10 | "fmt" |
| 11 | "os" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/fiston-user/payments/internal/platform/authn" |
| 15 | "github.com/golang-jwt/jwt/v5" |
| 16 | "github.com/google/uuid" |
| 17 | ) |
| 18 | |
| 19 | // Signer issues access tokens: short-lived JWTs, signed with the auth |
| 20 | // service's Ed25519 private key. No other service ever has that key. |
| 21 | type Signer struct { |
| 22 | key ed25519.PrivateKey |
| 23 | keyID string |
| 24 | ttl time.Duration |
| 25 | } |
| 26 | |
| 27 | // NewSigner returns a Signer whose tokens are valid for ttl. |
| 28 | func NewSigner(key ed25519.PrivateKey, ttl time.Duration) *Signer { |
| 29 | return &Signer{key: key, keyID: authn.KeyID(key.Public().(ed25519.PublicKey)), ttl: ttl} |
| 30 | } |
| 31 | |
| 32 | // PublicKey returns the key that verifies the Signer's tokens. |
| 33 | func (s *Signer) PublicKey() ed25519.PublicKey { |
| 34 | return s.key.Public().(ed25519.PublicKey) |
| 35 | } |
| 36 | |
| 37 | // Issue returns an access token for the user, with their roles, issued at |
| 38 | // now. Taking the time as an argument lets tests issue tokens that have |
| 39 | // already expired. |
| 40 | func (s *Signer) Issue(userID uuid.UUID, now time.Time, roles ...string) (string, error) { |
| 41 | claims := jwt.RegisteredClaims{ |
| 42 | Issuer: authn.Issuer, |
| 43 | Subject: userID.String(), |
| 44 | Audience: jwt.ClaimStrings{authn.Audience}, |
| 45 | IssuedAt: jwt.NewNumericDate(now), |
| 46 | ExpiresAt: jwt.NewNumericDate(now.Add(s.ttl)), |
| 47 | ID: uuid.NewString(), // unique per token, for logs and audits |
| 48 | } |
| 49 | token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, authn.Claims{RegisteredClaims: claims, Roles: roles}) |
| 50 | token.Header["kid"] = s.keyID |
| 51 | signed, err := token.SignedString(s.key) |
| 52 | if err != nil { |
| 53 | return "", fmt.Errorf("sign access token: %w", err) |
| 54 | } |
| 55 | return signed, nil |
| 56 | } |
| 57 | |
| 58 | // ReadPrivateKey reads an Ed25519 private key from a PEM file, in the PKCS #8 |
| 59 | // format that openssl genpkey writes. |
| 60 | func ReadPrivateKey(path string) (ed25519.PrivateKey, error) { |
| 61 | data, err := os.ReadFile(path) |
| 62 | if err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | block, _ := pem.Decode(data) |
| 66 | if block == nil || block.Type != "PRIVATE KEY" { |
| 67 | return nil, fmt.Errorf("%s: no PEM private key", path) |
| 68 | } |
| 69 | key, err := x509.ParsePKCS8PrivateKey(block.Bytes) |
| 70 | if err != nil { |
| 71 | return nil, fmt.Errorf("%s: %w", path, err) |
| 72 | } |
| 73 | ed, ok := key.(ed25519.PrivateKey) |
| 74 | if !ok { |
| 75 | return nil, fmt.Errorf("%s: a %T, not an Ed25519 key", path, key) |
| 76 | } |
| 77 | return ed, nil |
| 78 | } |
| 79 | |
| 80 | // newRefreshToken returns a refresh token: 32 random bytes, which is 256 |
| 81 | // bits that nobody can guess, as 43 URL-safe characters. |
| 82 | func newRefreshToken() string { |
| 83 | b := make([]byte, 32) |
| 84 | rand.Read(b) |
| 85 | return base64.RawURLEncoding.EncodeToString(b) |
| 86 | } |
| 87 | |
| 88 | // hashToken is how a refresh token is stored and looked up. Unlike a |
| 89 | // password, the token is random and long, so a fast hash is enough: there's |
| 90 | // nothing to guess, even with the hash in hand. |
| 91 | func hashToken(token string) []byte { |
| 92 | sum := sha256.Sum256([]byte(token)) |
| 93 | return sum[:] |
| 94 | } |