Authentication
This script is only for Cofactor's automated test runs: a person who claims a sandbox signs in through your app's own login with the email and password the claim prints, and only cofactor sandbox verify-env runs it outside a test (it signs every persona in on its claim to prove the script works). Native workflow login nodes use the persona declared in this sandbox definition. Declare authentication when your sandbox needs native persona login: exactly one of run (your script) or emulated (Cofactor signs the persona in through the Google or OIDC emulator; see "Google sign-in as a persona" and "Standard OIDC" below). Existing definitions can use personas in prepare, seeds and actions without this script; a native login without it fails with script_not_declared. Each run gets its own copy, so Cofactor asks the copy's authentication.run script to create an application session for the requested persona. The script receives the prepared copy environment and COFACTOR_AUTH_PERSONA; it returns Playwright storage state as JSON on stdout. The cookies must be for the copy's public origin (sign in through the public URL, as below), not localhost. The example needs no language runtime: a POSIX shell, curl, jq and awk:
A Workflow's sandbox.reset action replaces its active Sandbox v2 copy with
another copy of the same pinned snapshot and version. When the browser was
already signed in as a mapped persona, Cofactor creates fresh authentication
state for that same persona on the replacement before the action completes.
An anonymous browser remains anonymous. An authenticated identity that is not
mapped to a sandbox persona cannot be retained and causes the reset step to
fail. Reset remints authentication without replaying earlier Login steps or
copying old cookies/storage state; the app's authentication.run or
authentication.emulated contract must be able to sign in on each fresh copy.
See the Sandbox v2 guide's
seeds-and-actions topic for the reset action and its place in a test with
several named checkpoints.
personas:
admin: { email: admin@example.test }
member: { email: member@example.test }
authentication:
run: sandbox/auth.sh
#!/bin/sh
set -eu
persona=${COFACTOR_AUTH_PERSONA:?missing persona}
# This persona's email and generated password; fails if either is missing.
login=$(printf '%s' "$COFACTOR_PERSONAS" | jq -ec --arg p "$persona" \
'.[$p] | {email, password} | select((.email | type) == "string" and (.password | type) == "string")')
email=$(printf '%s' "$login" | jq -r .email)
jar=$(mktemp)
trap 'rm -f "$jar"' EXIT
# Sign in through the copy's public HTTPS API. This preserves Secure and
# __Host- cookie behavior; localhost HTTP is not suitable for those cookies.
printf '%s' "$login" | curl -fsS -c "$jar" -H 'content-type: application/json' \
--data-binary @- "$API_URL/api/auth/login" >/dev/null
# Check the resulting identity before giving the session to the browser.
curl -fsS -b "$jar" "$API_URL/api/auth/me" | jq -e --arg email "$email" '.user.email == $email' >/dev/null
# Convert the cookie jar to Playwright storage-state JSON. Curl's Netscape
# format does not carry SameSite, so adapt this field to your app's cookie.
awk -F '\t' '
{ httponly = "false" }
/^#HttpOnly_/ { sub(/^#HttpOnly_/, ""); httponly = "true" }
/^#/ || NF < 7 { next }
{ print $6 "\t" $7 "\t" $1 "\t" $3 "\t" $5 "\t" httponly "\t" $4 }
' "$jar" | jq -Rn '{
cookies: [inputs | split("\t") | {
name: .[0], value: .[1], domain: .[2], path: .[3], expires: (.[4] | tonumber | if . == 0 then -1 else . end),
httpOnly: (.[5] == "true"), secure: (.[6] == "TRUE"), sameSite: "Lax"
}],
origins: []
}'
If the app stores its access token in local storage, include
an origins entry for the exact copy origin, with {name, value} pairs in
localStorage. Do not print secrets to stderr, write state to a normal action,
or use a fixed browser profile. Cofactor validates the returned state against
the current copy's public origins and keeps it private to that execution.
When the script fails
Write diagnostics to stderr: stdout is the state and is never shown. When the script exits non-zero (or runs past its 60 s limit), the Login step fails with which persona, the exit code and the end of the script's stderr, for example:
sandbox authentication failed: script_failed (persona "admin": sandbox/auth.sh exited 127). Its stderr ended: sandbox/auth.sh: line 4: curl: command not found
Every org member can read that error. Only the copy's known values (secrets,
secret params, persona passwords) are scrubbed from it, verbatim: a session
cookie, token or login response the script prints is shown as is. So print
what failed, never a response body, curl -v or set -x trace.
Exit 127 is a command the image does not have: install it in the image, or
use what it has. cofactor sandbox verify-env signs every persona in on a
fresh claim and reports the same message per persona, so run it after every
push that changes the image or the script, before a test depends on it.
Third-party identity providers
For ordinary application tests, create the app's session directly. Use the
sandbox-only login API, a signed test token accepted only by the copy, an SDK,
or the provider's emulator-backed token exchange. The auth action should
finish with the application's own session cookie or local-storage token. A
flow that tests login itself must begin clean: retain its application login
node with performLogin: false to select the app and environment, without
seeding or preloading an app session. Then navigate to the app and traverse
its real sign-in UI against the declared provider emulator.
Google OAuth requires interception on both sides. Cofactor intercepts the browser authorization request, including an app HTTP redirect to Google, and answers it from the emulator: its account chooser, or a code for the copy's callback when the request's login_hint matches a persona. The declared sandbox emulator handles the app's token exchange and user-info requests. Verify the complete callback and resulting app identity; an intercepted browser redirect alone does not prove the server handshake works.
Google sign-in as a persona (authentication.emulated)
When the app's only login is "Sign in with Google", there is no password
endpoint for a script to call. Declare emulated instead of run, and
Cofactor signs the persona in itself, inside the copy, with no script:
authentication:
emulated:
provider: google-oauth
sign_in: ${params.web_url}/sign-in
authentication is exactly one of run or emulated; both, neither key
inside it, or an unknown key fails validation. provider must be
google-oauth or oidc (this section describes google-oauth; for oidc
see "Standard OIDC" below) and must be declared under emulation. sign_in is the app URL that starts the Google
sign-in: ${params.<name>}/path, where the param is a {port: ...}
param on a PUBLIC port, because the sign-in starts on the copy's public
origin. Use the port that serves your sign-in route, for example
${params.api_url}/auth/google when the API starts the flow and the
web app only links to it, or ${params.web_url}/sign-in for a single-port
app. A bare path, an undeclared param or a private-port param fails
validation.
A complete definition that passes cofactor sandbox validate:
version: 1
resources: { vcpus: 2, memory_mib: 4096 }
setup: |
apt-get update -qq
apt-get install -y -qq curl unzip >/dev/null
curl -fsSL https://bun.sh/install | bash >/dev/null
ports:
web: { port: 8300, access: public }
params:
web_url: { port: web }
env:
PUBLIC_URL: ${params.web_url}
GOOGLE_CLIENT_ID: sandbox
GOOGLE_CLIENT_SECRET: sandbox
GOOGLE_REDIRECT_URI: ${params.web_url}/auth/callback
services:
app:
run: bun server.ts
health: { http: 8300, path: /health }
reload_on_prepare: true
personas:
alice: { email: alice@example.test }
bob: { email: bob@example.test }
authentication:
emulated:
provider: google-oauth
sign_in: ${params.web_url}/sign-in
emulation:
google-oauth: {}
lifecycle:
build:
- name: install
run: bun install
inputs: [bun.lock, package.json]
prepare: []
environments:
default: { description: Stock data. }
setup is for GitHub-delivered definitions, as in the definition topic; a
pushed image omits it (it is already built).
What happens for a Login step as persona bob:
- The helper GETs
sign_inon the copy's public URL and follows the redirects with a cookie jar (at most 10). - At the hop to accounts.google.com, which resolves to the emulator
inside the VM, it adds
login_hint=bob@example.test. The emulator completes the authorize request for that persona without showing the chooser. - The emulator redirects to the app's callback; the app exchanges the code and sets its session cookie.
- The cookies for the copy's public origin become the Playwright
storage state, validated like the output of
authentication.run.
Every redirect hop must stay on the origins of your public {port}
params or on accounts.google.com; a hop anywhere else fails the
sign-in. Success needs the provider hop AND a cookie set for the copy
after it, so a pre-provider CSRF or state cookie is not mistaken for a
session. The
Login node, persona switching and landing check are the same as for
authentication.run. A failed emulated sign-in shows the Login step
error sandbox authentication failed: script_failed (persona "bob": the sandbox helper reported <reason>), where the reason is one of
sign_in_unreachable, sign_in_rejected, sign_in_no_session,
callback_origin or invalid_state. Look for what a
customer can fix: the app redirects to an origin the definition does not
declare as a public {port} param; sign_in never reaches Google; the
service that calls Google lacks reload_on_prepare or does not trust
/etc/emulation/ca.crt. The Login step can also fail with
state_origin_mismatch when the app sets a cookie for a parent Domain
outside the copy's public origins. The specific failure category is
visible to Cofactor support, and the emulator's own log is in the copy at
/var/lib/cofactor/logs/emulator.log.
Emulated sign-in covers sign-ins the server starts with HTTP redirects. It does not cover Google One Tap, FedCM or popup sign-ins done in browser JavaScript, and it does not cover a person using the copy in their own browser: accounts.google.com is hard-coded in apps and only Cofactor's browser (and the VM itself) reaches the emulator for it.
The chooser. When Cofactor's browser agent reaches Google's authorize URL, the emulator serves a real account-chooser page listing every persona by name and email; clicking one completes the sign-in as that persona. A flow that tests the Google journey itself clicks "Sign in with Google", picks a persona on the chooser, and asserts the signed-in identity.
login_hint preselects. An authorize request whose login_hint equals a
persona's email (case-insensitive) skips the chooser. This holds even
when the app also sends prompt=select_account, which real Google would
honor by showing its chooser; that is a deliberate deviation so the
helper and hint-sending apps sign in without a click. An absent or
unmatched hint shows the chooser.
Emulator limits. Authorization codes are single use, and are bound to the
redirect_uri of the authorize request, and to its client_id when both
the authorize request and the token request body carry client_id: a
replayed code, a code the emulator did not issue, or a mismatch is
invalid_grant. Send the same redirect_uri on authorize and on the token exchange, as real Google
requires. The emulator does NOT check that redirect_uri is registered
anywhere; any http(s) URL is accepted, so a wrong callback is caught only
by your app.
Google callback configuration
Supply the current copy's callback using the app's existing configuration:
params:
api_url: { port: api }
env:
GOOGLE_CLIENT_ID: sandbox
GOOGLE_CLIENT_SECRET: sandbox
GOOGLE_REDIRECT_URI: ${params.api_url}/auth/callback
emulation:
google-oauth: {}
personas:
alice: { email: alice@example.test }
This is a fragment: declare the public api port, use your app's actual
variable names and callback path, and set reload_on_prepare: true on the
backend calling Google. An app whose callback comes from configuration
can use this without auth code changes. A hardcoded production callback
must become configurable. No per-copy Google Console registration is
needed for the emulated path; real Google login keeps Google's rules.
Do not add live: true merely to avoid service restarts. That optimization
requires the app to re-read the live value per request; a normal {port}
param with reload_on_prepare works for apps that read env at startup.
Google needs both browser authorization interception and sandbox-side token/user-info emulation. Verify the app callback and a protected request, not just that the browser received an emulated code.
Each persona is a Google account: its email is the Google email, and its
Google sub is derived from the persona name, so it is the same in every
copy. The identity claims are sub, email, email_verified, name and
given_name (both the persona name), plus the id_token's standard
iss/aud/azp/nonce and time claims. No family_name, picture or hd.
There is no default Google user; a
definition that declares google-oauth with no personas fails validation.
If Google is reached through hosted Auth0, Clerk or another intermediary,
this Google emulator does not emulate that intermediary. If the app lets
you configure its own OIDC provider (an issuer or authority setting), use
the oidc emulator instead: see "Standard OIDC" below. Otherwise inspect where
token exchange occurs. Prove the customer's actual library and trust setup;
do not disable token verification or alter production auth to pass a test.
Non-Node clients must trust /etc/emulation/ca.crt through their runtime's
supported mechanism. This native Login-node contract does not inject
authentication into an external Playwright suite.
Standard OIDC (Auth0, Okta, Cognito, Keycloak, Clerk, ...)
For an app that signs in through any standard OpenID Connect provider,
declare the oidc emulator and point the app's issuer at it. The emulator
is a generic OIDC provider, not a copy of one vendor: use it with the
vendor's own SDK or any OIDC library, as long as the app's issuer (or
authority, domain or base URL) setting is configurable. An app that signs
in through an Amazon Cognito user pool with the AWS SDK, Amplify or the
hosted UI, with the pool's own ids and hosts, uses emulation.aws.cognito
instead (see the AWS section of the emulation topic).
This is a fragment: declare the public web port, use your app's actual
variable names and callback path, and set reload_on_prepare: true on the
service that reads the issuer.
params:
web_url: { port: web }
issuer_url: { port: emulation }
env:
OIDC_ISSUER: ${params.issuer_url}
OIDC_CLIENT_ID: sandbox
OIDC_CLIENT_SECRET: sandbox
OIDC_REDIRECT_URI: ${params.web_url}/auth/callback
services:
app:
run: bun server.ts
health: { http: 8300, path: /health }
reload_on_prepare: true
personas:
alice: { email: alice@example.test }
emulation:
oidc: {}
issuer_url: { port: emulation } is the copy's public emulator address and
is the issuer, exactly: an https origin with no trailing slash, with a real
TLS certificate. The app needs no CA and no /etc/hosts entry, and a
library that refuses an http issuer is satisfied. Point the vendor SDK's
issuer, authority or domain setting at it (OIDC_ISSUER above); the SDK
discovers everything else from
<issuer>/.well-known/openid-configuration. The service that reads the
issuer needs reload_on_prepare: true, because the address is per copy.
Endpoints: /.well-known/openid-configuration, /authorize, /token, /userinfo (GET and POST), /jwks.
Client id and secret are accepted as-is: use any values, such as
sandbox. The token endpoint takes client credentials in the body or by
HTTP Basic and never checks the secret. PKCE is advertised (S256 and
plain) so libraries that send it proceed, but the challenge is not
verified.
Redirect rule. The redirect_uri on /authorize must be an http(s) URL on
one of the copy's public origins (any public {port} param of the
definition); anything else is a 400 and nothing is redirected. Use the
port that serves the callback, as in "Google callback configuration".
Each persona is an account: its email is the account email. Claims, in the
id_token and from /userinfo, are sub (stable per persona, the same in every
copy), email, email_verified (true) and name, plus the id_token's
standard iss/aud/azp/nonce and time claims. Nothing else: no groups, roles,
picture or vendor-specific claims, so an app that depends on those needs
its own handling in the sandbox. Authorization codes are single use and are
issued only by /authorize; a replayed or never-issued code is invalid_grant,
as is a different redirect_uri. The id_token is signed RS256 with a key
published at /jwks.
The sign-in link. /authorize is locked: signing in needs a browser that has
opened the copy's sign-in link. Without it, /authorize shows a page saying to
open the sandbox's sign-in link from Cofactor (HTTP 403) and the app is not
signed in. The link is <emulation origin>/oidc/enter?key=.... Opening it
sets a browser-session cookie and shows "Sign-in is unlocked"; after that the
app's Sign in button reaches the account chooser, which lists each persona by
name and email, and picking one signs in as that persona. The unlock lasts
until that browser session ends; the link itself works for the copy's life,
so reopen it if you land on the locked page again. cofactor sandbox claim and cofactor sandbox show <id>
print the link as Open sign-in: ... next to the persona logins, and the
sandbox API returns it as signInUrl. Only organization members who can read
sandboxes see it. A preview has no sign-in link. Treat the link like the
persona passwords: it is a credential for that copy. --json output includes
it, so keep that output out of CI logs.
Cofactor's own browser agent and native Login steps pass the gate automatically, so a flow that tests the sign-in journey needs no link step.
Login steps. authentication.emulated with provider: oidc signs a persona
in with no script:
authentication:
emulated:
provider: oidc
sign_in: ${params.web_url}/login
oidc must be declared under emulation, and sign_in follows the same
rules as for Google (${params.<name>}/path on a public {port} param).
Inside the copy the helper GETs sign_in, follows the redirects with a cookie
jar, and at the hop to the issuer's /authorize adds the persona's
login_hint and the gate; the emulator redirects to the app's callback, the
app sets its session, and the cookies become the storage state. Every
redirect hop must stay on a public {port} origin of the definition or the
issuer, and a session cookie must be set after the issuer hop. Failures are
reported as for Google, and the emulator's own log is in the copy at
/var/lib/cofactor/logs/emulator.log. The helper requires the issuer to be
https.
A complete definition that passes cofactor sandbox validate:
version: 1
resources: { vcpus: 2, memory_mib: 4096 }
setup: |
apt-get update -qq
apt-get install -y -qq curl unzip >/dev/null
curl -fsSL https://bun.sh/install | bash >/dev/null
ports:
web: { port: 8400, access: public }
params:
web_url: { port: web }
issuer_url: { port: emulation }
session_secret: { secret: true }
env:
OIDC_ISSUER: ${params.issuer_url}
OIDC_CLIENT_ID: sandbox
OIDC_CLIENT_SECRET: sandbox
OIDC_REDIRECT_URI: ${params.web_url}/auth/callback
SESSION_SECRET: ${params.session_secret}
services:
app:
run: bun server.ts
health: { http: 8400, path: /health }
reload_on_prepare: true
personas:
alice: { email: alice@example.test }
bob: { email: bob@example.test }
emulation:
oidc: {}
authentication:
emulated:
provider: oidc
sign_in: ${params.web_url}/login
lifecycle:
build:
- name: install
run: bun install
inputs: [bun.lock, package.json]
prepare: []
environments:
default: { description: Stock data. }
The sample app in the Cofactor repository, packages/demo-app-oidc, is a
working example using the openid-client library.
References
- https://docs.runcofactor.com/reference/sandbox-definition#authentication
- https://docs.runcofactor.com/reference/sandbox-emulation#google-oauth-and-third-party-login
cofactor sandbox guide v2 personascofactor sandbox guide v2 emulationcofactor sandbox guide v2 ports