165 lines
4.9 KiB
Go
165 lines
4.9 KiB
Go
// Package licence issues and verifies the CLI licence JWTs the registry
|
|
// hands to Werkpilot and Firmwerk (decision 13): Ed25519-signed, verified
|
|
// offline by the CLI against /.well-known/licence-keys.json, refreshed by
|
|
// the heartbeat endpoint. The grace ladder (ERP/02 SKU sheet) rides inside
|
|
// the token so an offline CLI degrades on its own clock.
|
|
package licence
|
|
|
|
import (
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-jose/go-jose/v4"
|
|
"github.com/go-jose/go-jose/v4/jwt"
|
|
)
|
|
|
|
// GracePolicy — days after expiry: warning (still full), degraded (read-only
|
|
// / reduced), hard stop. Healthy 0-7 / Warning 7-14 / Degraded 14-30 / Hard-stop.
|
|
type GracePolicy struct {
|
|
WarningDays int `json:"warning_days"`
|
|
DegradedDays int `json:"degraded_days"`
|
|
HardStopDays int `json:"hard_stop_days"`
|
|
}
|
|
|
|
var DefaultGrace = GracePolicy{WarningDays: 7, DegradedDays: 14, HardStopDays: 30}
|
|
|
|
// Claims is the licence token body.
|
|
type Claims struct {
|
|
jwt.Claims
|
|
TenantID string `json:"tenant_id"`
|
|
TenantSlug string `json:"tenant_slug,omitempty"`
|
|
Product string `json:"product"`
|
|
Plan string `json:"plan,omitempty"`
|
|
Seats int `json:"seats,omitempty"`
|
|
Device string `json:"device,omitempty"`
|
|
Grace GracePolicy `json:"grace"`
|
|
Heartbeat string `json:"heartbeat_url,omitempty"`
|
|
// Kind is "ci" for a licence fetched with an API key in CI (no seat,
|
|
// no heartbeat); empty for interactive licences.
|
|
Kind string `json:"kind,omitempty"`
|
|
}
|
|
|
|
// Signer holds the Ed25519 key. Ephemeral is true when no key was
|
|
// configured (dev): tokens then die with the process.
|
|
type Signer struct {
|
|
priv ed25519.PrivateKey
|
|
kid string
|
|
issuer string
|
|
Ephemeral bool
|
|
}
|
|
|
|
// NewSigner parses a base64 (std or url, padded or not) 32-byte seed or a
|
|
// 64-byte private key. Empty seed → ephemeral key.
|
|
func NewSigner(seedB64, issuer string) (*Signer, error) {
|
|
if issuer == "" {
|
|
issuer = "tenant-registry"
|
|
}
|
|
var priv ed25519.PrivateKey
|
|
ephemeral := false
|
|
if strings.TrimSpace(seedB64) == "" {
|
|
_, k, err := ed25519.GenerateKey(rand.Reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
priv, ephemeral = k, true
|
|
} else {
|
|
raw, err := decodeB64(seedB64)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("LICENCE_SIGNING_KEY: %w", err)
|
|
}
|
|
switch len(raw) {
|
|
case ed25519.SeedSize:
|
|
priv = ed25519.NewKeyFromSeed(raw)
|
|
case ed25519.PrivateKeySize:
|
|
priv = ed25519.PrivateKey(raw)
|
|
default:
|
|
return nil, fmt.Errorf("LICENCE_SIGNING_KEY: want 32-byte seed, got %d bytes", len(raw))
|
|
}
|
|
}
|
|
pub := priv.Public().(ed25519.PublicKey)
|
|
sum := sha256.Sum256(pub)
|
|
return &Signer{priv: priv, kid: hex.EncodeToString(sum[:4]), issuer: issuer, Ephemeral: ephemeral}, nil
|
|
}
|
|
|
|
func decodeB64(s string) ([]byte, error) {
|
|
s = strings.TrimSpace(s)
|
|
for _, enc := range []*base64.Encoding{base64.RawURLEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.StdEncoding} {
|
|
if b, err := enc.DecodeString(strings.TrimRight(s, "=")); err == nil {
|
|
return b, nil
|
|
}
|
|
if b, err := enc.DecodeString(s); err == nil {
|
|
return b, nil
|
|
}
|
|
}
|
|
return nil, errors.New("not base64")
|
|
}
|
|
|
|
func (s *Signer) KID() string { return s.kid }
|
|
func (s *Signer) Issuer() string { return s.issuer }
|
|
|
|
// PublicJWK is the verification key entry for /.well-known/licence-keys.json.
|
|
func (s *Signer) PublicJWK() jose.JSONWebKey {
|
|
return jose.JSONWebKey{Key: s.priv.Public(), KeyID: s.kid, Algorithm: string(jose.EdDSA), Use: "sig"}
|
|
}
|
|
|
|
// Issue signs c (iss/iat/jti filled in when empty).
|
|
func (s *Signer) Issue(c Claims) (string, error) {
|
|
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.EdDSA, Key: s.priv},
|
|
(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", s.kid))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if c.Issuer == "" {
|
|
c.Issuer = s.issuer
|
|
}
|
|
if c.IssuedAt == nil {
|
|
c.IssuedAt = jwt.NewNumericDate(time.Now().UTC())
|
|
}
|
|
if c.Grace == (GracePolicy{}) {
|
|
c.Grace = DefaultGrace
|
|
}
|
|
return jwt.Signed(signer).Claims(c).Serialize()
|
|
}
|
|
|
|
// Verify checks the signature and issuer but NOT expiry — the caller decides
|
|
// what an expired licence means (grace ladder).
|
|
func (s *Signer) Verify(raw string) (*Claims, error) {
|
|
tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.EdDSA})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var c Claims
|
|
if err := tok.Claims(s.priv.Public(), &c); err != nil {
|
|
return nil, err
|
|
}
|
|
if c.Issuer != s.issuer {
|
|
return nil, fmt.Errorf("issuer %q is not %q", c.Issuer, s.issuer)
|
|
}
|
|
return &c, nil
|
|
}
|
|
|
|
// State classifies a licence at `now` against the grace policy.
|
|
func (p GracePolicy) State(expiry, now time.Time) string {
|
|
if !now.After(expiry) {
|
|
return "ok"
|
|
}
|
|
over := now.Sub(expiry)
|
|
day := 24 * time.Hour
|
|
switch {
|
|
case over >= time.Duration(p.HardStopDays)*day:
|
|
return "hard_stop"
|
|
case over >= time.Duration(p.DegradedDays)*day:
|
|
return "degraded"
|
|
case over >= time.Duration(p.WarningDays)*day:
|
|
return "warning"
|
|
}
|
|
return "warning"
|
|
}
|