Files
OwnCord/Server/api/client_update_test.go
T
J3vbandClaude Fable 5 1fe3df7962 test(b2-1): capture the epoch-1 protocol fixtures and retire S-15 (#1435)
* refactor(protocol): retire reserved voice_speakers and member_leave (S-15)

Neither type was ever emitted by the server; B2-1 clears them from the
schema before the epoch-1 wire fixtures are captured, so the frozen epoch
does not carry two dead message types.

Client: dropped the dead `ws.on(MEMBER_LEAVE)` / `ws.on(VOICE_SPEAKERS)`
dispatcher handlers, the `MemberLeavePayload` type and both `ServerMessage`
union members, and the tests that only exercised those WS paths.
`removeMember` (member_ban) and `setSpeakers` (LiveKit ActiveSpeakers) stay
live and keep their direct unit tests.

* test(ws): capture the epoch-1 wire fixtures

alpha.4 is the last client on the pre-epoch wire and B2-2 adds a protocol
epoch to the auth handshake next, so record what epoch 1 actually looks
like while it is still observable.

TestEpoch1Fixtures drives eleven journeys through the ws package's
in-process hub harness (full migrations, real hub, httptest WebSocket
server) and compares each journey's per-connection frame sequence with a
transcript under protocol/fixtures/epoch-1/:

- fresh-connect, auth-failure, ping
- chat-send-fanout, chat-edit-delete, reaction-add-remove
- typing, mark-read, dm-send
- resume-replay (last_seq + buffer-tier replay burst)
- voice-join-e2ee-leave (join, both voice_state forms, announce and
  offer relay, leave)

Volatile values are replaced by typed placeholders before both writing
and comparison -- any key that is id/seq/last_seq, ends in _id (except
channel_id and role_id) or _at, is timestamp/ts/last_seen, or contains
token, becomes "<class:json-type>" so a field that changes type is still
a diff, while everything else is compared verbatim.

Regenerate with: go test ./ws -run TestEpoch1Fixtures -update

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(client): pin the epoch-1 auth frame contract

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(updater): pin the epoch-1 manifest and client-update shapes

* test(ws): harden the epoch-1 fixtures against trailing frames and absent optionals

Every journey now ends with the ping/pong barrier on each recorded
connection, so a frame the server emits after the last read fails as
`expected "pong", got "X"` instead of going unrecorded; auth-failure
asserts the StatusPolicyViolation close instead, its socket being gone.

alice carries a display name, avatar, about text, custom status, identity
public key and an announce signature (bob carries none), so every optional
field is frozen in its present form as well as its absent one — a rename or
a retype of display_name or identity_public_key now moves a fixture.

The typing journey focuses the channel on "a" before typing: without the
subscription registerNow only makes for a focused client, its ping/pong
proved nothing about excludeUserID.

Comment fixes: the escaped placeholder form MarshalIndent would write, the
real (headroom) reason for the raised read limit, a note that bare id and
active_channel_id are normalised by design, and a .prettierignore line
saying these fixtures are verified by the Go comparison, not by git diff.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(protocol): document the epoch-1 fixtures

* docs(protocol): match the epoch-1 wire where the fixtures contradicted the doc

- voice_state: note the unsequenced relay-to-joiner form (table row + section)
- auth_error: correct the example message and list the real rejection messages
- member_join/presence connect example: add the seq both frames actually carry
- chat_message.user: document display_name
- voice_join reply order: state that the joiner's own voice_state broadcast is not ordered against the other three frames

* test(ws): freeze the null forms of auth_ok and member_join user fields

buildAuthOK emits display_name/about/custom_status/avatar as
always-present nulls, but only alice — who has all four set — ever
authenticated on a recorded connection, so the fixtures froze those
fields in their populated form alone. A rename, a retype or a dropped
null would have moved nothing, on the very frame B2-2 edits.

fresh-connect now records bob's handshake too, on a second connection:
his auth_ok carries the four nulls, his member_join carries avatar null
with display_name and identity_public_key omitted, and alice — idle by
then, so her reads stay in hub order — records the same pair as an
already-connected observer sees it. In voice-join-e2ee-leave bob answers
alice's signed announce with a legacy unsigned one, which freezes the
absent form of signature next to her present one. The auth frames the
test writes now carry the correlation id the real client stamps on every
frame (ws.ts send()); normalisation renders it <id:string>.

expectClosed also asserts the close reason ("authentication failed"),
not just code 1008 — HP-2 asks for both.

Comment precision, no behaviour change: the barrier guarantee now states
that pong may overtake a pending LOW-priority frame (writePump) and that
no journey is affected because every barrier is sent on an idle
connection; the ping-budget ceiling is six connections, not four; the
typing journey cites handleChannelFocusV2 rather than registerNow as the
subscribe site; resume-replay's b barrier explains why moving it past
the resume would be a flake, not a fix; and the header notes that
normalisation hides that chat_send_ok.id echoes the request id.

The client contract test's cited range for ws.ts's send() call is
441-453, not 441-454.

Regenerate with: go test ./ws -run TestEpoch1Fixtures -update

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(protocol): shape-not-value fixture rule, voice_max_video default, auth close code

The fixture rule read "a fixture may only change with an epoch bump",
which is false for the seeded values the transcripts record verbatim:
role permission masks and colours, motd, server_name, voice_max_video,
the voice_config preset. A migration that changes a default mask diffs
fresh-connect.json, and the README told the author to revert a change
that never touched the wire.

Split the rule along shape versus value. A key set, a JSON type, a key
appearing or disappearing, or per-connection frame order is a protocol
change and earns fixtures/epoch-<n+1>/. A seeded default value is a seed
change: regenerate in the same PR and read the diff frame by frame.
Normalising those values is explicitly not the answer — a placeholder
over a mask or over an enum such as voice_config.threshold_mode would
hide the drift the fixtures exist to catch.

Two wire facts corrected against the fixtures:

- voice_max_video on an unconfigured channel is 25, not 0 (migration
  004 is DEFAULT 25); the doc listed it among the zero values.
- auth_error is followed by a close with code 1008 (policy violation)
  and reason "authentication failed" (serve.go:128), which the doc left
  as "closes the connection".

Also: voice_speakers moves from discord-parity's "still dead" list to
"came off the list" — it was retired earlier on this branch. And Kick
says sessions are revoked and sockets drop on the next sweep, which is
what ForceLogout does (moderation.go:236); it does not cut sockets.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(protocol): fixture rule covers enum vocabularies; header comment precision

Re-check minors from the whole-branch review: a fixed-vocabulary value the client switches on is shape, not a seeded value; drop the false 'new default channel' clause (the seed asserts channel ids); the low-priority frame is presence_update, not connect presence.

* docs(plans): record B2-1 evidence for HP-2 (PR #1435, fixture commit SHAs)

* docs(protocol): additive changes stay within an epoch; bump only for what old clients cannot process

Codex review on #1435: B2-2 keeps protocol_epoch = 1 while adding auth/ready/auth_error fields, which the previous wording would have called a break to revert. An epoch is a compatibility boundary, not a snapshot: additive keys regenerate in the same PR and are documented; removals, renames, retypes, dropped frames and reordering bump the epoch. The plan's B2-1 evidence records the refinement and hands B2-2/B2-4 the open questions (additive-tolerant replay of the epoch-1 transcript; epoch 0 vs 1 naming).

* test(client): compare auth-frame key sets order-independently

Codex review on #1435: Object.keys preserves insertion order, so a harmless property reorder in ws.ts would fail the pin. Key order has no wire meaning; the Go fixtures already compare with sorted keys. Sort both sides.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 15:43:30 +02:00

346 lines
11 KiB
Go

package api_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/J3vb/OwnCord/Server/api"
"github.com/J3vb/OwnCord/Server/updater"
"github.com/go-chi/chi/v5"
)
// fakeGitHubRelease returns a test HTTP server that mimics the GitHub
// Releases API, serving a release with the given tag and the client update
// assets for every platform the release workflow publishes.
// Asset download URLs point back to the test server so FetchTextAsset works.
func fakeGitHubRelease(t *testing.T, tag string) *httptest.Server {
t.Helper()
var srv *httptest.Server
mux := http.NewServeMux()
assetNames := []string{
"OwnCord_1.0.0_x64-setup.nsis.zip",
"OwnCord_1.0.0_x64-setup.nsis.zip.sig",
"OwnCord_1.0.0_amd64.AppImage.tar.gz",
"OwnCord_1.0.0_amd64.AppImage.tar.gz.sig",
"OwnCord_1.0.0_aarch64.AppImage.tar.gz",
"OwnCord_1.0.0_aarch64.AppImage.tar.gz.sig",
}
mux.HandleFunc("/repos/test/repo/releases/latest", func(w http.ResponseWriter, r *http.Request) {
assets := make([]map[string]any, 0, len(assetNames))
for _, name := range assetNames {
assets = append(assets, map[string]any{
"name": name,
"browser_download_url": srv.URL + "/download/" + name,
})
}
resp := map[string]any{
"tag_name": tag,
"body": "Release notes here",
"html_url": "https://github.com/test/repo/releases/" + tag,
"assets": assets,
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
})
// Serve signature file content for any .sig asset.
mux.HandleFunc("/download/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".sig") {
_, _ = w.Write([]byte("dW50cnVzdGVkIGNvbW1lbnQ="))
return
}
http.NotFound(w, r)
})
srv = httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
// platformEntry decodes the response body and returns the platforms entry for
// the given target, failing the test if it is missing.
func platformEntry(t *testing.T, rr *httptest.ResponseRecorder, target string) map[string]any {
t.Helper()
var resp map[string]any
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
platforms, ok := resp["platforms"].(map[string]any)
if !ok {
t.Fatalf("response missing platforms map: %v", resp)
}
entry, ok := platforms[target].(map[string]any)
if !ok {
t.Fatalf("platforms missing key %q: %v", target, platforms)
}
return entry
}
func buildClientUpdateRouter(u *updater.Updater) http.Handler {
r := chi.NewRouter()
api.MountClientUpdateRoute(r, u)
return r
}
func TestClientUpdate_NewVersionAvailable(t *testing.T) {
srv := fakeGitHubRelease(t, "v2.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/windows-x86_64-nsis/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
var resp map[string]any
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp["version"] == nil {
t.Error("response missing 'version' field")
}
if resp["platforms"] == nil {
t.Error("response missing 'platforms' field")
}
}
func TestClientUpdate_AlreadyLatest(t *testing.T) {
srv := fakeGitHubRelease(t, "v1.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/windows-x86_64-nsis/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusNoContent {
t.Errorf("status = %d, want 204; body: %s", rr.Code, rr.Body.String())
}
}
func TestClientUpdate_FutureVersion(t *testing.T) {
srv := fakeGitHubRelease(t, "v1.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
// Client has a newer version than the release.
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/windows-x86_64-nsis/2.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusNoContent {
t.Errorf("status = %d, want 204; body: %s", rr.Code, rr.Body.String())
}
}
func TestClientUpdate_WindowsTargetGetsNSISInstaller(t *testing.T) {
srv := fakeGitHubRelease(t, "v2.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/windows-x86_64-nsis/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
entry := platformEntry(t, rr, "windows-x86_64-nsis")
url, _ := entry["url"].(string)
if !strings.HasSuffix(url, "_x64-setup.nsis.zip") {
t.Errorf("windows url = %q, want NSIS installer", url)
}
}
func TestClientUpdate_LinuxTargetGetsAppImage(t *testing.T) {
srv := fakeGitHubRelease(t, "v2.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/linux-x86_64-appimage/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
entry := platformEntry(t, rr, "linux-x86_64-appimage")
url, _ := entry["url"].(string)
if !strings.HasSuffix(url, "_amd64.AppImage.tar.gz") {
t.Errorf("linux url = %q, want x86_64 AppImage updater archive", url)
}
if sig, _ := entry["signature"].(string); sig == "" {
t.Error("linux platform entry missing signature")
}
}
func TestClientUpdate_LinuxArm64TargetGetsAarch64AppImage(t *testing.T) {
srv := fakeGitHubRelease(t, "v2.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/linux-aarch64-appimage/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
entry := platformEntry(t, rr, "linux-aarch64-appimage")
url, _ := entry["url"].(string)
if !strings.HasSuffix(url, "_aarch64.AppImage.tar.gz") {
t.Errorf("linux arm64 url = %q, want aarch64 AppImage updater archive", url)
}
}
func TestClientUpdate_UnsupportedTargetNoContent(t *testing.T) {
srv := fakeGitHubRelease(t, "v2.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
// No darwin client is published; the updater must not be offered a
// Windows installer for it.
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/darwin-aarch64-app/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusNoContent {
t.Errorf("status = %d, want 204; body: %s", rr.Code, rr.Body.String())
}
}
func TestClientUpdate_DebTargetNoContent(t *testing.T) {
srv := fakeGitHubRelease(t, "v2.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
// The release ships .deb packages but no signed deb UPDATER artifact.
// A deb client falling back to the AppImage archive would fail install
// forever (the plugin's install_deb rejects gzip bytes), so it must get
// 204 rather than an artifact for a different installer.
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/linux-x86_64-deb/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusNoContent {
t.Errorf("status = %d, want 204; body: %s", rr.Code, rr.Body.String())
}
}
func TestClientUpdate_GitHubError(t *testing.T) {
// Server that always returns 500.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
t.Cleanup(srv.Close)
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/windows-x86_64-nsis/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusBadGateway {
t.Errorf("status = %d, want 502; body: %s", rr.Code, rr.Body.String())
}
}
// TestClientUpdate_Epoch1ResponseShape pins the exact JSON shape of the
// client-update 200 and 204 responses as of protocol epoch 1. B2-3 adds a
// protocol-epoch field to this response; when it does, this test WILL fail
// until it is extended on purpose to include the new field in the expected
// shape below.
//
// fakeGitHubRelease always publishes non-empty release notes and has no
// parameter for an empty body, so this covers the non-empty-notes case
// (top-level keys exactly {version, notes, platforms}) plus an explicit
// assertion that "pub_date" — omitempty, and never set by the handler —
// stays absent.
func TestClientUpdate_Epoch1ResponseShape(t *testing.T) {
srv := fakeGitHubRelease(t, "v2.0.0")
u := updater.NewUpdater("1.0.0", "", "test", "repo")
u.SetBaseURL(srv.URL)
router := buildClientUpdateRouter(u)
req := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/windows-x86_64-nsis/1.0.0", nil)
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rr.Code, rr.Body.String())
}
if ct := rr.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
t.Errorf("Content-Type = %q, want %q", ct, "application/json; charset=utf-8")
}
var resp map[string]any
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
want := map[string]any{
"version": "2.0.0",
"notes": "Release notes here",
"platforms": map[string]any{
"windows-x86_64-nsis": map[string]any{
"signature": "dW50cnVzdGVkIGNvbW1lbnQ=",
"url": srv.URL + "/download/OwnCord_1.0.0_x64-setup.nsis.zip",
},
},
}
if !reflect.DeepEqual(resp, want) {
t.Errorf("200 response = %#v, want %#v — a new field (e.g. protocol epoch) must be added here deliberately", resp, want)
}
if _, ok := resp["pub_date"]; ok {
t.Errorf("response has a \"pub_date\" key = %v, want absent", resp["pub_date"])
}
// 204 (already latest) has an empty body, not "{}" or any other JSON.
srv204 := fakeGitHubRelease(t, "v1.0.0")
u204 := updater.NewUpdater("1.0.0", "", "test", "repo")
u204.SetBaseURL(srv204.URL)
router204 := buildClientUpdateRouter(u204)
req204 := httptest.NewRequest(http.MethodGet, "/api/v1/client-update/windows-x86_64-nsis/1.0.0", nil)
rr204 := httptest.NewRecorder()
router204.ServeHTTP(rr204, req204)
if rr204.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204; body: %s", rr204.Code, rr204.Body.String())
}
if rr204.Body.Len() != 0 {
t.Errorf("204 body length = %d, want 0 (body: %q)", rr204.Body.Len(), rr204.Body.String())
}
}