buzz icon indicating copy to clipboard operation
buzz copied to clipboard

A rejected CORS preflight is invisible on both sides: no relay log at any level, and the desktop reports it as a clipboard failure

Open xBFour opened this issue 4 months ago • 2 comments

Summary

This is not another report of the missing Tauri origins in deploy/compose — that is already well covered by #2872, #3490, #2617, #2908 and the open fixes in #2888 / #3595.

This issue is about why that misconfiguration takes so long to diagnose. When the desktop webview's origin is not in BUZZ_CORS_ORIGINS, the failure produces zero usable signal anywhere:

  • no relay log line, even with tower_http=debug
  • no row in relay_invites
  • a desktop toast that names the wrong subsystem entirely

I spent several hours on a self-host bring-up chasing this. Everything else about the deployment was healthy — WebSocket chat connected, NIP-42 auth passed, /query and /events were logging status=200 — so every visible signal pointed away from CORS. Fixing the two points below would have turned that into a two-minute fix, and would help everyone who lands on the already-reported config problem.

Environment

  • Relay: ghcr.io/block/buzz@sha256:5aaf1f0e34e3806e69eea2a271c4809f08517bfb259b59a900d7ca71233eeeb3, NIP-11 reports "version": "0.2.0"
  • Desktop: Windows (origin http://tauri.localhost)
  • Deployment: deploy/compose behind Cloudflare Tunnel, TLS terminated at the edge, RELAY_URL=wss://<host>
  • BUZZ_CORS_ORIGINS set exactly as deploy/compose/.env.example suggests — the public host only

Reproduce

  1. Deploy with BUZZ_CORS_ORIGINS=https://<your-host> (i.e. the shipped .env.example default, line 13).
  2. Connect the desktop app to that relay. Chat works; you are owner in buzz-admin list-members.
  3. Open the community members panel and click Copy link to mint an invite.

Observed:

  • Toast: Couldn't copy the invite link. Try again.
  • SELECT count(*) FROM relay_invites; → 0
  • docker logs buzz-relay | grep -i invite → nothing, including with RUST_LOG=buzz_relay=debug,buzz_auth=debug,tower_http=debug

Expected: some indication that the request was rejected, and by what.


Problem 1 — the CORS layer sits outside the trace layer, so rejections are never logged

crates/buzz-relay/src/router.rs:189-192

merged
    .layer(middleware::from_fn(track_metrics))
    .layer(http_trace_layer())
    .layer(build_cors_layer(&state.config.cors_origins))

The last .layer() is outermost, so CorsLayer wraps TraceLayer. A preflight OPTIONS with a non-allowlisted Origin is answered by the CORS layer and never reaches the inner service — so TraceLayer never sees it and nothing is emitted at any log level.

This also explains why the usual debugging advice doesn't help here: raising RUST_LOG changes nothing, because the request never gets far enough to be traced.

Additionally, build_cors_layer (router.rs:423-446) uses AllowOrigin::list(origins) — exact string matching, no wildcards — but never logs a rejected origin. Note there is already a good precedent right there: the "no valid origins could be parsed" branch logs at error!. The rejection path has no equivalent.

Suggested fix (either or both):

  • Put http_trace_layer() outside build_cors_layer(...) so every request is traced regardless of CORS outcome.

  • Log rejected origins at warn! with the received Origin and the configured allowlist. For a self-hoster this single line replaces hours of guessing:

    WARN CORS rejected origin "http://tauri.localhost" — not in BUZZ_CORS_ORIGINS
         (allowed: ["https://buzz.example.com"])
    

Problem 2 — the invite dialog reports a network failure as a clipboard failure

desktop/src/features/community-members/ui/InviteLinkSection.tsx:72-84

async function handleCopy() {
  if (copyStatus === "copying") return;
  setCopyStatus("copying");
  try {
    const invite = await mintInvite({ ttlSecs, maxUses });
    await writeTextToClipboard(invite.url);
    setCopyStatus("copied");
    toast.success("Invite link copied");
  } catch {
    setCopyStatus("idle");
    toast.error("Couldn't copy the invite link. Try again.");
  }
}

One try covers two unrelated operations — a network call and a clipboard write — and the catch is bare, discarding the error. Any mintInvite failure (CORS, 401 NIP-98, 403 role, timeout, 5xx) surfaces as "couldn't copy".

This actively misled me. Clipboard copy demonstrably worked elsewhere in the app (the Copy button on the MembershipDenied screen uses the same writeTextToClipboard), so the message sent me looking at Tauri clipboard permissions instead of the network. Worth noting that the closed Wayland clipboard issues (#2896, #2904, #2922) make this wording especially sticky — searching the tracker for it leads to real-but-unrelated clipboard bugs.

Suggested fix: separate the two failure modes and surface the underlying message.

let invite;
try {
  invite = await mintInvite({ ttlSecs, maxUses });
} catch (error) {
  setCopyStatus("idle");
  toast.error(
    `Couldn't create the invite: ${error instanceof Error ? error.message : "unknown error"}`,
  );
  return;
}
try {
  await writeTextToClipboard(invite.url);
  setCopyStatus("copied");
  toast.success("Invite link copied");
} catch {
  setCopyStatus("idle");
  toast.error("Invite created, but copying to the clipboard failed.");
}

invitePost (desktop/src/shared/api/invites.ts:78-104) already throws a useful Error — either the server's json.error string or HTTP <status> — so the message is there, just discarded.

The second branch matters on its own: because relay_invites stores only token_hash (migrations/0025_relay_invites.sql), an invite whose code fails to reach the clipboard is unrecoverable. Telling the user it was created but not copied is materially different from telling them to just try again.


Why this is worth fixing separately from the config default

Even after #2888 / #3595 land, the same silence will affect any other origin mismatch — a reverse proxy rewriting Origin, a browser-based client, a custom deployment, a future platform whose webview origin differs again. The config default fixes one instance; these two changes fix the class.

Also worth noting: /api/invites is reached via the webview's fetch(), whereas /query and /events go through the Tauri native side and bypass CORS entirely. That asymmetry is what makes the deployment look healthy while invites silently fail — the same applies to getJoinPolicy and acceptJoinPolicy in invites.ts. It may be worth documenting, or routing the invite calls through native networking as #2862 did for join policies.

Workaround for anyone who finds this first

BUZZ_CORS_ORIGINS=https://<your-host>,tauri://localhost,http://tauri.localhost,https://tauri.localhost

Recreate the container afterwards — restarting is not enough for env changes to apply.

xBFour avatar Jul 29 '26 22:07 xBFour

Opened https://github.com/block/buzz/pull/4278 — implements both fixes you suggested.

  • relay: adds a warn! inside the AllowOrigin predicate so every non-allowlisted origin is logged with its received value. Skipped reordering the CORS vs trace layers to keep the change minimal — the warn-log achieves the "make rejections visible" goal without touching middleware semantics.
  • desktop: splits the combined try exactly as you described — mint failures now surface error.message from invitePost (which already includes the server's json.error or HTTP <status>); clipboard failures keep a distinct message noting the invite was created (since relay_invites stores only the hash, that distinction matters).

Verified: cargo check/clippy clean, side_effects 5/5, tsc clean, webview 3906/3906.

iroiro147 avatar Aug 02 '26 08:08 iroiro147

Confirming this on macOS today, on a fresh deploy/compose bring-up. Same invisibility, and I lost about the same amount of time to it. Three things to add: wire-level evidence, a fourth blind spot, and a status update on Problem 2.

Environment

  • Relay ghcr.io/block/buzz@sha256:888121e21b4b84832ff57fbb6bdb65d4e2b655ff6dc887e97df1d0ec711c2e1c, NIP-11 "version": "0.2.1"
  • Desktop on macOS, origin tauri://localhost
  • deploy/compose with BUZZ_COMPOSE_TLS=true (Caddy terminating TLS on the host, not a tunnel)
  • BUZZ_CORS_ORIGINS set exactly as .env.example line 13 suggests — public host only

The preflight succeeds, which makes it worse

Your report says nothing is logged. Worth adding what the response actually is when you do manage to see it — because it does not look like a failure:

OPTIONS /api/invites
  Origin:                         tauri://localhost
  Access-Control-Request-Method:  POST
  Access-Control-Request-Headers: authorization,content-type

→ 200
  Access-Control-Allow-Methods: *
  Access-Control-Allow-Headers: *
  Vary: origin, access-control-request-method, access-control-request-headers
  (no Access-Control-Allow-Origin)

A 200 carrying two wildcard CORS headers reads as "CORS is fine" to anyone eyeballing it. The single absent header is the whole failure, and it is absent rather than present-and-wrong, so it is easy to miss even when you are looking straight at it. tower_http::cors is behaving correctly here — this is only about how the failure presents.

Problem 3 — the shipped Caddyfile has no access log either

Problem 1 explains why the relay logs nothing. But in a deploy/compose deployment there is a second component in front of it that does see the request, and it is silent too:

deploy/compose/Caddyfile is

{$BUZZ_DOMAIN} {
  encode zstd gzip
  reverse_proxy relay:3000
}

No log directive, so Caddy emits no HTTP access log at all. On our host the container had 44 log lines total, every one of them ACME. So the rejected preflight is invisible at the edge and in the relay, and the operator's first instinct — "check the reverse proxy logs" — also returns nothing.

Adding this made the problem visible in under a minute, and it is what actually diagnosed it for us:

{$BUZZ_DOMAIN} {
  encode zstd gzip

  log {
    output stdout
    format json
  }

  reverse_proxy relay:3000
}

Suggest shipping that in the bundle regardless of how Problem 1 is resolved. Even with the trace layer reordered, an edge access log is the first place a self-hoster looks, and its absence is a separate gap from the relay-side one.

Problem 2 is now half-fixed on main

Current InviteLinkSection.tsx has been refactored since you filed this: minting and clipboard are separate operations with distinct messages, so the misattribution you hit is gone. Our toast read "Couldn't create an invite link." — correctly naming the network call, not the clipboard.

The other half of your suggested fix still stands. The mint catch is still bare and still discards the error:

    } catch {
      if (inviteRequests.current.get(inviteSettingsKey) === inviteRequest) {
        inviteRequests.current.delete(inviteSettingsKey);
      }
      if (generationRequestId.current === requestId) {
        setGenerationStatus("failed");
        toast.error("Couldn’t create an invite link.");
      }
    }

So CORS, 401 NIP-98, 403 role and 5xx still collapse into one message with no underlying detail. Naming the right subsystem is a real improvement; surfacing why is the part that would have ended this in two minutes.

Why this still matters

#2888 and #3595 have been open since late July, so new self-hosters following deploy/compose/README.md continue to land on the config problem — which makes the diagnosability gap this issue is about the thing they actually hit.

Happy to open a PR for the Caddyfile log block if that is useful.

— Posted by Claude Code on behalf of @samsymbia

samsymbia avatar Sep 03 '26 07:09 samsymbia