From dda3825786dca5835b9bfbb57d3ecbf457b7b24d Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 01:07:55 +0300 Subject: [PATCH] feat(identity): hash passwords with Argon2id and bounded inputs --- .env.example | 5 + backend/config/config.go | 10 + backend/config/password_hash.go | 47 ++ backend/config/password_hash_test.go | 47 ++ .../00002_create_identity_tables.sql | 2 +- backend/go.mod | 6 +- backend/integration_test/identity_test.go | 14 +- .../adapter/secondary/argon2id/hasher.go | 304 ++++++++++++ .../adapter/secondary/argon2id/hasher_test.go | 433 ++++++++++++++++++ backend/internal/domain/email_address.go | 29 +- backend/internal/domain/password.go | 96 ++++ backend/internal/domain/password_test.go | 132 ++++++ backend/internal/domain/redaction_test.go | 90 ++++ backend/internal/domain/secret_token.go | 28 +- backend/internal/domain/user.go | 16 +- backend/internal/port/outbound/password.go | 62 +++ backend/internal/usecase/identity/.gitkeep | 0 .../internal/usecase/identity/credentials.go | 39 ++ .../usecase/identity/credentials_test.go | 83 ++++ deploy/docker/docker-compose.yml | 6 + docs/en/ARCHITECTURE.md | 21 +- docs/en/DEPLOY.md | 2 + docs/en/DEVELOPMENT.md | 6 +- docs/ru/ARCHITECTURE.md | 21 +- docs/ru/DEPLOY.md | 2 + docs/ru/DEVELOPMENT.md | 6 +- 26 files changed, 1475 insertions(+), 32 deletions(-) create mode 100644 backend/config/password_hash.go create mode 100644 backend/config/password_hash_test.go create mode 100644 backend/internal/adapter/secondary/argon2id/hasher.go create mode 100644 backend/internal/adapter/secondary/argon2id/hasher_test.go create mode 100644 backend/internal/domain/password.go create mode 100644 backend/internal/domain/password_test.go create mode 100644 backend/internal/domain/redaction_test.go create mode 100644 backend/internal/port/outbound/password.go delete mode 100644 backend/internal/usecase/identity/.gitkeep create mode 100644 backend/internal/usecase/identity/credentials.go create mode 100644 backend/internal/usecase/identity/credentials_test.go diff --git a/.env.example b/.env.example index 34904f9..78c866f 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,11 @@ SMTP_USERNAME= SMTP_PASSWORD= SMTP_TLS_MODE= +# Password hashing: Argon2id derivations that may run at once, from 1 to 4. +# Each takes 64 MiB; the backend container has 1 CPU and 768 MB of memory, so +# more than 1 only adds memory while the derivations share the CPU. +PASSWORD_HASH_CONCURRENCY=1 + # Optional PostgreSQL metrics login, created when the database volume is initialized. POSTGRES_EXPORTER_USER=metrics_reader POSTGRES_EXPORTER_PASSWORD=replace-this-metrics-password diff --git a/backend/config/config.go b/backend/config/config.go index 3230330..23fae2d 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -59,6 +59,10 @@ type Config struct { LogLevel string ReadinessTimeout time.Duration ShutdownTimeout time.Duration + + // PasswordHashConcurrency is the number of password hash derivations + // that may run at once; further logins and registrations wait. + PasswordHashConcurrency int } type LookupEnv func(string) (string, bool) @@ -93,6 +97,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadMail(lookup); err != nil { return Config{}, err } + if err := config.loadPasswordHash(lookup); err != nil { + return Config{}, err + } var err error config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart) @@ -134,6 +141,9 @@ func (config Config) Validate() error { if err := config.ValidateMail(); err != nil { return err } + if err := config.ValidatePasswordHash(); err != nil { + return err + } if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil { return err } diff --git a/backend/config/password_hash.go b/backend/config/password_hash.go new file mode 100644 index 0000000..d131c68 --- /dev/null +++ b/backend/config/password_hash.go @@ -0,0 +1,47 @@ +package config + +import ( + "fmt" + "runtime" + "strconv" + "strings" +) + +const ( + // defaultPasswordHashConcurrency is the default number of Argon2id + // derivations with the current parameters (64 MiB, 4 lanes each) that may + // run at once. The default is lowered to GOMAXPROCS, which Go derives from + // the container CPU limit, because more parallel derivations than CPUs + // only share the same CPUs while holding more memory. + defaultPasswordHashConcurrency = 2 + // maxPasswordHashConcurrency keeps the hashing budget at 256 MiB, which + // fits under the 600 MiB GOMEMLIMIT of the 768 MiB backend container + // together with the rest of the process. + maxPasswordHashConcurrency = 4 +) + +// loadPasswordHash reads PASSWORD_HASH_CONCURRENCY. An unset value takes the +// smaller of the default and GOMAXPROCS; an empty or non-integer value is an +// error. +func (config *Config) loadPasswordHash(lookup LookupEnv) error { + config.PasswordHashConcurrency = min(defaultPasswordHashConcurrency, runtime.GOMAXPROCS(0)) + value, ok := lookup("PASSWORD_HASH_CONCURRENCY") + if !ok { + return nil + } + number, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return fmt.Errorf("Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and %d", maxPasswordHashConcurrency) + } + config.PasswordHashConcurrency = number + return nil +} + +// ValidatePasswordHash checks the password hashing budget: the number of +// derivations with the current parameters that may run at once. +func (config Config) ValidatePasswordHash() error { + if config.PasswordHashConcurrency < 1 || config.PasswordHashConcurrency > maxPasswordHashConcurrency { + return fmt.Errorf("Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and %d", maxPasswordHashConcurrency) + } + return nil +} diff --git a/backend/config/password_hash_test.go b/backend/config/password_hash_test.go new file mode 100644 index 0000000..ffe7179 --- /dev/null +++ b/backend/config/password_hash_test.go @@ -0,0 +1,47 @@ +package config + +import ( + "runtime" + "strings" + "testing" +) + +func TestLoadFromEnvPasswordHashConcurrency(t *testing.T) { + tests := map[string]struct { + values map[string]string + want int + }{ + "default": {values: nil, want: min(2, runtime.GOMAXPROCS(0))}, + "explicit": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "3"}, want: 3}, + "spaces": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": " 1 "}, want: 1}, + "upper bound": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "4"}, want: 4}, + } + for name, test := range tests { + settings, err := LoadFromEnv(testEnvironment(test.values)) + if err != nil { + t.Fatalf("LoadFromEnv(%s) error = %v", name, err) + } + if settings.PasswordHashConcurrency != test.want { + t.Fatalf("LoadFromEnv(%s) PasswordHashConcurrency = %d, want %d", name, settings.PasswordHashConcurrency, test.want) + } + } +} + +func TestLoadFromEnvRejectsPasswordHashConcurrency(t *testing.T) { + tests := map[string]struct { + value string + want string + }{ + "empty": {value: "", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and 4"}, + "not integer": {value: "four", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY"}, + "zero": {value: "0", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and 4"}, + "negative": {value: "-1", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"}, + "over bound": {value: "5", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"}, + } + for name, test := range tests { + _, err := LoadFromEnv(testEnvironment(map[string]string{"PASSWORD_HASH_CONCURRENCY": 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) + } + } +} diff --git a/backend/db/migrations/00002_create_identity_tables.sql b/backend/db/migrations/00002_create_identity_tables.sql index 7733be4..a40df8e 100644 --- a/backend/db/migrations/00002_create_identity_tables.sql +++ b/backend/db/migrations/00002_create_identity_tables.sql @@ -49,7 +49,7 @@ CREATE TABLE users ( CONSTRAINT users_password_hash_format CHECK ( char_length(password_hash) <= 512 AND password_hash - ~ '^\$argon2id\$v=19\$m=[0-9]+,t=[0-9]+,p=[0-9]+\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' + ~ '^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' ), CONSTRAINT users_scenario_onboarding_step CHECK ( ( diff --git a/backend/go.mod b/backend/go.mod index f8da735..b80c456 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -26,6 +26,9 @@ require ( go.opentelemetry.io/otel v1.47.0 go.opentelemetry.io/otel/metric v1.47.0 go.opentelemetry.io/otel/trace v1.47.0 + golang.org/x/crypto v0.57.0 + golang.org/x/sync v0.23.0 + golang.org/x/text v0.42.0 ) require ( @@ -376,15 +379,12 @@ require ( go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect - golang.org/x/crypto v0.57.0 // indirect golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect golang.org/x/mod v0.41.0 // indirect golang.org/x/net v0.59.0 // indirect - golang.org/x/sync v0.23.0 // indirect golang.org/x/sys v0.48.0 // indirect golang.org/x/term v0.46.0 // indirect - golang.org/x/text v0.42.0 // indirect golang.org/x/tools v0.50.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a // indirect diff --git a/backend/integration_test/identity_test.go b/backend/integration_test/identity_test.go index b75e683..5c31764 100644 --- a/backend/integration_test/identity_test.go +++ b/backend/integration_test/identity_test.go @@ -945,6 +945,17 @@ func TestIdentityRepositories(t *testing.T) { statement: `UPDATE users SET password_hash = 'correct horse battery staple' WHERE id = $1`, args: []any{user.ID}, }, + { + // The domain regex rejects zero and leading-zero parameters too. + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=0,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=019456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`, + args: []any{user.ID}, + }, { // The key matches the address, so only the ASCII rule fails. constraint: "users_email_ascii", @@ -1111,7 +1122,8 @@ func assertSameUser(t *testing.T, got, want domain.User) { t.Helper() sameVerification := (got.EmailVerifiedAt == nil) == (want.EmailVerifiedAt == nil) && (got.EmailVerifiedAt == nil || got.EmailVerifiedAt.Equal(*want.EmailVerifiedAt)) - if got.ID != want.ID || got.Email != want.Email || got.PasswordHash.PHC() != want.PasswordHash.PHC() || + if got.ID != want.ID || got.Email.Address() != want.Email.Address() || got.Email.Normalized() != want.Email.Normalized() || + got.PasswordHash.PHC() != want.PasswordHash.PHC() || got.Scenario != want.Scenario || got.OnboardingStep != want.OnboardingStep || !sameVerification || got.RegistrationVersion != want.RegistrationVersion || !got.LastRegisteredAt.Equal(want.LastRegisteredAt) || got.Version != want.Version || !got.CreatedAt.Equal(want.CreatedAt) || !got.UpdatedAt.Equal(want.UpdatedAt) { diff --git a/backend/internal/adapter/secondary/argon2id/hasher.go b/backend/internal/adapter/secondary/argon2id/hasher.go new file mode 100644 index 0000000..1ff659a --- /dev/null +++ b/backend/internal/adapter/secondary/argon2id/hasher.go @@ -0,0 +1,304 @@ +// Package argon2id implements outbound.PasswordHasher with Argon2id (RFC 9106) +// from golang.org/x/crypto/argon2 and the PHC string format. +package argon2id + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strconv" + "strings" + + "golang.org/x/crypto/argon2" + "golang.org/x/sync/semaphore" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// Parameters of new hashes: the second recommended option of RFC 9106, +// section 4 (64 MiB, 3 passes, 4 lanes). It is stronger than the OWASP +// Password Storage Cheat Sheet baseline (19 MiB, 2 passes, 1 lane). +const ( + recommendedMemoryKiB = 64 * 1024 + recommendedIterations = 3 + recommendedParallelism = 4 + // RFC 9106 recommends a 128-bit salt and a 256-bit tag. + saltBytes = 16 + keyBytes = 32 +) + +// Bounds for stored hashes. Verify recomputes a hash with the parameters +// stored in it, so a crafted or corrupted row must not be able to demand +// unbounded memory or time. They leave room to raise the current parameters +// and still verify older hashes until a login rehashes them. A stored hash +// must also fit the memory budget of the hasher (see Hasher). +const ( + maxStoredMemoryKiB = 2 * recommendedMemoryKiB + maxStoredIterations = 16 + maxStoredParallelism = 16 + // Argon2 needs at least 8 KiB per lane; x/crypto silently raises a lower + // value, which no conforming encoder writes. + minMemoryKiBPerLane = 8 + // The salt and digest minimums match domain.NewPasswordHash. + minStoredSaltBytes = 8 + maxStoredSaltBytes = 64 + minStoredKeyBytes = 16 + maxStoredKeyBytes = 64 + phcFieldCount = 6 + phcParameterCount = 3 +) + +type parameters struct { + memoryKiB uint32 + iterations uint32 + parallelism uint8 +} + +func recommendedParameters() parameters { + return parameters{ + memoryKiB: recommendedMemoryKiB, + iterations: recommendedIterations, + parallelism: recommendedParallelism, + } +} + +// Hasher is safe for concurrent use. Derivations share a memory budget of +// concurrency times the current memory parameter: each one holds its own +// memory parameter in a weighted semaphore while it runs, so at most +// concurrency current-parameter derivations run at once, and a stored hash +// with a larger memory parameter takes a larger share. Other calls wait in +// FIFO order until the budget frees up or their context ends; the queue is +// bounded only by the callers' contexts, and request rate limiting belongs +// to the HTTP layer. +type Hasher struct { + current parameters + budgetKiB int64 + memory *semaphore.Weighted + // dummy has the current parameters, a random salt, and a random digest + // that no password derives in practice. + dummy domain.PasswordHash +} + +var _ outbound.PasswordHasher = (*Hasher)(nil) + +// NewHasher returns a hasher with the RFC 9106 parameters and a memory +// budget for concurrency derivations with those parameters. +func NewHasher(concurrency int) (*Hasher, error) { + return newHasher(recommendedParameters(), concurrency) +} + +func newHasher(current parameters, concurrency int) (*Hasher, error) { + if concurrency < 1 { + return nil, errors.New("argon2id.newHasher - concurrency must be positive") + } + if violation := current.violation(); violation != "" { + return nil, errors.New("argon2id.newHasher - " + violation) + } + salt, err := randomBytes(saltBytes) + if err != nil { + return nil, fmt.Errorf("argon2id.newHasher - generate dummy salt: %w", err) + } + digest, err := randomBytes(keyBytes) + if err != nil { + return nil, fmt.Errorf("argon2id.newHasher - generate dummy digest: %w", err) + } + dummy, err := domain.NewPasswordHash(encodePHC(current, salt, digest)) + if err != nil { + return nil, fmt.Errorf("argon2id.newHasher - encode dummy hash: %w", err) + } + budgetKiB := int64(concurrency) * int64(current.memoryKiB) + return &Hasher{ + current: current, + budgetKiB: budgetKiB, + memory: semaphore.NewWeighted(budgetKiB), + dummy: dummy, + }, nil +} + +// Hash derives a 32-byte key with a fresh 16-byte salt from crypto/rand. +func (hasher *Hasher) Hash(ctx context.Context, password domain.Password) (domain.PasswordHash, error) { + if password.IsZero() { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - password must be built by a domain constructor: %w", domain.ErrInvalidPassword) + } + salt, err := randomBytes(saltBytes) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - generate salt: %w", err) + } + key, err := hasher.derive(ctx, password, hasher.current, salt, keyBytes) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - derive key: %w", err) + } + hash, err := domain.NewPasswordHash(encodePHC(hasher.current, salt, key)) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Hasher.Hash - encode hash: %w", err) + } + return hash, nil +} + +// Verify recomputes the key with the salt, parameters, and key length stored +// in the hash and compares it in constant time. +func (hasher *Hasher) Verify(ctx context.Context, password domain.Password, stored domain.PasswordHash) (bool, error) { + if password.IsZero() { + return false, fmt.Errorf("Hasher.Verify - password must be built by a domain constructor: %w", domain.ErrInvalidPassword) + } + decoded, err := parsePHC(stored.PHC()) + if err != nil { + return false, fmt.Errorf("Hasher.Verify - parse stored hash: %w", err) + } + // The semaphore would block until the context ends on a weight above its + // size, so such a hash is refused up front. + if int64(decoded.parameters.memoryKiB) > hasher.budgetKiB { + return false, corruptHash("Hasher.Verify", "memory exceeds the hashing budget") + } + keyLength := uint32(len(decoded.key)) //nolint:gosec // parsePHC bounds the digest to 64 bytes. + key, err := hasher.derive(ctx, password, decoded.parameters, decoded.salt, keyLength) + if err != nil { + return false, fmt.Errorf("Hasher.Verify - derive key: %w", err) + } + if subtle.ConstantTimeCompare(key, decoded.key) != 1 { + return false, fmt.Errorf("Hasher.Verify - compare keys: %w", outbound.ErrPasswordMismatch) + } + needsRehash := decoded.parameters != hasher.current || len(decoded.salt) != saltBytes || len(decoded.key) != keyBytes + return needsRehash, nil +} + +// VerifyDummy runs Verify against the dummy hash, so it parses, waits for a +// slot, derives, and compares exactly as a real verification does. +func (hasher *Hasher) VerifyDummy(ctx context.Context, password domain.Password) error { + _, err := hasher.Verify(ctx, password, hasher.dummy) + if err != nil { + return fmt.Errorf("Hasher.VerifyDummy - verify dummy hash: %w", err) + } + // Unreachable in practice (a 2^-256 chance); fail closed all the same. + return fmt.Errorf("Hasher.VerifyDummy - dummy hash matched: %w", outbound.ErrPasswordMismatch) +} + +func (hasher *Hasher) derive(ctx context.Context, password domain.Password, params parameters, salt []byte, keyLength uint32) ([]byte, error) { + weight := int64(params.memoryKiB) + if err := hasher.acquire(ctx, weight); err != nil { + return nil, err + } + defer hasher.memory.Release(weight) + secret := []byte(password.Reveal()) + // Best effort: this clears only the byte copy handed to Argon2. The + // normalized string inside domain.Password cannot be wiped in Go and stays + // in memory until the garbage collector reuses it. + defer clear(secret) + return argon2.IDKey(secret, salt, params.iterations, params.memoryKiB, params.parallelism, keyLength), nil +} + +// acquire checks the context first, because Acquire may succeed on an ended +// context when the budget is free. +func (hasher *Hasher) acquire(ctx context.Context, weight int64) error { + if err := ctx.Err(); err != nil { + return fmt.Errorf("Hasher.acquire - context ended before hashing: %w", err) + } + if err := hasher.memory.Acquire(ctx, weight); err != nil { + return fmt.Errorf("Hasher.acquire - wait for hashing memory: %w", err) + } + return nil +} + +func randomBytes(size int) ([]byte, error) { + buffer := make([]byte, size) + if _, err := rand.Read(buffer); err != nil { + return nil, fmt.Errorf("argon2id.randomBytes - read random bytes: %w", err) + } + return buffer, nil +} + +// encodePHC writes $argon2id$v=19$m=,t=,p=$$ +// with unpadded standard base64, the format of the reference implementation. +func encodePHC(params parameters, salt, key []byte) string { + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, params.memoryKiB, params.iterations, params.parallelism, + base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(key)) +} + +type decodedHash struct { + parameters parameters + salt []byte + key []byte +} + +// parsePHC accepts only what encodePHC writes: Argon2id version 19, the +// parameters in the order m, t, p as decimals without leading zeros, and +// unpadded standard base64. Every failure wraps outbound.ErrPasswordHashCorrupt, +// and through it domain.ErrInvalidPasswordHash, and never quotes the input. +func parsePHC(encoded string) (decodedHash, error) { + fields := strings.Split(encoded, "$") + if len(fields) != phcFieldCount || fields[0] != "" || fields[1] != "argon2id" { + return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must be an Argon2id PHC string") + } + if fields[2] != "v="+strconv.Itoa(argon2.Version) { + return decodedHash{}, corruptHash("argon2id.parsePHC", "hash must use Argon2 version 19") + } + params, err := parseParameters(fields[3]) + if err != nil { + return decodedHash{}, err + } + salt, err := base64.RawStdEncoding.Strict().DecodeString(fields[4]) + if err != nil || len(salt) < minStoredSaltBytes || len(salt) > maxStoredSaltBytes { + return decodedHash{}, corruptHash("argon2id.parsePHC", "salt must be unpadded base64 of 8 to 64 bytes") + } + key, err := base64.RawStdEncoding.Strict().DecodeString(fields[5]) + if err != nil || len(key) < minStoredKeyBytes || len(key) > maxStoredKeyBytes { + return decodedHash{}, corruptHash("argon2id.parsePHC", "digest must be unpadded base64 of 16 to 64 bytes") + } + return decodedHash{parameters: params, salt: salt, key: key}, nil +} + +func parseParameters(field string) (parameters, error) { + values := strings.Split(field, ",") + if len(values) != phcParameterCount { + return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p") + } + memory, memoryOK := parseParameter(values[0], "m=", 32) + iterations, iterationsOK := parseParameter(values[1], "t=", 32) + parallelism, parallelismOK := parseParameter(values[2], "p=", 8) + if !memoryOK || !iterationsOK || !parallelismOK { + return parameters{}, corruptHash("argon2id.parseParameters", "parameters must be m, t, and p as decimals without leading zeros") + } + params := parameters{ + memoryKiB: uint32(memory), //nolint:gosec // ParseUint limited the value to 32 bits. + iterations: uint32(iterations), //nolint:gosec // ParseUint limited the value to 32 bits. + parallelism: uint8(parallelism), //nolint:gosec // ParseUint limited the value to 8 bits. + } + if violation := params.violation(); violation != "" { + return parameters{}, corruptHash("argon2id.parseParameters", violation) + } + return params, nil +} + +// parseParameter reads one "" value that fits bitSize bits. +func parseParameter(value, prefix string, bitSize int) (uint64, bool) { + digits, found := strings.CutPrefix(value, prefix) + if !found || digits == "" || digits[0] == '0' { + return 0, false + } + number, err := strconv.ParseUint(digits, 10, bitSize) + return number, err == nil +} + +// violation returns the stored-hash bound that params break, or "". The +// current parameters must pass it too, so every new hash stays verifiable. +func (params parameters) violation() string { + switch { + case params.parallelism < 1 || params.parallelism > maxStoredParallelism: + return "parallelism must be between 1 and 16" + case params.iterations < 1 || params.iterations > maxStoredIterations: + return "iterations must be between 1 and 16" + case params.memoryKiB < minMemoryKiBPerLane*uint32(params.parallelism) || params.memoryKiB > maxStoredMemoryKiB: + return "memory must be between 8 KiB per lane and 128 MiB" + default: + return "" + } +} + +func corruptHash(location, reason string) error { + return fmt.Errorf("%s - %s: %w", location, reason, outbound.ErrPasswordHashCorrupt) +} diff --git a/backend/internal/adapter/secondary/argon2id/hasher_test.go b/backend/internal/adapter/secondary/argon2id/hasher_test.go new file mode 100644 index 0000000..e84f035 --- /dev/null +++ b/backend/internal/adapter/secondary/argon2id/hasher_test.go @@ -0,0 +1,433 @@ +package argon2id + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const testRawPassword = "correct horse battery staple" + +// cheapParameters keep unit tests fast under the race detector. Tests that +// need the production cost use NewHasher. +var cheapParameters = parameters{memoryKiB: 64, iterations: 1, parallelism: 1} + +func newCheapHasher(t *testing.T, concurrency int) *Hasher { + t.Helper() + hasher, err := newHasher(cheapParameters, concurrency) + if err != nil { + t.Fatalf("newHasher() error = %v", err) + } + return hasher +} + +func newTestPassword(t *testing.T, raw string) domain.Password { + t.Helper() + password, err := domain.ParseLoginPassword(raw) + if err != nil { + t.Fatalf("ParseLoginPassword() error = %v", err) + } + return password +} + +// holdBudget takes the whole memory budget so that any derivation blocks, +// and returns the release function. +func holdBudget(t *testing.T, hasher *Hasher) func() { + t.Helper() + if !hasher.memory.TryAcquire(hasher.budgetKiB) { + t.Fatal("the hashing budget is already in use") + } + return func() { hasher.memory.Release(hasher.budgetKiB) } +} + +func mustPasswordHash(t *testing.T, phc string) domain.PasswordHash { + t.Helper() + hash, err := domain.NewPasswordHash(phc) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + return hash +} + +func TestNewHasherUsesTheRecommendedParameters(t *testing.T) { + hasher, err := NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + if !strings.HasPrefix(hash.PHC(), "$argon2id$v=19$m=65536,t=3,p=4$") { + t.Fatal("Hash() did not use Argon2id v19 with m=65536, t=3, p=4") + } + decoded, err := parsePHC(hash.PHC()) + if err != nil { + t.Fatalf("parsePHC(Hash()) error = %v", err) + } + if len(decoded.salt) != saltBytes || len(decoded.key) != keyBytes { + t.Fatalf("salt and key lengths = %d, %d, want %d, %d", len(decoded.salt), len(decoded.key), saltBytes, keyBytes) + } + needsRehash, err := hasher.Verify(context.Background(), password, hash) + if err != nil || needsRehash { + t.Fatalf("Verify(correct password) = %v, %v, want false, nil", needsRehash, err) + } +} + +func TestHashUsesAUniqueSaltAndBothHashesVerify(t *testing.T) { + hasher := newCheapHasher(t, 2) + password := newTestPassword(t, testRawPassword) + first, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + second, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + firstDecoded, err := parsePHC(first.PHC()) + if err != nil { + t.Fatalf("parsePHC() error = %v", err) + } + secondDecoded, err := parsePHC(second.PHC()) + if err != nil { + t.Fatalf("parsePHC() error = %v", err) + } + if bytes.Equal(firstDecoded.salt, secondDecoded.salt) || bytes.Equal(firstDecoded.key, secondDecoded.key) { + t.Fatal("two hashes of the same password share a salt or a key") + } + for _, hash := range []domain.PasswordHash{first, second} { + if needsRehash, err := hasher.Verify(context.Background(), password, hash); err != nil || needsRehash { + t.Fatalf("Verify() = %v, %v, want false, nil", needsRehash, err) + } + } +} + +func TestVerifyRejectsAWrongPassword(t *testing.T) { + hasher := newCheapHasher(t, 1) + hash, err := hasher.Hash(context.Background(), newTestPassword(t, testRawPassword)) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + for _, raw := range []string{"correct horse battery stapl", "Correct horse battery staple", "x"} { + needsRehash, err := hasher.Verify(context.Background(), newTestPassword(t, raw), hash) + if !errors.Is(err, outbound.ErrPasswordMismatch) || needsRehash { + t.Fatalf("Verify(wrong password) = %v, %v, want false, ErrPasswordMismatch", needsRehash, err) + } + if errors.Is(err, outbound.ErrPasswordHashCorrupt) { + t.Fatal("a wrong password was reported as a corrupt hash") + } + } +} + +func TestVerifyRejectsATamperedDigestAsAMismatch(t *testing.T) { + hasher := newCheapHasher(t, 1) + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + decoded, err := parsePHC(hash.PHC()) + if err != nil { + t.Fatalf("parsePHC() error = %v", err) + } + decoded.key[0] ^= 0x01 + tampered := mustPasswordHash(t, encodePHC(decoded.parameters, decoded.salt, decoded.key)) + if _, err := hasher.Verify(context.Background(), password, tampered); !errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("Verify(tampered digest) error = %v, want ErrPasswordMismatch", err) + } +} + +func TestVerifyMatchesTheReferenceImplementation(t *testing.T) { + tests := map[string]struct { + phc string + heavy bool + }{ + // The Argon2id test of phc-winner-argon2 src/test.c (password + // "password", salt "somesalt"), the encoded form of the reference + // implementation. It takes 64 MiB. + "phc-winner-argon2 test.c": { + phc: "$argon2id$v=19$m=65536,t=2,p=1$c29tZXNhbHQ$CTFhFdXPJO1aFaMaO6Mm5c8y7cJHAph8ArZWb2GRPPc", + heavy: true, + }, + // The m=4096, t=4, p=4 entry of testVectors in + // golang.org/x/crypto/argon2/argon2_test.go, which that file states was + // generated with the phc-winner-argon2 CLI (24-byte tag), encoded here + // as PHC. + "x/crypto CLI vector": {phc: "$argon2id$v=19$m=4096,t=4,p=4$c29tZXNhbHQ$FF25czqfTuQ+3zPFCb6WuTTVBaTvszxa"}, + } + // The budget of one production derivation fits both vectors. + hasher, err := NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + for name, test := range tests { + if test.heavy && testing.Short() { + continue + } + needsRehash, err := hasher.Verify(context.Background(), newTestPassword(t, "password"), mustPasswordHash(t, test.phc)) + if err != nil { + t.Fatalf("Verify(%s) error = %v", name, err) + } + if !needsRehash { + t.Fatalf("Verify(%s) did not request a rehash for other parameters or sizes", name) + } + if _, err := hasher.Verify(context.Background(), newTestPassword(t, "passwore"), mustPasswordHash(t, test.phc)); !errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("Verify(%s, wrong password) error = %v, want ErrPasswordMismatch", name, err) + } + } +} + +func TestVerifyReportsRehashForOtherParameters(t *testing.T) { + password := newTestPassword(t, testRawPassword) + older := newCheapHasher(t, 1) + hash, err := older.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + stronger, err := newHasher(parameters{memoryKiB: 128, iterations: 2, parallelism: 1}, 1) + if err != nil { + t.Fatalf("newHasher() error = %v", err) + } + needsRehash, err := stronger.Verify(context.Background(), password, hash) + if err != nil || !needsRehash { + t.Fatalf("Verify(older parameters) = %v, %v, want true, nil", needsRehash, err) + } +} + +func TestVerifyRejectsCorruptHashesWithoutDerivation(t *testing.T) { + salt := base64.RawStdEncoding.EncodeToString([]byte("saltsaltsaltsalt")) + digest := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes)) + // Each value passes domain.NewPasswordHash, so only the hasher's bounds + // stop it. + tests := map[string]string{ + "huge memory": "$argon2id$v=19$m=4294967295,t=1,p=1$" + salt + "$" + digest, + "memory over 128 MiB": "$argon2id$v=19$m=131073,t=1,p=1$" + salt + "$" + digest, + "memory over the budget": "$argon2id$v=19$m=128,t=1,p=1$" + salt + "$" + digest, + "memory below 8 KiB/lane": "$argon2id$v=19$m=31,t=1,p=4$" + salt + "$" + digest, + "memory over uint32": "$argon2id$v=19$m=4294967296,t=1,p=1$" + salt + "$" + digest, + "huge iterations": "$argon2id$v=19$m=64,t=4294967295,p=1$" + salt + "$" + digest, + "iterations over 16": "$argon2id$v=19$m=64,t=17,p=1$" + salt + "$" + digest, + "parallelism over 16": "$argon2id$v=19$m=256,t=1,p=17$" + salt + "$" + digest, + "parallelism over uint8": "$argon2id$v=19$m=4096,t=1,p=256$" + salt + "$" + digest, + "salt over 64 bytes": "$argon2id$v=19$m=64,t=1,p=1$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)) + "$" + digest, + "digest over 64 bytes": "$argon2id$v=19$m=64,t=1,p=1$" + salt + "$" + base64.RawStdEncoding.EncodeToString(make([]byte, 65)), + } + // The budget is already taken: a derivation would block until the context + // ends, so a quick ErrPasswordHashCorrupt proves none started. The budget + // of one cheap derivation is 64 KiB. + hasher := newCheapHasher(t, 1) + defer holdBudget(t, hasher)() + password := newTestPassword(t, testRawPassword) + for name, phc := range tests { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + needsRehash, err := hasher.Verify(ctx, password, mustPasswordHash(t, phc)) + cancel() + if !errors.Is(err, outbound.ErrPasswordHashCorrupt) || needsRehash { + t.Fatalf("Verify(%s) = %v, %v, want false, ErrPasswordHashCorrupt", name, needsRehash, err) + } + if errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("Verify(%s) reported a corrupt hash as a wrong password", name) + } + if !errors.Is(err, domain.ErrInvalidPasswordHash) { + t.Fatalf("Verify(%s) error = %v, want it to match domain.ErrInvalidPasswordHash too", name, err) + } + } + if _, err := hasher.Verify(context.Background(), password, domain.PasswordHash{}); !errors.Is(err, outbound.ErrPasswordHashCorrupt) { + t.Fatalf("Verify(zero hash) error = %v, want ErrPasswordHashCorrupt", err) + } +} + +func TestParsePHCAcceptsOnlyTheCanonicalForm(t *testing.T) { + salt := base64.RawStdEncoding.EncodeToString([]byte("saltsaltsaltsalt")) + digest := base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes)) + valid := "$argon2id$v=19$m=64,t=1,p=1$" + salt + "$" + digest + if _, err := parsePHC(valid); err != nil { + t.Fatalf("parsePHC(valid) error = %v", err) + } + for name, phc := range map[string]string{ + "empty": "", + "argon2i": strings.Replace(valid, "argon2id", "argon2i", 1), + "version 16": strings.Replace(valid, "v=19", "v=16", 1), + "missing version": strings.Replace(valid, "$v=19", "", 1), + "reordered": strings.Replace(valid, "m=64,t=1,p=1", "t=1,m=64,p=1", 1), + "leading zero": strings.Replace(valid, "m=64", "m=064", 1), + "zero iterations": strings.Replace(valid, "t=1", "t=0", 1), + "signed value": strings.Replace(valid, "t=1", "t=+1", 1), + "extra parameter": strings.Replace(valid, "p=1", "p=1,k=1", 1), + "data parameter": strings.Replace(valid, "p=1", "p=1$data=abc", 1), + "padded salt": strings.Replace(valid, salt, salt+"==", 1), + "url-safe digest": strings.Replace(valid, digest, strings.ReplaceAll(digest, "B", "-"), 1), + "short salt": strings.Replace(valid, salt, "c2FsdA", 1), + "short digest": strings.Replace(valid, digest, "aGFzaA", 1), + "trailing separator": valid + "$", + "missing leading sep": strings.TrimPrefix(valid, "$"), + } { + if _, err := parsePHC(phc); !errors.Is(err, outbound.ErrPasswordHashCorrupt) { + t.Fatalf("parsePHC(%s) error = %v, want ErrPasswordHashCorrupt", name, err) + } + } +} + +func TestVerifyDummyDoesTheSameWorkAndNeverMatches(t *testing.T) { + hasher := newCheapHasher(t, 1) + dummy, err := parsePHC(hasher.dummy.PHC()) + if err != nil { + t.Fatalf("parsePHC(dummy) error = %v", err) + } + if dummy.parameters != hasher.current || len(dummy.salt) != saltBytes || len(dummy.key) != keyBytes { + t.Fatal("the dummy hash does not use the current parameters and sizes") + } + other := newCheapHasher(t, 1) + if hasher.dummy.PHC() == other.dummy.PHC() { + t.Fatal("two hashers share a dummy hash") + } + err = hasher.VerifyDummy(context.Background(), newTestPassword(t, testRawPassword)) + if !errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("VerifyDummy() error = %v, want ErrPasswordMismatch", err) + } + + // VerifyDummy waits for hashing memory like Verify does. + defer holdBudget(t, hasher)() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if err := hasher.VerifyDummy(ctx, newTestPassword(t, testRawPassword)); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("VerifyDummy(no free slot) error = %v, want DeadlineExceeded", err) + } +} + +func TestHashingWaitsForItsShareOfTheMemoryBudget(t *testing.T) { + // Budget for two current-parameter derivations. + hasher := newCheapHasher(t, 2) + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + // A stored hash with twice the current memory needs the whole budget. + double, err := newHasher(parameters{memoryKiB: 2 * cheapParameters.memoryKiB, iterations: 1, parallelism: 1}, 1) + if err != nil { + t.Fatalf("newHasher() error = %v", err) + } + doubleHash, err := double.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + + // One share taken: a current derivation still runs, a double one waits. + share := int64(cheapParameters.memoryKiB) + if !hasher.memory.TryAcquire(share) { + t.Fatal("the hashing budget is already in use") + } + if _, err := hasher.Verify(context.Background(), password, hash); err != nil { + t.Fatalf("Verify(one free share) error = %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + if _, err := hasher.Verify(ctx, password, doubleHash); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Verify(double memory, one free share) error = %v, want DeadlineExceeded", err) + } + hasher.memory.Release(share) + if needsRehash, err := hasher.Verify(context.Background(), password, doubleHash); err != nil || !needsRehash { + t.Fatalf("Verify(double memory, free budget) = %v, %v, want true, nil", needsRehash, err) + } + + // The whole budget taken: every call waits until its context ends. + release := holdBudget(t, hasher) + if _, err := hasher.Hash(ctx, password); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Hash(no free memory) error = %v, want DeadlineExceeded", err) + } + if _, err := hasher.Verify(ctx, password, hash); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Verify(no free memory) error = %v, want DeadlineExceeded", err) + } + release() + + canceled, cancelNow := context.WithCancel(context.Background()) + cancelNow() + if _, err := hasher.Hash(canceled, password); !errors.Is(err, context.Canceled) { + t.Fatalf("Hash(canceled context) error = %v, want Canceled even with free memory", err) + } + // Failed and finished calls returned their share. + holdBudget(t, hasher)() +} + +func TestHasherRejectsAZeroPasswordAndInvalidSettings(t *testing.T) { + hasher := newCheapHasher(t, 1) + hash, err := hasher.Hash(context.Background(), newTestPassword(t, testRawPassword)) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + if _, err := hasher.Hash(context.Background(), domain.Password{}); !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("Hash(zero password) error = %v, want ErrInvalidPassword", err) + } + if _, err := hasher.Verify(context.Background(), domain.Password{}, hash); !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("Verify(zero password) error = %v, want ErrInvalidPassword", err) + } + if err := hasher.VerifyDummy(context.Background(), domain.Password{}); !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("VerifyDummy(zero password) error = %v, want ErrInvalidPassword", err) + } + for _, concurrency := range []int{0, -1} { + if _, err := NewHasher(concurrency); err == nil { + t.Fatalf("NewHasher(%d) error = nil, want an error", concurrency) + } + } + if _, err := newHasher(parameters{memoryKiB: 8, iterations: 1, parallelism: 4}, 1); err == nil { + t.Fatal("newHasher(memory below 8 KiB per lane) error = nil, want an error") + } +} + +func TestErrorsAndLogsNeverContainThePasswordOrTheHash(t *testing.T) { + hasher := newCheapHasher(t, 1) + password := newTestPassword(t, testRawPassword) + hash, err := hasher.Hash(context.Background(), password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + _, mismatch := hasher.Verify(context.Background(), newTestPassword(t, "wrong password value"), hash) + corruptPHC := "$argon2id$v=19$m=131073,t=1,p=1$c2FsdHNhbHRzYWx0c2FsdA$" + base64.RawStdEncoding.EncodeToString(bytes.Repeat([]byte{7}, keyBytes)) + _, corrupt := hasher.Verify(context.Background(), password, mustPasswordHash(t, corruptPHC)) + dummy := hasher.VerifyDummy(context.Background(), password) + + var logs bytes.Buffer + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + for _, err := range []error{mismatch, corrupt, dummy} { + if err == nil { + t.Fatal("expected an error") + } + logger.Error("password check failed", "error", err, "password", password, "hash", hash) + } + output := logs.String() + fmt.Sprint(mismatch, corrupt, dummy) + for _, secret := range []string{testRawPassword, "wrong password value", hash.PHC(), corruptPHC, hasher.dummy.PHC()} { + if strings.Contains(output, secret) { + t.Fatalf("errors or logs expose a secret: %s", output) + } + } +} + +// BenchmarkHashRecommendedParameters measures one Hash with the production +// parameters: go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/ +func BenchmarkHashRecommendedParameters(b *testing.B) { + hasher, err := NewHasher(1) + if err != nil { + b.Fatalf("NewHasher() error = %v", err) + } + password, err := domain.NewPassword(testRawPassword) + if err != nil { + b.Fatalf("NewPassword() error = %v", err) + } + for b.Loop() { + if _, err := hasher.Hash(context.Background(), password); err != nil { + b.Fatalf("Hash() error = %v", err) + } + } +} diff --git a/backend/internal/domain/email_address.go b/backend/internal/domain/email_address.go index 1bc5274..9b553a5 100644 --- a/backend/internal/domain/email_address.go +++ b/backend/internal/domain/email_address.go @@ -38,8 +38,15 @@ var ErrInvalidEmailAddress = errors.New("invalid email address") // the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. // // String, GoString, Format, and LogValue redact the address so it does not -// reach logs by accident; Address returns the real value. +// reach logs by accident; Address returns the real value. Both forms sit +// behind a pointer: fmt cannot call Format on an unexported field of an +// enclosing struct and prints its contents instead, but for a pointer it +// prints only the address. A nil pointer is the zero, invalid value. type EmailAddress struct { + value *emailAddressValue +} + +type emailAddressValue struct { address string normalized string } @@ -69,7 +76,7 @@ func NewEmailAddress(raw string) (EmailAddress, error) { if err := validateEmailDomain(domainPart); err != nil { return EmailAddress{}, err } - return EmailAddress{address: address, normalized: normalizeEmailKey(address)}, nil + return EmailAddress{value: &emailAddressValue{address: address, normalized: normalizeEmailKey(address)}}, nil } // RestoreEmailAddress rebuilds an EmailAddress from storage. It checks only @@ -79,7 +86,7 @@ func RestoreEmailAddress(address, normalized string) (EmailAddress, error) { if address == "" || normalized != normalizeEmailKey(address) { return EmailAddress{}, fmt.Errorf("domain.RestoreEmailAddress - stored key does not match the stored address: %w", ErrInvalidEmailAddress) } - return EmailAddress{address: address, normalized: normalized}, nil + return EmailAddress{value: &emailAddressValue{address: address, normalized: normalized}}, nil } // normalizeEmailKey lowercases A-Z only, independent of locale and Unicode @@ -139,13 +146,23 @@ func invalidEmailAddress(reason string) error { // Address returns the delivery form. Use it only where the address is needed: // storage, mail delivery, and the account view. -func (email EmailAddress) Address() string { return email.address } +func (email EmailAddress) Address() string { + if email.value == nil { + return "" + } + return email.value.address +} // Normalized returns the comparison key that storage keeps unique. -func (email EmailAddress) Normalized() string { return email.normalized } +func (email EmailAddress) Normalized() string { + if email.value == nil { + return "" + } + return email.value.normalized +} // IsZero reports an EmailAddress not built by NewEmailAddress. -func (email EmailAddress) IsZero() bool { return email.normalized == "" } +func (email EmailAddress) IsZero() bool { return email.value == nil } func (email EmailAddress) String() string { return redactedEmailAddress } diff --git a/backend/internal/domain/password.go b/backend/internal/domain/password.go new file mode 100644 index 0000000..e3cbce8 --- /dev/null +++ b/backend/internal/domain/password.go @@ -0,0 +1,96 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "unicode/utf8" + + "golang.org/x/text/unicode/norm" +) + +const ( + // MinNewPasswordCodePoints follows NIST SP 800-63B-4 for a password used + // as the only authentication factor (the NewPassword contract schema). + MinNewPasswordCodePoints = 15 + // MaxPasswordCodePoints bounds the hashing input of new and login + // passwords (NewPassword and LoginPassword in the contract). + MaxPasswordCodePoints = 128 + // minLoginPasswordCodePoints only rejects an empty login password; login + // applies no registration policy, so a policy change locks nobody out. + minLoginPasswordCodePoints = 1 + // maxPasswordInputBytes caps the raw input before NFKC normalization so + // an oversized value never reaches the normalizer. 128 code points take at + // most 4 bytes each in UTF-8, so every value that the contract schema + // accepts fits. + maxPasswordInputBytes = MaxPasswordCodePoints * utf8.UTFMax +) + +// ErrInvalidPassword reports a password outside the length rules. Errors that +// wrap it name the rule, never the value or its length. +var ErrInvalidPassword = errors.New("invalid password") + +// Password is a plaintext password normalized to Unicode NFKC, as NIST SP +// 800-63B-4 recommends, so that equivalent input from different keyboards +// and platforms hashes the same. It exists only between the request and the +// password hasher and is never stored. String, GoString, Format, LogValue, +// and MarshalJSON redact it; Reveal returns the value for the hasher. The +// value sits behind a pointer so that printing an enclosing struct shows only +// an address (see redactedValue). +type Password struct { + value *string +} + +// NewPassword applies the registration policy: 15 to 128 Unicode code points +// after NFKC normalization. The blocklist of common or breached passwords is +// a separate check. +func NewPassword(raw string) (Password, error) { + return parsePassword("domain.NewPassword", raw, MinNewPasswordCodePoints) +} + +// ParseLoginPassword accepts a password entered at login: 1 to 128 Unicode +// code points after NFKC normalization. +func ParseLoginPassword(raw string) (Password, error) { + return parsePassword("domain.ParseLoginPassword", raw, minLoginPasswordCodePoints) +} + +// parsePassword runs only cheap checks, so a caller can reject a value before +// any expensive hashing. The raw byte cap comes first, then UTF-8 validity, +// then normalization and the code point count. +func parsePassword(location, raw string, minCodePoints int) (Password, error) { + if len(raw) > maxPasswordInputBytes { + return Password{}, fmt.Errorf("%s - password must have at most %d bytes before normalization: %w", + location, maxPasswordInputBytes, ErrInvalidPassword) + } + if !utf8.ValidString(raw) { + return Password{}, fmt.Errorf("%s - password must be valid UTF-8: %w", location, ErrInvalidPassword) + } + normalized := norm.NFKC.String(raw) + if count := utf8.RuneCountInString(normalized); count < minCodePoints || count > MaxPasswordCodePoints { + return Password{}, fmt.Errorf("%s - password must have %d to %d code points after NFKC normalization: %w", + location, minCodePoints, MaxPasswordCodePoints, ErrInvalidPassword) + } + return Password{value: newRedactedValue(normalized)}, nil +} + +// Reveal returns the normalized password for the password hasher. Never +// store, log, or return it. +func (password Password) Reveal() string { return redactedValue(password.value) } + +// IsZero reports a Password not built by NewPassword or ParseLoginPassword. +func (password Password) IsZero() bool { return password.value == nil } + +func (password Password) String() string { return redactedSecret } + +func (password Password) GoString() string { return redactedSecret } + +func (password Password) LogValue() slog.Value { return slog.StringValue(redactedSecret) } + +// Format redacts every verb; without it %d would print the struct fields. +func (password Password) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } + +// MarshalJSON redacts the value in any JSON output, including a struct that +// embeds a Password. +func (password Password) MarshalJSON() ([]byte, error) { return redactedSecretJSON(), nil } + +func redactedSecretJSON() []byte { return []byte(`"` + redactedSecret + `"`) } diff --git a/backend/internal/domain/password_test.go b/backend/internal/domain/password_test.go new file mode 100644 index 0000000..7fec25d --- /dev/null +++ b/backend/internal/domain/password_test.go @@ -0,0 +1,132 @@ +package domain + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestNewPasswordCountsCodePointsAfterNFKC(t *testing.T) { + tests := map[string]struct { + raw string + want string + }{ + "15 ASCII characters": {raw: strings.Repeat("a", 15), want: strings.Repeat("a", 15)}, + "128 ASCII characters": {raw: strings.Repeat("a", 128), want: strings.Repeat("a", 128)}, + // 15 code points in 30 bytes: the limit counts code points, not bytes. + "15 Cyrillic letters": {raw: strings.Repeat("ж", 15), want: strings.Repeat("ж", 15)}, + // 128 code points in 512 bytes: the largest input the byte cap allows. + "128 four-byte characters": {raw: strings.Repeat("\U0001F600", 128), want: strings.Repeat("\U0001F600", 128)}, + // Fullwidth forms normalize to ASCII. + "fullwidth letters": {raw: strings.Repeat("pass", 4), want: strings.Repeat("pass", 4)}, + // 14 raw code points become 15 after NFKC expands the ligature. + "expanding ligature": {raw: strings.Repeat("a", 13) + "fi", want: strings.Repeat("a", 13) + "fi"}, + // Spaces and surrounding whitespace are part of the password. + "spaces kept": {raw: " correct horse battery ", want: " correct horse battery "}, + } + for name, test := range tests { + password, err := NewPassword(test.raw) + if err != nil { + t.Fatalf("NewPassword(%s) error = %v", name, err) + } + if password.Reveal() != test.want { + t.Fatalf("NewPassword(%s) did not normalize to the expected NFKC form", name) + } + } +} + +func TestNewPasswordRejectsValuesOutsideThePolicy(t *testing.T) { + tests := map[string]string{ + "empty": "", + "14 ASCII characters": strings.Repeat("a", 14), + "129 ASCII characters": strings.Repeat("a", 129), + "over the byte cap": strings.Repeat("a", maxPasswordInputBytes+1), + "129 four-byte runes": strings.Repeat("\U0001F600", 129), + "one megabyte": strings.Repeat("a", 1<<20), + "invalid UTF-8": strings.Repeat("a", 20) + "\xff", + "truncated UTF-8": strings.Repeat("a", 20) + "\xe2\x82", + "expands past the limit": strings.Repeat("fi", 65), + // 16 raw code points compose into 8 after NFKC. + "composes below the minimum": strings.Repeat("é", 8), + } + for name, raw := range tests { + _, err := NewPassword(raw) + if !errors.Is(err, ErrInvalidPassword) { + t.Fatalf("NewPassword(%s) error = %v, want ErrInvalidPassword", name, err) + } + if raw != "" && strings.Contains(err.Error(), raw) { + t.Fatalf("NewPassword(%s) error exposes the input", name) + } + } +} + +func TestNewPasswordChecksTheByteCapBeforeNormalizing(t *testing.T) { + // Valid UTF-8 would normalize; the byte cap must answer first. + _, err := NewPassword(strings.Repeat("fi", maxPasswordInputBytes)) + if !errors.Is(err, ErrInvalidPassword) || !strings.Contains(err.Error(), "bytes before normalization") { + t.Fatalf("NewPassword(oversized) error = %v, want the byte cap", err) + } +} + +func TestParseLoginPasswordAppliesOnlyTheHashingBound(t *testing.T) { + for _, raw := range []string{"a", "short", strings.Repeat("a", 128)} { + if _, err := ParseLoginPassword(raw); err != nil { + t.Fatalf("ParseLoginPassword(%d bytes) error = %v", len(raw), err) + } + } + for _, raw := range []string{"", strings.Repeat("a", 129), strings.Repeat("a", maxPasswordInputBytes+1), "\xff"} { + if _, err := ParseLoginPassword(raw); !errors.Is(err, ErrInvalidPassword) { + t.Fatalf("ParseLoginPassword(%d bytes) error = %v, want ErrInvalidPassword", len(raw), err) + } + } +} + +func TestNewPasswordAndLoginPasswordNormalizeAlike(t *testing.T) { + registered, err := NewPassword("correct horse battery") + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + login, err := ParseLoginPassword("correct horse battery") + if err != nil { + t.Fatalf("ParseLoginPassword() error = %v", err) + } + if registered.Reveal() != login.Reveal() { + t.Fatal("equivalent registration and login input normalized differently") + } + if !(Password{}).IsZero() || registered.IsZero() { + t.Fatal("IsZero() does not distinguish a built password from the zero value") + } +} + +func TestPasswordAndPasswordHashAreRedacted(t *testing.T) { + const raw = "correct horse battery staple" + password, err := NewPassword(raw) + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + passwordHash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + var logs bytes.Buffer + slog.New(slog.NewTextHandler(&logs, nil)).Info("redaction", "password", password, "hash", passwordHash) + slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "password", password, "hash", passwordHash) + encoded, err := json.Marshal(map[string]any{"password": password, "hash": passwordHash}) + if err != nil { + t.Fatalf("json.Marshal() error = %v", err) + } + formatted := fmt.Sprintf("%v %+v %#v %s %q %d", password, password, password, password, password, password) + + logs.String() + string(encoded) + for _, secret := range []string{raw, testPasswordHash, "c2FsdHNhbHRzYWx0"} { + if strings.Contains(formatted, secret) { + t.Fatalf("formatted output exposes a secret: %s", formatted) + } + } + if !strings.Contains(string(encoded), redactedSecret) { + t.Fatalf("json.Marshal() = %s, want redacted values", encoded) + } +} diff --git a/backend/internal/domain/redaction_test.go b/backend/internal/domain/redaction_test.go new file mode 100644 index 0000000..5820bc3 --- /dev/null +++ b/backend/internal/domain/redaction_test.go @@ -0,0 +1,90 @@ +package domain + +import ( + "bytes" + "encoding/json" + "fmt" + "log/slog" + "strings" + "testing" +) + +// nestedSecrets holds every secret type in unexported fields, where fmt does +// not call their Format, String, or GoString methods. +type nestedSecrets struct { + password Password + hash PasswordHash + token SecretToken + email EmailAddress +} + +// exportedSecrets is the same with exported fields, as in domain.User. +type exportedSecrets struct { + Password Password `json:"password"` + Hash PasswordHash `json:"hash"` + Token SecretToken `json:"token"` + Email EmailAddress `json:"email"` +} + +func TestSecretsAreRedactedInsideEnclosingStructs(t *testing.T) { + const rawPassword = "correct horse battery staple" + const rawEmail = "Secret.Person@Example.com" + password, err := NewPassword(rawPassword) + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + hash, err := NewPasswordHash(testPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + token, err := NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + email, err := NewEmailAddress(rawEmail) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + nested := nestedSecrets{password: password, hash: hash, token: token, email: email} + exported := exportedSecrets{Password: password, Hash: hash, Token: token, Email: email} + pointer := &nested + + var logs bytes.Buffer + for _, logger := range []*slog.Logger{ + slog.New(slog.NewTextHandler(&logs, nil)), + slog.New(slog.NewJSONHandler(&logs, nil)), + } { + logger.Info("nested", "unexported", nested, "exported", exported, "pointer", pointer) + } + encoded, err := json.Marshal(exported) + if err != nil { + t.Fatalf("json.Marshal() error = %v", err) + } + output := fmt.Sprintf("%v %+v %#v %v %+v %#v %v %+v %v", + nested, nested, nested, exported, exported, exported, pointer, []nestedSecrets{nested}, map[string]nestedSecrets{"k": nested}) + + logs.String() + string(encoded) + + secrets := []string{ + rawPassword, testPasswordHash, "c2FsdHNhbHRzYWx0", token.Reveal(), rawEmail, strings.ToLower(rawEmail), + } + for _, secret := range secrets { + if strings.Contains(output, secret) { + t.Fatalf("printing an enclosing struct exposes a secret: %s", output) + } + } +} + +func TestZeroSecretValuesAreEmptyAndInvalid(t *testing.T) { + if !(Password{}).IsZero() || (Password{}).Reveal() != "" { + t.Fatal("zero Password is not empty and zero") + } + if !(PasswordHash{}).IsZero() || (PasswordHash{}).PHC() != "" { + t.Fatal("zero PasswordHash is not empty and zero") + } + if !(SecretToken{}).IsZero() || (SecretToken{}).Reveal() != "" { + t.Fatal("zero SecretToken is not empty and zero") + } + if !(EmailAddress{}).IsZero() || (EmailAddress{}).Address() != "" || (EmailAddress{}).Normalized() != "" { + t.Fatal("zero EmailAddress is not empty and zero") + } +} diff --git a/backend/internal/domain/secret_token.go b/backend/internal/domain/secret_token.go index 56d498a..0ad7e5e 100644 --- a/backend/internal/domain/secret_token.go +++ b/backend/internal/domain/secret_token.go @@ -31,8 +31,10 @@ var ( // 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 + value *string } // NewSecretToken returns a token with 256 bits from crypto/rand. @@ -41,7 +43,7 @@ func NewSecretToken() (SecretToken, error) { 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 + return SecretToken{value: newRedactedValue(base64.RawURLEncoding.EncodeToString(entropy))}, nil } // ParseSecretToken accepts a raw token from a request. It checks only the @@ -50,19 +52,19 @@ 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 + 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.value))) + 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 token.value } +func (token SecretToken) Reveal() string { return redactedValue(token.value) } func (token SecretToken) String() string { return redactedSecret } @@ -73,12 +75,26 @@ func (token SecretToken) LogValue() slog.Value { return slog.StringValue(redacte // 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 == "" } +func (token SecretToken) IsZero() bool { return token.value == nil } // SecretTokenHash is the SHA-256 digest of a SecretToken. type SecretTokenHash [SecretTokenHashSize]byte diff --git a/backend/internal/domain/user.go b/backend/internal/domain/user.go index 574c113..7cc3f43 100644 --- a/backend/internal/domain/user.go +++ b/backend/internal/domain/user.go @@ -105,9 +105,11 @@ func ParseOnboardingStep(value string) (OnboardingStep, error) { } // PasswordHash is an Argon2id hash in the PHC string format. It is never the -// password itself. String and LogValue redact it. +// password itself. String and LogValue redact it. The string sits behind a +// pointer so that printing an enclosing struct shows only an address (see +// redactedValue). type PasswordHash struct { - phc string + phc *string } // NewPasswordHash validates the structure of a PHC string produced by the @@ -129,7 +131,7 @@ func NewPasswordHash(phc string) (PasswordHash, error) { if err != nil || len(digest) < minPasswordDigestBytes { return PasswordHash{}, invalidPasswordHash("digest must be unpadded base64 of at least 16 bytes") } - return PasswordHash{phc: phc}, nil + return PasswordHash{phc: newRedactedValue(phc)}, nil } func invalidPasswordHash(reason string) error { @@ -137,7 +139,7 @@ func invalidPasswordHash(reason string) error { } // PHC returns the encoded hash for storage and verification. -func (hash PasswordHash) PHC() string { return hash.phc } +func (hash PasswordHash) PHC() string { return redactedValue(hash.phc) } func (hash PasswordHash) String() string { return redactedSecret } @@ -148,8 +150,12 @@ func (hash PasswordHash) LogValue() slog.Value { return slog.StringValue(redacte // Format redacts every verb; without it %d would print the struct fields. func (hash PasswordHash) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } +// MarshalJSON redacts the hash in any JSON output, including a serialized +// User. +func (hash PasswordHash) MarshalJSON() ([]byte, error) { return redactedSecretJSON(), nil } + // IsZero reports a PasswordHash not built by NewPasswordHash. -func (hash PasswordHash) IsZero() bool { return hash.phc == "" } +func (hash PasswordHash) IsZero() bool { return hash.phc == nil } // Registration is the validated content of one registration request. type Registration struct { diff --git a/backend/internal/port/outbound/password.go b/backend/internal/port/outbound/password.go new file mode 100644 index 0000000..4848448 --- /dev/null +++ b/backend/internal/port/outbound/password.go @@ -0,0 +1,62 @@ +package outbound + +import ( + "context" + "errors" + "fmt" + + "lincodex/backend/internal/domain" +) + +var ( + // ErrPasswordMismatch reports a password that does not match the hash. + // VerifyDummy ends with it whenever it completes the work. + ErrPasswordMismatch = errors.New("password does not match") + + // ErrPasswordHashCorrupt reports a stored hash that cannot be verified: + // it is not a well-formed Argon2id v19 PHC string, or its parameters are + // outside the bounds the hasher accepts. It wraps + // domain.ErrInvalidPasswordHash, which the repository returns when a + // stored hash fails domain.NewPasswordHash on read, so + // errors.Is(err, domain.ErrInvalidPasswordHash) matches both cases. It is + // a storage problem, not a wrong password. + ErrPasswordHashCorrupt = fmt.Errorf("password hash corrupt: %w", domain.ErrInvalidPasswordHash) +) + +// PasswordHasher derives and checks password hashes with a slow, salted KDF. +// +// Callers validate the password with domain.NewPassword or +// domain.ParseLoginPassword first, so the hasher only receives bounded +// input; a zero domain.Password returns an error wrapping +// domain.ErrInvalidPassword without hashing. Every derivation waits for its +// share of a fixed memory budget, which bounds the memory and CPU of +// concurrent hashing; a context that ends while waiting returns the context +// error and computes nothing. Errors never contain the password or the hash. +// +// Login (TASK-055) must answer invalid_credentials for an unknown email, a +// wrong password, and a stored hash that is invalid +// (domain.ErrInvalidPasswordHash, from the repository or from Verify). For +// an invalid hash it must also log an error and call VerifyDummy, because a +// corrupt hash is refused without a derivation and would otherwise answer +// faster than a real check. +type PasswordHasher interface { + // Hash returns a new hash with a fresh random salt and the current + // parameters. + Hash(ctx context.Context, password domain.Password) (domain.PasswordHash, error) + + // Verify returns nil when password matches stored. needsRehash then + // reports that stored was made with other parameters, salt length, or key + // length than the current ones, so a login can store Hash(password) in + // its place. A wrong password returns ErrPasswordMismatch and a malformed + // or out-of-bounds hash returns ErrPasswordHashCorrupt without a + // derivation; needsRehash is false with any error. + Verify(ctx context.Context, password domain.Password, stored domain.PasswordHash) (needsRehash bool, err error) + + // VerifyDummy does the same work as Verify against a hash with the current + // parameters that no password matches. It returns ErrPasswordMismatch + // after the work, the context error when the context ended before the + // derivation, or domain.ErrInvalidPassword for a zero password; it never + // returns nil. A login calls it for an unknown email so that the response + // time does not reveal whether the account exists. + VerifyDummy(ctx context.Context, password domain.Password) error +} diff --git a/backend/internal/usecase/identity/.gitkeep b/backend/internal/usecase/identity/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/usecase/identity/credentials.go b/backend/internal/usecase/identity/credentials.go new file mode 100644 index 0000000..c0a2680 --- /dev/null +++ b/backend/internal/usecase/identity/credentials.go @@ -0,0 +1,39 @@ +// Package identity holds the account usecases. +package identity + +import ( + "context" + "fmt" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// Credentials applies the password rules in the order that keeps hashing +// bounded: the cheap length and encoding checks first, the expensive KDF only +// for a password that passes them. +type Credentials struct { + hasher outbound.PasswordHasher +} + +func NewCredentials(hasher outbound.PasswordHasher) *Credentials { + return &Credentials{hasher: hasher} +} + +// HashNewPassword applies the registration password policy to raw and hashes +// the normalized password. A password outside the policy returns an error +// wrapping domain.ErrInvalidPassword without calling the hasher. Errors +// never contain raw. Registration (TASK-053, not implemented yet) must call +// it on every branch before it looks up the email, so that neither the +// outcome nor the time depends on whether the account exists. +func (credentials *Credentials) HashNewPassword(ctx context.Context, raw string) (domain.PasswordHash, error) { + password, err := domain.NewPassword(raw) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - validate password: %w", err) + } + hash, err := credentials.hasher.Hash(ctx, password) + if err != nil { + return domain.PasswordHash{}, fmt.Errorf("Credentials.HashNewPassword - hash password: %w", err) + } + return hash, nil +} diff --git a/backend/internal/usecase/identity/credentials_test.go b/backend/internal/usecase/identity/credentials_test.go new file mode 100644 index 0000000..d112ae5 --- /dev/null +++ b/backend/internal/usecase/identity/credentials_test.go @@ -0,0 +1,83 @@ +package identity + +import ( + "bytes" + "context" + "errors" + "log/slog" + "strings" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// countingHasher records calls so a test can prove that validation stops a +// password before any hashing. +type countingHasher struct { + hashCalls int + hashed domain.Password +} + +func (hasher *countingHasher) Hash(_ context.Context, password domain.Password) (domain.PasswordHash, error) { + hasher.hashCalls++ + hasher.hashed = password + return domain.NewPasswordHash("$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g") +} + +func (hasher *countingHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) { + return false, errors.New("countingHasher.Verify - not used") +} + +func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error { + return errors.New("countingHasher.VerifyDummy - not used") +} + +var _ outbound.PasswordHasher = (*countingHasher)(nil) + +func TestHashNewPasswordRefusesAnOversizedPasswordBeforeHashing(t *testing.T) { + const marker = "do-not-log-this-password-" + tests := map[string]string{ + "129 code points": marker + strings.Repeat("x", 129-len(marker)), + "over the raw byte cap": marker + strings.Repeat("\U0001F600", 200), + "one megabyte": marker + strings.Repeat("y", 1<<20), + "too long after normalization": marker + strings.Repeat("fi", 60), + } + for name, raw := range tests { + hasher := &countingHasher{} + var logs bytes.Buffer + // The handling boundary logs the error as an HTTP handler would. + logger := slog.New(slog.NewJSONHandler(&logs, nil)) + + _, err := NewCredentials(hasher).HashNewPassword(context.Background(), raw) + logger.Error("registration refused", "error", err) + + if !errors.Is(err, domain.ErrInvalidPassword) { + t.Fatalf("HashNewPassword(%s) error = %v, want ErrInvalidPassword", name, err) + } + if hasher.hashCalls != 0 { + t.Fatalf("HashNewPassword(%s) called the hasher %d times, want none", name, hasher.hashCalls) + } + if strings.Contains(logs.String(), marker) || strings.Contains(err.Error(), marker) { + t.Fatalf("HashNewPassword(%s) exposed the input in the error or the log: %s", name, logs.String()) + } + } +} + +func TestHashNewPasswordRefusesAShortPasswordBeforeHashing(t *testing.T) { + hasher := &countingHasher{} + _, err := NewCredentials(hasher).HashNewPassword(context.Background(), "fourteen chars") + if !errors.Is(err, domain.ErrInvalidPassword) || hasher.hashCalls != 0 { + t.Fatalf("HashNewPassword(14 code points) = %v after %d hash calls, want ErrInvalidPassword and no call", err, hasher.hashCalls) + } +} + +func TestHashNewPasswordHashesTheNormalizedPassword(t *testing.T) { + hasher := &countingHasher{} + if _, err := NewCredentials(hasher).HashNewPassword(context.Background(), "correct horse battery"); err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + if hasher.hashCalls != 1 || hasher.hashed.Reveal() != "correct horse battery" { + t.Fatalf("hasher received %d calls, want one with the NFKC form", hasher.hashCalls) + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 89945cf..5a5857a 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -197,6 +197,12 @@ services: SMTP_USERNAME: ${SMTP_USERNAME:-} SMTP_PASSWORD: ${SMTP_PASSWORD:-} SMTP_TLS_MODE: ${SMTP_TLS_MODE:-} + # Argon2id derivations that may run at once, 64 MiB each (1 to 4). + PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-1} + # Soft Go heap limit at about 78% of the 768M container limit below; the + # rest covers goroutine stacks, runtime metadata, and non-heap memory. + # Change both together. + GOMEMLIMIT: 600MiB depends_on: postgres: condition: service_healthy diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index a3d946c..dafdbb1 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -122,7 +122,8 @@ backend/ domain/ flat package; DomainEvent, identity types usecase/health/ operational readiness usecase port/inbound/ readiness input boundary - port/outbound/ readiness, cache, object storage, transaction, outbox, identity, and mail boundaries + usecase/identity/ password validation before hashing (Credentials) + port/outbound/ readiness, cache, object storage, transaction, outbox, identity, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler middleware/ request metrics @@ -130,6 +131,7 @@ backend/ v1/ handwritten health endpoint router.go chi composition adapter/secondary/ + argon2id/ Argon2id password hasher with a memory budget mail/disabled/ mail transport that sends nothing and reports the channel unavailable ml/api/ generated client from backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, outbox writer, identity repositories, health check @@ -143,11 +145,11 @@ backend/ pkg/ reserved for justified shared technical helpers ``` -Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`. +Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. @@ -268,6 +270,19 @@ What the ports guarantee: - Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. - Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent. +### Password hashing + +Implemented (TASK-052) and tested, but not wired into bootstrap: registration (TASK-053) and login (TASK-055) will create the hasher from configuration and call it. + +- `domain.Password` holds the password normalized to Unicode NFKC. `domain.NewPassword` applies the registration policy, 15 to 128 code points after normalization; `domain.ParseLoginPassword` accepts 1 to 128. Before normalizing, both reject raw input over 512 bytes (128 code points of at most 4 UTF-8 bytes, so every value the contract schema accepts fits) and invalid UTF-8. These checks run before any hashing and fail with `domain.ErrInvalidPassword`, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check. +- The `outbound.PasswordHasher` port (`port/outbound/password.go`) has `Hash`, `Verify`, and `VerifyDummy`; the `adapter/secondary/argon2id` adapter implements it with `golang.org/x/crypto/argon2`. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as `$argon2id$v=19$m=65536,t=3,p=4$$` in unpadded base64, the format that `domain.NewPasswordHash` and the `users_password_hash_format` CHECK accept. One hash took about 26 to 33 ms on an Apple M5 development machine (`BenchmarkHashRecommendedParameters`, also with one CPU); this is not a production latency figure. +- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; request rate limiting comes with the HTTP operations. +- `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones, so a login can store a new hash. +- `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login will call it for an unknown email, so both branches parse, wait for memory, derive, and compare alike. +- Login (TASK-055) must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it. +- `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration will call it on every branch before it looks up the email. +- Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index f4acea1..494c981 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -62,6 +62,8 @@ The Compose health check runs `kafka-broker-api-versions.sh` against `localhost: The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The backend has no Kafka client yet: it does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue. +`PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login will use it once they are implemented. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). + down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. ## Mail diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index ff97aa8..6d1bed2 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -48,7 +48,7 @@ The repository contains a verifiable technical scaffold, not a product. Values b What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail. -- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. A generated Go client for the ML contract exists but is not wired into bootstrap. +- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, and sqlc-backed identity repositories for accounts, email tokens, and sessions; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap. - Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has a home page, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). @@ -56,7 +56,7 @@ What exists now: - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, and the required `aggregate` result. See [TESTING.md](TESTING.md) for sharding. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table and the identity storage tables (`users`, `email_tokens`, `sessions`) and no other business schema; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, the Go Kafka client, the outbox relay, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table and the identity storage tables (`users`, `email_tokens`, `sessions`) and no other business schema; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing pieces contain only placeholders, and `make -C deploy test-e2e` is a deferred placeholder that exits with an error. The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop @@ -166,6 +166,8 @@ Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, an The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage). +Passwords enter the backend only as `domain.Password`: `domain.NewPassword` for a new password (15 to 128 code points after NFKC) and `domain.ParseLoginPassword` at login (1 to 128). Raw input over 512 bytes or with invalid UTF-8 is rejected before normalization, and every length check runs before hashing. The `argon2id` adapter implements `outbound.PasswordHasher` with m=65536 KiB, t=3, p=4, a memory budget of `PASSWORD_HASH_CONCURRENCY` derivations (1 to 4; unset means the smaller of 2 and GOMAXPROCS), `ErrPasswordMismatch` for a wrong password, `ErrPasswordHashCorrupt` for a malformed or out-of-bounds stored hash, a `needsRehash` result for older parameters, and `VerifyDummy` for unknown accounts. A stored hash that fails parsing or bounds wraps both `ErrPasswordHashCorrupt` and `domain.ErrInvalidPasswordHash`. Unit tests use cheap parameters; the 64 MiB reference vector is skipped with `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` in `backend/` measures one hash with the production parameters. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). + ## Go readability - Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index bdc3ba8..706144c 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -122,7 +122,8 @@ backend/ domain/ плоский пакет; DomainEvent, типы identity usecase/health/ operational readiness usecase port/inbound/ inbound граница readiness - port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity и почты + usecase/identity/ проверка пароля до хеширования (Credentials) + port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, хеширования паролей и почты adapter/primary/http/ api/ generated ogen handler middleware/ метрики запросов @@ -130,6 +131,7 @@ backend/ v1/ написанный вручную health endpoint router.go сборка chi router adapter/secondary/ + argon2id/ hasher паролей Argon2id с бюджетом памяти mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала ml/api/ generated client из backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, запись outbox, репозитории identity, health check @@ -143,11 +145,11 @@ backend/ pkg/ резерв для обоснованных общих технических helpers ``` -Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`. +Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. `domain/`, продуктовые `usecase/`, адаптеры Resend, SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -268,6 +270,19 @@ contact_grant относится к паре кандидат-компания - Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки. - Порядок блокировок: операция, которая меняет и аккаунт, и его токены, сначала блокирует токены. Подтверждение гасит токен, а затем подтверждает аккаунт, поэтому повторная регистрация или повторная отправка вызывает `InvalidateActive` до обновления аккаунта или вставки токена; обратный порядок может привести к взаимной блокировке. Единственное исключение - очистка: она блокирует аккаунт раньше токенов и сессий, и это безопасно, потому что каждая из этих блокировок берется с SKIP LOCKED и никогда не ждет. Если взаимная блокировка (SQLSTATE 40P01) или ошибка сериализации (40001) все же случится, `Transactor.WithinTransaction` и репозитории identity сообщают ее как `outbound.ErrTransactionConflict`; ничего не зафиксировано, и usecase или job может повторить всю операцию с паузой, оставаясь идемпотентным. +### Хеширование паролей + +Реализовано (TASK-052) и покрыто тестами, но в bootstrap не подключено: регистрация (TASK-053) и вход (TASK-055) будут создавать hasher из конфигурации и вызывать его. + +- `domain.Password` хранит пароль, нормализованный в Unicode NFKC. `domain.NewPassword` применяет политику регистрации: от 15 до 128 кодовых точек после нормализации; `domain.ParseLoginPassword` принимает от 1 до 128. До нормализации оба отклоняют исходный ввод длиннее 512 байт (128 кодовых точек по 4 байта UTF-8 максимум, поэтому любое значение, принятое схемой контракта, помещается) и некорректный UTF-8. Эти проверки выполняются до любого хеширования и завершаются `domain.ErrInvalidPassword` с названием правила, но без значения. Blocklist распространенных и утекших паролей - отдельная запланированная проверка. +- Порт `outbound.PasswordHasher` (`port/outbound/password.go`) содержит `Hash`, `Verify` и `VerifyDummy`; адаптер `adapter/secondary/argon2id` реализует его через `golang.org/x/crypto/argon2`. Новые хеши используют Argon2id v19 с m=65536 KiB, t=3, p=4 (второй рекомендованный вариант RFC 9106, выше базового уровня OWASP 19 MiB, t=2, p=1), соль 16 байт из crypto/rand и ключ 32 байта в формате `$argon2id$v=19$m=65536,t=3,p=4$$` в base64 без дополнения - этот формат принимают `domain.NewPasswordHash` и CHECK `users_password_hash_format`. Один хеш занял примерно 26-33 ms на машине разработчика Apple M5 (`BenchmarkHashRecommendedParameters`, в том числе на одном CPU); это не измерение задержки в production. +- Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; ограничение частоты запросов появится вместе с HTTP-операциями. +- `Verify` строго разбирает сохраненную строку PHC, заново вычисляет ключ с сохраненными параметрами, солью и длиной ключа и сравнивает за постоянное время. Неверный пароль возвращает `outbound.ErrPasswordMismatch`. Некорректный хеш или хеш вне границ для сохраненных значений (память от 8 KiB на lane до 128 MiB и в пределах бюджета хеширования, от 1 до 16 проходов, от 1 до 16 lanes, соль 8-64 байта, digest 16-64 байта) возвращает `outbound.ErrPasswordHashCorrupt` без вычисления, поэтому подделанная строка не может потребовать неограниченную память или время. `ErrPasswordHashCorrupt` оборачивает `domain.ErrInvalidPasswordHash`, который репозиторий возвращает для сохраненного хеша, не прошедшего `domain.NewPasswordHash`. При совпадении `needsRehash` сообщает, что параметры, соль или длина ключа отличаются от текущих, и вход может сохранить новый хеш. +- `VerifyDummy` выполняет `Verify` для хеша с текущими параметрами, случайной солью и случайным digest и возвращает `ErrPasswordMismatch` (или ошибку контекста). Вход будет вызывать его для неизвестного email, поэтому обе ветки одинаково разбирают хеш, ждут память, вычисляют и сравнивают. +- Вход (TASK-055) должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует. +- `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация будет вызывать его в каждой ветке до поиска email. +- Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index f810b1f..561a701 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -64,6 +64,8 @@ Compose healthcheck запускает `kafka-broker-api-versions.sh` проти Backend получает `KAFKA_BROKERS` - список адресов bootstrap в формате `host:port` через запятую. Compose задает `kafka:9092`; прямой запуск Go по умолчанию использует `localhost:9092`. Явно пустое значение, пустой элемент списка, отсутствующий или нулевой порт либо схема URL приводят к ошибке конфигурации. Kafka клиента в backend пока нет: backend не ждет Kafka при старте, а `/readyz` ее не проверяет. Объявленный адрес `kafka:9092` разрешается только внутри Compose сети, поэтому для прямого запуска нужен отдельно доступный брокер. Redis остается кешем и не используется как очередь. +`PASSWORD_HASH_CONCURRENCY` задает бюджет памяти Argon2id в вычислениях по 64 MiB и четыре lanes каждое (от 1 до 4). Compose передает значение из `.env`, по умолчанию 1, потому что у backend-контейнера 1 CPU и 768 MB: второе вычисление только добавило бы 64 MiB, деля тот же CPU. Backend, запущенный напрямую без переменной, берет меньшее из 2 и GOMAXPROCS. Следующие регистрации и входы ждут память, пока не завершится контекст запроса. Compose также задает `GOMEMLIMIT=600MiB`, примерно 78% лимита контейнера, чтобы сборщик Go освобождал память завершенных вычислений раньше, чем контейнеру ее не хватит; меняйте его вместе с лимитом памяти. Значение читается и проверяется при старте; регистрация и вход начнут его использовать, когда будут реализованы. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей). + down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. ## Почта diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index f1ff49e..26859c0 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -48,7 +48,7 @@ Frontend зависимости выбираются из актуальных s Что есть сейчас: - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет. -- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Generated Go client для ML контракта есть, но в bootstrap не подключен. +- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox и репозитории identity на sqlc для аккаунтов, email-токенов и сессий; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен. - Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть домашняя страница, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). @@ -56,7 +56,7 @@ Frontend зависимости выбираются из актуальных s - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke` и обязательный итог `aggregate`. Шардирование описано в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox и таблицы хранения identity (`users`, `email_tokens`, `sessions`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, Go клиент Kafka, relay для outbox, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox и таблицы хранения identity (`users`, `email_tokens`, `sessions`), другой бизнес-схемы нет; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей, содержат только заглушки, а `make -C deploy test-e2e` остается отложенной заглушкой и завершается ошибкой. Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -166,6 +166,8 @@ goose выполняет каждую миграцию в отдельной т База данных никогда не получает пароль, исходный email-токен или исходный токен сессии. Репозитории принимают `domain.PasswordHash` (строку PHC Argon2id v19) и `domain.SecretTokenHash` (SHA-256 от `domain.SecretToken`). Email-адреса пока принимаются только в ASCII; поддержка IDN и SMTPUTF8 - будущая работа, для которой нужен IDNA ToASCII для домена. `SecretToken`, `PasswordHash` и `EmailAddress` скрывают значение в выводе `fmt` и `slog`; `SecretToken.Reveal` и `EmailAddress.Address` возвращают настоящие значения там, где они нужны. Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, а PostgreSQL хранит микросекунды. Взаимная блокировка или ошибка сериализации сообщается как `outbound.ErrTransactionConflict`, и вызывающий код может повторить всю операцию. Схема и принятые решения описаны в [ARCHITECTURE.md](ARCHITECTURE.md#хранение-identity). +Пароль попадает в backend только как `domain.Password`: `domain.NewPassword` для нового пароля (от 15 до 128 кодовых точек после NFKC) и `domain.ParseLoginPassword` при входе (от 1 до 128). Исходный ввод длиннее 512 байт или с некорректным UTF-8 отклоняется до нормализации, и все проверки длины выполняются до хеширования. Адаптер `argon2id` реализует `outbound.PasswordHasher` с m=65536 KiB, t=3, p=4, бюджетом памяти на `PASSWORD_HASH_CONCURRENCY` вычислений (от 1 до 4; без значения - меньшее из 2 и GOMAXPROCS), `ErrPasswordMismatch` для неверного пароля, `ErrPasswordHashCorrupt` для некорректного или выходящего за границы сохраненного хеша, результатом `needsRehash` для старых параметров и `VerifyDummy` для неизвестных аккаунтов. Сохраненный хеш, не прошедший разбор или границы, оборачивает и `ErrPasswordHashCorrupt`, и `domain.ErrInvalidPasswordHash`. Unit-тесты используют дешевые параметры; эталонный вектор на 64 MiB пропускается с `-short`; `go test -run '^$' -bench . ./internal/adapter/secondary/argon2id/` в `backend/` измеряет один хеш с production-параметрами. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна.