Files
lincodex/backend/internal/usecase/identity/keyring.go
T

209 lines
8.5 KiB
Go

package identity
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/google/uuid"
"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"
labelCandidateView = "lincodex/identity/candidate-view/v1"
labelAnswerFingerprint = "lincodex/assessment/answer-fingerprint/v1"
labelSignalSession = "lincodex/assessment/signal-session/v1"
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
labelResultCursor = "lincodex/assessment/result-history-cursor/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
candidateViewKey []byte
answerKey []byte
signalSessionKey []byte
signalNetworkKey []byte
resultCursorKey []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),
candidateViewKey: derive(secret, labelCandidateView),
answerKey: derive(secret, labelAnswerFingerprint),
signalSessionKey: derive(secret, labelSignalSession),
signalNetworkKey: derive(secret, labelSignalNetwork),
resultCursorKey: derive(secret, labelResultCursor),
}, nil
}
// CandidateViewPseudonymKey returns a purpose-specific key for anonymous
// candidate view aliases without exposing the root identity secret.
func (keyring *Keyring) CandidateViewPseudonymKey() (domain.CandidateViewPseudonymKey, error) {
if keyring == nil {
return domain.CandidateViewPseudonymKey{}, fmt.Errorf("identity.Keyring.CandidateViewPseudonymKey - keyring is nil")
}
key, err := domain.NewCandidateViewPseudonymKey(keyring.candidateViewKey)
if err != nil {
return domain.CandidateViewPseudonymKey{}, fmt.Errorf("identity.Keyring.CandidateViewPseudonymKey - derive typed key: %w", err)
}
return key, 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))
}
// ResultHistoryCursorSignature signs the position of a result history page for
// one candidate under a key of its own, so a cursor can never be replayed as an
// idempotency scope or the other way round.
func (keyring *Keyring) ResultHistoryCursorSignature(position, candidateID string) [outbound.IdempotencyDigestSize]byte {
mac := hmac.New(sha256.New, keyring.resultCursorKey)
mac.Write([]byte(position))
mac.Write([]byte{0})
mac.Write([]byte(candidateID))
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))
}
// AssessmentDigestKeyVersion is the key generation of the assessment
// fingerprints and digests. It is stored next to each of them; a rotation adds
// a new generation instead of silently changing the old values.
func (keyring *Keyring) AssessmentDigestKeyVersion() int16 { return 1 }
// AssessmentAnswerFingerprint is the keyed digest of a normalized answer to a
// family version. It is the same for every candidate and every seed, which
// lets stored fingerprints be compared without the answer text.
func (keyring *Keyring) AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, canonicalAnswer []byte) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.answerKey)
mac.Write(familyID[:])
mac.Write(binary.BigEndian.AppendUint32(nil, uint32(familyVersion))) //nolint:gosec // A family version is a positive int32.
mac.Write(canonicalAnswer)
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentSessionDigest identifies a login session inside one attempt. The
// digest changes with the attempt, so it cannot link attempts or reveal the
// session identifier.
func (keyring *Keyring) AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.signalSessionKey)
mac.Write(attemptID[:])
mac.Write(sessionID[:])
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentNetworkDigest identifies a client network inside one attempt from
// its limiter key. The address itself is never stored, and the digest cannot
// link attempts.
func (keyring *Keyring) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.signalNetworkKey)
mac.Write(attemptID[:])
mac.Write([]byte(clientKey))
return domain.AssessmentDigest(mac.Sum(nil))
}