Docs/Emulation
#

Emulation

Emulation makes third-party services deterministic and inspectable: instead of a sandbox's outbound calls to an email provider, Google, Jira or Slack leaving the VM, they're intercepted by an in-sandbox emulator that behaves like the real thing well enough for tests, and lets a test look at what was sent.

Plugins

Declaring a plugin id under emulation: turns on its interception and adds it to what envs reports.

yaml
emulation:
  email: {}

Available plugin ids (each plugin's summary comes from the emulator registry Cofactor serves, so it lists emulators newer than your CLI):

  • aws: AWS Secrets Manager, KMS, SSM Parameter Store and Cognito user pools, answered to the app's own unmodified AWS SDK.
  • email: Captures outbound mail from SES, SendGrid, Resend, Postmark and Mailgun instead of sending it, and can serve it back through the Mailosaur API.
  • esri: A slice of the ArcGIS REST API for hosted feature layers: token, query and applyEdits.
  • github: api.github.com and github.com from a declared fixture: GitHub App installations, users, orgs, repositories, signed webhooks and Git over HTTP.
  • google-oauth: Google sign-in without a real Google account; every persona is a Google account.
  • jira: The Jira Cloud REST API of your site, plus Atlassian's OAuth gateway, with operations to create and read issues.
  • maximo-stub: A slice of the IBM Maximo MBO and object structure REST APIs over built-in sample records, including bulk upserts and a location hierarchy: read them, and create and update work orders, assets, locations and service requests.
  • oidc: A standard OpenID Connect provider for apps on Auth0, Okta, Keycloak, Clerk or any provider with a configurable issuer; every persona is an account.
  • scripted: Your own emulator for a service no plugin covers: a script in your repository answering the domains you name.
  • slack: Slack's API, for flows that post messages.
  • stripe: api.stripe.com for the self-serve billing journey: customers, subscription Checkout, subscriptions and the billing portal, with signed webhooks.

cofactor sandbox emulators [id] prints the same list and, for one emulator, its docs link, domains, config keys and operations.

cofactor sandbox envs lists each declared plugin's operations.

Email

The email plugin intercepts the HTTP send APIs of several providers (SES, SendGrid, Resend, Postmark, Mailgun) so outbound mail is captured instead of actually sent. SES is intercepted in us-east-1 unless you list others: email: { sesRegions: [eu-west-1] }; add other hosts with extraDomains. Mail through a host that isn't intercepted leaves the sandbox for real. email: { mailosaur: {} } also serves the Mailosaur API from what was captured (see Mailosaur below).

SMTP (nodemailer, Django's SMTP backend, Action Mailer...) is not intercepted. Leave SMTP unconfigured in the sandbox so the app sends nothing, or ship an SMTP catcher such as Mailpit in the image, run it as one of your services, and point the app's SMTP host at 127.0.0.1.

Jira

jira: { tenant: acme } intercepts the Jira Cloud REST API of your site: it serves acme.atlassian.net, plus api.atlassian.com (the OAuth gateway) and auth.atlassian.com. tenant is required (validate doesn't check it). The app registers its own webhook through the emulated API; operations jira.create-issue, jira.add-label (delivers the tag webhook to what the app registered), jira.get-issue and jira.get-comments drive and read it.

Sign-in emulators

google-oauth intercepts Google's OAuth endpoints, for testing login flows without a real Google account. Every declared persona is a Google account (its email is the Google email), so the definition must declare at least one persona.

oidc is a standard OpenID Connect provider for apps that sign in through Auth0, Okta, Keycloak, Clerk or any other OIDC provider whose issuer the app lets you configure (Amazon Cognito has its own emulator: aws.cognito). It takes no options: oidc: {}. Its address is the copy's public emulation URL, which is the issuer; point the app's OIDC issuer setting at ${params.issuer_url} with issuer_url: { port: emulation }. Every declared persona is an account, so the definition must declare at least one persona. See cofactor sandbox guide v2 authentication.

AWS

Seed the secrets an app reads from Secrets Manager at startup. A string is the SecretString as is; an object is served as its JSON. Values that are sandbox-internal (the in-sandbox database's password, a connection string) are plain values or {secret: true} params, referenced as ${params.NAME} (only aws resolves references; one in another plugin's config fails validate):

yaml
params:
  db_password: { secret: true }
env:
  DB_PASSWORD: ${params.db_password}   # what the local database is set up with
  AWS_ACCESS_KEY_ID: emulated            # any credentials work; the SDK
  AWS_SECRET_ACCESS_KEY: emulated        # needs some to sign a request
emulation:
  aws:
    regions: [us-east-1]                 # optional; the default
    secrets_manager:
      secrets:
        app/prod/db: { host: 127.0.0.1, username: app, password: "${params.db_password}", dbname: app }
        app/prod/feature-flags: "on"

If the app fetches a real third-party key (an AI provider's or payment provider's test key) from Secrets Manager at run time, keep that key in the secret store (see the secrets topic) and reference it as ${secrets.NAME}; the definition only names it:

yaml
app/prod/ai-key: "${secrets.AI_API_KEY}"

Local values do not belong in the secret store: it is for real third-party credentials only.

References are resolved inside the sandbox when prepare runs, with the environment's values (a secret's environment override wins, as for env). Fast copies keep the snapshot's config and secret values until it is rebuilt by a new commit or image push; legacy prepare claims see changes on the next claim. A ${secrets.NAME} that is not set for the environment fails prepare, naming the secret, so the snapshot build or legacy prepare claim fails. A ${params.NAME} must name a declared param (validate checks it). Resolved values reach only the emulator: they are not written into the definition, not printed, not recorded with the emulator's requests, and not returned by aws.secrets.

Served: GetSecretValue (by name, full ARN or ARN without its suffix; VersionStage AWSCURRENT), BatchGetSecretValue, DescribeSecret and ListSecrets (Filters on name and all, MaxResults/NextToken). An unknown name is AWS's ResourceNotFoundException. ARNs look like arn:aws:secretsmanager:us-east-1:000000000000:secret:app/prod/db-1a2b3c and, like version ids, are the same in every copy. Secrets are read-only: CreateSecret, PutSecretValue and other writes answer 501.

KMS. Ciphertext made by real KMS (say, a data key hardcoded in the app) cannot be decrypted in a sandbox, so seed what it decrypts to, both base64:

yaml
kms:
  decrypt:
    - ciphertext: AQICAHh...base64...
      plaintext: "${params.aes_key}"   # or a base64 literal
      key_id: alias/app                # optional: the KeyId Decrypt answers with

kms: {} alone serves Encrypt, Decrypt and GenerateDataKey under one emulated key (any KeyId is accepted), so an app that encrypts at run time round-trips, including what the snapshot's seeds encrypted: the key is generated inside the sandbox when the snapshot is built and is never shown. Unknown ciphertext is AWS's InvalidCiphertextException; a different EncryptionContext fails the same way (seeded ciphertext ignores the context). A referenced plaintext must resolve to base64, or the claim fails naming the field. Other KMS calls answer 501.

SSM Parameter Store. Seed parameters by name; type is String (the default), StringList or SecureString, and values take references too:

yaml
ssm:
  parameters:
    /app/prod/feature-x: { value: "on" }
    /app/prod/db-password: { value: "${params.db_password}", type: SecureString }

Served: GetParameter (by name or ARN), GetParameters (unknown names come back in InvalidParameters), GetParametersByPath (one level, or every depth with Recursive; MaxResults/NextToken) and DescribeParameters (ParameterFilters on Name, Type and Path). A SecureString's value is returned only WithDecryption; without it the value is an opaque stand-in. Every parameter is version 1; version and label selectors (name:1) are not supported. An unknown name is AWS's ParameterNotFound. Writes (PutParameter, ...) and other filters answer 501. Operation aws.parameters lists names, types, versions, ARNs and read counts, never a value.

Cognito. An app that signs in through an Amazon Cognito user pool (the AWS SDK, Amplify, amazon-cognito-identity-js or the hosted UI) signs in unmodified. Every persona is a CONFIRMED user of every pool you declare, with the persona's name as its username, the persona's password and its email (cofactor sandbox show prints the logins); a definition declaring cognito with no personas fails validate. Declare each pool with the ids the app is configured with (a client id may be a ${params.NAME}):

yaml
cognito:
  user_pools:
    - id: us-east-1_AbCdEfGhI        # the region prefix must be one of `regions`
      domain: acme-auth              # hosted UI: acme-auth.auth.us-east-1.amazoncognito.com
      clients: [1h57kf5cpq17m0eml12EXAMPLE]
      groups: { admins: [alice] }    # optional: group -> personas, shown as cognito:groups
      attributes:                    # optional: persona -> custom attributes
        alice: { "custom:tenant": acme }

Served on cognito-idp.<region>.amazonaws.com: InitiateAuth and AdminInitiateAuth with USER_PASSWORD_AUTH (ADMIN_USER_PASSWORD_AUTH), USER_SRP_AUTH and REFRESH_TOKEN_AUTH; RespondToAuthChallenge for PASSWORD_VERIFIER and NEW_PASSWORD_REQUIRED; GetUser, AdminGetUser and AdminCreateUser (the new user is FORCE_CHANGE_PASSWORD and signs in through NEW_PASSWORD_REQUIRED). USERNAME may be the persona name or its email. Any other operation or auth flow (CUSTOM_AUTH, MFA, sign-up, password reset) answers 501. A client secret (SECRET_HASH) is accepted unchecked. Tokens are RS256 JWTs shaped like Cognito's (iss https://cognito-idp.<region>.amazonaws.com/<poolId>, token_use, client_id or aud, sub, cognito:username, cognito:groups, auth_time, exp), signed with a key per pool, published at /<poolId>/.well-known/jwks.json with /<poolId>/.well-known/openid-configuration beside it, so aws-jwt-verify and other verifiers accept them. The key is new each time the emulator starts. The hosted UI at <domain>.auth.<region>.amazoncognito.com serves /oauth2/authorize, /login (a username and password form), /oauth2/token (authorization_code and refresh_token), /oauth2/userInfo and /logout. It is the oidc emulator's code flow and has its rules: the redirect_uri and logout_uri must be http(s) addresses of the copy (its public ports). There is no sign-in gate: a persona's password is the only check.

Where it is reachable. The cognito-idp host and each hosted domain exist only inside the copy (the sandbox's /etc/hosts points them at the emulator), so the app's server, and a browser running in the copy (Cofactor's session browser and test runs, including a private copy of a PR preview), reach them by their real names. A person's own browser, as on a PR preview or a claimed sandbox's public URL, resolves the real AWS names instead, so the hosted UI is also served at the copy's public emulator address (the implicit public emulation port), with the same paths. To use it from a person's browser, give the app that address as its Cognito domain:

yaml
params:
  cognito_domain: { port: emulation }    # https://<the copy's emulator host>
env:
  COGNITO_DOMAIN: ${params.cognito_domain}

and have the app build its hosted-UI URLs on it (/oauth2/authorize, /oauth2/token, /logout) instead of <domain>.auth.<region>.amazoncognito.com. The param is a full URL with the https scheme and no trailing slash; there is no way to strip the scheme in a definition, so an app whose setting wants a bare host (Amplify's oauth.domain) must derive it in code (new URL(process.env.COGNITO_DOMAIN).host). On the public address the app client (client_id) picks the pool, so each declared client id must belong to one pool (validate checks the ids as written); the token endpoint, as in Cognito, needs the client_id (body or HTTP Basic). Anyone who knows the preview's emulator host and a persona's password can sign in as that persona there, as on the app's own preview login. The cognito-idp JSON API and CORS are not served there, so an app that calls cognito-idp from the browser (Amplify's sign-in forms, amazon-cognito- identity-js) does not work for a person's own browser: only the hosted UI redirect flow does. The server-side token check is unchanged: tokens still carry the cognito-idp.<region>.amazonaws.com/<poolId> issuer, which the app's server verifies inside the copy. Operation aws.cognito-pools lists each pool's ids, hosted host, clients and users with status, groups and attributes, never a password or token.

The SDK still needs credentials (any value) and a region: set them in env: unless the app or a declared object_storage: { provider: s3 } already does. Operation aws.secrets lists each secret's name, ARNs, version id and how often the app read it, never a value.

Mailosaur

A test suite that reads the app's mail through Mailosaur (its API or an official SDK) runs unchanged in the sandbox. Declare the inbox on the email plugin:

yaml
emulation:
  email:
    mailosaur: {}

mailosaur.com is then answered inside the sandbox from the mail the app sent through any intercepted provider (SES, SendGrid, Resend, Postmark, Mailgun). A message addressed to <anything>@<server id>.mailosaur.net is in that server's inbox; mail to other addresses is in none. Any server id works, there is nothing to create. The suite needs no base URL change and no code change: keep the SDK's default host, the real server id and the real addresses. A Playwright suite Cofactor runs on the sandbox gets NODE_EXTRA_CA_CERTS, as actions do, so its Node trusts the emulator (unless the suite sets its own NODE_EXTRA_CA_CERTS, which then wins and must include /etc/emulation/ca.crt). The SDK still needs a key; any value works, so give the suite one in its cofactor.tests.yaml:

yaml
env:
  MAILOSAUR_API_KEY: emulated

Served (the read side, as the SDKs call it): list messages, search them (sentFrom and sentTo match a whole address, subject and body match any part, ignoring case; match ALL or ANY; receivedAfter, page, itemsPerPage), get one message, delete one, delete all of a server's, list servers and get one. The SDKs' wait-for (messages.get, search with a timeout) works as against Mailosaur, polling until the mail arrives. A message carries from, to, cc, bcc, subject, received, the html and text bodies with their links (html <a> links, text URLs), html images, verification codes (each standalone run of 4 to 8 digits, or 4 to 8 upper-case letters and digits with both, in order of appearance, never inside a URL; a year in a footer counts too), attachment names and types, and From/To/Subject/ Date headers. Deleting hides a message from the Mailosaur inbox only: email.sent-emails still returns it, and email-reset clears both. The emulator keeps the last 500 emails the app sent, to any address, so in a long run the oldest leave the inbox.

Not emulated (501, recorded): creating servers or messages, forward, reply, attachment and raw-message downloads, spam and deliverability analysis, previews, devices (TOTP) and usage; SMS; mail the app sends over SMTP (see Email above).

Scripted emulators

When no plugin covers a service your app calls, write the emulator yourself as a script in your repository. emulation.scripted maps a name to the script, the domains it answers and a loopback port:

yaml
emulation:
  scripted:
    acme:
      run: exec python3 emulators/acme.py
      domains: [api.acme.example.com]
      port: 4100
      env:
        ACME_API_URL: https://api.acme.example.com
        ACME_CA_PEM: ${emulation.ca_pem}

Every field is required (env may be {}).

  • run: The command that starts the script, run from the checkout like a service's run. Prefix it with exec.
  • domains: Hostnames the emulator answers, lowercase, no wildcard, port or IP address. A domain an emulator plugin already serves, or another scripted emulator claims, is refused.
  • port: The loopback port the script listens on, 1024-65535, not one of your declared ports and not another emulator's.
  • env: Environment variables applied to EVERY service, prepare command and action (like emulation.env), not only the emulator. A name that is also in the top-level env, another emulator's env, or one the sandbox sets itself (PATH, HOME, USER, LANG, NODE_EXTRA_CA_CERTS) is refused, since it would silently override that value everywhere. ${emulation.ca_pem} is replaced by the PEM text of the emulator's CA, for clients that take a certificate in a variable instead of a file; no other ${...} reference is resolved here (not ${params.*} or ${secrets.*}). ${emulation.ca_pem} is refused anywhere outside a scripted emulator's env.

How it behaves:

  • Always on. Declaring it adds a service named scripted-<name> (it starts after the build, and restarts on every prepare). Don't declare a service of that name yourself.
  • The script's service gets the same environment as your app's other services (it is your own code in your own sandbox).
  • The script runs as the unprivileged sandbox user and listens on 127.0.0.1:<port>, plain HTTP. TLS, the CA and the /etc/hosts entries for your domains are handled for you (see "How interception works"): the app calls https://api.acme.example.com/... unmodified and the emulator forwards every request on that domain to your script, with its method, path, query, headers and body (DELETE and OPTIONS bodies included), and returns your response as it streams, with every Set-Cookie header. A response may be held open as long as you like; when the caller disconnects, the emulator drops its connection to your script. If the script isn't listening (crashed, restarting), the caller gets 502 scripted_emulator_unreachable, recorded like any request.
  • The script must answer GET / with a status below 400: that is its health check, and the copy isn't ready until it passes.
  • Every request on the domain reaches your script; there is no 501 for a path you didn't write. Return your own 404 for what you don't serve. Requests show in GET /_emulation/requests like a plugin's.
  • The runtime (Python, Node, ...) is your definition's concern: install it in setup (or the image), like any service's.

A minimal Python (standard library only) example, emulators/acme.py:

python
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

class Handler(BaseHTTPRequestHandler):
    def _send(self, status, body):
        payload = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def do_GET(self):
        if self.path == "/":  # the health check
            self._send(200, {"ok": True})
        elif self.path == "/v1/widgets":
            self._send(200, {"widgets": [{"id": "w_1", "name": "Sprocket"}]})
        else:
            self._send(404, {"error": "not_found"})

ThreadingHTTPServer(("127.0.0.1", 4100), Handler).serve_forever()

How interception works

Most plugins own real domains. Inside the sandbox, those domains (e.g. email.us-east-1.amazonaws.com for the email plugin's SES routes, or accounts.google.com for google-oauth) are resolved via /etc/hosts to the emulator instead of the real internet. The emulator serves them over real TLS, using a CA generated when the version's ready snapshot is built (every copy shares it). It survives an emulator restart, so services that read NODE_EXTRA_CA_CERTS once at startup don't break when the emulator restarts. Services with reload_on_prepare: true, prepare commands and actions get NODE_EXTRA_CA_CERTS=/etc/emulation/ca.crt so they trust that CA. The CA is also added to the system trust store when the image has update-ca-certificates (Debian, Ubuntu, Alpine with the ca-certificates package), which .NET, Go, curl and OpenSSL-based clients read; on an image without it, a non-Node runtime must trust /etc/emulation/ca.crt itself. Some clients carry their own bundle and ignore the system store; point them at the system bundle in env:: boto3/botocore with AWS_CA_BUNDLE: /etc/ssl/certs/ca-certificates.crt, Python requests with REQUESTS_CA_BUNDLE (same path). Java reads its own keystore, updated by the same command only when the image has ca-certificates-java. A service WITHOUT reload_on_prepare never gets it (nor any emulation env): its calls to an emulated domain fail TLS. Any service that talks to an emulated provider must be reload_on_prepare.

oidc owns no domain and needs neither /etc/hosts nor the CA. It is reached at its public URL (the copy's emulation port), which has a publicly trusted certificate, so any client reaches it the way it reaches a real provider. The other plugins keep using /etc/hosts and the CA.

No passthrough. An unmatched path on an emulated domain doesn't fall through to the real provider — it returns 501 and the attempt is recorded, so a route the app calls that no plugin has implemented yet fails loudly and visibly instead of silently reaching a real third party.

The emulator depends on openssl for certificate generation. For a GitHub-delivered app, the platform installs it before your setup runs, so a definition doesn't need to install it itself; a pushed image that declares emulation must include it (apt-get install -y openssl), or the emulator never turns healthy and prepare fails.

Operations

Each plugin declares typed operations — the same shape as an action (id, description, typed input, typed output) — that appear right alongside your definition's own actions, named <plugin>.<op>. They run exactly like an action: cofactor sandbox run <id> <plugin.op>, or as a seed step (action: email.sent-emails). Cofactor calls the emulator's control plane directly rather than shelling into the sandbox for these.

Today: aws.secrets, aws.parameters and aws.cognito-pools — no input, return the seeded secrets' / parameters' names, ARNs, versions and read counts, and the Cognito pools' users (never values, passwords or tokens). email.sent-emails — no input, returns every email captured since boot or the last reset. In the example app, it verifies that invite-user actually sent the invitation:

bash
cofactor sandbox run <id> invite-user \
  --input workspace_id=<acme.workspace_id> \
  --input email=new@example.test --input role=member --input as=owner
cofactor sandbox run <id> email.sent-emails

Authentication and provider login

For normal persona-based flows, have authentication.run create the application's session; see cofactor sandbox guide v2 authentication. For a flow testing Google login, start without that pre-authenticated state and use the google-oauth emulator through the app's actual login button. This avoids treating a successful pre-authenticated landing as proof of the provider redirect and callback.

For Google callback configuration, app-code compatibility, the account chooser and authentication.emulated (Cofactor signs a persona in through Google with no script), read cofactor sandbox guide v2 authentication. Each persona is a Google account; a definition declaring google-oauth with no personas fails validation: "each persona is a Google account; declare at least one". Google browser authorization and the backend token/user-info handshake both need to work; verify the full signed-out journey. For apps that use a standard OIDC provider (Auth0, Okta, Cognito, Keycloak, Clerk...), declare oidc instead; see the "Standard OIDC" section of cofactor sandbox guide v2 authentication. Hosted identity intermediaries are not covered by declaring google-oauth alone, and neither are One Tap, FedCM or popup sign-ins or a person using the copy in their own browser.

Reference: https://docs.runcofactor.com/reference/sandbox-emulation#google-oauth-and-third-party-login