# Feasibility: Check What the App Needs First

Check what the app needs before you write its cofactor.sandbox.yaml.

## The goal: a hermetic sandbox

The app and everything it depends on run inside the sandbox: its
databases, queues and workers as services, object storage and sign-in
as built-ins, third parties as emulators. Every copy is seeded the same
way at every commit and has its own data, so a test can't be flaked by
anything shared, a pull request's backend changes are exercised, and a
result at a commit means what it says.

Build a hermetic sandbox unless this check shows it isn't feasible or
the user tells you not to. Don't ask first, and don't offer the
frontend-only escape hatch below as an equal choice.

A sandbox is one Linux amd64 machine with no Docker inside, open egress,
and emulators for some third parties. A dependency that can't run there
is far cheaper to find now than after the first failed snapshot.

## The check

1. List the app's dependencies from its own files, not from memory:

   - compose files (each `image:` is a dependency) and Dockerfiles
     (`FROM`: base OS and architecture);
   - package manifests (`package.json`, `requirements.txt`,
     `pyproject.toml`, `Gemfile`, `go.mod`, `*.csproj`; database
     drivers, queue clients, cloud SDKs such as `@aws-sdk/client-*` or
     `boto3`, payment, email and SMS libraries);
   - `.env.example` or the env schema (`*_URL`, `*_QUEUE_URL`,
     `*_TOPIC_ARN`, `AWS_*`, `SMTP_*`, provider keys);
   - infrastructure code (Terraform, CloudFormation or SAM, Serverless,
     CDK) for managed services the code reaches at runtime;
   - how users sign in.

2. Give each one its verdict from the Support section below:

   - `built-in`: Cofactor runs it for you.
   - `emulated`: An `emulation` plugin answers it inside the sandbox.
   - `native`: Nothing in the sandbox stops it, but Cofactor doesn't
     provide it: install it in `setup` (or the image) and
     run it as one of your `services`. Prove it comes up in
     a claimed copy.
   - `real`: The call leaves the sandbox for the real provider.
     Egress is open: a test key reaches the provider's test
     mode, a real credential acts on the real account.
   - `unsupported`: No way to run it in a sandbox today.

   Anything not listed is unknown: say so, and say what you would try.

3. Report it to the user before building anything: one line per
   dependency with its verdict, the file that shows it, and your plan
   (install it, declare the emulator, set a test key, leave the journey
   out). Put the same list in your final report and in the pull request
   that adds the definition.
4. Stop and ask the user when anything is unsupported, unknown on a
   journey they care about, or real with no test mode and no stand-in
   named for it in the Support section (a call to it acts on the real service:
   never give the sandbox real credentials for one). A `real` item with
   a stand-in named for it, such as ElasticMQ for SQS, is no blocker:
   run the stand-in as a service and point the app at it. Each blocker
   needs a decision: leave the journey out, disable the feature in the
   sandbox, stub it in the app, sign in another way, or, when the gaps
   make a hermetic sandbox infeasible, the escape hatch below. A
   procedure that batches its questions, such as `plan`, puts these
   per-item questions in its one plan, for the human to answer
   together when they approve it; it still stops before building when a
   hermetic sandbox isn't feasible.
5. A gap blocks a hermetic sandbox only when the app can't start or
   users can't sign in without it. A gap confined to some journeys, a
   feature or a test mode takes one of the step 4 decisions instead, and
   the sandbox is still hermetic. If nothing blocks, build it: go on to
   `definition`. If something does, explain to the user why, show them
   the table under "Hermetic or frontend-only" with your recommendation,
   and build only once they decide.

AWS deserves a second look. `emulation.aws` answers only the services
the definition gives a section, `emulation.email` answers SES, and
`object_storage` answers S3 for a client that reads the standard
endpoint settings. Every other AWS SDK client the app creates reaches
real AWS: list each one in the report.

## The escape hatch: a frontend-only sandbox

Only when the check shows a hermetic sandbox isn't feasible (the app
can't start or users can't sign in without an unsupported dependency:
step 5), or the user explicitly asks for it, run only
the frontend in the sandbox and point it at an existing backend: a
staging or dev API. Never a production backend: tests and seeds create,
change and delete data there. Ask the user which backend, and have them
confirm it is not production and holds no real customer data, before you
write it into the definition.

It needs a backend the public internet can reach. Sandbox egress is
open, but a backend only reachable over a VPN or a private network, or
one that only accepts listed IP addresses, can't be reached.

Serve the frontend and proxy the backend from the same origin. Each
sandbox copy has its own public origin, and the browser sends a
backend's cookies only to the host they were set for: a frontend on the
copy's origin calling the backend's own origin is a cross-site call, its
session cookies are third-party, and the backend's CORS would have to
allow every copy's origin. So the sandbox's web service serves the
frontend and forwards one fixed API path to the backend, and the
browser only ever talks to the copy's own origin. Rewrite only the
cookie's domain if the backend sets one (nginx `proxy_cookie_domain`, a
dev server proxy's `cookieDomainRewrite`); keep Secure and SameSite as
they are, since the copy is https. Hard-code the target: a proxy that
takes it from the request is an open proxy on a public URL. Never have
the proxy add a credential of its own (a service token, an
Authorization header): anyone with the copy's URL would inherit it. The
frontend's own API base URL becomes that same-origin path, and the
backend's URL goes to the proxy. Both are fixed values in the
definition's top-level `env` (with no credentials in the URL): secrets
never reach build steps, so a bundle that bakes its API URL at build
time reads it from there. The parts that differ from a hermetic
definition (add `version`, `resources` and `environments` as in
`definition`; install nginx and gettext-base in `setup`; for a pushed
image, put them and the built bundle in the image instead, and leave
`lifecycle.build` out):

```yaml
ports:
  web: { port: 3000, access: public }
params:
  web_url: { port: web }
env:
  PUBLIC_URL: ${params.web_url}
  API_BASE_URL: /api
  BACKEND_URL: https://api.staging.example.com
  BACKEND_HOST: api.staging.example.com
services:
  web:
    run: sandbox/serve-web.sh
    health: { http: 3000, path: / }
    after_build: true         # starts once the build made the bundle
    reload_on_prepare: true   # sees the copy's PUBLIC_URL and secrets
personas:
  owner: { email: qa-owner@example.com }
authentication:
  run: sandbox/sign-in.sh
lifecycle:
  build:
    - { name: frontend, run: npm ci && npm run build, inputs: [package-lock.json, "src/**"] }
  prepare: []
```

where serve-web.sh renders the proxy config from `$BACKEND_URL` and
`$BACKEND_HOST` with `envsubst` (nginx doesn't read the environment;
pass envsubst the variable list so nginx's own `$host` is kept), then
serves the built frontend on 3000 with:

```text
location /api/ {
  proxy_pass ${BACKEND_URL}/;   # the trailing / strips /api
  proxy_ssl_server_name on;
  proxy_cookie_domain ${BACKEND_HOST} $host;
  proxy_redirect ${BACKEND_URL}/ /api/;
}
```

(`BACKEND_URL` is an origin with no trailing slash or path.)
An app that sends a bearer token instead of a cookie can call the
backend directly if the backend's CORS already allows the copy's
origin. Don't loosen a shared backend's CORS for it (never `*` with
credentials): use the proxy.
A backend that checks the Origin header (CSRF protection, an origin
allowlist) also sees the copy's origin through the proxy: have the
proxy set Origin to the backend's own, or allow the copy's origin there.

Personas are existing accounts on that backend: dedicated test accounts
with only the access a test needs, never a person's own account or an
administrator. The user stores each one's password as a secret from
their own shell, never in the definition or a committed file:

```bash
read -rs PASSWORD; printf %s "$PASSWORD" | cofactor sandbox secret set OWNER_PASSWORD --application <app>
```

Give the user that command to run; don't
run it yourself. Name one secret per persona, `<PERSONA>_PASSWORD` with
the persona's name upper-cased and `-` turned into `_` (`OWNER_PASSWORD`
for `owner`); a secret is 8 to 8192 bytes. The user sets them before the
first claim (after `push` or `connect` creates the application, since
neither builds a snapshot): a snapshot built without them keeps failing
sign-in until a new image push, or a new default-branch commit followed
by `cofactor sandbox refresh --wait`, replaces it (`secrets`).
`authentication.run` signs in through `$PUBLIC_URL`
(see `authentication`) with the persona's email from `COFACTOR_PERSONAS`
and the password from the secret for `$COFACTOR_AUTH_PERSONA`, which
reaches the script as an environment variable; have the script stop with
an error when that variable is empty. In POSIX sh:

```sh
var="$(printf %s "$COFACTOR_AUTH_PERSONA" | tr 'a-z-' 'A-Z_')_PASSWORD"
password="$(printenv "$var" || true)"
[ -n "$password" ] || { echo "$var is not set" >&2; exit 1; }
```

Never use the `password` in `COFACTOR_PERSONAS` here, as the
`authentication` example does: it is the snapshot's generated one, which
the backend doesn't know. This is what lets Cofactor's test runs and
`cofactor sandbox verify-env` sign in (`validate` doesn't run the
script). Every test run and agent acts as that account. Leave the
persona step out of `lifecycle.prepare`: you can't set passwords on a
shared backend. The password a claim prints for each persona is the
snapshot's generated one, which that backend doesn't know, so a person
using a frontend-only sandbox signs in with the account's own password.

Seeds and actions change the shared backend for everyone using it:
create what a test needs under names a later run can find and remove,
and never delete or reset data a seed didn't create.

Emulators only cover calls made inside the sandbox. In a frontend-only
sandbox the backend makes its own third-party calls, from wherever it
runs.

## Hermetic or frontend-only

When a hermetic sandbox isn't feasible, show the user this with why and
what you recommend, and let them decide:

| | Hermetic | Frontend-only |
| --- | --- | --- |
| Setup | More work: every dependency runs inside | Fast: the frontend and a proxy |
| Data | Every copy has its own, seeded the same way | Shared with everyone using that backend; tests change real data there and need cleaning up |
| Pull requests | Frontend and backend changes are both exercised | Frontend changes only; the PR's backend changes are not |
| Flakiness | Nothing shared | The backend's uptime, data and deploys |
| As proof at a commit | Strong: everything at that commit | Weaker: the backend is whatever it runs today |
| Credentials | Generated for each snapshot | Real accounts on that backend, kept as secrets |
| Backend | Inside the sandbox | Staging or dev, never production |

## Support

### Databases

| Verdict | Item | What to do |
| --- | --- | --- |
| native | Postgres | Install it in `setup` (or the image) and run it as a service. The only engine whose restored dump `database.fast-forward` can move forward: declare it under `databases` (`data-fast-forward`). |
| native | MySQL / MariaDB | Run it as a service. No `database.fast-forward`: a restored dump keeps its original dates. |
| native | SQLite | A file in the checkout or image; nothing to run. |
| native | MongoDB | Run `mongod` as a service; size `resources` for its memory. |
| native | Redis / Valkey | Run it as a service. |
| native | Elasticsearch / OpenSearch | Run it as a service and give it 1-2 GiB of memory; check it is healthy in a claimed copy. |
| native | DynamoDB | Run DynamoDB Local (needs Java) as a service and set `AWS_ENDPOINT_URL_DYNAMODB`, a region and dummy credentials in `env`. |
| real | Managed-only data services (Aurora Data API, Snowflake, BigQuery) | No local equivalent: calls reach the real service. Use a test account through `secrets`, or leave those journeys out. |

### Queues and events

| Verdict | Item | What to do |
| --- | --- | --- |
| real | Amazon SQS | Not emulated: calls reach real AWS (a dummy key fails, a real one reaches your account). Run an SQS-compatible server such as ElasticMQ (a JVM image or native binary) as a service with `AWS_ENDPOINT_URL_SQS`, or leave those journeys out. |
| real | Amazon SNS | Not emulated: calls reach real AWS, and no stand-in is named for it: ask the user, who can leave those journeys out or name an SNS-compatible server to run as a service. |
| native | Kafka / Redpanda | Run it as a service (Redpanda is a single binary); check it comes back healthy in a claimed copy. |
| native | RabbitMQ | Run it as a service. Erlang binds to the node name: check it comes back healthy in a claimed copy. |
| native | NATS, Redis streams | Run it as a service. |
| native | Google Pub/Sub | Run the Pub/Sub emulator (needs Java) as a service and set `PUBSUB_EMULATOR_HOST` in `env`. |
| real | Kinesis, Step Functions | Not emulated: calls reach real AWS. Run kinesalite (Kinesis, unmaintained) as a service and point the app at it, or leave those journeys out. Step Functions Local is no longer maintained by AWS and calls real Lambda for Task states: ask the user before relying on it. |
| real | Azure Service Bus, Amazon EventBridge | Not emulated: calls reach the real service, and no stand-in is named for them: ask the user, who can leave those journeys out or stub the calls in the app. |

### Functions

| Verdict | Item | What to do |
| --- | --- | --- |
| real | AWS Lambda | Not emulated: invokes reach real AWS. No stand-in is named for it: ask the user, who can leave those journeys out or have the app call the handler code as a service directly (a change to its code path). |
| unsupported | The app's own HTTP API served by API Gateway and Lambda | Ask the user: serve the app's HTTP API from its own server process in the sandbox, or leave those journeys out. |
| native | Google Cloud Functions / Azure Functions | Run the Functions Framework or Core Tools as a service; cloud triggers are not delivered, so call the function over HTTP. |

### Object storage

| Verdict | Item | What to do |
| --- | --- | --- |
| built-in | Amazon S3, Google Cloud Storage | Declare `object_storage` and its buckets; the sandbox runs the server (`object-storage`). |
| native | Azure Blob Storage | Run Azurite as a service. |

### Secrets and config

| Verdict | Item | What to do |
| --- | --- | --- |
| emulated | AWS Secrets Manager, KMS, SSM Parameter Store | Declare them under `emulation.aws`; the app's unmodified SDK reads the seeded values (`emulation`). |
| real | Vault, Doppler, 1Password | Calls reach the real service. The stand-in is sandbox secrets: set the values as secrets and read them from the environment (`secrets`); ask the user if the app must call the service itself. |

### Email

| Verdict | Item | What to do |
| --- | --- | --- |
| emulated | SES, SendGrid, Resend, Postmark, Mailgun (HTTP APIs); Mailosaur reads | Declare `emulation.email`; sent mail is captured and readable. SES is intercepted in us-east-1 unless you list its regions (`emulation`). |
| native | SMTP | Not intercepted: run an SMTP catcher such as Mailpit as a service and point the app's SMTP host at 127.0.0.1 (`emulation`). |

### SMS and voice

| Verdict | Item | What to do |
| --- | --- | --- |
| real | Twilio, Vonage | Calls reach the real provider: set its test credentials as secrets (`secrets`). |

### Sign-in

| Verdict | Item | What to do |
| --- | --- | --- |
| built-in | Password or session sign-in | Declare personas and an `authentication` step (`personas`, `authentication`). |
| emulated | Google sign-in | Declare `emulation.google-oauth` (`authentication`). |
| emulated | OIDC providers (Auth0, Okta, Keycloak, Clerk) | Declare `emulation.oidc` (`authentication`). |
| emulated | Amazon Cognito user pools | Declare `emulation.aws.cognito`: each persona is a user, served through the SDK API, the issuer JWKS and the hosted UI (`emulation`). |
| native | Firebase Auth | Run the Firebase Auth emulator (needs Java) as a service. |
| unsupported | SAML, Google One Tap / FedCM / popup sign-in, hosted identity intermediaries | Sign personas in another way the app supports (a password or session login), or leave the sign-in journey itself out. |

### Third-party APIs

| Verdict | Item | What to do |
| --- | --- | --- |
| emulated | Jira, Slack, Esri, Maximo | Declare `emulation.jira`, `emulation.slack`, `emulation.esri` or `emulation.maximo-stub` (`emulation`). |
| emulated | Any other API with no plugin | Write the emulator as a script and declare it under `emulation.scripted` (`emulation`). |
| real | APIs with a test mode (Stripe, OpenAI, ...) | Calls reach the real provider: set its test key as a secret, never a live one (`secrets`). |

### Platform

| Verdict | Item | What to do |
| --- | --- | --- |
| native | Background workers and crons | Run each as another service. |
| unsupported | Docker, compose or Kubernetes inside the sandbox | A sandbox is one machine with no Docker: run each container's process as a service (`upload`). |
| unsupported | arm64-only images | Sandboxes are linux/amd64: build for that platform (`upload`). |
| unsupported | Windows, .NET Framework, IIS | Linux only. .NET (Core) on Linux runs as a service. |
| unsupported | GPU; more than 32 vCPUs or 64 GiB of memory | `resources` allows 1-32 vCPUs and 1-64 GiB, with no GPU (`definition`). |
