feat(identity): register accounts and resend verification mail

This commit is contained in:
shira committed 2026-10-06 23:59:51 +03:00
1 parent 5e202ac972
commit 4436f626a3
55 files changed
+3227 -88

No files matched your search

+23 -2
View File
@@ -120,6 +120,23 @@ type Config struct {
// that may run at once; further logins and registrations wait.
PasswordHashConcurrency int
// IdentityKeySecret keys the HMACs that scope idempotency records and
// rate limit counters by email address, so neither holds a plain hash of
// an address or a password. Empty means a random secret for the life of
// the process.
IdentityKeySecret string
// IdentityAllowEphemeralKey lets a development stand run without
// IDENTITY_KEY_SECRET, with a random secret per process.
IdentityAllowEphemeralKey bool
// VerificationMailMinInterval and VerificationMailDailyLimit bound the
// verification messages to one address: the registration and every
// resend count against both.
VerificationMailMinInterval time.Duration
VerificationMailDailyLimit int
// IdentityClientHourlyLimit bounds the registrations and resends of one
// client network address per hour.
IdentityClientHourlyLimit int
// TrustedProxyCIDRs are the reverse proxies in front of the API. The
// client address is taken from X-Forwarded-For only through them (see
// middleware.ClientIP). Empty trusts no proxy.
@@ -173,6 +190,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadPasswordHash(lookup); err != nil {
return Config{}, err
}
if err := config.loadIdentity(lookup); err != nil {
return Config{}, err
}
if err := config.loadTrustedProxies(lookup); err != nil {
return Config{}, err
}
@@ -223,6 +243,9 @@ func (config Config) Validate() error {
if err := config.ValidatePasswordHash(); err != nil {
return err
}
if err := config.ValidateIdentity(); err != nil {
return err
}
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
return err
}
@@ -267,8 +290,6 @@ func DatabaseURLFromEnv(lookup LookupEnv) string {
// boolOrDefault accepts only "true" or "false", ignoring case and surrounding
// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands,
// which are easy to mistype in deployment files.
//
//nolint:unparam // Every setting names its own default; that all current defaults are true is a coincidence.
func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) {
value, ok := lookup(key)
if !ok {
+3
View File
@@ -112,6 +112,9 @@ func testEnvironment(values map[string]string) LookupEnv {
if value, ok := values[key]; ok {
return value, true
}
if key == "IDENTITY_KEY_SECRET" {
return "config-test-identity-key-secret-0123456789", true
}
if key == "SEAWEEDFS_ACCESS_KEY" {
return "test-access", true
}
+98
View File
@@ -0,0 +1,98 @@
package config
import (
"errors"
"fmt"
"strings"
"time"
)
const (
// defaultVerificationMailMinInterval is the shortest time between two
// verification messages to one address, counting the registration and
// every resend.
defaultVerificationMailMinInterval = time.Minute
// minVerificationMailMinInterval and maxVerificationMailMinInterval bound
// the setting: a shorter interval is no brake, a longer one is a
// lock-out that a person who mistyped cannot wait out.
minVerificationMailMinInterval = time.Second
maxVerificationMailMinInterval = time.Hour
// defaultVerificationMailDailyLimit is the number of verification
// messages to one address per 24 hours.
defaultVerificationMailDailyLimit = 5
maxVerificationMailDailyLimit = 50
// defaultIdentityClientHourlyLimit is the number of registrations and
// resends per client network address per hour. It is a brake on one
// source reaching many addresses; the per-address limits above protect
// one address from many sources.
defaultIdentityClientHourlyLimit = 30
maxIdentityClientHourlyLimit = 10000
// MinIdentityKeySecretBytes is the shortest accepted IDENTITY_KEY_SECRET.
MinIdentityKeySecretBytes = 32
// examplePlaceholderPrefix starts the placeholder values of the example
// environment file; a secret that keeps it is public.
examplePlaceholderPrefix = "replace-this"
)
// loadIdentity reads the registration settings. IDENTITY_KEY_SECRET is
// required: without it ValidateIdentity refuses the configuration, unless
// IDENTITY_ALLOW_EPHEMERAL_KEY is true, which lets a development stand draw a
// random secret for the life of the process and so forget idempotency records
// and rate limit counters on every restart.
//
// The three limits treat an empty value as unset, as the mail quota does:
// Compose passes an unset variable as an empty string.
func (config *Config) loadIdentity(lookup LookupEnv) error {
config.IdentityKeySecret = strings.TrimSpace(valueOrDefault(lookup, "IDENTITY_KEY_SECRET", ""))
var err error
config.IdentityAllowEphemeralKey, err = boolOrDefault(lookup, "IDENTITY_ALLOW_EPHEMERAL_KEY", false)
if err != nil {
return err
}
setOnly := func(key string) (string, bool) {
value, ok := lookup(key)
if strings.TrimSpace(value) == "" {
return "", false
}
return value, ok
}
config.VerificationMailMinInterval, err = durationOrDefault(setOnly, "VERIFICATION_MAIL_MIN_INTERVAL", defaultVerificationMailMinInterval)
if err != nil {
return err
}
config.VerificationMailDailyLimit, err = intOrDefault(setOnly, "VERIFICATION_MAIL_DAILY_LIMIT", defaultVerificationMailDailyLimit)
if err != nil {
return err
}
config.IdentityClientHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_CLIENT_HOURLY_LIMIT", defaultIdentityClientHourlyLimit)
return err
}
// ValidateIdentity checks the registration settings. Errors never include
// the secret.
func (config Config) ValidateIdentity() error {
if config.IdentityKeySecret == "" && !config.IdentityAllowEphemeralKey {
return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is required (generate one with: openssl rand -base64 48); " +
"set IDENTITY_ALLOW_EPHEMERAL_KEY=true only on a development stand")
}
if strings.HasPrefix(config.IdentityKeySecret, examplePlaceholderPrefix) {
return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is an example placeholder; generate a real one with: openssl rand -base64 48")
}
if config.IdentityKeySecret != "" && len(config.IdentityKeySecret) < MinIdentityKeySecretBytes {
return fmt.Errorf("Config.ValidateIdentity - IDENTITY_KEY_SECRET must have at least %d bytes", MinIdentityKeySecretBytes)
}
if config.VerificationMailMinInterval < minVerificationMailMinInterval || config.VerificationMailMinInterval > maxVerificationMailMinInterval {
return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be between %s and %s",
minVerificationMailMinInterval, maxVerificationMailMinInterval)
}
if config.VerificationMailDailyLimit < 1 || config.VerificationMailDailyLimit > maxVerificationMailDailyLimit {
return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT must be between 1 and %d", maxVerificationMailDailyLimit)
}
if config.IdentityClientHourlyLimit < 1 || config.IdentityClientHourlyLimit > maxIdentityClientHourlyLimit {
return fmt.Errorf("Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT must be between 1 and %d", maxIdentityClientHourlyLimit)
}
if config.VerificationMailMinInterval >= 24*time.Hour {
return errors.New("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be shorter than the daily window")
}
return nil
}
+113
View File
@@ -0,0 +1,113 @@
package config
import (
"strings"
"testing"
"time"
)
func TestLoadFromEnvIdentityDefaults(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_ALLOW_EPHEMERAL_KEY": "true", "IDENTITY_KEY_SECRET": ""}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.IdentityKeySecret != "" ||
settings.VerificationMailMinInterval != time.Minute ||
settings.VerificationMailDailyLimit != 5 ||
settings.IdentityClientHourlyLimit != 30 {
t.Fatalf("identity defaults = %q, %s, %d, %d", settings.IdentityKeySecret,
settings.VerificationMailMinInterval, settings.VerificationMailDailyLimit, settings.IdentityClientHourlyLimit)
}
}
func TestLoadFromEnvIdentityExplicit(t *testing.T) {
secret := strings.Repeat("k", MinIdentityKeySecretBytes)
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"IDENTITY_KEY_SECRET": " " + secret + " ",
"VERIFICATION_MAIL_MIN_INTERVAL": "90s",
"VERIFICATION_MAIL_DAILY_LIMIT": "3",
"IDENTITY_CLIENT_HOURLY_LIMIT": "100",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.IdentityKeySecret != secret || settings.VerificationMailMinInterval != 90*time.Second ||
settings.VerificationMailDailyLimit != 3 || settings.IdentityClientHourlyLimit != 100 {
t.Fatalf("identity settings were not read: %+v", settings)
}
}
func TestLoadFromEnvRejectsIdentitySettings(t *testing.T) {
tests := map[string]struct {
key, value, want string
}{
"short secret": {"IDENTITY_KEY_SECRET", "too-short", "Config.ValidateIdentity - IDENTITY_KEY_SECRET"},
"interval below": {"VERIFICATION_MAIL_MIN_INTERVAL", "500ms", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"},
"interval above": {"VERIFICATION_MAIL_MIN_INTERVAL", "2h", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"},
"interval malformed": {"VERIFICATION_MAIL_MIN_INTERVAL", "soon", "config.durationOrDefault - parse VERIFICATION_MAIL_MIN_INTERVAL"},
"daily zero": {"VERIFICATION_MAIL_DAILY_LIMIT", "0", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"},
"daily too high": {"VERIFICATION_MAIL_DAILY_LIMIT", "51", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"},
"daily malformed": {"VERIFICATION_MAIL_DAILY_LIMIT", "five", "config.intOrDefault - VERIFICATION_MAIL_DAILY_LIMIT"},
"client zero": {"IDENTITY_CLIENT_HOURLY_LIMIT", "0", "Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT"},
}
for name, test := range tests {
_, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value}))
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv(%s) error = %v, want an error starting with %q", name, err, test.want)
}
}
}
func TestIdentityErrorsDoNotQuoteTheSecret(t *testing.T) {
_, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": "short-secret-value"}))
if err == nil || strings.Contains(err.Error(), "short-secret-value") {
t.Fatalf("LoadFromEnv() error = %v, want an error without the secret", err)
}
}
func TestLoadFromEnvIdentityEmptyLimitsMeanUnset(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"VERIFICATION_MAIL_MIN_INTERVAL": "",
"VERIFICATION_MAIL_DAILY_LIMIT": " ",
"IDENTITY_CLIENT_HOURLY_LIMIT": "",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.VerificationMailMinInterval != time.Minute || settings.VerificationMailDailyLimit != 5 || settings.IdentityClientHourlyLimit != 30 {
t.Fatalf("empty limits = %s, %d, %d, want the defaults", settings.VerificationMailMinInterval,
settings.VerificationMailDailyLimit, settings.IdentityClientHourlyLimit)
}
}
func TestLoadFromEnvRequiresTheIdentityKeySecret(t *testing.T) {
// Not through testEnvironment, which supplies a secret.
lookup := func(key string) (string, bool) {
if key == "IDENTITY_KEY_SECRET" || key == "IDENTITY_ALLOW_EPHEMERAL_KEY" {
return "", false
}
return testEnvironment(nil)(key)
}
_, err := LoadFromEnv(lookup)
if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET is required") || !strings.Contains(err.Error(), "openssl rand") {
t.Fatalf("LoadFromEnv() error = %v, want the missing secret named with how to generate one", err)
}
ephemeral := func(key string) (string, bool) {
if key == "IDENTITY_ALLOW_EPHEMERAL_KEY" {
return "true", true
}
return lookup(key)
}
settings, err := LoadFromEnv(ephemeral)
if err != nil || !settings.IdentityAllowEphemeralKey {
t.Fatalf("LoadFromEnv(ephemeral) = %v, %v, want an accepted development configuration", settings.IdentityAllowEphemeralKey, err)
}
}
func TestLoadFromEnvRejectsThePlaceholderSecret(t *testing.T) {
const placeholder = "replace-this-identity-key-secret-0123456789abcdef"
_, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": placeholder}))
if err == nil || !strings.Contains(err.Error(), "example placeholder") || strings.Contains(err.Error(), placeholder) {
t.Fatalf("LoadFromEnv() error = %v, want a refusal that does not quote the value", err)
}
}