@@ -0,0 +1,298 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +// Package runnerjwt signs and verifies the short-lived job tokens used by |
| 4 | +// shithub Actions runners. |
| 5 | +// |
| 6 | +// Registration tokens authenticate a runner to the heartbeat endpoint. A |
| 7 | +// successful claim receives one JWT scoped to one workflow_jobs row; job |
| 8 | +// endpoints verify the signature, expiry, path/job match, and then consume |
| 9 | +// the jti through runner_jwt_used so the token is single-use. |
| 10 | +package runnerjwt |
| 11 | + |
| 12 | +import ( |
| 13 | + "crypto/hkdf" |
| 14 | + "crypto/hmac" |
| 15 | + "crypto/rand" |
| 16 | + "crypto/sha256" |
| 17 | + "encoding/base64" |
| 18 | + "encoding/json" |
| 19 | + "errors" |
| 20 | + "fmt" |
| 21 | + "io" |
| 22 | + "strconv" |
| 23 | + "strings" |
| 24 | + "time" |
| 25 | +) |
| 26 | + |
| 27 | +const ( |
| 28 | + // DefaultTTL is the runner job-token lifetime from the S41c contract. |
| 29 | + DefaultTTL = 15 * time.Minute |
| 30 | + |
| 31 | + signingKeySize = 32 |
| 32 | + hkdfInfo = "actions-runner-jwt-v1" |
| 33 | + jtiBytes = 32 |
| 34 | +) |
| 35 | + |
| 36 | +var ( |
| 37 | + ErrEmptyKey = errors.New("runnerjwt: empty key") |
| 38 | + ErrInvalidKey = errors.New("runnerjwt: key must be 32 bytes") |
| 39 | + ErrMalformed = errors.New("runnerjwt: malformed token") |
| 40 | + ErrInvalidSignature = errors.New("runnerjwt: invalid signature") |
| 41 | + ErrExpired = errors.New("runnerjwt: expired token") |
| 42 | + ErrInvalidClaims = errors.New("runnerjwt: invalid claims") |
| 43 | + ErrUnsupportedHeader = errors.New("runnerjwt: unsupported header") |
| 44 | +) |
| 45 | + |
| 46 | +// Claims are the JWT payload fields accepted by runner job endpoints. |
| 47 | +type Claims struct { |
| 48 | + Sub string `json:"sub"` |
| 49 | + JobID int64 `json:"job_id"` |
| 50 | + RunID int64 `json:"run_id"` |
| 51 | + RepoID int64 `json:"repo_id"` |
| 52 | + Exp int64 `json:"exp"` |
| 53 | + JTI string `json:"jti"` |
| 54 | +} |
| 55 | + |
| 56 | +// RunnerID extracts the runner id encoded in sub="runner:<id>". |
| 57 | +func (c Claims) RunnerID() (int64, error) { |
| 58 | + const prefix = "runner:" |
| 59 | + if !strings.HasPrefix(c.Sub, prefix) { |
| 60 | + return 0, ErrInvalidClaims |
| 61 | + } |
| 62 | + id, err := strconv.ParseInt(strings.TrimPrefix(c.Sub, prefix), 10, 64) |
| 63 | + if err != nil || id <= 0 { |
| 64 | + return 0, ErrInvalidClaims |
| 65 | + } |
| 66 | + return id, nil |
| 67 | +} |
| 68 | + |
| 69 | +// MintParams describes a job token to issue. |
| 70 | +type MintParams struct { |
| 71 | + RunnerID int64 |
| 72 | + JobID int64 |
| 73 | + RunID int64 |
| 74 | + RepoID int64 |
| 75 | + TTL time.Duration |
| 76 | +} |
| 77 | + |
| 78 | +// Signer signs and verifies HS256 runner JWTs. |
| 79 | +type Signer struct { |
| 80 | + key []byte |
| 81 | + now func() time.Time |
| 82 | + rng io.Reader |
| 83 | +} |
| 84 | + |
| 85 | +// Option customizes a Signer. Tests use these for deterministic time/randomness. |
| 86 | +type Option func(*Signer) |
| 87 | + |
| 88 | +// WithClock overrides the clock used for exp validation and issuance. |
| 89 | +func WithClock(now func() time.Time) Option { |
| 90 | + return func(s *Signer) { |
| 91 | + if now != nil { |
| 92 | + s.now = now |
| 93 | + } |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +// WithRand overrides the random source used for jti generation. |
| 98 | +func WithRand(r io.Reader) Option { |
| 99 | + return func(s *Signer) { |
| 100 | + if r != nil { |
| 101 | + s.rng = r |
| 102 | + } |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +// NewFromTOTPKeyB64 decodes cfg.Auth.TOTPKeyB64 and derives an isolated |
| 107 | +// runner-JWT signing key via HKDF. The raw TOTP/secretbox key is never used |
| 108 | +// directly for JWT signatures. |
| 109 | +func NewFromTOTPKeyB64(totpKeyB64 string, opts ...Option) (*Signer, error) { |
| 110 | + key, err := DeriveKeyFromTOTPKeyB64(totpKeyB64) |
| 111 | + if err != nil { |
| 112 | + return nil, err |
| 113 | + } |
| 114 | + return NewFromKey(key, opts...) |
| 115 | +} |
| 116 | + |
| 117 | +// DeriveKeyFromTOTPKeyB64 returns the HS256 key derived from the configured |
| 118 | +// 32-byte TOTP/secretbox key. |
| 119 | +func DeriveKeyFromTOTPKeyB64(totpKeyB64 string) ([]byte, error) { |
| 120 | + if totpKeyB64 == "" { |
| 121 | + return nil, ErrEmptyKey |
| 122 | + } |
| 123 | + raw, err := decodeKey(totpKeyB64) |
| 124 | + if err != nil { |
| 125 | + return nil, fmt.Errorf("runnerjwt: decode key: %w", err) |
| 126 | + } |
| 127 | + if len(raw) != signingKeySize { |
| 128 | + return nil, ErrInvalidKey |
| 129 | + } |
| 130 | + key, err := hkdf.Key(sha256.New, raw, nil, hkdfInfo, signingKeySize) |
| 131 | + if err != nil { |
| 132 | + return nil, fmt.Errorf("runnerjwt: derive key: %w", err) |
| 133 | + } |
| 134 | + return key, nil |
| 135 | +} |
| 136 | + |
| 137 | +// NewFromKey constructs a Signer from an already-derived 32-byte HS256 key. |
| 138 | +func NewFromKey(key []byte, opts ...Option) (*Signer, error) { |
| 139 | + if len(key) != signingKeySize { |
| 140 | + return nil, ErrInvalidKey |
| 141 | + } |
| 142 | + copied := make([]byte, len(key)) |
| 143 | + copy(copied, key) |
| 144 | + s := &Signer{ |
| 145 | + key: copied, |
| 146 | + now: time.Now, |
| 147 | + rng: rand.Reader, |
| 148 | + } |
| 149 | + for _, opt := range opts { |
| 150 | + opt(s) |
| 151 | + } |
| 152 | + return s, nil |
| 153 | +} |
| 154 | + |
| 155 | +// Mint signs a new job token and returns the token plus the exact claims. |
| 156 | +func (s *Signer) Mint(p MintParams) (string, Claims, error) { |
| 157 | + ttl := p.TTL |
| 158 | + if ttl == 0 { |
| 159 | + ttl = DefaultTTL |
| 160 | + } |
| 161 | + if p.RunnerID <= 0 || p.JobID <= 0 || p.RunID <= 0 || p.RepoID <= 0 || ttl <= 0 { |
| 162 | + return "", Claims{}, ErrInvalidClaims |
| 163 | + } |
| 164 | + jti, err := newJTI(s.rng) |
| 165 | + if err != nil { |
| 166 | + return "", Claims{}, err |
| 167 | + } |
| 168 | + claims := Claims{ |
| 169 | + Sub: fmt.Sprintf("runner:%d", p.RunnerID), |
| 170 | + JobID: p.JobID, |
| 171 | + RunID: p.RunID, |
| 172 | + RepoID: p.RepoID, |
| 173 | + Exp: s.now().Add(ttl).Unix(), |
| 174 | + JTI: jti, |
| 175 | + } |
| 176 | + if err := validateClaims(claims); err != nil { |
| 177 | + return "", Claims{}, err |
| 178 | + } |
| 179 | + token, err := s.sign(claims) |
| 180 | + if err != nil { |
| 181 | + return "", Claims{}, err |
| 182 | + } |
| 183 | + return token, claims, nil |
| 184 | +} |
| 185 | + |
| 186 | +// Verify checks token shape, HS256 signature, registered claims, and expiry. |
| 187 | +// It does not consume jti; callers perform that DB operation after verifying |
| 188 | +// path/job ownership. |
| 189 | +func (s *Signer) Verify(token string) (Claims, error) { |
| 190 | + parts := strings.Split(token, ".") |
| 191 | + if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" { |
| 192 | + return Claims{}, ErrMalformed |
| 193 | + } |
| 194 | + headerBytes, err := base64.RawURLEncoding.DecodeString(parts[0]) |
| 195 | + if err != nil { |
| 196 | + return Claims{}, ErrMalformed |
| 197 | + } |
| 198 | + var header struct { |
| 199 | + Alg string `json:"alg"` |
| 200 | + Typ string `json:"typ"` |
| 201 | + } |
| 202 | + if err := json.Unmarshal(headerBytes, &header); err != nil { |
| 203 | + return Claims{}, ErrMalformed |
| 204 | + } |
| 205 | + if header.Alg != "HS256" || header.Typ != "JWT" { |
| 206 | + return Claims{}, ErrUnsupportedHeader |
| 207 | + } |
| 208 | + |
| 209 | + signingInput := parts[0] + "." + parts[1] |
| 210 | + gotSig, err := base64.RawURLEncoding.DecodeString(parts[2]) |
| 211 | + if err != nil { |
| 212 | + return Claims{}, ErrMalformed |
| 213 | + } |
| 214 | + wantSig := signHS256(s.key, signingInput) |
| 215 | + if !hmac.Equal(gotSig, wantSig) { |
| 216 | + return Claims{}, ErrInvalidSignature |
| 217 | + } |
| 218 | + |
| 219 | + payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[1]) |
| 220 | + if err != nil { |
| 221 | + return Claims{}, ErrMalformed |
| 222 | + } |
| 223 | + var claims Claims |
| 224 | + if err := json.Unmarshal(payloadBytes, &claims); err != nil { |
| 225 | + return Claims{}, ErrMalformed |
| 226 | + } |
| 227 | + if err := validateClaims(claims); err != nil { |
| 228 | + return Claims{}, err |
| 229 | + } |
| 230 | + if !s.now().Before(time.Unix(claims.Exp, 0)) { |
| 231 | + return Claims{}, ErrExpired |
| 232 | + } |
| 233 | + return claims, nil |
| 234 | +} |
| 235 | + |
| 236 | +func (s *Signer) sign(claims Claims) (string, error) { |
| 237 | + headerJSON, err := json.Marshal(struct { |
| 238 | + Alg string `json:"alg"` |
| 239 | + Typ string `json:"typ"` |
| 240 | + }{Alg: "HS256", Typ: "JWT"}) |
| 241 | + if err != nil { |
| 242 | + return "", err |
| 243 | + } |
| 244 | + payloadJSON, err := json.Marshal(claims) |
| 245 | + if err != nil { |
| 246 | + return "", err |
| 247 | + } |
| 248 | + header := base64.RawURLEncoding.EncodeToString(headerJSON) |
| 249 | + payload := base64.RawURLEncoding.EncodeToString(payloadJSON) |
| 250 | + signingInput := header + "." + payload |
| 251 | + sig := base64.RawURLEncoding.EncodeToString(signHS256(s.key, signingInput)) |
| 252 | + return signingInput + "." + sig, nil |
| 253 | +} |
| 254 | + |
| 255 | +func signHS256(key []byte, signingInput string) []byte { |
| 256 | + mac := hmac.New(sha256.New, key) |
| 257 | + _, _ = mac.Write([]byte(signingInput)) |
| 258 | + return mac.Sum(nil) |
| 259 | +} |
| 260 | + |
| 261 | +func newJTI(r io.Reader) (string, error) { |
| 262 | + buf := make([]byte, jtiBytes) |
| 263 | + if _, err := io.ReadFull(r, buf); err != nil { |
| 264 | + return "", fmt.Errorf("runnerjwt: jti: %w", err) |
| 265 | + } |
| 266 | + return base64.RawURLEncoding.EncodeToString(buf), nil |
| 267 | +} |
| 268 | + |
| 269 | +func validateClaims(c Claims) error { |
| 270 | + if _, err := c.RunnerID(); err != nil { |
| 271 | + return err |
| 272 | + } |
| 273 | + if c.JobID <= 0 || c.RunID <= 0 || c.RepoID <= 0 || c.Exp <= 0 { |
| 274 | + return ErrInvalidClaims |
| 275 | + } |
| 276 | + if len(c.JTI) < 16 || len(c.JTI) > 128 { |
| 277 | + return ErrInvalidClaims |
| 278 | + } |
| 279 | + return nil |
| 280 | +} |
| 281 | + |
| 282 | +func decodeKey(s string) ([]byte, error) { |
| 283 | + encodings := []*base64.Encoding{ |
| 284 | + base64.StdEncoding, |
| 285 | + base64.RawStdEncoding, |
| 286 | + base64.URLEncoding, |
| 287 | + base64.RawURLEncoding, |
| 288 | + } |
| 289 | + var lastErr error |
| 290 | + for _, enc := range encodings { |
| 291 | + raw, err := enc.DecodeString(s) |
| 292 | + if err == nil { |
| 293 | + return raw, nil |
| 294 | + } |
| 295 | + lastErr = err |
| 296 | + } |
| 297 | + return nil, lastErr |
| 298 | +} |