//go:build integration package integration_test import ( "bytes" "context" "encoding/json" "fmt" "net/http" "strconv" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/adapter/primary/cli/demoseed" "lincodex/backend/internal/adapter/secondary/argon2id" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/anonymousprofile" "lincodex/backend/internal/usecase/assessment" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/companyquota" seedusecase "lincodex/backend/internal/usecase/demoseed" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/policy" ) const ( demoSeedTimeout = 4 * time.Minute demoSeedActor = "operator:demo-seed-test" demoSeedPassword = "synthetic demo stand password" // demoSeedKeySecret keys the in-test attempt and view services only. demoSeedKeySecret = "demo-seed-integration-key-secret-0123456789" ordinaryEmail = "visitor@example.test" ) // demoSeedStand is one isolated database with the startup policy seeded, as // a freshly started backend leaves it. type demoSeedStand struct { ctx context.Context pool *pgxpool.Pool databaseURL string } func newDemoSeedStand(ctx context.Context, t *testing.T, env *testEnvironment) demoSeedStand { t.Helper() databaseURL := env.createIsolatedDatabase(ctx, t) applyMigrations(ctx, t, databaseURL) pool := newPoolFor(ctx, t, databaseURL) if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { t.Fatalf("EnsureDemoProductPolicy() error = %v", err) } return demoSeedStand{ctx: ctx, pool: pool, databaseURL: databaseURL} } // run executes the operator command with the given environment overrides on // top of the stand's DATABASE_URL, the isolated mode, and the password. func (stand demoSeedStand) run(t *testing.T, overrides map[string]string, args ...string) (string, error) { t.Helper() environment := map[string]string{ "DATABASE_URL": stand.databaseURL, demoseed.DemoModeName: demoseed.IsolatedDemoMode, demoseed.PasswordName: demoSeedPassword, } for key, value := range overrides { if value == "" { delete(environment, key) continue } environment[key] = value } lookup := func(key string) (string, bool) { value, ok := environment[key] return value, ok } var output bytes.Buffer err := demoseed.Run(stand.ctx, args, lookup, &output, time.Now) return output.String(), err } func (stand demoSeedStand) inventory(t *testing.T) string { t.Helper() output, err := stand.run(t, nil, "inventory") if err != nil { t.Fatalf("inventory error = %v (output %q)", err, output) } return output } func (stand demoSeedStand) count(t *testing.T, query string, args ...any) int { t.Helper() var value int if err := stand.pool.QueryRow(stand.ctx, query, args...).Scan(&value); err != nil { t.Fatalf("count %q: %v", query, err) } return value } func (stand demoSeedStand) userID(t *testing.T, email string) uuid.UUID { t.Helper() var id uuid.UUID if err := stand.pool.QueryRow(stand.ctx, `SELECT id FROM users WHERE email_normalized = $1`, email).Scan(&id); err != nil { t.Fatalf("read account %s: %v", email, err) } return id } // createOrdinaryAccount stores an unconfirmed registration outside the // synthetic domain, the way a visitor's own sign-up leaves it. func (stand demoSeedStand) createOrdinaryAccount(t *testing.T) uuid.UUID { t.Helper() hasher, err := argon2id.NewHasher(1) if err != nil { t.Fatalf("NewHasher() error = %v", err) } password, err := domain.NewPassword("ordinary visitor password") if err != nil { t.Fatalf("NewPassword() error = %v", err) } hash, err := hasher.Hash(stand.ctx, password) if err != nil { t.Fatalf("Hash() error = %v", err) } address, err := domain.NewEmailAddress(ordinaryEmail) if err != nil { t.Fatalf("NewEmailAddress() error = %v", err) } user, err := domain.NewUser(domain.Registration{ Email: address, PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: time.Now().UTC().Truncate(time.Microsecond), }) if err != nil { t.Fatalf("NewUser() error = %v", err) } err = postgresadapter.NewTransactor(stand.pool).WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return unit.Users().Create(ctx, user) }) if err != nil { t.Fatalf("create ordinary account: %v", err) } return user.ID } func demoEmail(local string) string { return local + "@" + seedusecase.SyntheticDomain } func TestDemoSeedCommand(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), demoSeedTimeout) defer cancel() t.Run("refuses without the isolated mode before it connects", func(t *testing.T) { stand := newDemoSeedStand(ctx, t, env) for _, args := range [][]string{{"seed", "--actor", demoSeedActor}, {"check-reset"}, {"inventory"}} { for _, mode := range []string{"", "production", "Isolated"} { overrides := map[string]string{demoseed.DemoModeName: mode} if _, err := stand.run(t, overrides, args...); err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") { t.Errorf("%v with DEMO_MODE=%q error = %v, want the isolated mode refusal", args, mode, err) } } } // An unreachable database proves that the guard runs before connecting. if _, err := stand.run(t, map[string]string{demoseed.DemoModeName: "", "DATABASE_URL": "postgres://nobody@127.0.0.1:1/none"}, "check-reset"); err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") { t.Errorf("check-reset against an unreachable database error = %v, want the mode refusal first", err) } if _, err := stand.run(t, map[string]string{demoseed.PasswordName: "short"}, "seed", "--actor", demoSeedActor); err == nil || !strings.Contains(err.Error(), demoseed.PasswordName) { t.Errorf("seed with a short password error = %v, want a password refusal", err) } if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 0 { t.Fatalf("accounts after refusals = %d, want none", accounts) } if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 { t.Fatalf("policy versions after refusals = %d, want only the startup version", versions) } }) t.Run("refuses a stand with ordinary accounts that was never seeded", func(t *testing.T) { stand := newDemoSeedStand(ctx, t, env) visitor := stand.createOrdinaryAccount(t) if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err == nil || !strings.Contains(err.Error(), "never seeded") { t.Fatalf("seed over an ordinary account = %q, %v, want a refusal", output, err) } if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "never deletes ordinary data") { t.Fatalf("check-reset with an ordinary account = %q, %v, want a refusal", output, err) } if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 1 || stand.userID(t, ordinaryEmail) != visitor { t.Fatalf("accounts after the refused seed = %d, want only the visitor", accounts) } if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 { t.Fatalf("policy versions after the refused seed = %d, want the startup version only", versions) } }) t.Run("seeds once, repeats without change, and keeps ordinary data", func(t *testing.T) { stand := newDemoSeedStand(ctx, t, env) if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (empty)") { t.Fatalf("check-reset on an empty stand = %q, %v, want allowed", output, err) } first, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) if err != nil { t.Fatalf("first seed error = %v (output %q)", err, first) } if strings.Contains(first, demoSeedPassword) || !strings.Contains(first, "login: candidate@"+seedusecase.SyntheticDomain) || !strings.Contains(first, "prepared full attempt: ") || strings.Contains(first, "created 0 records") { t.Fatalf("first seed output = %q, want logins and prepared attempts without the password", first) } afterFirst := stand.inventory(t) for _, want := range []string{ "synthetic_accounts=9\n", "verified_synthetic_accounts=9\n", "ordinary_accounts=0\n", "organizations=2\n", "memberships=3\n", "candidate_profiles=7\n", "questionnaires=7\n", "attempts=6\n", "attempt_results=6\n", "current_categories=6\n", "published_cards=6\n", "product_policy_versions=2\n", "published_families=28\n", "category_openings=1\n", "category_attestations=1\n", "training_bindings=1\n", } { if !strings.Contains(afterFirst, want) { t.Errorf("inventory after the first seed lacks %q:\n%s", want, afterFirst) } } if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts < 6 { t.Errorf("evidence facts after the prepared attempts = %d, want the projection of six results", facts) } second, err := stand.run(t, nil, "seed", "--actor", "operator:another-operator") if err != nil || !strings.Contains(second, "created 0 records") { t.Fatalf("second seed = %q, %v, want nothing created", second, err) } if afterSecond := stand.inventory(t); afterSecond != afterFirst { t.Fatalf("inventory changed on the repeat:\nfirst:\n%s\nsecond:\n%s", afterFirst, afterSecond) } assertDemoSeedMarkers(t, stand) assertDemoSeedPermissions(t, stand) assertDemoSeedVisibleCohort(t, stand) assertExpressAssignsNoCategory(t, stand) if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (synthetic)") { t.Fatalf("check-reset on the seeded stand = %q, %v, want allowed", output, err) } visitor := stand.createOrdinaryAccount(t) if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "1 accounts outside") { t.Fatalf("check-reset with a visitor = %q, %v, want a refusal that counts one ordinary account", output, err) } // A repeat after a visitor registered is still a no-op and leaves the // visitor alone. if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err != nil || !strings.Contains(output, "created 0 records") { t.Fatalf("seed after a visitor = %q, %v, want nothing created", output, err) } if stand.userID(t, ordinaryEmail) != visitor { t.Fatal("the visitor account changed") } }) } // assertDemoSeedMarkers checks that every organization and profile of the seed // names itself as synthetic and that the categories come from the synthetic // demonstration source. func assertDemoSeedMarkers(t *testing.T, stand demoSeedStand) { t.Helper() if unmarked := stand.count(t, `SELECT count(*) FROM organizations WHERE name NOT LIKE '%(синтетические данные)'`); unmarked != 0 { t.Errorf("organizations without the synthetic marker = %d", unmarked) } if unmarked := stand.count(t, `SELECT count(*) FROM candidate_profiles AS profile WHERE NOT EXISTS ( SELECT 1 FROM candidate_profile_claims AS claim WHERE claim.user_id = profile.user_id AND claim.kind = 'full_name' AND claim.value::text LIKE '%синтетический профиль%')`); unmarked != 0 { t.Errorf("profiles without the synthetic marker in the name = %d", unmarked) } if prepared := stand.count(t, `SELECT count(DISTINCT user_id) FROM candidate_profile_claims WHERE kind = 'experience' AND value::text LIKE '%подготовлена командой demo-seed%'`); prepared != 6 { t.Errorf("profiles that label the prepared attempt = %d, want 6", prepared) } if other := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE source <> 'synthetic_demo' OR calibration_status <> 'uncalibrated'`); other != 0 { t.Errorf("categories outside the uncalibrated synthetic source = %d", other) } if outside := stand.count(t, `SELECT count(*) FROM users WHERE email_normalized NOT LIKE '%@' || $1`, seedusecase.SyntheticDomain); outside != 0 { t.Errorf("seeded accounts outside the synthetic domain = %d", outside) } } // assertDemoSeedPermissions checks the two organizations: each has its own // owner, and the owner of Alpha is only a recruiter of Beta. func assertDemoSeedPermissions(t *testing.T, stand demoSeedStand) { t.Helper() rows, err := stand.pool.Query(stand.ctx, ` SELECT split_part(users.email_normalized, '@', 1), organizations.name, memberships.role, memberships.state FROM memberships JOIN users ON users.id = memberships.user_id JOIN organizations ON organizations.id = memberships.organization_id ORDER BY 1, 2`) if err != nil { t.Fatalf("read memberships: %v", err) } defer rows.Close() var got []string for rows.Next() { var account, organization, role, state string if err := rows.Scan(&account, &organization, &role, &state); err != nil { t.Fatalf("scan membership: %v", err) } got = append(got, fmt.Sprintf("%s|%s|%s|%s", account, strings.Fields(organization)[1], role, state)) } want := []string{ "employer-alpha|«Альфа»|owner|active", "employer-alpha|«Бета»|recruiter|active", "employer-beta|«Бета»|owner|active", } if strings.Join(got, ",") != strings.Join(want, ",") { t.Fatalf("memberships = %v, want %v", got, want) } } func demoSeedKeyring(t *testing.T) *identity.Keyring { t.Helper() keyring, err := identity.NewKeyring([]byte(demoSeedKeySecret)) if err != nil { t.Fatalf("NewKeyring() error = %v", err) } return keyring } // assertDemoSeedVisibleCohort checks that the owner of Alpha sees the six // prepared cards, which pass the minimum cohort of five, and no card of the // self-service candidate, who did not publish. func assertDemoSeedVisibleCohort(t *testing.T, stand demoSeedStand) { t.Helper() key, err := demoSeedKeyring(t).CandidateViewPseudonymKey() if err != nil { t.Fatalf("CandidateViewPseudonymKey() error = %v", err) } transactor := postgresadapter.NewTransactor(stand.pool) quota := companyquota.NewService(time.Now) views, err := candidateview.NewService(candidateview.Dependencies{ Transactor: transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(stand.pool), key, time.Now), PseudonymKey: key, Clock: time.Now, Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveCardView(ctx, unit, organization, candidateID) }, }) if err != nil { t.Fatalf("candidateview.NewService() error = %v", err) } owner := stand.userID(t, demoEmail("employer-alpha")) var organizationID uuid.UUID if err := stand.pool.QueryRow(stand.ctx, `SELECT organization_id FROM memberships WHERE user_id = $1 AND role = 'owner'`, owner).Scan(&organizationID); err != nil { t.Fatalf("read Alpha: %v", err) } var cards []domain.VisibleCandidateCard err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error cards, err = views.ListVisibleCards(ctx, unit, owner, organizationID) return err }) if err != nil { t.Fatalf("ListVisibleCards() error = %v", err) } selfService := stand.userID(t, demoEmail("candidate")) if len(cards) != 6 { t.Fatalf("visible cards of Alpha = %d, want the six prepared candidates", len(cards)) } for _, card := range cards { if card.CandidateID == selfService { t.Fatal("the unpublished self-service candidate is visible") } } } // assertExpressAssignsNoCategory runs the express as the self-service // candidate through the ordinary attempt operations, then checks that it // created no category and no evidence, and that the full test still starts. func assertExpressAssignsNoCategory(t *testing.T, stand demoSeedStand) { t.Helper() transactor := postgresadapter.NewTransactor(stand.pool) attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, demoSeedKeyring(t), time.Now, assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) if err != nil { t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err) } candidateID := stand.userID(t, demoEmail("candidate")) factsBefore := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`) created, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{ ActorID: candidateID, IdempotencyKey: "express-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindDemoExpress, }) if err != nil || created.Outcome.StatusCode != http.StatusCreated { t.Fatalf("create express = %+v, %v", created.Outcome, err) } var express domain.AssessmentAttempt err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error express, err = unit.AssessmentAttempts().GetForCandidate(ctx, candidateID, created.Outcome.Response.ID) return err }) if err != nil { t.Fatalf("read express attempt: %v", err) } snapshot := express.Snapshot() if len(snapshot.Items) != 3 || snapshot.BankCategory != domain.AssessmentCategory(seedusecase.TrainingCategory) { t.Fatalf("express has %d items from %q, want 3 from the training category", len(snapshot.Items), snapshot.BankCategory) } version := snapshot.Version for _, item := range snapshot.Items { reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64) if err != nil { t.Fatalf("express reference answer %q: %v", item.Variant.ReferenceAnswer, err) } answer, err := json.Marshal(map[string]any{"format": "number", "number": reference}) if err != nil { t.Fatalf("marshal express answer: %v", err) } result, err := attempts.SubmitAnswer(stand.ctx, assessment.SubmitAttemptAnswerCommand{ ActorID: candidateID, AttemptID: express.ID(), ItemID: item.ID, ExpectedVersion: version, IdempotencyKey: "express-answer-" + uuid.NewString(), Answer: answer, }) if err != nil || result.Outcome.StatusCode != http.StatusOK { t.Fatalf("answer express item = %+v, %v", result.Outcome, err) } version = result.Outcome.Response.Version } finalized, err := attempts.FinalizeAttempt(stand.ctx, assessment.FinalizeAssessmentAttemptCommand{ ActorID: candidateID, AttemptID: express.ID(), ExpectedVersion: version, IdempotencyKey: "express-finalize-" + uuid.NewString(), }) if err != nil || finalized.Outcome.StatusCode != http.StatusOK { t.Fatalf("finalize express = %+v, %v", finalized.Outcome, err) } if categories := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id = $1`, candidateID); categories != 0 { t.Fatalf("categories after a perfect express = %d, want none", categories) } if outcome := stand.count(t, `SELECT count(*) FROM assessment_attempts WHERE id = $1 AND outcome = 'demonstration'`, express.ID().UUID()); outcome != 1 { t.Fatalf("express outcome rows = %d, want one demonstration outcome", outcome) } if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts != factsBefore { t.Fatalf("evidence facts after the express = %d, want %d", facts, factsBefore) } specialization, grade, language := domain.SpecializationBackend, domain.GradeJunior, domain.TaskLanguageGo full, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{ ActorID: candidateID, IdempotencyKey: "full-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindRoot, Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language, }) if err != nil || full.Outcome.StatusCode != http.StatusCreated { t.Fatalf("start the full test = %+v, %v, want a new attempt", full.Outcome, err) } }