Files

284 lines
12 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"
labelVerificationCode = "lincodex/identity/verification-code/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"
labelWatermark = "lincodex/assessment/watermark/v1"
labelSignalAgent = "lincodex/assessment/signal-agent/v1"
labelWorkClient = "lincodex/assessment/work-client/v1"
labelLeakText = "lincodex/assessment/leak-text/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
codeKey []byte
sessionCSRFKey []byte
candidateViewKey []byte
answerKey []byte
signalSessionKey []byte
signalNetworkKey []byte
resultCursorKey []byte
watermarkKey []byte
signalAgentKey []byte
workClientKey []byte
leakTextKey []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),
codeKey: derive(secret, labelVerificationCode),
sessionCSRFKey: derive(secret, labelSessionCSRF),
candidateViewKey: derive(secret, labelCandidateView),
answerKey: derive(secret, labelAnswerFingerprint),
signalSessionKey: derive(secret, labelSignalSession),
signalNetworkKey: derive(secret, labelSignalNetwork),
resultCursorKey: derive(secret, labelResultCursor),
watermarkKey: derive(secret, labelWatermark),
signalAgentKey: derive(secret, labelSignalAgent),
workClientKey: derive(secret, labelWorkClient),
leakTextKey: derive(secret, labelLeakText),
}, 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))
}
// VerificationCodeDigest keys a six-digit verification code under the code
// purpose key. The code space holds only a million values, so an unkeyed digest
// could be reversed by enumeration; the keyed digest cannot be checked offline
// without the server secret.
func (keyring *Keyring) VerificationCodeDigest(code domain.VerificationCode) domain.VerificationCodeHash {
mac := hmac.New(sha256.New, keyring.codeKey)
mac.Write([]byte(code.Reveal()))
return domain.VerificationCodeHash(mac.Sum(nil))
}
// VerifyVerificationCode compares a supplied code with a stored digest in
// constant time.
func (keyring *Keyring) VerifyVerificationCode(code domain.VerificationCode, stored domain.VerificationCodeHash) bool {
if code.IsZero() || stored.IsZero() {
return false
}
computed := keyring.VerificationCodeDigest(code)
return hmac.Equal(computed[:], stored[:])
}
// 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))
}
// AssessmentWatermarkSeed is the secret stream that marks the task text of one
// attempt. It is derived under a key of its own, so it cannot be computed from
// an idempotency scope or a digest, and it is never sent to a client: the
// visible code and the invisible mark are read from it on the server.
func (keyring *Keyring) AssessmentWatermarkSeed(attemptID uuid.UUID) domain.AssessmentWatermarkSeed {
mac := hmac.New(sha256.New, keyring.watermarkKey)
mac.Write(attemptID[:])
return domain.AssessmentWatermarkSeed(mac.Sum(nil))
}
// AssessmentAgentDigest identifies the User-Agent of a request inside one
// attempt. The digest changes with the attempt, so it cannot link attempts or
// fingerprint a browser across them, and the raw value is never stored.
func (keyring *Keyring) AssessmentAgentDigest(attemptID uuid.UUID, userAgent string) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.signalAgentKey)
mac.Write(attemptID[:])
mac.Write([]byte(userAgent))
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentWorkClientDigest identifies the open page that holds the work
// session of an attempt from the identifier the page generated. The digest
// binds the attempt, so the value is not reusable and not linkable.
func (keyring *Keyring) AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.workClientKey)
mac.Write(attemptID[:])
mac.Write([]byte(clientID))
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentLeakTextDigest stands for the text of one operator search in the
// audit. It is keyed, so the audit can show that a text was searched twice
// without keeping it, and nobody can confirm a guess about a text from the
// audit alone.
func (keyring *Keyring) AssessmentLeakTextDigest(text []byte) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.leakTextKey)
mac.Write(text)
return domain.AssessmentDigest(mac.Sum(nil))
}