Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

test(browser): add full federation e2e flows, admin page coverage, and agent-friendly failure reporting

Gabe Kangas8948f72cc614
diff --git a/.gitignore b/.gitignore
index 8c5c3484ce..619b92c05e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,6 +43,9 @@ test/automated/browser/screenshots
lefthook-local.yml
test/automated/browser/cypress/screenshots
test/automated/browser/cypress/videos
+test/automated/browser/cypress/results
+# ffmpeg binaries downloaded into the test suites by test/automated/tools.sh
+test/**/ffmpeg
web/style-definitions/build/
web/public/sw.js
diff --git a/test/automated/browser/README.md b/test/automated/browser/README.md
index 3db82b682f..d5d77eac68 100644
--- a/test/automated/browser/README.md
+++ b/test/automated/browser/README.md
@@ -2,7 +2,8 @@
Cypress end-to-end tests for the Owncast web UI. They run against a real built
web bundle served by a real Owncast binary, with a real RTMP test stream for
-the online specs. Nothing is mocked.
+the online specs and a real (local) remote ActivityPub server for the
+federation specs. Nothing is mocked inside Owncast.
## Running
@@ -12,16 +13,16 @@ the online specs. Nothing is mocked.
This builds the web project into the server, installs npm dependencies, builds
and starts Owncast on port 8080 with a throwaway database, and runs every test
-group. A full local run takes about 2.5 minutes after the web build.
+group. A failed group does not stop the run: all groups execute so a single
+run reports every failure.
Useful variations:
```bash
-SKIP_BUILD=1 ./run.sh # reuse the existing web bundle and node_modules
-npx cypress run --browser chrome \
- --env tags=desktop \
- --spec "cypress/e2e/offline/*.cy.js" # one group, against an already-running server
-npx cypress open --env tags=desktop # interactive runner
+SKIP_BUILD=1 ./run.sh # reuse the existing web bundle and node_modules
+./run.sh desktop-federation # run only one group (see table below)
+SKIP_BUILD=1 ./run.sh desktop-online # fastest iteration on one group
+npx cypress open --env tags=desktop # interactive runner, against a running server
```
Cypress needs the `tags` env value (`desktop` or `mobile`) to decide which
@@ -31,17 +32,37 @@ skipped entirely.
Results are recorded to Cypress Cloud only when `CI` is set. Local runs upload
nothing and work offline.
+## Reading failures
+
+The suite is built so a failing run tells you exactly what broke:
+
+- `cypress/results/failures.json` is written across all groups of a run and
+ printed by `run.sh` at the end. Each entry has the spec, the full test
+ title, the complete error text, and the failure screenshot paths.
+- Any `console.error` logged by the application fails the current test, and
+ the assertion message contains the logged error text itself (see
+ `cypress/support/setup.js`).
+- Failure screenshots land in `cypress/screenshots/`.
+- Federation task failures (`cy.task('fediverse:*')`) time out with a message
+ describing what the fake remote server received instead and what to check.
+
+The intended loop for automated agents: make a change, `./run.sh`, read
+`cypress/results/failures.json`, fix, re-run the single affected group with
+`SKIP_BUILD=1 ./run.sh <group>` (after re-running `build/web/bundleWeb.sh`
+from the repo root if web code changed).
+
## Test groups
-`run.sh` runs five groups, in this order:
+`run.sh` runs six groups, in this order:
-| Group | Specs | Viewport | Server state |
-|-----------------|------------------------|-----------|--------------|
-| desktop-offline | `cypress/e2e/offline/` | default | offline |
-| mobile-offline | `cypress/e2e/offline/` | 375x667 | offline |
-| desktop-admin | `cypress/e2e/admin/` | default | offline |
-| desktop-online | `cypress/e2e/online/` | default | live stream |
-| mobile-online | `cypress/e2e/online/` | 375x667 | live stream |
+| Group | Specs | Viewport | Server state |
+|--------------------|---------------------------|----------|--------------|
+| desktop-offline | `cypress/e2e/offline/` | default | offline |
+| mobile-offline | `cypress/e2e/offline/` | 375x667 | offline |
+| desktop-admin | `cypress/e2e/admin/` | default | offline |
+| desktop-online | `cypress/e2e/online/` | default | live stream |
+| mobile-online | `cypress/e2e/online/` | 375x667 | live stream |
+| desktop-federation | `cypress/e2e/federation/` | default | live stream |
The offline and online directories run twice, once per viewport. Tests that
only make sense at one size are wrapped in `filterTests(['desktop'])` or
@@ -56,8 +77,9 @@ starts `ocTestStream.sh` and polls `/api/status` until the server reports
that theme authors rely on (`05-*_identifier_check`). If you rename one of
those identifiers you must update the customization docs.
- **Embeds**: `/embed/video`, `/embed/chat/readwrite`, `/embed/chat/readonly`.
-- **Chat**: visibility toggling, the mobile chat modal, name changes round-
- tripped over the websocket.
+- **Chat**: visibility toggling, the mobile chat modal, name changes and
+ message sends round-tripped over the real websocket (main page, mobile
+ modal, and the readwrite embed).
- **Fediverse viewer UI** (`offline/07`): the offline banner account string,
followers collection, and the follow modal end to end. The modal test
submits `[email protected]` to `/api/remotefollow`, which fails
@@ -65,16 +87,48 @@ starts `ocTestStream.sh` and polls `/api/status` until the server reports
surface the error alert. Known issue: at the mobile viewport the
`#follow-button` fails Cypress's visibility check, so the modal tests are
desktop-only. This may be a real mobile layout bug worth investigating.
-- **Admin UI** (`admin/01-admin_smoke`): authenticated visit, sidebar
- navigation sections, federation-gated menu items, status indicator, the
- General configuration page and its tabs, and the followers table. The admin
- is the most Ant Design-heavy surface in the project, so this group is the
- early-warning system for antd upgrades.
-
-Federation protocol behavior (signed activities, follows from real fediverse
-servers, delivery) is tested separately in `test/automated/activitypub/`. API
-behavior is tested in `test/automated/api/`. Don't duplicate either here:
-this suite is for what a browser renders and what a user clicks.
+- **Admin UI** (`admin/`): authenticated navigation smoke tests
+ (`01-admin_smoke`) plus a render check of every admin page
+ (`02-admin_pages`), each as its own named test. The admin is the most Ant
+ Design-heavy surface in the project, so this group is the early-warning
+ system for antd upgrades: a page that crashes or logs a React/antd error
+ fails its own test, naming the page. `/admin/upgrade` is excluded because
+ it fetches from the GitHub API.
+- **Federation flows** (`federation/`): full end-to-end flows against the
+ fake remote fediverse server (below). A signed inbound Follow must produce
+ a federated Accept, a live engagement card in chat ("followed this
+ stream"), the follower in the Followers tab, and a row in the admin
+ followers table. Fediverse chat authentication runs the whole OTP journey:
+ the account form, a real WebFinger lookup and signed DM delivery of the
+ code, code entry, and the authenticated badge on a subsequent chat message.
+
+Federation protocol behavior against real fediverse software (snac2) is
+tested separately in `test/automated/activitypub/`. API behavior is tested in
+`test/automated/api/`. Don't duplicate either here: this suite is for what a
+browser renders and what a user clicks.
+
+## The fake remote fediverse server
+
+`cypress/support/remote-fediverse-server.js` runs inside the Cypress Node
+process and is exposed to specs as `cy.task()`s:
+
+- `fediverse:createActor` starts the server (idempotent) and returns a fresh
+ remote actor `{ name, account, iri }` with its own RSA keypair and inbox.
+- `fediverse:sendFollow` delivers a signed Follow to Owncast's inbox and
+ waits for the Accept to arrive back.
+- `fediverse:waitForOTPCode` waits for the one-time-code DM and extracts the
+ code.
+
+It serves real WebFinger, actor documents, and an inbox over self-signed
+HTTPS on `https://127.0.0.1:9443`, and signs outbound activities with
+draft-cavage HTTP signatures. Owncast treats it exactly like a remote
+fediverse server. This requires `OWNCAST_ALLOW_INTERNAL_FEDERATION=true` and
+`OWNCAST_INSECURE_SKIP_VERIFY=true` in Owncast's environment at process
+start; `run.sh` exports both before starting the server.
+
+Flow specs create a fresh actor per test attempt because Owncast
+deduplicates repeat follows and pending OTP requests per account; a fresh
+actor keeps Cypress retries meaningful.
## Conventions
@@ -83,11 +137,14 @@ this suite is for what a browser renders and what a user clicks.
in `cypress/support/commands.js`. These chain into the Cypress command
queue, so a following `cy.visit()` sees the new config. Don't use raw
`fetch()` for setup, it races the test.
-- `setup()` from `cypress/support/setup.js` spies on `console.error` and
- fails any test that logged one. Call it at the top of every spec.
-- `testIsolation` is off (`cypress.config.js`): specs visit a page once per
- `describe` and assert across multiple `it()` blocks. Keep new specs
+- `setup()` from `cypress/support/setup.js` fails any test whose page logged
+ a `console.error`, and includes the logged text in the failure. Call it at
+ the top of every spec.
+- `testIsolation` is off (`cypress.config.js`): most specs visit a page once
+ per `describe` and assert across multiple `it()` blocks. Keep new specs
compatible with that pattern, and remember state carries between tests.
+ Multi-step journeys (like the federation flows) should instead run as one
+ `it()` so a retry replays the whole journey.
- Failed tests retry up to 3 times. Prefer an assertion that waits for the
real effect (`cy.get('#user-menu').should('contain', ...)`) over
`cy.wait(ms)`.
@@ -95,7 +152,8 @@ this suite is for what a browser renders and what a user clicks.
`{ auth: { username, password } }`.
- The `before()` hook in `cypress/support/e2e.js` sets the server URL to
`https://testing.biz` for every spec file. Several assertions depend on
- that exact value.
+ that exact value, including the Owncast actor IRI used by the federation
+ specs (`https://testing.biz/federation/user/streamer`).
## CI
@@ -103,7 +161,7 @@ this suite is for what a browser renders and what a user clicks.
requests that touch `web/`, Go code, or this directory, with 3 retry
attempts and a 20 minute timeout per attempt. In CI the groups are recorded
to Cypress Cloud under one build ID (`--record --parallel --group`), so all
-five groups appear as a single run in the dashboard.
+groups appear as a single run in the dashboard.
## Versions
diff --git a/test/automated/browser/cypress.config.js b/test/automated/browser/cypress.config.js
index 51b87bbb47..8dc95d472b 100644
--- a/test/automated/browser/cypress.config.js
+++ b/test/automated/browser/cypress.config.js
@@ -1,4 +1,35 @@
+const fs = require('node:fs');
+const path = require('node:path');
const { defineConfig } = require('cypress');
+const remoteFediverse = require('./cypress/support/remote-fediverse-server');
+
+// Append this spec's final failures to cypress/results/failures.json. run.sh
+// clears the file at the start of a run and prints it at the end, so one run
+// yields one machine-readable list of every failure across every group —
+// spec, test, error text and screenshots — that an agent (or human) can act
+// on without scrolling back through five groups of output.
+function recordFailures(spec, results) {
+ if (!results || !results.tests) return;
+ const failures = results.tests
+ .filter((test) => test.state === 'failed')
+ .map((test) => ({
+ spec: spec.relative,
+ test: test.title.join(' > '),
+ error: test.displayError,
+ screenshots: (results.screenshots || []).map((s) => s.path),
+ }));
+ if (!failures.length) return;
+
+ const out = path.join(__dirname, 'cypress', 'results', 'failures.json');
+ fs.mkdirSync(path.dirname(out), { recursive: true });
+ let existing = [];
+ try {
+ existing = JSON.parse(fs.readFileSync(out, 'utf8'));
+ } catch {
+ // first failing spec of the run
+ }
+ fs.writeFileSync(out, JSON.stringify(existing.concat(failures), null, 2));
+}
module.exports = defineConfig({
projectId: 'wwi3xe',
@@ -9,6 +40,11 @@ module.exports = defineConfig({
// uses the app. Cypress 12+ would otherwise reset to about:blank
// between tests.
testIsolation: false,
+ setupNodeEvents(on, config) {
+ on('task', remoteFediverse.tasks);
+ on('after:spec', recordFailures);
+ return config;
+ },
},
video: false,
retries: 3,
diff --git a/test/automated/browser/cypress/e2e/admin/02-admin_pages.cy.js b/test/automated/browser/cypress/e2e/admin/02-admin_pages.cy.js
new file mode 100644
index 0000000000..fbc97ecc99
--- /dev/null
+++ b/test/automated/browser/cypress/e2e/admin/02-admin_pages.cy.js
@@ -0,0 +1,61 @@
+/*
+Renders every admin page and fails on any console error (see support/setup.js:
+the error text is included in the failure). The admin is the most Ant
+Design-heavy surface in the project, so this spec is the early-warning system
+for antd upgrades: a page that crashes, renders the Next.js client-exception
+screen, or logs a React/antd error fails its own named test, telling you
+exactly which page broke.
+
+One it() per page keeps failures independent: a broken Video config page does
+not hide a broken Webhooks page.
+*/
+
+import { setup } from '../../support/setup.js';
+import filterTests from '../../support/filterTests';
+
+setup();
+
+const ADMIN_AUTH = { username: 'admin', password: 'abc123' };
+
+// Every admin page reachable without extra route params.
+// Deliberately excluded: /admin/upgrade (fetches releases from the GitHub
+// API, an external dependency that would make this suite flaky offline).
+const pages = [
+ '/admin',
+ '/admin/viewer-info',
+ '/admin/users',
+ '/admin/chat/messages',
+ '/admin/chat/emojis',
+ '/admin/access-tokens',
+ '/admin/actions',
+ '/admin/webhooks',
+ '/admin/plugins',
+ '/admin/config/general',
+ '/admin/config/server',
+ '/admin/config-video',
+ '/admin/config-chat',
+ '/admin/config-featured',
+ '/admin/config-federation',
+ '/admin/config-notify',
+ '/admin/config-social-items',
+ '/admin/hardware-info',
+ '/admin/stream-health',
+ '/admin/logs',
+ '/admin/help',
+ '/admin/federation/followers',
+ '/admin/federation/actions',
+];
+
+filterTests(['desktop'], () => {
+ describe('Every admin page renders', () => {
+ pages.forEach((page) => {
+ it(`Renders ${page}`, () => {
+ cy.visit(`http://localhost:8080${page}`, { auth: ADMIN_AUTH });
+ cy.get('#admin-page').should('exist');
+ // The Next.js static export shows this text when a page throws
+ // during client-side render.
+ cy.contains('Application error').should('not.exist');
+ });
+ });
+ });
+});
diff --git a/test/automated/browser/cypress/e2e/federation/01-fediverse_follow.cy.js b/test/automated/browser/cypress/e2e/federation/01-fediverse_follow.cy.js
new file mode 100644
index 0000000000..1bc47656e3
--- /dev/null
+++ b/test/automated/browser/cypress/e2e/federation/01-fediverse_follow.cy.js
@@ -0,0 +1,75 @@
+/*
+Full end-to-end inbound follow flow, using the fake remote fediverse server
+in cypress/support/remote-fediverse-server.js. Nothing is mocked inside
+Owncast: the harness delivers a real signed Follow activity to the inbox,
+Owncast verifies the HTTP signature, resolves the remote actor over HTTPS,
+persists the follower, federates a signed Accept back to the harness, and
+broadcasts an engagement event to chat.
+
+Assertions cover both layers:
+ - protocol: the Accept arrives back at the remote server's inbox
+ - UI: the follow appears live in chat, in the Followers tab, and in the
+ admin followers table
+
+Each test attempt creates a fresh remote actor because Owncast deduplicates
+repeat follows per actor (a re-follow does not re-fire the chat event).
+*/
+
+import { setup } from '../../support/setup.js';
+import filterTests from '../../support/filterTests';
+
+setup();
+
+const OWNCAST_INBOX = 'http://localhost:8080/federation/user/streamer/inbox';
+// Actor IRIs are derived from the configured server URL (set to
+// https://testing.biz for the whole suite in support/e2e.js).
+const OWNCAST_ACTOR_IRI = 'https://testing.biz/federation/user/streamer';
+
+filterTests(['desktop'], () => {
+ describe('Inbound fediverse follow', () => {
+ it('A signed Follow is Accepted and shows live in chat', () => {
+ cy.setConfig('federation/enable', true);
+ cy.setConfig('federation/private', false);
+ cy.setConfig('federation/showengagement', true);
+
+ // Chat must be connected before the follow arrives: engagement
+ // events are broadcast live over the websocket and are not part of
+ // the chat history backlog.
+ cy.visit('http://localhost:8080/');
+ cy.get('#chat-container').should('be.visible');
+
+ cy.task('fediverse:createActor').then((actor) => {
+ cy.task('fediverse:sendFollow', {
+ actorName: actor.name,
+ owncastInbox: OWNCAST_INBOX,
+ owncastActorIri: OWNCAST_ACTOR_IRI,
+ }).then((accept) => {
+ // Protocol-level proof: Owncast federated a signed Accept
+ // back to the remote server.
+ expect(accept.type).to.equal('Accept');
+ expect(accept.actor).to.equal(OWNCAST_ACTOR_IRI);
+ });
+
+ // Visual proof: the follow shows up in the chat feed as a
+ // social event card.
+ cy.get('.chat-message_social', { timeout: 15000 })
+ .should('contain', actor.name)
+ .and('contain', 'followed this stream');
+
+ // The new follower is listed in the Followers tab.
+ cy.contains('Followers').click();
+ cy.get('#followers-collection').should('contain', actor.name);
+ });
+ });
+
+ it('The follower appears in the admin followers table', () => {
+ cy.visit('http://localhost:8080/admin/federation/followers', {
+ auth: { username: 'admin', password: 'abc123' },
+ });
+ // The table lists the follower's name and actor URL. Any follower
+ // from the harness domain proves persistence without coupling this
+ // test to the actor created by the previous one.
+ cy.get('.ant-table').should('contain', '127.0.0.1:9443/actor/');
+ });
+ });
+});
diff --git a/test/automated/browser/cypress/e2e/federation/02-fediverse_chat_auth.cy.js b/test/automated/browser/cypress/e2e/federation/02-fediverse_chat_auth.cy.js
new file mode 100644
index 0000000000..3cff853816
--- /dev/null
+++ b/test/automated/browser/cypress/e2e/federation/02-fediverse_chat_auth.cy.js
@@ -0,0 +1,72 @@
+/*
+Full end-to-end fediverse chat authentication (OTP over ActivityPub), using
+the fake remote fediverse server in cypress/support/remote-fediverse-server.js.
+
+The whole login loop runs with no mocks inside Owncast: the viewer asks to
+link a fediverse account, Owncast performs a real WebFinger lookup against
+the remote server, resolves the actor, and delivers a signed direct message
+containing a one-time code to the remote inbox. The test reads the code out
+of the harness inbox exactly like a human reading their DMs, submits it, and
+verifies the chat user is visibly authenticated.
+
+The flow is one test on purpose: a retry re-runs the whole journey with a
+fresh remote account (Owncast will not re-send a DM for a still-pending
+account, and codes are single-use).
+*/
+
+import { setup } from '../../support/setup.js';
+import filterTests from '../../support/filterTests';
+
+setup();
+
+filterTests(['desktop'], () => {
+ describe('Fediverse chat authentication', () => {
+ it('Authenticates chat with a one-time code sent over ActivityPub', () => {
+ cy.setConfig('federation/enable', true);
+
+ cy.task('fediverse:createActor').then((actor) => {
+ cy.visit('http://localhost:8080/');
+
+ // Open the auth modal from the user menu and pick FediAuth.
+ cy.get('#user-menu').click();
+ cy.contains('Authenticate').click();
+ cy.contains('.ant-tabs-tab', 'FediAuth').click();
+
+ // Request a code for the remote account. Scope to the active tab
+ // pane: antd keeps the inactive IndieAuth pane mounted, and it
+ // contains its own search input and button.
+ cy.get('.ant-modal .ant-tabs-tabpane-active').within(() => {
+ cy.get('input[placeholder="[email protected]"]').type(
+ actor.account,
+ );
+ cy.get('.ant-input-search-button').click();
+ });
+
+ // The code travels over real federation: WebFinger, actor
+ // resolution, then a signed DM into the harness inbox.
+ cy.task('fediverse:waitForOTPCode', { actorName: actor.name }).then(
+ (code) => {
+ cy.get('.ant-modal .ant-tabs-tabpane-active').within(() => {
+ cy.get('input[placeholder="123456"]').type(code);
+ cy.contains('button', 'Verify Code').click();
+ });
+ },
+ );
+
+ // Successful verification reloads the page; the auth modal from
+ // the old document is gone once the new one is active.
+ cy.get('.ant-modal', { timeout: 15000 }).should('not.exist');
+ cy.get('#user-menu').should('be.visible');
+
+ // Visual proof: messages from this user now carry the
+ // authenticated badge in chat.
+ cy.get('#chat-input-content-editable').type(
+ 'hello from the fediverse{enter}',
+ );
+ cy.contains('.chat-message_user', 'hello from the fediverse')
+ .find('.chat-user-badge')
+ .should('have.attr', 'title', 'Authenticated');
+ });
+ });
+ });
+});
diff --git a/test/automated/browser/cypress/e2e/online/01_online_live.cy.js b/test/automated/browser/cypress/e2e/online/01_online_live.cy.js
index 99df6554b0..8b8a1dcd97 100644
--- a/test/automated/browser/cypress/e2e/online/01_online_live.cy.js
+++ b/test/automated/browser/cypress/e2e/online/01_online_live.cy.js
@@ -63,5 +63,17 @@ filterTests(['desktop'], () => {
it('Refresh page with new socket host', () => {
cy.visit('http://localhost:8080');
});
+
+ it('Can send a chat message over the overridden websocket host', () => {
+ // Round-trips a real message: typed into the input, sent over the
+ // overridden socket, broadcast back, and rendered in the feed
+ // under the name set earlier in this spec.
+ cy.get('#chat-input-content-editable').type(
+ 'e2e message via custom socket{enter}',
+ );
+ cy.contains('.chat-message_user', 'e2e message via custom socket')
+ .should('be.visible')
+ .and('contain', 'my-new-name');
+ });
});
});
diff --git a/test/automated/browser/cypress/e2e/online/02_online_video_embed.cy.js b/test/automated/browser/cypress/e2e/online/02_online_video_embed.cy.js
index b13ce8eb3c..359993b385 100644
--- a/test/automated/browser/cypress/e2e/online/02_online_video_embed.cy.js
+++ b/test/automated/browser/cypress/e2e/online/02_online_video_embed.cy.js
@@ -3,7 +3,7 @@ setup();
describe(`Online video embed`, () => {
it('Can visit the page', () => {
- cy.visit('http://localhost:8080');
+ cy.visit('http://localhost:8080/embed/video');
});
it('Should have a play button', () => {
diff --git a/test/automated/browser/cypress/e2e/online/03_online_readwrite_chat_embed.cy.js b/test/automated/browser/cypress/e2e/online/03_online_readwrite_chat_embed.cy.js
index e4496b8d64..fdd5f840ce 100644
--- a/test/automated/browser/cypress/e2e/online/03_online_readwrite_chat_embed.cy.js
+++ b/test/automated/browser/cypress/e2e/online/03_online_readwrite_chat_embed.cy.js
@@ -18,6 +18,11 @@ describe(`Online readwrite chat embed`, () => {
cy.contains('joined the chat').should('be.visible');
});
+ it('Can send a chat message from the embed', () => {
+ cy.get('#chat-input-content-editable').type('embed e2e message{enter}');
+ cy.contains('.chat-message_user', 'embed e2e message').should('be.visible');
+ });
+
it('Click on user menu', () => {
cy.get('#user-menu').click();
});
diff --git a/test/automated/browser/cypress/e2e/online/06_online_mobile_live.cy.js b/test/automated/browser/cypress/e2e/online/06_online_mobile_live.cy.js
index 4c095dd534..2d037fd2f1 100644
--- a/test/automated/browser/cypress/e2e/online/06_online_mobile_live.cy.js
+++ b/test/automated/browser/cypress/e2e/online/06_online_mobile_live.cy.js
@@ -29,6 +29,13 @@ filterTests(['mobile'], () => {
cy.get('#chat-input').should('be.visible');
});
+ it('Can send a chat message from the mobile chat modal', () => {
+ cy.get('#chat-input-content-editable').type('mobile e2e message{enter}');
+ cy.contains('.chat-message_user', 'mobile e2e message').should(
+ 'be.visible',
+ );
+ });
+
it('Chat user menu should be visible', () => {
cy.get('#chat-modal-user-menu').should('be.visible');
});
diff --git a/test/automated/browser/cypress/support/remote-fediverse-server.js b/test/automated/browser/cypress/support/remote-fediverse-server.js
new file mode 100644
index 0000000000..fcf28d86d8
--- /dev/null
+++ b/test/automated/browser/cypress/support/remote-fediverse-server.js
@@ -0,0 +1,303 @@
+// A fake remote fediverse server for full end-to-end federation tests.
+//
+// Runs inside the Cypress Node process (wired up as cy.task()s in
+// cypress.config.js) and speaks just enough real ActivityPub for Owncast to
+// treat it as a genuine remote server:
+//
+// - WebFinger (GET /.well-known/webfinger) account -> actor IRI
+// - Actor (GET /actor/<name>) Person doc with a public key
+// - Inbox (POST /inbox/<name>) captures deliveries (DMs,
+// Accepts) for assertions
+//
+// It can also SEND signed activities (e.g. Follow) to Owncast's inbox using
+// draft-cavage HTTP signatures, the same scheme real fediverse servers use.
+//
+// Owncast must run with OWNCAST_ALLOW_INTERNAL_FEDERATION=true and
+// OWNCAST_INSECURE_SKIP_VERIFY=true (set in run.sh) so its SSRF guard and TLS
+// verification accept this loopback, self-signed server. The server listens
+// on https://127.0.0.1:9443: Owncast requires https actor/key IRIs, and the
+// web UI's account validator requires a dot in the hostname, which 127.0.0.1
+// satisfies and "localhost" does not.
+
+const crypto = require('node:crypto');
+const https = require('node:https');
+const { execFileSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+const HOST = '127.0.0.1';
+const PORT = 9443;
+const BASE_URL = `https://${HOST}:${PORT}`;
+
+let server = null;
+
+// name -> { name, account, iri, publicKeyPem, privateKey, inbox: [] }
+const actors = new Map();
+
+// The https server needs a TLS certificate; Node cannot mint one natively, so
+// shell out to openssl (present on dev machines and CI runners).
+function makeSelfSignedCert() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'owncast-fedi-harness-'));
+ const keyPath = path.join(dir, 'key.pem');
+ const certPath = path.join(dir, 'cert.pem');
+ execFileSync(
+ 'openssl',
+ [
+ 'req',
+ '-x509',
+ '-newkey',
+ 'rsa:2048',
+ '-keyout',
+ keyPath,
+ '-out',
+ certPath,
+ '-days',
+ '2',
+ '-nodes',
+ '-subj',
+ `/CN=${HOST}`,
+ ],
+ { stdio: 'ignore' },
+ );
+ return { key: fs.readFileSync(keyPath), cert: fs.readFileSync(certPath) };
+}
+
+function actorDocument(actor) {
+ return {
+ '@context': [
+ 'https://www.w3.org/ns/activitystreams',
+ 'https://w3id.org/security/v1',
+ ],
+ type: 'Person',
+ id: actor.iri,
+ preferredUsername: actor.name,
+ name: actor.name,
+ inbox: `${BASE_URL}/inbox/${actor.name}`,
+ publicKey: {
+ id: `${actor.iri}#main-key`,
+ owner: actor.iri,
+ publicKeyPem: actor.publicKeyPem,
+ },
+ };
+}
+
+function handleRequest(req, res) {
+ const url = new URL(req.url, BASE_URL);
+ const respondJSON = (code, body) => {
+ res.writeHead(code, { 'Content-Type': 'application/activity+json' });
+ res.end(JSON.stringify(body));
+ };
+
+ if (url.pathname === '/.well-known/webfinger') {
+ // resource=acct:[email protected]:9443
+ const resource = url.searchParams.get('resource') || '';
+ const name = resource.replace(/^acct:/, '').split('@')[0];
+ const actor = actors.get(name);
+ if (!actor) return respondJSON(404, { error: `no such actor ${name}` });
+ return respondJSON(200, {
+ subject: `acct:${actor.account}`,
+ links: [
+ { rel: 'self', type: 'application/activity+json', href: actor.iri },
+ ],
+ });
+ }
+
+ if (url.pathname.startsWith('/actor/')) {
+ const actor = actors.get(url.pathname.split('/')[2]);
+ if (!actor) return respondJSON(404, { error: 'no such actor' });
+ return respondJSON(200, actorDocument(actor));
+ }
+
+ if (req.method === 'POST' && url.pathname.startsWith('/inbox/')) {
+ const actor = actors.get(url.pathname.split('/')[2]);
+ if (!actor) return respondJSON(404, { error: 'no such actor' });
+ let body = '';
+ req.on('data', (chunk) => {
+ body += chunk;
+ });
+ req.on('end', () => {
+ try {
+ actor.inbox.push(JSON.parse(body));
+ } catch {
+ actor.inbox.push({ unparseable: body });
+ }
+ res.writeHead(202);
+ res.end();
+ });
+ return undefined;
+ }
+
+ return respondJSON(404, { error: `unhandled ${req.method} ${url.pathname}` });
+}
+
+function ensureStarted() {
+ if (server) return Promise.resolve(BASE_URL);
+ return new Promise((resolve, reject) => {
+ server = https.createServer(makeSelfSignedCert(), handleRequest);
+ server.on('error', (err) => {
+ server = null;
+ reject(
+ new Error(
+ `fediverse harness failed to listen on ${BASE_URL}: ${err.message}`,
+ ),
+ );
+ });
+ server.listen(PORT, HOST, () => resolve(BASE_URL));
+ });
+}
+
+// Create a fresh actor (new name, new keypair, empty inbox). Flow specs
+// create a new actor per test attempt so Cypress retries start clean:
+// Owncast deduplicates repeat follows and OTP requests per account.
+function createActor() {
+ const name = `feditest${crypto.randomBytes(4).toString('hex')}`;
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
+ modulusLength: 2048,
+ });
+ const actor = {
+ name,
+ account: `${name}@${HOST}:${PORT}`,
+ iri: `${BASE_URL}/actor/${name}`,
+ publicKeyPem: publicKey.export({ type: 'spki', format: 'pem' }),
+ privateKey,
+ inbox: [],
+ };
+ actors.set(name, actor);
+ return { name: actor.name, account: actor.account, iri: actor.iri };
+}
+
+// Sign and deliver an activity to an Owncast inbox with a draft-cavage HTTP
+// signature over (request-target), date and digest — what Owncast verifies.
+async function deliverSignedActivity(actor, inboxUrl, activity) {
+ const body = JSON.stringify(activity);
+ const url = new URL(inboxUrl);
+ const digest = `SHA-256=${crypto.createHash('sha256').update(body).digest('base64')}`;
+ const date = new Date().toUTCString();
+ const signingString = [
+ `(request-target): post ${url.pathname}`,
+ `date: ${date}`,
+ `digest: ${digest}`,
+ ].join('\n');
+ const signature = crypto
+ .sign('sha256', Buffer.from(signingString), actor.privateKey)
+ .toString('base64');
+
+ let response;
+ try {
+ response = await fetch(inboxUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/activity+json',
+ Date: date,
+ Digest: digest,
+ Signature: `keyId="${actor.iri}#main-key",algorithm="rsa-sha256",headers="(request-target) date digest",signature="${signature}"`,
+ },
+ body,
+ });
+ } catch (err) {
+ throw new Error(
+ `Could not reach the Owncast inbox at ${inboxUrl}: ${err.cause?.message || err.message}. Is Owncast running?`,
+ );
+ }
+ if (response.status >= 400) {
+ throw new Error(
+ `Owncast inbox POST ${inboxUrl} responded ${response.status}: ${await response.text()}`,
+ );
+ }
+ return response.status;
+}
+
+// Wait for an activity matching `predicate` to arrive in the actor's inbox.
+// On timeout, throw an error describing everything that DID arrive so a
+// failing test explains itself.
+async function waitForInboxActivity(actor, description, predicate, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const match = actor.inbox.find(predicate);
+ if (match) return match;
+ if (Date.now() > deadline) {
+ const seen =
+ actor.inbox.map((a) => a.type || 'unknown').join(', ') || 'nothing';
+ throw new Error(
+ `Timed out after ${timeoutMs}ms waiting for ${description} in ${actor.account}'s inbox. ` +
+ `Activities received instead: ${seen}. ` +
+ `Check that Owncast is running with OWNCAST_ALLOW_INTERNAL_FEDERATION=true ` +
+ `and OWNCAST_INSECURE_SKIP_VERIFY=true, and see the owncast log for delivery errors.`,
+ );
+ }
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((r) => {
+ setTimeout(r, 250);
+ });
+ }
+}
+
+function getActorOrThrow(name) {
+ const actor = actors.get(name);
+ if (!actor) {
+ throw new Error(
+ `unknown harness actor "${name}" — call fediverse:createActor first`,
+ );
+ }
+ return actor;
+}
+
+// cy.task() handlers. Tasks return JSON-serializable values; thrown errors
+// fail the test with the error message.
+const tasks = {
+ // Start the harness (idempotent) and create a fresh remote actor.
+ // Returns { name, account, iri }.
+ async 'fediverse:createActor'() {
+ await ensureStarted();
+ return createActor();
+ },
+
+ // Send a signed Follow from the named actor to Owncast and wait for the
+ // Accept to be federated back to the actor's inbox. Proves the entire
+ // round trip: signature verification, actor resolution over webfinger-less
+ // direct fetch, follower persistence, and outbound signed delivery.
+ // Returns the Accept activity.
+ async 'fediverse:sendFollow'({
+ actorName,
+ owncastInbox,
+ owncastActorIri,
+ timeoutMs = 15000,
+ }) {
+ const actor = getActorOrThrow(actorName);
+ const follow = {
+ '@context': 'https://www.w3.org/ns/activitystreams',
+ id: `${BASE_URL}/activities/${crypto.randomUUID()}`,
+ type: 'Follow',
+ actor: actor.iri,
+ object: owncastActorIri,
+ };
+ await deliverSignedActivity(actor, owncastInbox, follow);
+ return waitForInboxActivity(
+ actor,
+ 'an Accept of the Follow',
+ (a) => a.type === 'Accept',
+ timeoutMs,
+ );
+ },
+
+ // Wait for a direct message (Create/Note) to arrive for the named actor
+ // and extract the 6-digit one-time code from it. Returns the code string.
+ async 'fediverse:waitForOTPCode'({ actorName, timeoutMs = 20000 }) {
+ const actor = getActorOrThrow(actorName);
+ const create = await waitForInboxActivity(
+ actor,
+ 'the one-time-code direct message',
+ (a) =>
+ a.type === 'Create' && /\d{6}/.test(JSON.stringify(a.object || '')),
+ timeoutMs,
+ );
+ const content =
+ typeof create.object === 'object'
+ ? create.object.content
+ : String(create.object);
+ return content.match(/(\d{6})/)[1];
+ },
+};
+
+module.exports = { tasks };
diff --git a/test/automated/browser/cypress/support/setup.js b/test/automated/browser/cypress/support/setup.js
index 4de6e796ff..51946cc511 100644
--- a/test/automated/browser/cypress/support/setup.js
+++ b/test/automated/browser/cypress/support/setup.js
@@ -1,8 +1,32 @@
+// Shared per-spec setup: fail any test whose page logged a console error.
+//
+// The captured error text is included in the assertion failure, so a failing
+// run tells you exactly what the application logged, not just that
+// "a spy was called".
export function setup() {
- let windowErrorSpy;
+ let consoleErrors = [];
Cypress.on('window:before:load', (win) => {
- windowErrorSpy = cy.spy(win.console, 'error');
+ const original = win.console.error;
+ // eslint-disable-next-line no-param-reassign
+ win.console.error = (...args) => {
+ consoleErrors.push(
+ args
+ .map((a) => {
+ if (a instanceof win.Error) return a.stack || a.message;
+ if (typeof a === 'object') {
+ try {
+ return JSON.stringify(a);
+ } catch {
+ return String(a);
+ }
+ }
+ return String(a);
+ })
+ .join(' '),
+ );
+ original.apply(win.console, args);
+ };
});
Cypress.on(
@@ -15,7 +39,12 @@ export function setup() {
// Give any in-flight async work a beat to surface console errors
// before asserting. Kept short: this runs after every single test.
cy.wait(300).then(() => {
- expect(windowErrorSpy).to.not.be.called;
+ const errors = consoleErrors;
+ consoleErrors = [];
+ expect(
+ errors,
+ `the page logged console.error:\n${errors.join('\n---\n')}`,
+ ).to.be.empty;
});
});
});
diff --git a/test/automated/browser/run.sh b/test/automated/browser/run.sh
index 0ab5290ecb..22baa5c47e 100755
--- a/test/automated/browser/run.sh
+++ b/test/automated/browser/run.sh
@@ -1,11 +1,24 @@
#!/bin/bash
+# Browser test runner. Runs every Cypress group against a real Owncast
+# instance, then prints a consolidated failure summary.
+#
+# ./run.sh # run all groups
+# ./run.sh desktop-online # run a single group (faster iteration)
+# SKIP_BUILD=1 ./run.sh # reuse existing web bundle + node_modules
+#
+# A failed group does not stop the run: every group executes so one run
+# reports every failure. The exit code is non-zero if any group failed, and
+# cypress/results/failures.json holds machine-readable details per failure.
+
set -o errexit
set -o pipefail
# shellcheck disable=SC1091 # tools.sh is sourced at runtime; not available to the linter
source ../tools.sh
+GROUP_FILTER="${1:-}"
+
BUILD_ID=$((RANDOM % 7200 + 600))
CYPRESS_RECORD_KEY="e9c8b547-7a8f-452d-8c53-fd7531491e3b"
BROWSER="electron" # Default. Will try to use Google Chrome.
@@ -42,25 +55,46 @@ fi
set -o nounset
+FAILED_GROUPS=()
+
# Run one cypress group. Cloud recording (and the flags that require it) is
-# CI-only: local runs stay fast and work offline.
+# CI-only: local runs stay fast and work offline. A failing group is recorded
+# and the run continues, so a single run surfaces every broken group.
# run_cypress <group> <tags-env> <spec-glob> [extra cypress args...]
run_cypress() {
local group=$1 tags=$2 spec=$3
shift 3
+ if [ -n "$GROUP_FILTER" ] && [ "$group" != "$GROUP_FILTER" ]; then
+ return 0
+ fi
+
local args=(--browser "$BROWSER" --env "tags=$tags" --spec "$spec")
if [ -n "${CI:-}" ]; then
args+=(--record --key "$CYPRESS_RECORD_KEY" --parallel --ci-build-id "$BUILD_ID" --group "$group" --tag "${group/-/,}")
fi
- npx cypress run "${args[@]}" "$@"
+ if ! npx cypress run "${args[@]}" "$@"; then
+ FAILED_GROUPS+=("$group")
+ fi
}
+# The federation specs drive real signed ActivityPub exchanges between a fake
+# remote fediverse server (cypress/support/remote-fediverse-server.js) and
+# this Owncast instance, both on localhost. These env vars relax Owncast's
+# SSRF guard and TLS verification for that loopback federation. They are read
+# once at first use (sync.Once), so they must be set before the server starts.
+export OWNCAST_ALLOW_INTERNAL_FEDERATION=true
+export OWNCAST_INSECURE_SKIP_VERIFY=true
+
install_ffmpeg
start_owncast
+# Start each run with a clean failure ledger (appended to by after:spec in
+# cypress.config.js across all groups).
+rm -f cypress/results/failures.json
+
run_cypress "desktop-offline" desktop "cypress/e2e/offline/*.cy.js"
run_cypress "mobile-offline" mobile "cypress/e2e/offline/*.cy.js" --config viewportWidth=375,viewportHeight=667
@@ -73,3 +107,20 @@ start_stream
run_cypress "desktop-online" desktop "cypress/e2e/online/*.cy.js"
run_cypress "mobile-online" mobile "cypress/e2e/online/*.cy.js" --config viewportWidth=375,viewportHeight=667
+# Full end-to-end federation flows (fediverse chat auth, inbound follows)
+# against the fake remote fediverse server. Runs while the stream is live so
+# chat is fully available.
+run_cypress "desktop-federation" desktop "cypress/e2e/federation/*.cy.js"
+
+echo ""
+echo "=================================================="
+if [ ${#FAILED_GROUPS[@]} -gt 0 ]; then
+ echo "FAILED groups: ${FAILED_GROUPS[*]}"
+ if [ -f cypress/results/failures.json ]; then
+ echo "Failure details (cypress/results/failures.json):"
+ cat cypress/results/failures.json
+ fi
+ echo "Failure screenshots: cypress/screenshots/"
+ exit 1
+fi
+echo "All browser test groups passed."