package bootstrap import ( "context" "crypto/rand" "fmt" "log/slog" "net/netip" "time" "lincodex/backend/config" "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/argon2id" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" redisadapter "lincodex/backend/internal/adapter/secondary/redis" "lincodex/backend/internal/domain" "lincodex/backend/internal/usecase/consent" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/notification" "lincodex/backend/internal/usecase/notification/mailtemplate" ) // identityPoolMaxConns bounds the connections of the registration requests: // each holds one for a short transaction, after the password hash is done. const identityPoolMaxConns = 8 // newTrustedProxies hands the configured reverse proxies to the router. func newTrustedProxies(settings config.Config) []netip.Prefix { return settings.TrustedProxyCIDRs } // newAPIHandler composes the handler of the public API from the business // areas that are built. An area without a handler answers 501. func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identityHandler *v1.IdentityHandler) *v1.Handler { return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler)) } // newIdentityHandler builds the registration operations and the PostgreSQL // pool they own. Nothing connects here, so an unavailable database never // blocks startup. It returns no handler when DATABASE_URL is unset, and the // operations then answer 501. The application clock is time.Now. func newIdentityHandler( ctx context.Context, settings config.Config, logger *slog.Logger, cache *redisadapter.Cache, metrics *prometheus.Metrics, ) (*v1.IdentityHandler, func(), error) { if settings.DatabaseURL == "" { logger.Warn("registration is not served because DATABASE_URL is not set") return nil, func() {}, nil } keyring, err := newIdentityKeyring(settings, logger) if err != nil { return nil, nil, err } renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create mail renderer: %w", err) } // New deliveries are pinned to the transport and account configured now. account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - mail provider account: %w", err) } hasher, err := argon2id.NewHasher(settings.PasswordHashConcurrency) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create password hasher: %w", err) } pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, identityPoolMaxConns) if err != nil { return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create pool: %w", err) } transactor := postgres.NewTransactor(pool) store := postgres.NewIdentityStore(pool) credentials := identity.NewCredentials(hasher) registration, err := identity.NewRegistration(identity.RegistrationDependencies{ Transactor: transactor, ConsentTexts: postgres.NewConsentStore(pool), Idempotency: store.IdempotencyRecords(), Consents: consent.NewService(transactor, time.Now), Credentials: credentials, Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, time.Now), Limiter: cache, Keyring: keyring, Clock: time.Now, Metrics: metrics, }, identity.RegistrationSettings{ MailMinInterval: settings.VerificationMailMinInterval, MailDailyLimit: int64(settings.VerificationMailDailyLimit), ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit), }) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create registration: %w", err) } confirmation, err := identity.NewEmailConfirmation(identity.ConfirmationDependencies{ Transactor: transactor, Tokens: store.EmailTokens(), Credentials: credentials, Limiter: cache, Keyring: keyring, Clock: time.Now, Metrics: metrics, }, identity.ConfirmationSettings{ TokenHourlyLimit: identity.DefaultTokenHourlyLimit, ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit), }) if err != nil { pool.Close() return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create confirmation: %w", err) } // The HTTP server stops before this cleanup runs, so no request uses the // pool while it closes. return v1.NewIdentityHandler(registration, v1.WithEmailConfirmation(confirmation, settings.AppPublicURL)), pool.Close, nil } // newIdentityKeyring keys the idempotency scopes and rate limit buckets with // IDENTITY_KEY_SECRET. Only with IDENTITY_ALLOW_EPHEMERAL_KEY, which the // configuration check demands for an unset secret, a random one is drawn for // this process: idempotency records and counters written before a restart no // longer match, and instances of one deployment do not agree. func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) { secret := []byte(settings.IdentityKeySecret) if len(secret) == 0 { secret = make([]byte, identity.MinKeySecretBytes) if _, err := rand.Read(secret); err != nil { return nil, fmt.Errorf("bootstrap.newIdentityKeyring - generate secret: %w", err) } logger.Warn("IDENTITY_ALLOW_EPHEMERAL_KEY is set and IDENTITY_KEY_SECRET is not; a random secret is used, so idempotency records and rate limits do not survive a restart") } keyring, err := identity.NewKeyring(secret) if err != nil { return nil, fmt.Errorf("bootstrap.newIdentityKeyring - create keyring: %w", err) } return keyring, nil }