authn.go189 lines, 5.8 KB
| 1 | // Package authn checks who sent a request. The auth service issues access |
| 2 | // tokens: JWTs signed with its Ed25519 private key. Any service can verify |
| 3 | // them with the public key alone, without calling the auth service. |
| 4 | package authn |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "crypto/ed25519" |
| 9 | "crypto/sha256" |
| 10 | "crypto/x509" |
| 11 | "encoding/base64" |
| 12 | "encoding/pem" |
| 13 | "fmt" |
| 14 | "log/slog" |
| 15 | "net/http" |
| 16 | "os" |
| 17 | "slices" |
| 18 | "strings" |
| 19 | "time" |
| 20 | |
| 21 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 22 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 23 | "github.com/fiston-user/payments/internal/platform/logging" |
| 24 | "github.com/golang-jwt/jwt/v5" |
| 25 | "github.com/google/uuid" |
| 26 | ) |
| 27 | |
| 28 | // Who issues access tokens, and who they're for. A token for another issuer |
| 29 | // or audience is refused, even with a valid signature. |
| 30 | const ( |
| 31 | Issuer = "payments-auth" |
| 32 | Audience = "payments-api" |
| 33 | ) |
| 34 | |
| 35 | // Errors a client sees. Both are a 401. |
| 36 | var ( |
| 37 | ErrMissingToken = fmt.Errorf("%w: missing bearer token", apperr.ErrUnauthenticated) |
| 38 | ErrInvalidToken = fmt.Errorf("%w: invalid or expired access token", apperr.ErrUnauthenticated) |
| 39 | ) |
| 40 | |
| 41 | // KeyID names a public key: the start of its SHA-256. Tokens carry it in their |
| 42 | // header, so after a key rotation, a verifier knows which key signed them. |
| 43 | func KeyID(key ed25519.PublicKey) string { |
| 44 | sum := sha256.Sum256(key) |
| 45 | return base64.RawURLEncoding.EncodeToString(sum[:8]) |
| 46 | } |
| 47 | |
| 48 | // Verifier checks access tokens. |
| 49 | type Verifier struct { |
| 50 | key ed25519.PublicKey |
| 51 | keyID string |
| 52 | parser *jwt.Parser |
| 53 | } |
| 54 | |
| 55 | // NewVerifier returns a Verifier for tokens signed with key's private half. |
| 56 | func NewVerifier(key ed25519.PublicKey) *Verifier { |
| 57 | return &Verifier{ |
| 58 | key: key, |
| 59 | keyID: KeyID(key), |
| 60 | parser: jwt.NewParser( |
| 61 | // Only EdDSA. The token's header names its algorithm, and a |
| 62 | // verifier that believes it can be tricked into accepting none. |
| 63 | jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}), |
| 64 | jwt.WithIssuer(Issuer), |
| 65 | jwt.WithAudience(Audience), |
| 66 | jwt.WithExpirationRequired(), |
| 67 | jwt.WithIssuedAt(), |
| 68 | jwt.WithLeeway(30*time.Second), // clocks on different servers drift |
| 69 | ), |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | // Claims are what an access token says: the registered claims, and the |
| 74 | // user's roles, when they have any. |
| 75 | type Claims struct { |
| 76 | jwt.RegisteredClaims |
| 77 | Roles []string `json:"roles,omitempty"` |
| 78 | } |
| 79 | |
| 80 | // A User is who an access token was issued to. |
| 81 | type User struct { |
| 82 | ID uuid.UUID |
| 83 | Roles []string // what they may do besides move their own money, like reviewer |
| 84 | } |
| 85 | |
| 86 | // Verify checks token's signature and claims, and returns the user it was |
| 87 | // issued to. Any problem is an ErrInvalidToken, with the details. |
| 88 | func (v *Verifier) Verify(token string) (User, error) { |
| 89 | var claims Claims |
| 90 | _, err := v.parser.ParseWithClaims(token, &claims, func(t *jwt.Token) (any, error) { |
| 91 | if kid, _ := t.Header["kid"].(string); kid != v.keyID { |
| 92 | return nil, fmt.Errorf("unknown key ID %q", kid) |
| 93 | } |
| 94 | return v.key, nil |
| 95 | }) |
| 96 | if err != nil { |
| 97 | return User{}, fmt.Errorf("%w: %w", ErrInvalidToken, err) |
| 98 | } |
| 99 | id, err := uuid.Parse(claims.Subject) |
| 100 | if err != nil { |
| 101 | return User{}, fmt.Errorf("%w: subject %q is not a user ID", ErrInvalidToken, claims.Subject) |
| 102 | } |
| 103 | return User{ID: id, Roles: claims.Roles}, nil |
| 104 | } |
| 105 | |
| 106 | type userKey struct{} |
| 107 | |
| 108 | // Require is middleware that only lets requests with a valid access token |
| 109 | // through, sent as Authorization: Bearer <token>. Handlers behind it get the |
| 110 | // caller's ID from UserID. |
| 111 | func (v *Verifier) Require(next http.Handler) http.Handler { |
| 112 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 113 | token := bearer(r.Header.Get("Authorization")) |
| 114 | if token == "" { |
| 115 | w.Header().Set("WWW-Authenticate", "Bearer") |
| 116 | httpx.Error(w, r, ErrMissingToken) |
| 117 | return |
| 118 | } |
| 119 | user, err := v.Verify(token) |
| 120 | if err != nil { |
| 121 | // The client only learns that the token is no good. The log says why. |
| 122 | slog.InfoContext(r.Context(), "access token refused", "err", err) |
| 123 | w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`) |
| 124 | httpx.Error(w, r, ErrInvalidToken) |
| 125 | return |
| 126 | } |
| 127 | next.ServeHTTP(w, r.WithContext(withUser(r.Context(), user))) |
| 128 | }) |
| 129 | } |
| 130 | |
| 131 | // RequireRole is middleware, behind Require, that only lets users with role |
| 132 | // through. Anyone else gets a 403. |
| 133 | func RequireRole(role string) httpx.Middleware { |
| 134 | return func(next http.Handler) http.Handler { |
| 135 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 136 | user, _ := r.Context().Value(userKey{}).(User) |
| 137 | if !slices.Contains(user.Roles, role) { |
| 138 | httpx.Error(w, r, fmt.Errorf("%w: only a %s may do this", apperr.ErrForbidden, role)) |
| 139 | return |
| 140 | } |
| 141 | next.ServeHTTP(w, r) |
| 142 | }) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // bearer returns the token in an Authorization value, "Bearer <token>", or "". |
| 147 | func bearer(value string) string { |
| 148 | scheme, token, _ := strings.Cut(value, " ") |
| 149 | if !strings.EqualFold(scheme, "Bearer") { |
| 150 | return "" |
| 151 | } |
| 152 | return token |
| 153 | } |
| 154 | |
| 155 | // withUser returns a copy of ctx that carries the caller, for UserID and |
| 156 | // RequireRole, and their ID for every line logged with it. |
| 157 | func withUser(ctx context.Context, user User) context.Context { |
| 158 | ctx = context.WithValue(ctx, userKey{}, user) |
| 159 | return logging.With(ctx, slog.String("user_id", user.ID.String())) |
| 160 | } |
| 161 | |
| 162 | // UserID returns the ID of the user who sent the request, as Require stored |
| 163 | // it in ctx. |
| 164 | func UserID(ctx context.Context) (uuid.UUID, bool) { |
| 165 | user, ok := ctx.Value(userKey{}).(User) |
| 166 | return user.ID, ok |
| 167 | } |
| 168 | |
| 169 | // ReadPublicKey reads an Ed25519 public key from a PEM file, in the PKIX |
| 170 | // format that openssl pkey -pubout writes. |
| 171 | func ReadPublicKey(path string) (ed25519.PublicKey, error) { |
| 172 | data, err := os.ReadFile(path) |
| 173 | if err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | block, _ := pem.Decode(data) |
| 177 | if block == nil || block.Type != "PUBLIC KEY" { |
| 178 | return nil, fmt.Errorf("%s: no PEM public key", path) |
| 179 | } |
| 180 | key, err := x509.ParsePKIXPublicKey(block.Bytes) |
| 181 | if err != nil { |
| 182 | return nil, fmt.Errorf("%s: %w", path, err) |
| 183 | } |
| 184 | ed, ok := key.(ed25519.PublicKey) |
| 185 | if !ok { |
| 186 | return nil, fmt.Errorf("%s: a %T, not an Ed25519 key", path, key) |
| 187 | } |
| 188 | return ed, nil |
| 189 | } |