330 lines
13 KiB
Go
330 lines
13 KiB
Go
// Package demoseed implements the local operator command of the isolated
|
|
// demonstration stand: it seeds the synthetic demo world, checks whether the
|
|
// stand's database may be discarded by a reset, and prints an inventory of
|
|
// counts. Every subcommand requires DEMO_MODE=isolated, and the command never
|
|
// deletes anything; the reset itself is a deploy target that discards the
|
|
// dedicated demo Compose project after this check.
|
|
package demoseed
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"lincodex/backend/config"
|
|
"lincodex/backend/internal/adapter/secondary/argon2id"
|
|
"lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/assessment"
|
|
"lincodex/backend/internal/usecase/candidateprivacy"
|
|
"lincodex/backend/internal/usecase/consent"
|
|
seedusecase "lincodex/backend/internal/usecase/demoseed"
|
|
"lincodex/backend/internal/usecase/identity"
|
|
"lincodex/backend/internal/usecase/profile"
|
|
"lincodex/backend/internal/usecase/questionnaire"
|
|
)
|
|
|
|
const (
|
|
usage = "usage: demo-seed seed --actor operator:<handle> | demo-seed check-reset | demo-seed inventory"
|
|
|
|
// DemoModeName and IsolatedDemoMode are the explicit guard of the command.
|
|
DemoModeName = "DEMO_MODE"
|
|
IsolatedDemoMode = "isolated"
|
|
// PasswordName holds the shared password of the synthetic accounts. It
|
|
// comes from the demo env file and is never printed.
|
|
PasswordName = "DEMO_ACCOUNT_PASSWORD" //nolint:gosec // The name of an environment variable, not a credential.
|
|
|
|
// poolSize covers the seed's sequential transactions and the nested
|
|
// reads of the services it drives.
|
|
poolSize = 4
|
|
// hashConcurrency is one Argon2id derivation at a time; the seed creates a
|
|
// handful of accounts once.
|
|
hashConcurrency = 1
|
|
// ephemeralKeyBytes is the size of the per-run idempotency secret. The
|
|
// seed is idempotent by the state it reads, so its idempotency records
|
|
// need no key shared with the backend.
|
|
ephemeralKeyBytes = 48
|
|
)
|
|
|
|
const syntheticWarning = "warning: synthetic demonstration data for an isolated demo stand only; never on a stand with real people\n"
|
|
|
|
// Subcommand names one action.
|
|
type Subcommand string
|
|
|
|
const (
|
|
SubcommandSeed Subcommand = "seed"
|
|
SubcommandCheckReset Subcommand = "check-reset"
|
|
SubcommandInventory Subcommand = "inventory"
|
|
)
|
|
|
|
// Command is a parsed, validated request.
|
|
type Command struct {
|
|
Subcommand Subcommand
|
|
Actor domain.AssessmentOperator
|
|
}
|
|
|
|
// Parse validates every argument before Run reads configuration or connects.
|
|
func Parse(args []string) (Command, error) {
|
|
if len(args) == 0 {
|
|
return Command{}, errors.New(usage)
|
|
}
|
|
switch Subcommand(args[0]) {
|
|
case SubcommandCheckReset, SubcommandInventory:
|
|
if len(args) != 1 {
|
|
return Command{}, errors.New(usage)
|
|
}
|
|
return Command{Subcommand: Subcommand(args[0])}, nil
|
|
case SubcommandSeed:
|
|
default:
|
|
return Command{}, errors.New(usage)
|
|
}
|
|
flags := flag.NewFlagSet("demo-seed seed", flag.ContinueOnError)
|
|
flags.SetOutput(io.Discard)
|
|
actor := flags.String("actor", "", "operator handle")
|
|
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
|
return Command{}, errors.New(usage)
|
|
}
|
|
operator, err := domain.ParseAssessmentOperator(strings.TrimSpace(*actor))
|
|
if err != nil {
|
|
return Command{}, errors.New("actor must be operator:<handle>")
|
|
}
|
|
return Command{Subcommand: SubcommandSeed, Actor: operator}, nil
|
|
}
|
|
|
|
// settings are the validated environment values of one run.
|
|
type settings struct {
|
|
databaseURL string
|
|
password domain.Password
|
|
}
|
|
|
|
// readSettings checks the demo mode guard, DATABASE_URL, and, for the seed,
|
|
// the account password, all before any connection. It loads no dotenv file.
|
|
func readSettings(command Command, lookup config.LookupEnv) (settings, error) {
|
|
mode, _ := lookup(DemoModeName)
|
|
if strings.TrimSpace(mode) != IsolatedDemoMode {
|
|
return settings{}, errors.New("DEMO_MODE=isolated is required; the demo seed runs only on an isolated demo stand")
|
|
}
|
|
databaseURL := config.DatabaseURLFromEnv(lookup)
|
|
if databaseURL == "" {
|
|
return settings{}, errors.New("DATABASE_URL is not set")
|
|
}
|
|
result := settings{databaseURL: databaseURL}
|
|
if command.Subcommand != SubcommandSeed {
|
|
return result, nil
|
|
}
|
|
raw, _ := lookup(PasswordName)
|
|
password, err := domain.NewPassword(raw)
|
|
if err != nil {
|
|
return settings{}, fmt.Errorf("%s must be a password of at least %d characters", PasswordName, domain.MinNewPasswordCodePoints)
|
|
}
|
|
result.password = password
|
|
return result, nil
|
|
}
|
|
|
|
// Run parses the command, validates the environment, connects, and executes.
|
|
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
|
|
command, err := Parse(args)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if lookup == nil || output == nil || clock == nil {
|
|
return errors.New("demo seed command dependencies are required")
|
|
}
|
|
values, err := readSettings(command, lookup)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := io.WriteString(output, syntheticWarning); err != nil {
|
|
return errors.New("could not write the result")
|
|
}
|
|
pool, err := postgres.NewSizedPool(ctx, values.databaseURL, poolSize)
|
|
if err != nil {
|
|
return errors.New("database configuration is invalid")
|
|
}
|
|
defer pool.Close()
|
|
if err := pool.Ping(ctx); err != nil {
|
|
return errors.New("database is unavailable")
|
|
}
|
|
store := postgres.NewDemoSeedStore(pool)
|
|
inspector, err := seedusecase.NewInspector(store)
|
|
if err != nil {
|
|
return errors.New("demo seed is unavailable")
|
|
}
|
|
switch command.Subcommand {
|
|
case SubcommandCheckReset:
|
|
return ExecuteCheckReset(ctx, inspector, output)
|
|
case SubcommandInventory:
|
|
return ExecuteInventory(ctx, inspector, output)
|
|
case SubcommandSeed:
|
|
seeder, err := newSeeder(pool, store, clock)
|
|
if err != nil {
|
|
return errors.New("demo seed is unavailable")
|
|
}
|
|
return ExecuteSeed(ctx, seeder, seedusecase.Input{Actor: command.Actor, Password: values.password}, output)
|
|
}
|
|
return errors.New(usage)
|
|
}
|
|
|
|
// newSeeder wires the product services the seed drives. Synthetic category
|
|
// assignment is on because the command runs only with DEMO_MODE=isolated.
|
|
func newSeeder(pool *pgxpool.Pool, store outbound.DemoSeedStore, clock func() time.Time) (*seedusecase.Seeder, error) {
|
|
transactor := postgres.NewTransactor(pool)
|
|
hasher, err := argon2id.NewHasher(hashConcurrency)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("demoseed.newSeeder - create hasher: %w", err)
|
|
}
|
|
secret := make([]byte, ephemeralKeyBytes)
|
|
if _, err := rand.Read(secret); err != nil {
|
|
return nil, fmt.Errorf("demoseed.newSeeder - draw idempotency secret: %w", err)
|
|
}
|
|
keyring, err := identity.NewKeyring(secret)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("demoseed.newSeeder - create keyring: %w", err)
|
|
}
|
|
attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock,
|
|
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("demoseed.newSeeder - create attempt service: %w", err)
|
|
}
|
|
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("demoseed.newSeeder - create privacy service: %w", err)
|
|
}
|
|
attestor, err := assessment.NewCategoryAttestor(transactor)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("demoseed.newSeeder - create attestor: %w", err)
|
|
}
|
|
return seedusecase.NewSeeder(seedusecase.Dependencies{
|
|
Transactor: transactor, Store: store, Hasher: hasher,
|
|
Consents: consent.NewService(transactor, clock),
|
|
Profiles: profile.NewService(transactor, clock),
|
|
Questionnaires: questionnaire.NewService(transactor, clock),
|
|
Privacy: privacy, Attempts: attempts,
|
|
Bank: assessment.NewBank(transactor), Attestor: attestor, Clock: clock,
|
|
})
|
|
}
|
|
|
|
// Seeder runs the seed.
|
|
type Seeder interface {
|
|
Seed(ctx context.Context, input seedusecase.Input) (seedusecase.Report, error)
|
|
}
|
|
|
|
// ExecuteSeed seeds and prints what was created, the logins, and the
|
|
// prepared attempts. It prints synthetic addresses and identifiers only; the
|
|
// password stays in the demo env file.
|
|
func ExecuteSeed(ctx context.Context, seeder Seeder, input seedusecase.Input, output io.Writer) error {
|
|
if seeder == nil || output == nil {
|
|
return errors.New("demo seed command dependencies are required")
|
|
}
|
|
report, err := seeder.Seed(ctx, input)
|
|
if err != nil {
|
|
return safeSeedError(err)
|
|
}
|
|
var text strings.Builder
|
|
fmt.Fprintf(&text, "seeded: product policy version %d; created %d records, found %d already present\n",
|
|
report.PolicyVersion, len(report.Created), len(report.Present))
|
|
for _, item := range report.Created {
|
|
fmt.Fprintf(&text, "created: %s\n", item)
|
|
}
|
|
for _, login := range report.Logins {
|
|
fmt.Fprintf(&text, "login: %s (%s)\n", login.Email, login.Role)
|
|
}
|
|
text.WriteString("password: the " + PasswordName + " value of the demo env file; it is not printed\n")
|
|
for _, prepared := range report.PreparedAttempts {
|
|
fmt.Fprintf(&text, "prepared full attempt: %s of %s\n", prepared.AttemptID, prepared.Email)
|
|
}
|
|
text.WriteString("note: the prepared attempts were answered by the seed through the ordinary attempt operations; " +
|
|
"they are synthetic and no person took them. The express mode has its own policy section and bank and never assigns a category.\n")
|
|
if _, err := io.WriteString(output, text.String()); err != nil {
|
|
return errors.New("could not write the result")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func safeSeedError(err error) error {
|
|
switch {
|
|
case errors.Is(err, seedusecase.ErrStandNotFresh):
|
|
return errors.New("the stand holds ordinary accounts and was never seeded; seed only a fresh isolated demo stand")
|
|
case errors.Is(err, seedusecase.ErrForeignPolicy):
|
|
return errors.New("the product policy is neither the initial demo version nor the seeded one; seed only a fresh isolated demo stand")
|
|
case errors.Is(err, seedusecase.ErrAccountConflict):
|
|
return errors.New("a demo address belongs to an account the seed did not create; reset the isolated demo stand")
|
|
case errors.Is(err, seedusecase.ErrPreparedAttemptFailed):
|
|
return errors.New("a prepared attempt did not assign its demonstration category; reset the isolated demo stand")
|
|
case errors.Is(err, outbound.ErrPolicyVersionNotFound):
|
|
return errors.New("the product policy has no version yet; start the backend once so that it seeds the demo policy")
|
|
default:
|
|
return errors.New("demo seed failed")
|
|
}
|
|
}
|
|
|
|
// Inspector reads the census and the inventory.
|
|
type Inspector interface {
|
|
CheckReset(ctx context.Context) (seedusecase.ResetCheck, error)
|
|
Inventory(ctx context.Context) (outbound.DemoInventory, error)
|
|
}
|
|
|
|
// ExecuteCheckReset prints the verdict and fails when the database holds an
|
|
// account outside the synthetic domain, so the reset target stops before it
|
|
// discards anything.
|
|
func ExecuteCheckReset(ctx context.Context, inspector Inspector, output io.Writer) error {
|
|
if inspector == nil || output == nil {
|
|
return errors.New("demo seed command dependencies are required")
|
|
}
|
|
check, err := inspector.CheckReset(ctx)
|
|
if err != nil {
|
|
return errors.New("reset check failed")
|
|
}
|
|
if !check.Verdict.Allowed() {
|
|
return fmt.Errorf("reset refused: the stand holds %d accounts outside @%s; the reset never deletes ordinary data",
|
|
check.Census.Ordinary(), seedusecase.SyntheticDomain)
|
|
}
|
|
if _, err := fmt.Fprintf(output, "reset allowed (%s): %d accounts, all on @%s\n",
|
|
check.Verdict, check.Census.Total, seedusecase.SyntheticDomain); err != nil {
|
|
return errors.New("could not write the result")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ExecuteInventory prints stable key=value counts, so two runs can be
|
|
// compared line by line.
|
|
func ExecuteInventory(ctx context.Context, inspector Inspector, output io.Writer) error {
|
|
if inspector == nil || output == nil {
|
|
return errors.New("demo seed command dependencies are required")
|
|
}
|
|
inventory, err := inspector.Inventory(ctx)
|
|
if err != nil {
|
|
return errors.New("inventory failed")
|
|
}
|
|
lines := []struct {
|
|
name string
|
|
value int64
|
|
}{
|
|
{"synthetic_accounts", inventory.SyntheticAccounts}, {"verified_synthetic_accounts", inventory.VerifiedSynthetic},
|
|
{"ordinary_accounts", inventory.OrdinaryAccounts}, {"organizations", inventory.Organizations},
|
|
{"memberships", inventory.Memberships}, {"consent_records", inventory.ConsentRecords},
|
|
{"candidate_profiles", inventory.CandidateProfiles}, {"questionnaires", inventory.Questionnaires},
|
|
{"attempts", inventory.Attempts}, {"attempt_results", inventory.AttemptResults},
|
|
{"current_categories", inventory.CurrentCategories}, {"evidence_facts", inventory.EvidenceFacts},
|
|
{"published_cards", inventory.PublishedCards}, {"product_policy_versions", inventory.ProductPolicyVersions},
|
|
{"published_families", inventory.PublishedFamilies}, {"category_openings", inventory.CategoryOpenings},
|
|
{"category_attestations", inventory.CategoryAttestations}, {"training_bindings", inventory.TrainingBindings},
|
|
}
|
|
var text strings.Builder
|
|
for _, line := range lines {
|
|
fmt.Fprintf(&text, "%s=%d\n", line.name, line.value)
|
|
}
|
|
if _, err := io.WriteString(output, text.String()); err != nil {
|
|
return errors.New("could not write the result")
|
|
}
|
|
return nil
|
|
}
|