package domain import ( "crypto/rand" "crypto/sha256" "encoding/base64" "errors" "fmt" "log/slog" "regexp" ) const ( // secretTokenEntropyBytes gives 256 bits of entropy. The encoded value is // 43 base64url characters, inside the 32 to 128 character bounds that the // contract sets for VerificationToken and CsrfToken. secretTokenEntropyBytes = 32 // SecretTokenHashSize is the size of a SHA-256 digest. SecretTokenHashSize = sha256.Size redactedSecret = "[redacted]" ) var ( ErrInvalidSecretToken = errors.New("invalid secret token") // The contract pattern for raw tokens that arrive in requests. secretTokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32,128}$`) ) // SecretToken is a random bearer secret: the token in an email link or the // session cookie value. Only the holder sees the raw value; storage keeps // SecretTokenHash. String and LogValue redact the value so it does not reach // logs by accident; Reveal returns it for the one place that must send it. type SecretToken struct { value string } // NewSecretToken returns a token with 256 bits from crypto/rand. func NewSecretToken() (SecretToken, error) { entropy := make([]byte, secretTokenEntropyBytes) if _, err := rand.Read(entropy); err != nil { return SecretToken{}, fmt.Errorf("domain.NewSecretToken - read random bytes: %w", err) } return SecretToken{value: base64.RawURLEncoding.EncodeToString(entropy)}, nil } // ParseSecretToken accepts a raw token from a request. It checks only the // contract shape; whether the token exists is decided by its hash in storage. func ParseSecretToken(raw string) (SecretToken, error) { if !secretTokenPattern.MatchString(raw) { return SecretToken{}, fmt.Errorf("domain.ParseSecretToken - token must have 32 to 128 base64url characters: %w", ErrInvalidSecretToken) } return SecretToken{value: raw}, nil } // Hash returns the SHA-256 digest that storage keeps. A token carries 256 bits // of entropy, so a fast unsalted digest cannot be reversed by guessing, unlike // a password, and lookups by digest stay a single index probe. func (token SecretToken) Hash() SecretTokenHash { return SecretTokenHash(sha256.Sum256([]byte(token.value))) } // Reveal returns the raw value for delivery to its holder: the email link or // the Set-Cookie header. Never store or log it. func (token SecretToken) Reveal() string { return token.value } func (token SecretToken) String() string { return redactedSecret } func (token SecretToken) GoString() string { return redactedSecret } func (token SecretToken) LogValue() slog.Value { return slog.StringValue(redactedSecret) } // Format redacts every verb; without it %d would print the struct fields. func (token SecretToken) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } func writeRedacted(state fmt.State, placeholder string) { _, _ = state.Write([]byte(placeholder)) } // IsZero reports a SecretToken not built by NewSecretToken or ParseSecretToken. func (token SecretToken) IsZero() bool { return token.value == "" } // SecretTokenHash is the SHA-256 digest of a SecretToken. type SecretTokenHash [SecretTokenHashSize]byte // IsZero reports the all-zero value, which no real token hashes to in practice // and which marks a missing hash. func (hash SecretTokenHash) IsZero() bool { return hash == SecretTokenHash{} }