Files
lincodex/backend/internal/domain/secret_token.go
T

105 lines
4.0 KiB
Go

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.
// The value sits behind a pointer so that printing an enclosing struct shows
// only an address (see redactedValue).
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: newRedactedValue(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: newRedactedValue(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.Reveal())))
}
// 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 redactedValue(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) }
// newRedactedValue and redactedValue hold a secret string behind a pointer.
// fmt calls Format, String, or GoString only on values it can reach through
// an interface; for an unexported field of an enclosing struct it prints the
// fields with reflection instead. A pointer field is then printed as an
// address, so the secret never appears. A nil pointer is the zero value.
func newRedactedValue(value string) *string { return &value }
func redactedValue(value *string) string {
if value == nil {
return ""
}
return *value
}
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 == nil }
// 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{} }