Metadata-Version: 2.5
Name: fauxbus
Version: 0.5.0
Summary: A wire-level fake of the Globus API for E2E testing
Project-URL: Homepage, https://github.com/atmarx/fauxbus
Project-URL: Issues, https://github.com/atmarx/fauxbus/issues
Author: Andrew Marx
License-Expression: MIT
License-File: LICENSE
Keywords: fake,globus,http,integration-tests,testing
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.11
Provides-Extra: conformance
Requires-Dist: globus-sdk==4.8.1; extra == 'conformance'
Provides-Extra: dev
Requires-Dist: pytest<9,>=8; extra == 'dev'
Requires-Dist: ruff<1,>=0.5; extra == 'dev'
Description-Content-Type: text/markdown

# Fauxbus

A wire-level fake of the Globus API for E2E testing.

## The problem

Globus is the data fabric of research computing: it moves datasets
between universities, national labs, and HPC centers, and its API is how
institutions automate that world — group rosters that gate who can reach
which collection, permissions, transfer pipelines.  If you run research
infrastructure, sooner or later you have code calling this API, and that
code matters more than most: it decides who can touch the data.

Testing that code is where it gets uncomfortable.  Globus has no
sandbox, no emulator, no local mode.  The SDK ships a testing module,
but it is in-process canned responses — by its own docs "a best
approximation of API responses" — which serves unit tests well and
cannot back a socket.  So an integration test has two options: a real
tenancy (real credentials in CI, real groups with real people in them,
rate limits, shared mutable state, network weather), or nothing.  A lot
of shops choose nothing.  The layer that gates access to research data
ends up the least-tested code in the pipeline, precisely because it is
the riskiest thing to point a test at.

Fauxbus is a third option: a standalone HTTP server that imitates the
Globus API at the wire level.  Point your `globus-sdk` client at
`http://localhost:9800` instead of the real service and run your
existing suite — same requests, same response shapes, same status
codes.  Your code never learns it isn't talking to Globus.  And because
the whole point of a fake is control, failure is a feature you schedule:
a 429 on exactly the request where your retry logic needs exercise, an
identity that is already in the group, a batch action that partially
fails the way the real service partially fails.

**Status: early but real.**  Imitated today, against globus-sdk 4.8.1:

- **Groups** — the complete `GroupsClient` surface: all fourteen
  methods, all eleven batch membership verbs.
- **Auth, as a service** — the client-credentials grant, so a service
  can fetch a token as itself and spend it, plus introspection and
  revocation, so a resource server can ask whether a token is real and
  an issuer can take one back.
- **Auth, as a person** — the authorization-code flow with OIDC, so a
  real broker like Keycloak can sign a seeded person in, linked
  identities and all; native apps with PKCE and no secret, including
  the SDK's `UserApp`; refresh tokens, so an app can stay signed in
  past expiry; and identities lookup, so `IdentityMap` can turn a
  username into a UUID and back.
- **Transfer task monitoring** — the `endpoint_manager_*` calls a
  service uses to watch other people's transfers into a collection.

The conformance suite drives all of it through the actual globus-sdk,
unmodified, including the SDK's retry layer recovering through an
injected 429.  Response shapes not yet backed by a recording are marked
`PROVISIONAL` in code and tracked as conformance obligations — that
list is in [SPEC.md](SPEC.md), along with the full design.  Nothing is
stable yet.

## Fake, not mock

Your code doesn't know Fauxbus is there.  No monkeypatching, no fixture
dicts shaped like your guess about what Globus returns.  The client
library you ship is the client library you test against — Fauxbus
imitates what `globus-sdk` actually sends and expects, pinned to a
stated SDK version.  Shapes come from the SDK's own recorded fixtures
where they exist, from the published docs where they don't, and where
neither reaches, the guess is labelled `PROVISIONAL` in the code rather
than passed off as fact.

If canned responses inside a Python unit test are all you need, use the
SDK's own `globus_sdk.testing` — that's the in-process layer, and its
fixtures are Fauxbus's ground truth.  Fauxbus is for the layer it
architecturally can't reach: a real socket your whole stack can talk
to, with state behind it (think moto next to botocore's `Stubber`).

## Quick start

```sh
pipx install fauxbus
fauxbus serve --port 9800
```

Released on [PyPI](https://pypi.org/project/fauxbus/); `pipx install
git+https://github.com/atmarx/fauxbus` gets `main`.  Point your app at
that port (next section) and run your existing test suite.  Groups and
Auth's login and client-credentials flows are here; of
`TransferClient`, only the task-monitoring calls exist so far.
Anything else meets an honest `501` — see below.

## Point your app at Fauxbus

globus-sdk reads one environment variable per service when it builds a
client, ahead of everything else.  Set these and your app talks to
Fauxbus without a line of it changing:

```sh
export GLOBUS_SDK_SERVICE_URL_AUTH=http://localhost:9800/
export GLOBUS_SDK_SERVICE_URL_GROUPS=http://localhost:9800/
export GLOBUS_SDK_SERVICE_URL_TRANSFER=http://localhost:9800/
```

All three are the bare root, Groups included: the SDK's own paths
already start with `/v2/`.  In a Python test suite,
[`fauxbus.testing`](#from-a-python-test) does this for you.  This covers `ConfidentialAppAuthClient` login flows,
native apps (`NativeAppAuthClient`, and the SDK's `UserApp`), and the
SDK's `ClientApp`, which fetches its own tokens; the conformance suite
runs all of them this way.

A native app is a client with no secret.  Seed it as one:

```json
"clients": {
  "00000000-0000-4000-8000-0000000a7170": {"public_client": true, "name": "My CLI"}
}
```

It proves its login with PKCE, which the SDK does for you, and with no
redirect URI of its own the SDK sends the browser to
`/v2/web/auth-code` on the auth service, where a person would copy the
code.  Fauxbus serves that page and allows it for every native client,
matched against the issuer, so point `GLOBUS_SDK_SERVICE_URL_AUTH` at
the same name you gave `--issuer`.  A test never needs the page: the
code is already in the `Location` header of the redirect that leads to
it.  `fauxbus.testing` walks that redirect for you, for `UserApp` too.

Then drive the person from the test.  Seed accounts and a login client
(see "Brokered login" below).  `POST /_fauxbus/auth/session` signs a
headless test in so the authorize page skips the account picker, or the
test can walk the picker over plain HTTP, the way a browser would.
The person's Groups token acts as them, and changing
their group memberships changes what your app sees on its next check:
the "let them in if they're in the group" test, with the test deciding
the answer.

### From a Python test

`fauxbus.testing` starts a server on a free port, seeds it, points the
SDK at it, and puts it all back afterwards:

```python
from fauxbus.testing import running_fauxbus

with running_fauxbus(seed="seed.json") as fb:
    app = globus_sdk.NativeAppAuthClient(CLIENT_ID)
    app.oauth2_start_flow("openid")
    code = fb.login(app.oauth2_get_authorize_url(), ALICE).code
    tokens = app.oauth2_exchange_code_for_tokens(code)
```

Your test then decides what happens next:

| | |
|---|---|
| `fb.login(url, account)` | Be the browser: follow an authorize URL and pick an account.  Returns `.code`, `.state`, `.error` and the whole `.location`, for a web app's callback route. |
| `fb.login_flow_manager(account)` | Hand this to `GlobusAppConfig(login_flow_manager=...)` and a `UserApp` logs in with nobody at the terminal. |
| `fb.sign_in(account)` | The `Cookie` value that makes authorize skip the picker, for a real browser. |
| `fb.tick(seconds)` | Move the logical clock. |
| `fb.fail(path, status, times=...)` | Arm a failure.  The SDK retries a 429 or 5xx by itself, so `times=1` usually tests its retry and your app never sees the failure. |
| `fb.clear_failures()`, `fb.reset()`, `fb.seed(doc)`, `fb.state()` | The rest of the everyday control plane. |
| `fb.control(method, path, body)` | Any other `/_fauxbus/` route, such as creating a transfer task. |
| `fb.env` | The environment that points a subprocess here. |

A refusal raises `FauxbusError` at the call that caused it, with
`.status` and `.body`.

Three defaults are worth knowing:

- **The environment is pointed for you.**  Forgetting to would send an
  unmodified app to the real Globus, so this is on unless you pass
  `point_env=False`.  It is process-wide, so tests running in parallel
  threads want `point_env=False` and `fb.env`.
- **ID tokens carry real time**, unlike `fauxbus serve`, because the SDK
  checks them against the real clock when it decodes them.  Access
  tokens and codes still expire by `tick`.  Pass
  `signed_token_clock="logical"` to get byte-identical ID tokens.
- **Any bearer token works**, as on any Fauxbus.  For a `tick` to kill a
  token, pass `require_issued_tokens=True`.

For pytest, add `pytest_plugins = ["fauxbus.testing"]` to your top-level
`conftest.py`.  Each test that takes the `fauxbus` fixture gets a fresh
server.  Override the `fauxbus_options` fixture to pass arguments:

```python
@pytest.fixture
def fauxbus_options():
    return {"seed": "seed.json", "require_issued_tokens": True}

def test_login(fauxbus):
    ...
```

These methods only make HTTP calls, so `Fauxbus("http://fauxbus:9800")`
drives a server in a compose stack the same way.  The harness needs
neither pytest nor globus-sdk, apart from `login_flow_manager`, which
needs the SDK.

## Tokens

By default any bearer token works, and its identity is a stable function
of the token string — `t-alice` is the same caller on every run, on
every machine.  That is usually what you want in a test.

When you need the real thing, register a confidential client in the seed
document and fetch a token the way your service will in production:

```python
from globus_sdk import ConfidentialAppAuthClient, AccessTokenAuthorizer, GroupsClient

auth = ConfidentialAppAuthClient(CLIENT_ID, SECRET, base_url="http://localhost:9800")
tokens = auth.oauth2_client_credentials_tokens(
    "urn:globus:auth:scope:groups.api.globus.org:all"
)
access_token = tokens.by_resource_server["groups.api.globus.org"]["access_token"]

groups = GroupsClient(base_url="http://localhost:9800",
                      authorizer=AccessTokenAuthorizer(access_token))
```

A Globus client *is* an identity, so that token acts as the client
itself — create a group with it and the client shows up as its own
`admin`, exactly as it would against the real service.

Start with `--require-issued-tokens` and Fauxbus stops accepting
made-up tokens: it checks that a token was issued here, hasn't expired
(on the logical clock — `POST /_fauxbus/tick` ages it, no sleeping), and
is good for the service being called.  Three production failures you
otherwise cannot write a test for.

That is also the mode for testing an app that stays signed in.  Ask for
offline access the way your app already does (`refresh_tokens=True` on
a flow, `request_refresh_tokens=True` on `UserApp`, or `offline_access`
from a broker) and every token the login returns comes with a
`refresh_token`.  Then tick past expiry and call again:

```bash
curl --json '{"seconds": 172801}' localhost:9800/_fauxbus/tick
```

The expired token gets a 401, the SDK refreshes and retries, and the
call succeeds as the same person without anyone signing in.  The SDK
does not notice a tick in advance (it times expiry on its own wall
clock), so the 401 is what sets the refresh off, just as an
early-dying token would in production.  Revoke the refresh token and
the next refresh fails, which is your logout test.  The conformance
suite's `test_the_sdks_user_app_keeps_working_past_expiry` is a working
copy.

## Brokered login (OIDC)

Seed people and a login client, give Fauxbus an issuer, and a real
broker can sign someone in through it.  The browser lands on a plain
Fauxbus page listing the seeded accounts — no passwords, ever — picks
one, and the broker gets a code, a signed ID token, and userinfo, the
way it would from Globus.  `examples/seed.json` carries a working set:
alice, whose Globus ID account has a linked university identity, and a
login client that requires the university provider, so she signs in
*as her university identity*.

```sh
fauxbus serve --seed examples/seed.json --issuer http://localhost:9800 \
              --signed-token-clock wall
```

**`--signed-token-clock wall` is the flag that matters.**  Fauxbus runs
on a logical clock and never reads real time unless you ask; Keycloak
checks an ID token's `exp` against real time and cannot be asked to
tick.  Without the flag, the tokens say 1970 and the login "just
fails."  (The example seed sets it already.)

**One issuer, two names.**  In compose the browser reaches Fauxbus at
`localhost:9800` and Keycloak reaches it at `fauxbus:9800`.  Fauxbus
stamps every ID token with the configured issuer whichever name it was
reached by, so give Keycloak the browser's name for the authorize URL
and the issuer, and the network's name for everything else.  The
identity-provider settings `examples/keycloak_broker.py` proved against
Keycloak 26.0:

| Keycloak setting | Value |
| --- | --- |
| Issuer | `http://localhost:9800` |
| Authorization URL | `http://localhost:9800/v2/oauth2/authorize` |
| Token URL | `http://fauxbus:9800/v2/oauth2/token` |
| JWKS URL (Use JWKS URL: on) | `http://fauxbus:9800/jwk.json` |
| User Info URL | `http://fauxbus:9800/v2/oauth2/userinfo` |
| Client authentication | Client secret as basic auth (`client_secret_basic`) |
| Validate signatures | on |
| PKCE | on, S256 |
| Scopes | `openid profile email` |
| Sync mode | force |

Basic auth because that is the only method the real Globus advertises;
Fauxbus also accepts `client_secret_post`, which the real service may
not.  Ask for `profile` and `email` explicitly — under `openid` alone
Globus sends no name or address, and neither does Fauxbus.  Run the
proof yourself with `python examples/keycloak_broker.py` (needs docker;
cleans up after itself).

The fixture signing key is published in `src/fauxbus/signing.py` on
purpose.  Anyone can forge a Fauxbus token, so nobody can be tempted to
trust one.  Never configure it as a trusted issuer anywhere real —
and Fauxbus refuses to run with an issuer under a Globus domain.

## Looking people up

`AuthClient.get_identities` and `IdentityMap` work against the people a
seed describes under `accounts`, linked identities included: each comes
back with its username, provider, name, email and organization, by UUID
or by username.  An identity nobody seeded is simply absent, as it would
be at Globus.

The exception is an identity Fauxbus knows *of* but cannot describe: a
registered client, a pinned token, or a group member seeded by bare
UUID.  Globus would return a full record for each, and Fauxbus has no
provider or name to give, so the lookup answers with a 501 rather than
pretend they do not exist.  If your app shows names for group members,
seed those members as accounts.  `provision=true` for an unknown
username is a 501 too: Globus would create the identity, and Fauxbus
does not.

## Watching transfers

A service that watches a collection for finished transfers — the
completion signal Globus only offers by polling — can be tested end to
end.  Fauxbus answers three `TransferClient` calls:
`endpoint_manager_task_list` (with `filter_endpoint`,
`filter_endpoint_use`, `filter_status` and `filter_completion_time`,
paged by `last_key`), `endpoint_manager_get_task`, and
`endpoint_manager_task_successful_transfers` (paged by `next_marker`).
No bytes move, ever; a task is bookkeeping.

Seed a collection, its subscription, and who may watch it:

```json
"collections": {
  "<collection id>": {"display_name": "Landing", "subscription_id": "<id>",
                      "roles": {"<client id>": "activity_monitor"}}
}
```

Then make a researcher's transfer happen and move it along from the
test:

```sh
curl localhost:9800/_fauxbus/transfer/tasks --json '{
  "owner_id": "<identity id>", "source_endpoint_id": "<anything>",
  "destination_endpoint_id": "<collection id>", "duration": 60,
  "files": [{"source_path": "/home/a/x.dat", "destination_path": "/landing/x.dat",
             "size": 1024, "checksum": "...", "checksum_algorithm": "sha256"}]}'
curl --json '{"seconds": 60}' localhost:9800/_fauxbus/tick   # now SUCCEEDED
curl --json '{"status": "FAILED"}' localhost:9800/_fauxbus/transfer/tasks/<task id>
```

A task with a `duration` finishes on `tick`, files arriving evenly on
the way; `INACTIVE` pauses one, `FAILED` with `files_succeeded` fails
it part-way.  A role without a subscription does nothing, as in Globus.

**Seed the clock to a real second.**  Task times are the logical clock
rendered as ISO 8601, and a fresh world's clock is zero, so its tasks
finish in 1970.  A poller that asks for "completed in the last ten
minutes" by its own wall clock will find nothing.  Seed `"clock"` to the
second your test starts (the example seed uses `1767225600`), and tick
it forward rather than letting it fall behind.

## In a compose stack

The repo ships a `Containerfile`.  Zero runtime dependencies means the
image is the Python base plus one stdlib-only wheel — nothing else rides
along.  Mount a state document at `/seed.json` and the world exists
before the first test connects:

```yaml
services:
  fauxbus:
    build: { context: ., dockerfile: Containerfile }
    ports: ["9800:9800"]
    volumes: ["./seed.json:/seed.json:ro"]
```

Build it with `--pull` (`docker compose build --pull`), and rebuild it
now and then.  Fauxbus publishes no image of its own, so the base layer
is whatever your builder cached the first time — and a cached base
stops collecting security fixes the day it was pulled.  The final stage
is Alpine for a related reason: a pure-stdlib app needs little more than
the interpreter, so less distro means fewer CVEs nobody can patch.
CI scans every image it builds with grype and fails on anything at
Medium or above that `.grype.yaml` hasn't acknowledged.  Each ack names
the exact package version it covers and why, so it lapses as soon as
the package changes.  Pass the same file to your own scanner
(`grype --config .grype.yaml`) to get the same acks.

The image ships a healthcheck on the control-plane index, so
`depends_on: { fauxbus: { condition: service_healthy } }` does the
waiting for you.  A runnable example — sibling-service pattern, seed
file included, both round-trip tested in CI — is in
[`examples/`](examples/).

## The control plane

Everything test-harness-y lives under `/_fauxbus/`, a prefix no Globus
API will ever claim — the imitated surface stays pure.  `GET
/_fauxbus/state` dumps everything in the world for assertions; `POST
/_fauxbus/reset` returns the world to its canonical seed (or to empty)
between tests — mutate freely, reset comes home.  Full control-plane
surface is in [SPEC.md](SPEC.md).

It is unauthenticated by design — it imitates a service that answers
the network, and harnesses are often sibling containers.  Which means
anyone who can reach the port can rewrite the world and arm forged
responses; for a fake, the sharpest risk isn't a crash but a lie, since
tests that trust it would go green when they should go red.  Run it
where you'd run any test fixture.  On a shared host,
`--control-loopback-only` refuses `/_fauxbus/` from non-loopback peers
without touching the imitated surface.  The reasoning, and the two
things that flag deliberately doesn't solve, are in
[SPEC.md](SPEC.md#control-plane-reachability).

## Loud 501s, no fiction

Fauxbus only implements endpoints a real consumer needs.  Anything it
doesn't imitate yet returns a loud `501` with a pointer to file an
issue — never a silent wrong answer pretending to be Globus.  If you
hit one, that's the fastest way to get it prioritized.

## The source is meant to be read

Comments narrate the design decisions where they live — why uuid5 and
never uuid4, why one lock, why 404 instead of 403, why failure
injection can't touch the control plane — at a depth meant for someone
learning how to *build* a wire-level fake, not just use one.

## Not affiliated with Globus

Fauxbus is an independent test tool, not affiliated with or endorsed by
Globus or the University of Chicago.  "Globus" is their trademark; this
project imitates the API's behavior for local testing only — the name
is a confession, not an infringement.  It's *faux*.

## License

MIT.  Fauxbus contains no Globus code: it imitates publicly documented
wire behavior, grounded against the Apache-2.0 `globus-sdk` as a
test-time dependency only.
