# Seeding a Test User

A seeded user is a brand-new account minted for one run, created in the
application by a seed workflow, and handed to the tests that consume that
seed as a login credential plus `$var` values. This section is the recipe for
configuring one. The general seed model (outputs, execution modes,
teardowns) is in the Seed Workflows section; this only covers the user case.

## When to seed a user (and when not to)

Use a persona (`actor: Admin`) when the test only needs SOME logged-in
account of a role. Personas resolve per environment, need no seed, and are
the default for every authenticated test.

Seed a user when the test needs a NEW account it owns:

- signup, invite acceptance, onboarding, first-login flows
- anything that mutates or deletes the account itself (profile, MFA
  enrolment, password change, leave org, delete account)
- a fresh inbox: verification codes, invite links, magic links
- a user with no history, so counts/empty states are deterministic

The seed-only-when-reused rule still applies: one seed serves every test
that needs "a fresh user", so this is exactly the case a seed is for. Do
not create a per-test copy — reference the same seed from each test.

On sandbox environments the account can come from a sandbox action bound
to a persona instead (see SANDBOX ALTERNATIVE at the end). This section
covers the environment-agnostic seed-workflow path first.

## How it works (platform side)

A seed output with a `credentialOutput` block is a CREDENTIAL output. At the
start of every run that references the seed, before the seed body runs,
the platform:

1. Mints an email address from `emailPrefix` + the run's execution id:

   ```text
   <emailPrefix>+<8 hex chars>@<test-user inbox domain>
   ```

   e.g. `testuser+3fa92c1b@testuser.runcofactor.com`
2. Resolves `fieldMapping` — `"$generate.email"` becomes that address,
   `"$generate.phone"` reserves an SMS number, any other value is a
   literal — and creates an ephemeral credential
   (`"[Ephemeral] <dataKey> (<first 8 chars of exec id>)"`) on the
   `credentialOutput`'s property, with the mapped fields as its login data.
3. Creates an inbox recipient for the address when
   `createInboxRecipient` is true, so the seed and its consumers can read
   mail sent to it.
4. Injects the mapped fields into the seed body as

   ```text
   $var.<dataKey>.<field>   e.g. $var.new_user.username
   $var.credential.<field>  (alias; only unambiguous with one
                             credential output)
   ```

5. Binds the credential to any downstream login node that references
   the seed output (`credentialSource: from_seed`), and deletes the
   credential after the suite finishes — or on seed failure — with a
   24-hour age sweep as backstop.

Minting the credential does NOT create the account in your application.
That is the seed body's job (next section). A credential output with an
empty seed body is a login that will fail.

## Step 1 — declare the credential output

Create the seed shell with the outputs declared up front; the
`credentialOutput` block is only settable through JSON (CLI `--from-file` /
`--outputs-json`, `workflow patch --seed-outputs-file`, or the Flow Designer
output editor).

```json
{
  "name": "Create invited user",
  "description": "Fresh org + admin invite for a seed-minted email",
  "outputs": [
    {
      "dataKey": "new_user",
      "name": "Invited User",
      "credentialOutput": {
        "propertyId": "<uuid of the application under test>",
        "loginUrl": "https://app.example.com/login",
        "emailPrefix": "qa-invite",
        "fieldMapping": {
          "username": "$generate.email",
          "password": "QaTest-Passw0rd!"
        },
        "createInboxRecipient": true,
        "loginInstructions": "Email/password form at /login."
      }
    },
    { "dataKey": "invite_token", "name": "Invite token" },
    { "dataKey": "organization_id", "name": "Organization ID" }
  ]
}
```

```bash
cofactor workflow seed create --from-file seed.json
```

`credentialOutput` fields:

- `propertyId`: REQUIRED. The application the credential belongs
  to; without it the output is skipped with a
  warning and downstream logins fail.
- `fieldMapping`: REQUIRED. Credential field → value. Use
  `"$generate.email"` for the minted address (usually
  `username`, and `email` too if the login form wants
  both). Every other value is a literal stored
  verbatim — macros are NOT expanded here — so the
  password is exactly what you write; pick one your
  app's password policy accepts. Uniqueness comes
  from the email, not the password.
- `emailPrefix`: Local-part prefix; defaults to `"testuser"`. Use
  something that names the seed so inbox traffic is
  attributable.
- `createInboxRecipient`: `true` whenever the flow must read a message sent to
  the user (verification code, invite link, magic
  link). Without it the address exists but nothing
  captures its mail.
- `provisionPhoneNumber`: `true` (or a `"$generate.phone"` mapping) to reserve an
  SMS-capable number for OTP flows.
- `loginUrl`: Where the login agent goes to sign in as this user.
- `loginInstructions`: Extra guidance for the login agent (form location,
  SSO button to avoid, post-login landing).
- `provisioningInstructions`: Only if the account needs a manual step before
  first login; marks the credential as not yet
  provisioned.

Keep plain data outputs alongside the credential output for every id the
consumers or the teardown will need (org id, user id, invite token). Declare
ONLY what the seed body actually exports — a declared-but-unexported output
shows up as "missing" on every run.

## Step 2 — make the seed body create the account

The body turns the minted email into a real account. Prefer an API
sequence; fall back to browser nodes only when no API exists.

Typical shapes:

- Invite: admin/superadmin creates (or picks) an org → POST invite for
  `$var.new_user.username` → export the invite token. The consumer
  test then completes signup through the invite link.
- Direct: POST `/users` or `/signup` with `$var.new_user.username` and
  `$var.new_user.password` → export the user id. The account is
  ready to log in.
- Verify: if the app emails a verification code on signup, the seed can
  read it too (the inbox exists already) — but usually leave the
  verification step to the consumer test when that step IS what
  the test proves.

Example: a "create org & copy invite" seed — an `api_sequence` of
createOrg → switchOrg → createInvite (body
`{"email": "$var.credential.username", "role": "admin"}`) exporting
`organization_id` and `invite_key` for the tests that consume them.

Rules for the `api_sequence` steps:

- Authenticate as a persona (`credentialTemplateId`), never a hardcoded
  `credentialId` — the persona resolves per environment and is minted
  just-in-time on a fresh sandbox.
- Target `$var.ENV.api_url/...`, never a baked host, so the same seed runs
  on dev, prod, and every sandbox.
- Use `$var.<dataKey>.username` for the email. `$var.credential.username`
  also works but stops being unambiguous the moment a second credential
  output is added.
- Export every id the teardown needs.

## Step 3 — consume the user in a test

In the consuming workflow:

1. Add a Seed node referencing the seed (the seed's outputs become
   `$var.<key>` and `$var.<Seed_Name>.<key>`).
2. Point the login node at the seed's credential output:

   - `credentialSource: "from_seed"`
   - `seedCredentialRef: { "seedWorkflowId": "<seed uuid>", "dataKey": "new_user" }`
   - `performLogin: false` when the test performs signup/first login
     itself (invite acceptance, onboarding)
   - `performLogin: true` when the account is ready and the test starts
     logged in

   Both fields are required at run time, but you rarely write
   `seedWorkflowId` yourself: the Flow Designer's "Acting as → from seed"
   picker sets both, and `cofactor workflow create` fills it from the
   nearest preceding Seed node when only `dataKey` is given. Put the Seed
   node before the login node that uses its output.
3. Use the credential's fields in steps as `$var.new_user.username` and
   `$var.new_user.password` (signup forms, "confirm password", etc.), and
   the plain outputs as `$var.invite_token` etc.
4. Email steps: describe what to read — "open the verification email
   sent to `$var.new_user.username` and follow the accept-invite link".
   The agent has an inbox tool scoped to the credential's recipient. Do
   NOT hardcode a code value in the node's inputs; it is different every
   run.

Several tests can reference the same seed; each run mints its own user, so
they run in parallel without colliding. Order tests that must reuse ONE
user across flows as suite layers instead.

## Step 4 — teardown

Pair the seed with a teardown (created by default by `workflow seed
create`). The teardown receives the same `$var` values and should delete the
account through the API — the org if the seed created one, otherwise the
user — using the exported ids. Same rules: persona auth, `$var.ENV.api_url`.
The ephemeral credential and inbox recipient are removed by the platform;
only your application's rows need the teardown.

A seed that runs daily without a working teardown leaves one orphan user
(or org) per run. Check once after publishing that the object is gone.

## Checklist

- [ ] `credentialOutput.propertyId` set; `fieldMapping` has `"$generate.email"`
- [ ] `createInboxRecipient: true` if any step reads mail
- [ ] seed body creates the account and exports every id the teardown needs
- [ ] `api_sequence` steps use `credentialTemplateId` + `$var.ENV.api_url`
- [ ] declared outputs == exported outputs (no "missing" on the run)
- [ ] consumer login: `from_seed` with `dataKey`, and a Seed node before it
  (`seedWorkflowId` auto-fills from that Seed node at compile)
- [ ] no hardcoded verification codes in consumer inputs
- [ ] teardown deletes the app-side account/org; verified once by hand
- [ ] seed + teardown saved and verified before consumers join Regression

## Sandbox alternative — action-minted persona

On a sandbox template, a sandbox action with a `credentialOutputConfig` and
a `credentialTemplateId` mints the account server-side and binds it to a
PERSONA (e.g. `provision-tenant` → "Admin"). Tests then just say
`actor: Admin`; the persona is provisioned just-in-time on each fresh
instance and no seed node is needed. A second human member for "act on
someone else" tests comes from a follow-up action (e.g. `add-org-member`,
keyed to `$var.USER.org_id`). Constraint: consuming tests become
sandbox-only, and no teardown is needed because the instance is destroyed.
Prefer this on sandbox-backed properties; use the seed-workflow path
everywhere else.
