feat(deploy): add an isolated demo stand with synthetic seed and guarded reset

This commit is contained in:
shira committed 2026-10-09 14:46:18 +03:00
1 parent bd23c839fd
commit e1df4ff77c
26 files changed
+3292 -2

No files matched your search

@@ -0,0 +1,329 @@
// 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
}
@@ -0,0 +1,175 @@
package demoseed
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
seedusecase "lincodex/backend/internal/usecase/demoseed"
)
func TestParseAcceptsOnlyTheThreeSubcommands(t *testing.T) {
command, err := Parse([]string{"seed", "--actor", "operator:night"})
if err != nil || command.Subcommand != SubcommandSeed || command.Actor != "operator:night" {
t.Fatalf("Parse(seed) = %+v, %v", command, err)
}
for _, args := range [][]string{{"check-reset"}, {"inventory"}} {
if command, err := Parse(args); err != nil || string(command.Subcommand) != args[0] {
t.Errorf("Parse(%v) = %+v, %v", args, command, err)
}
}
for _, args := range [][]string{
nil, {"reset"}, {"seed"}, {"seed", "--actor", "alice"}, {"seed", "--actor", "system:demo-seed"},
{"seed", "--actor", "operator:night", "extra"}, {"check-reset", "--force"}, {"inventory", "all"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func lookupOf(values map[string]string) func(string) (string, bool) {
return func(key string) (string, bool) {
value, ok := values[key]
return value, ok
}
}
func TestRunRefusesWithoutTheIsolatedModeBeforeReadingAnythingElse(t *testing.T) {
for _, mode := range []string{"", "production", "ISOLATED", "isolated-ish"} {
values := map[string]string{"DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "a long synthetic password"}
if mode != "" {
values[DemoModeName] = mode
}
var output bytes.Buffer
err := Run(context.Background(), []string{"check-reset"}, lookupOf(values), &output, time.Now)
if err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") || output.Len() != 0 {
t.Errorf("Run with DEMO_MODE=%q = %v, output %q; want a refusal before any output", mode, err, output.String())
}
}
err := Run(context.Background(), []string{"seed", "--actor", "operator:night"},
lookupOf(map[string]string{DemoModeName: IsolatedDemoMode, "DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "short"}),
&bytes.Buffer{}, time.Now)
if err == nil || !strings.Contains(err.Error(), PasswordName) || strings.Contains(err.Error(), "short") {
t.Fatalf("Run(seed, short password) = %v, want a refusal that does not echo the value", err)
}
err = Run(context.Background(), []string{"inventory"}, lookupOf(map[string]string{DemoModeName: IsolatedDemoMode}), &bytes.Buffer{}, time.Now)
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
t.Fatalf("Run(inventory) without a database = %v", err)
}
}
type seederFake struct {
report seedusecase.Report
err error
}
func (fake seederFake) Seed(context.Context, seedusecase.Input) (seedusecase.Report, error) {
return fake.report, fake.err
}
func TestExecuteSeedPrintsLoginsAndAttemptsButNeverThePassword(t *testing.T) {
attemptID, err := domain.NewAssessmentAttemptID()
if err != nil {
t.Fatalf("NewAssessmentAttemptID() error = %v", err)
}
report := seedusecase.Report{
PolicyVersion: 2, Created: []string{"account candidate@demo.lincodex.test"},
Logins: []seedusecase.Login{{Email: "candidate@demo.lincodex.test", Role: "candidate"}},
PreparedAttempts: []seedusecase.PreparedAttempt{{Email: "prepared-1@demo.lincodex.test", AttemptID: attemptID}},
}
var output bytes.Buffer
password, err := domain.NewPassword("a long synthetic password")
if err != nil {
t.Fatalf("NewPassword() error = %v", err)
}
if err := ExecuteSeed(context.Background(), seederFake{report: report}, seedusecase.Input{Password: password}, &output); err != nil {
t.Fatalf("ExecuteSeed() error = %v", err)
}
text := output.String()
for _, want := range []string{
"created 1 records, found 0", "login: candidate@demo.lincodex.test", "prepared full attempt: " + attemptID.String(),
"no person took them", "never assigns a category",
} {
if !strings.Contains(text, want) {
t.Errorf("output lacks %q:\n%s", want, text)
}
}
if strings.Contains(text, "a long synthetic password") {
t.Fatal("the output contains the password")
}
for _, test := range []struct {
err error
want string
}{
{seedusecase.ErrStandNotFresh, "never seeded"},
{seedusecase.ErrForeignPolicy, "neither the initial demo version"},
{seedusecase.ErrAccountConflict, "did not create"},
{seedusecase.ErrPreparedAttemptFailed, "did not assign"},
{outbound.ErrPolicyVersionNotFound, "no version yet"},
{errors.New("pq: password authentication failed for user x"), "demo seed failed"},
} {
err := ExecuteSeed(context.Background(), seederFake{err: test.err}, seedusecase.Input{}, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "authentication") {
t.Errorf("ExecuteSeed(%v) = %v, want a safe message containing %q", test.err, err, test.want)
}
}
}
type inspectorFake struct {
census outbound.DemoAccountCensus
err error
}
func (fake inspectorFake) CheckReset(context.Context) (seedusecase.ResetCheck, error) {
return seedusecase.ResetCheck{Verdict: seedusecase.DecideReset(fake.census), Census: fake.census}, fake.err
}
func (fake inspectorFake) Inventory(context.Context) (outbound.DemoInventory, error) {
return outbound.DemoInventory{SyntheticAccounts: fake.census.Synthetic, OrdinaryAccounts: fake.census.Ordinary()}, fake.err
}
func TestExecuteCheckResetFailsOnOrdinaryAccounts(t *testing.T) {
for _, test := range []struct {
census outbound.DemoAccountCensus
want string
fails bool
}{
{outbound.DemoAccountCensus{}, "reset allowed (empty)", false},
{outbound.DemoAccountCensus{Total: 9, Synthetic: 9}, "reset allowed (synthetic): 9 accounts", false},
{outbound.DemoAccountCensus{Total: 10, Synthetic: 9}, "holds 1 accounts outside", true},
{outbound.DemoAccountCensus{Total: 1}, "holds 1 accounts outside", true},
} {
var output bytes.Buffer
err := ExecuteCheckReset(context.Background(), inspectorFake{census: test.census}, &output)
if test.fails != (err != nil) {
t.Fatalf("ExecuteCheckReset(%+v) = %v, want failure %v", test.census, err, test.fails)
}
text := output.String()
if err != nil {
text = err.Error()
}
if !strings.Contains(text, test.want) {
t.Errorf("ExecuteCheckReset(%+v) said %q, want %q", test.census, text, test.want)
}
}
if err := ExecuteCheckReset(context.Background(), inspectorFake{err: errors.New("connection reset")}, &bytes.Buffer{}); err == nil ||
err.Error() != "reset check failed" {
t.Fatalf("ExecuteCheckReset(store failure) = %v, want a refusal", err)
}
}
func TestExecuteInventoryPrintsStableCounts(t *testing.T) {
var output bytes.Buffer
if err := ExecuteInventory(context.Background(), inspectorFake{census: outbound.DemoAccountCensus{Total: 10, Synthetic: 9}}, &output); err != nil {
t.Fatalf("ExecuteInventory() error = %v", err)
}
if !strings.HasPrefix(output.String(), "synthetic_accounts=9\nverified_synthetic_accounts=0\nordinary_accounts=1\n") {
t.Fatalf("inventory = %q", output.String())
}
}
@@ -0,0 +1,252 @@
package postgres
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// DemoSeedStore implements outbound.DemoSeedStore on a pool. Its statements
// read counts and identifiers only.
type DemoSeedStore struct {
pool *pgxpool.Pool
}
var _ outbound.DemoSeedStore = (*DemoSeedStore)(nil)
// NewDemoSeedStore returns the store of the demo seed operator command.
func NewDemoSeedStore(pool *pgxpool.Pool) *DemoSeedStore {
return &DemoSeedStore{pool: pool}
}
// CountAccounts counts every account and those on the synthetic domain. The
// domain is compared on the normalized address, so letter case does not
// matter.
func (store *DemoSeedStore) CountAccounts(ctx context.Context, syntheticDomain string) (outbound.DemoAccountCensus, error) {
const location = "DemoSeedStore.CountAccounts"
var census outbound.DemoAccountCensus
if err := store.pool.QueryRow(ctx, `
SELECT count(*), count(*) FILTER (WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text)
FROM users`, syntheticDomain).Scan(&census.Total, &census.Synthetic); err != nil {
return outbound.DemoAccountCensus{}, fmt.Errorf("%s - count accounts: %w", location, sanitizeConnectError(err))
}
return census, nil
}
// CurrentCategoryAttempt returns the source attempt of the candidate's
// current category of the specialization.
func (store *DemoSeedStore) CurrentCategoryAttempt(
ctx context.Context,
candidateID uuid.UUID,
specialization domain.SpecializationCode,
) (domain.AssessmentAttemptID, bool, error) {
const location = "DemoSeedStore.CurrentCategoryAttempt"
var attemptID uuid.UUID
err := store.pool.QueryRow(ctx, `
SELECT source_attempt_id FROM candidate_assessment_categories
WHERE candidate_id = $1 AND specialization = $2`, candidateID, string(specialization)).Scan(&attemptID)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AssessmentAttemptID{}, false, nil
}
if err != nil {
return domain.AssessmentAttemptID{}, false, fmt.Errorf("%s - read current category: %w", location, sanitizeConnectError(err))
}
return domain.AssessmentAttemptID(attemptID), true, nil
}
// TrainingBindingExists reports whether the category has a binding for the
// policy version.
func (store *DemoSeedStore) TrainingBindingExists(
ctx context.Context,
category string,
policyVersionID domain.PolicyVersionID,
) (bool, error) {
const location = "DemoSeedStore.TrainingBindingExists"
var exists bool
if err := store.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM assessment_training_bank_bindings
WHERE category = $1 AND product_policy_version_id = $2
)`, category, uuid.UUID(policyVersionID)).Scan(&exists); err != nil {
return false, fmt.Errorf("%s - read training binding: %w", location, sanitizeConnectError(err))
}
return exists, nil
}
type demoTrainingFamily struct {
id uuid.UUID
key string
version int32
hash []byte
}
type demoTrainingManifestEntry struct {
FamilyKey string `json:"family_key"`
Version int32 `json:"version"`
ContentSHA256 string `json:"content_sha256"`
}
// BindTrainingBank pins every published family of the training category in
// one transaction. The binding triggers check that the category has no real
// opening, that the item count matches the policy, and that the policy is
// the one in force.
func (store *DemoSeedStore) BindTrainingBank(ctx context.Context, binding outbound.DemoTrainingBinding) error {
const location = "DemoSeedStore.BindTrainingBank"
if binding.Category == "" || binding.ItemCount < 1 || binding.PolicyVersionID == (domain.PolicyVersionID{}) {
return fmt.Errorf("%s - binding is incomplete: %w", location, outbound.ErrDemoTrainingBindingMismatch)
}
if _, err := domain.ParseAssessmentOperator(string(binding.ReviewedBy)); err != nil {
return fmt.Errorf("%s - validate reviewer: %w", location, err)
}
tx, err := store.pool.BeginTx(ctx, transactionOptions)
if err != nil {
return fmt.Errorf("%s - begin transaction: %w", location, sanitizeConnectError(err))
}
finished := false
defer func() {
if !finished {
_ = rollback(ctx, tx)
}
}()
families, err := readPublishedTrainingFamilies(ctx, tx, binding.Category)
if err != nil {
return fmt.Errorf("%s - %w", location, err)
}
if len(families) != binding.ItemCount {
return fmt.Errorf("%s - %d published families for %d items: %w",
location, len(families), binding.ItemCount, outbound.ErrDemoTrainingBindingMismatch)
}
if err := insertTrainingBinding(ctx, tx, binding, families); err != nil {
return fmt.Errorf("%s - %w", location, err)
}
finished = true
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("%s - commit transaction: %w", location, markTransactionConflict(err))
}
return nil
}
func readPublishedTrainingFamilies(ctx context.Context, tx pgx.Tx, category string) ([]demoTrainingFamily, error) {
rows, err := tx.Query(ctx, `
SELECT id, family_key, version, content_sha256
FROM assessment_families
WHERE category = $1 AND lifecycle = 'published'
ORDER BY family_key, version`, category)
if err != nil {
return nil, fmt.Errorf("read published families: %w", sanitizeConnectError(err))
}
defer rows.Close()
var families []demoTrainingFamily
for rows.Next() {
var family demoTrainingFamily
if err := rows.Scan(&family.id, &family.key, &family.version, &family.hash); err != nil {
return nil, fmt.Errorf("scan published family: %w", err)
}
families = append(families, family)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate published families: %w", sanitizeConnectError(err))
}
return families, nil
}
// insertTrainingBinding stores the binding with the JSON manifest and the
// same canonical manifest hash that a category opening uses.
func insertTrainingBinding(ctx context.Context, tx pgx.Tx, binding outbound.DemoTrainingBinding, families []demoTrainingFamily) error {
entries := make([]demoTrainingManifestEntry, len(families))
canonical := make([]domain.AssessmentCategoryManifestEntry, len(families))
for index, family := range families {
entries[index] = demoTrainingManifestEntry{
FamilyKey: family.key, Version: family.version, ContentSHA256: hex.EncodeToString(family.hash),
}
canonical[index] = domain.AssessmentCategoryManifestEntry{
FamilyKey: domain.AssessmentFamilyKey(family.key), Version: family.version, ContentSHA256: family.hash,
}
}
manifest, err := json.Marshal(entries)
if err != nil {
return fmt.Errorf("encode manifest: %w", err)
}
manifestHash, err := assessmentCategoryManifestFingerprint(canonical)
if err != nil {
return fmt.Errorf("hash manifest: %w", err)
}
bindingID, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("generate binding ID: %w", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO assessment_training_bank_bindings (
id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at
) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, clock_timestamp())`,
bindingID, binding.Category, uuid.UUID(binding.PolicyVersionID), binding.ItemCount,
manifestHash[:], manifest, string(binding.ReviewedBy)); err != nil {
return fmt.Errorf("insert binding: %w", sanitizeConnectError(err))
}
for index, family := range families {
if _, err := tx.Exec(ctx, `
INSERT INTO assessment_training_bank_binding_families (
binding_id, ordinal, family_id, family_key, family_version, content_sha256
) VALUES ($1, $2, $3, $4, $5, $6)`,
bindingID, index+1, family.id, family.key, family.version, family.hash); err != nil {
return fmt.Errorf("insert binding family: %w", sanitizeConnectError(err))
}
}
return nil
}
// Inventory counts the records of synthetic accounts and of the seed's bank
// categories in one read-only statement.
func (store *DemoSeedStore) Inventory(
ctx context.Context,
syntheticDomain string,
categories []string,
) (outbound.DemoInventory, error) {
const location = "DemoSeedStore.Inventory"
inventory := outbound.DemoInventory{SyntheticAccountDomain: syntheticDomain}
if err := store.pool.QueryRow(ctx, `
WITH synthetic AS (
SELECT id, email_verified_at FROM users
WHERE right(email_normalized, char_length($1::text) + 1) = '@' || $1::text
)
SELECT
(SELECT count(*) FROM synthetic),
(SELECT count(*) FROM synthetic WHERE email_verified_at IS NOT NULL),
(SELECT count(DISTINCT organization_id) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM memberships WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM consent_records WHERE subject_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_profiles WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_questionnaires WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM assessment_attempts WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM assessment_attempt_results WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM skill_evidence_facts WHERE candidate_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM candidate_effective_publications WHERE user_id IN (SELECT id FROM synthetic)),
(SELECT count(*) FROM policy_versions WHERE policy_key = 'product'),
(SELECT count(*) FROM assessment_families WHERE category = ANY($2::text[]) AND lifecycle = 'published'),
(SELECT count(*) FROM assessment_category_openings WHERE category = ANY($2::text[])),
(SELECT count(*) FROM assessment_synthetic_category_reviews WHERE category = ANY($2::text[])),
(SELECT count(*) FROM assessment_training_bank_bindings WHERE category = ANY($2::text[])),
(SELECT count(*) FROM users)`,
syntheticDomain, categories,
).Scan(
&inventory.SyntheticAccounts, &inventory.VerifiedSynthetic, &inventory.Organizations, &inventory.Memberships,
&inventory.ConsentRecords, &inventory.CandidateProfiles, &inventory.Questionnaires, &inventory.Attempts,
&inventory.AttemptResults, &inventory.CurrentCategories, &inventory.EvidenceFacts, &inventory.PublishedCards,
&inventory.ProductPolicyVersions, &inventory.PublishedFamilies, &inventory.CategoryOpenings,
&inventory.CategoryAttestations, &inventory.TrainingBindings, &inventory.TotalAccounts,
); err != nil {
return outbound.DemoInventory{}, fmt.Errorf("%s - count records: %w", location, sanitizeConnectError(err))
}
inventory.OrdinaryAccounts = inventory.TotalAccounts - inventory.SyntheticAccounts
return inventory, nil
}