package identity import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // MinKeySecretBytes is the shortest secret that NewKeyring accepts. const MinKeySecretBytes = 32 // Domain-separation labels. Each purpose gets its own key derived from the // one secret, so a digest made for one purpose never matches another. const ( labelIdempotencyScope = "lincodex/identity/idempotency-scope/v1" labelFingerprint = "lincodex/identity/request-fingerprint/v1" labelEmailBucket = "lincodex/identity/email-bucket/v1" labelClientBucket = "lincodex/identity/client-bucket/v1" labelTokenBucket = "lincodex/identity/verification-token-bucket/v1" labelSessionCSRF = "lincodex/identity/session-csrf/v1" ) // Keyring computes the keyed digests of the anonymous identity operations: // the idempotency scope, the request fingerprint, and the rate limit bucket // of an email address. All of them are HMAC-SHA-256 values, so what the // stores hold can neither confirm that an address is registered nor serve as // an offline check of a password without the server secret. type Keyring struct { scopeKey []byte fingerprintKey []byte bucketKey []byte clientKey []byte tokenKey []byte sessionCSRFKey []byte } // NewKeyring derives the purpose keys from secret. func NewKeyring(secret []byte) (*Keyring, error) { if len(secret) < MinKeySecretBytes { return nil, fmt.Errorf("identity.NewKeyring - secret must have at least %d bytes", MinKeySecretBytes) } return &Keyring{ scopeKey: derive(secret, labelIdempotencyScope), fingerprintKey: derive(secret, labelFingerprint), bucketKey: derive(secret, labelEmailBucket), clientKey: derive(secret, labelClientBucket), tokenKey: derive(secret, labelTokenBucket), sessionCSRFKey: derive(secret, labelSessionCSRF), }, nil } func derive(secret []byte, label string) []byte { mac := hmac.New(sha256.New, secret) mac.Write([]byte(label)) return mac.Sum(nil) } // IdempotencyScope scopes a key by the operation, the key, and the // normalized email. The parts are joined with NUL, which none of them can // contain: operation names and keys are limited to printable ASCII and the // email is printable ASCII. func (keyring *Keyring) IdempotencyScope(operation, key, normalizedEmail string) [outbound.IdempotencyDigestSize]byte { mac := hmac.New(sha256.New, keyring.scopeKey) mac.Write([]byte(operation)) mac.Write([]byte{0}) mac.Write([]byte(key)) mac.Write([]byte{0}) mac.Write([]byte(normalizedEmail)) return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil)) } // Fingerprint identifies a request by its canonical body. func (keyring *Keyring) Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte { mac := hmac.New(sha256.New, keyring.fingerprintKey) mac.Write(canonicalBody) return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil)) } // EmailBucket names the rate limit counters of one address, whether or not // an account exists for it, so a refusal does not reveal an account. func (keyring *Keyring) EmailBucket(normalizedEmail string) string { mac := hmac.New(sha256.New, keyring.bucketKey) mac.Write([]byte(normalizedEmail)) return "identity:email:" + hex.EncodeToString(mac.Sum(nil)) } // ClientBucket names the rate limit counters of one client from its opaque // key, so the store never holds a network address in clear form. func (keyring *Keyring) ClientBucket(clientKey string) string { mac := hmac.New(sha256.New, keyring.clientKey) mac.Write([]byte(clientKey)) return "identity:client:" + hex.EncodeToString(mac.Sum(nil)) } // VerificationTokenBucket names the rate limit counter for a raw // verification token without putting the token itself in the limiter store. func (keyring *Keyring) VerificationTokenBucket(rawToken string) string { mac := hmac.New(sha256.New, keyring.tokenKey) mac.Write([]byte(rawToken)) return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil)) } // SessionCSRF derives a synchronizer token for exactly one session. The // purpose key and message are both domain-separated from every other keyring // use, and only the encoded result is returned to the HTTP adapter. func (keyring *Keyring) SessionCSRF(token domain.SecretToken) string { if token.IsZero() { return "" } mac := hmac.New(sha256.New, keyring.sessionCSRFKey) mac.Write([]byte(labelSessionCSRF)) mac.Write([]byte{0}) mac.Write([]byte(token.Reveal())) return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) } // VerifySessionCSRF compares the supplied synchronizer token in constant // time with the token bound to this session. func (keyring *Keyring) VerifySessionCSRF(token domain.SecretToken, supplied string) bool { if token.IsZero() { return false } return hmac.Equal([]byte(keyring.SessionCSRF(token)), []byte(supplied)) }