Skip to content

feat(webcast): issue #44 backend -- BOCA export + revocable credentials - #73

Merged
matbrgz merged 4 commits into
masterfrom
feature/issue-44-webcast-export
Sep 11, 2026
Merged

matbrgz merged 4 commits into
masterfrom
feature/issue-44-webcast-export

Conversation

@matbrgz

@matbrgz matbrgz commented Sep 11, 2026

Copy link
Copy Markdown
Member

Addresses #44 (partially -- can_export stays off pending Animeitor consumer verification, see spec)

Summary

Implements the real backend behind resources/js/features/Webcast.vue's proposed /api/frontend/webcast* contract (previously non-existent, per docs/specs/44-webcast.md):

  • GET/POST/DELETE /api/frontend/webcast* (web session + CSRF, ['auth','admin'], routes/frontend_api_webcast.php required from the bottom of routes/web.php) for contest selection, credential issuance/listing/revocation, backed by a new webcast_credentials table. Raw secrets are generated with Str::random(40), stored only as sha256, and only ever appear once, in the create response.
  • A generic Idempotency-Key mechanism (idempotency_keys table + App\Services\IdempotencyGuard), reusable by future /api/frontend/* routes: same key + same payload replays the saved response; same key + a different payload -> 409; a create-time race on the same key (unique constraint collision) falls back to replay instead of crashing. Credential creation specifically reconciles metadata on replay without ever repeating the one-time secret (chosen policy — see spec).
  • A full BOCA webcast ZIP serializer (App\Services\BocaWebcastZipBuilder) producing contest/runs/version/time/icpc with the FS (0x1C) field separator, verified byte-for-byte in tests by round-tripping a real generated ZIP (multi-site, accented names, empty contest, all four result codes).
  • A standalone webcast-credential guard (App\Http\Middleware\AuthenticateWebcastCredential, Authorization: Bearer <secret>, sha256 lookup + hash_equals) registered in its own route group (routes/webcast_consumer.php, wired via bootstrap/app.php's withRouting(then: ...)) entirely outside both the web and api groups — no session, no CSRF, no Sanctum. It exposes exactly one route, the unfrozen scoreboard for the credential's own contest, and never calls Auth::login(), so the same token against any other route in the app (submit, judge, user management, its own admin issuance endpoints) fails exactly like an anonymous request. Active/expired/revoked/nonexistent tokens are denied with an identical 401. Rate-limited (throttle:20,1, running before the guard so wrong guesses count against the limit too).

capabilities.can_export stays false by default (config('webcast.export_enabled'), env WEBCAST_EXPORT_ENABLED), per the spec's explicit instruction — the linked Animeitor consumer repo 404'd during the spec's own research, so byte-format compatibility with any real consumer is unverified. The export endpoint and ZIP builder are fully implemented and tested regardless; flipping the flag is a product/ops decision for whoever confirms a real consumer fixture, not a default this deploy should assume.

Self-review fixes

Ran /code-review against the diff and fixed what it found before opening this PR:

  • BocaWebcastZipBuilder no longer aborts the entire export with a RuntimeException when a non-team account has a run in the contest (e.g. an admin's test run via POST /api/runs, which has no user_type restriction) — such runs are now silently excluded instead of taking down the whole export.
  • IdempotencyGuard::handle() now catches a QueryException from a create-time race on the same Idempotency-Key (two requests both pass the existence check, one loses the unique-constraint insert) and falls back to the normal replay path instead of propagating a raw 500.
  • WebcastController::storeCredential() no longer assumes the re-fetched Contest is non-null after validation (a TOCTOU window if the contest were deleted between the Rule::exists check and the Contest::find() call) — it now raises a clean 422 instead of risking a TypeError.

Also noted, deliberately not fixed (out of scope): this app has no personal_access_tokens migration despite Helium\User using HasApiTokens and routes/api.php gating everything behind auth:sanctum — any request presenting a genuine Authorization: Bearer header to a sanctum route 500s instead of 401ing, since Sanctum's guard queries a table that doesn't exist. Discovered while testing that a webcast credential can't reach sanctum-guarded API routes; documented in tests/Feature/WebcastCredentialAuthTest.php and routed around by testing the equivalent web-guarded surfaces instead.

Test plan

  • php artisan test -- 648 passed (618 baseline + 30 new), 3431 assertions.
  • tests/Feature/WebcastControllerTest.php -- capabilities gating, pagination, validation, idempotency (replay/conflict/race/validation-failure-doesn't-burn-key), revoke idempotency.
  • tests/Feature/WebcastExportTest.php -- 503 while disabled, 401/403 auth, 404 without wrapping HTML in a ZIP, headers, byte-level ZIP round-trip (multi-site + accents + all result codes), empty contest, FS/newline sanitization, stray non-team run doesn't break export.
  • tests/Feature/WebcastCredentialAuthTest.php -- valid credential reads its own unfrozen scoreboard; expired/revoked/nonexistent/missing tokens denied identically; cross-contest isolation; cannot submit/judge/manage users/reach its own admin endpoints; rate limiting.
  • vendor/bin/pint clean on all new/changed files.
  • docs/api/openapi.yaml updated (all new routes are under /api/*, so OpenApiSpecTest's drift guard requires them documented even though none use Sanctum).

Not done here (explicitly open)

  • Animeitor consumer version/repo confirmation, its validity ceiling, and its accepted auth mechanism are still open per the spec's "Perguntas para decisão" -- this PR documents the mechanism it chose (bearer token) as a proposal, not a confirmed answer.
  • Issue Managed accounts for minors (privacy lock with automatic lift at 18) #47's team public-name policy is unchanged by this PR; BocaWebcastZipBuilder::teams() should be revisited once that lands.

🤖 Generated with Claude Code

https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn

matbrgz and others added 3 commits September 11, 2026 01:03
… credentials

Implements the real backend behind resources/js/features/Webcast.vue's
proposed /api/frontend/webcast* contract:

- GET/POST/DELETE /api/frontend/webcast* (session admin + CSRF) for
  contest selection, credential issuance/listing/revocation, backed by a
  new webcast_credentials table. Raw secrets are never stored (sha256
  hash only) and never re-appear after the create response.
- A generic Idempotency-Key mechanism (idempotency_keys table +
  App\Services\IdempotencyGuard) reusable by other /api/frontend/*
  routes: same key+payload replays the saved response, same key with a
  different payload -> 409, and credential creation specifically
  reconciles metadata on replay without ever repeating the one-time
  secret.
- A full BOCA webcast ZIP serializer (App\Services\BocaWebcastZipBuilder)
  producing contest/runs/version/time/icpc with the FS (0x1C) field
  separator, verified byte-for-byte by round-tripping a real ZIP in
  tests. capabilities.can_export stays false by default
  (config('webcast.export_enabled')) per the spec's explicit
  instruction, since the linked Animeitor consumer is unverified -- the
  export endpoint and builder are fully implemented and tested
  regardless.
- A standalone webcast-credential guard (Authorization: Bearer, sha256
  lookup + hash_equals, routes/webcast_consumer.php registered outside
  both the web and api route groups) exposing only the unfrozen
  scoreboard for the credential's own contest. Active/expired/revoked/
  nonexistent tokens are all denied identically; rate-limited
  (throttle:20,1, running before the guard so wrong guesses count too).

Fixes found and applied during self-review: BocaWebcastZipBuilder no
longer aborts the whole export when a non-team account (e.g. an admin
test run via POST /api/runs) has a run in the contest -- it's excluded
instead. IdempotencyGuard now handles a create() race on the same key
(unique constraint collision) by falling back to replay instead of
propagating a raw QueryException. WebcastController::storeCredential()
no longer trusts a re-fetched Contest to be non-null after validation.

Updates docs/specs/44-webcast.md and the #44 row in docs/specs/README.md
to reflect what's implemented, and docs/api/openapi.yaml (all new
routes are under /api/*, so the existing drift-guard test requires
them documented even though they don't use Sanctum).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
1. Trim the credential label before validation (not after) -- a
   whitespace-only label previously passed `min:1` on its untrimmed
   length and only got emptied afterward, letting it slip past
   `required`.
2. Guarantee temp ZIP cleanup on export via register_shutdown_function()
   instead of an unlink() that only ran after readfile() completed --
   a client aborting the download mid-transfer previously left the temp
   file behind (a plain try/finally does not run on that kind of
   connection-abort termination).
3. Unify the create-credential response shape between a first-time
   success and an idempotent replay: both are now exactly {id, secret}
   (secret null on replay), instead of the replay also carrying
   label/status/expires_at that the original response never had.
4. Match the Authorization header's Bearer scheme case-insensitively
   (RFC 7235), so e.g. `authorization: bearer <token>` isn't silently
   treated as no credential at all.
5. Extract the duplicated contests-list transform in
   WebcastController::index() into contestOptions().
6. Drop the redundant ->orderBy('sort_order') in
   BocaWebcastZipBuilder::contestFile() -- Contest::problems() already
   orders by sort_order.

Adds regression tests for the whitespace-label rejection, the unified
replay response shape, and case-insensitive Bearer matching.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
Consolidates the Idempotency-Key mechanism: issue #47's managed-accounts
PR landed on master with its own App\Support\IdempotencyStore (service)
+ app/Models/IdempotencyKey.php + migration
2026_09_11_000202_create_idempotency_keys_table.php, built independently
and concurrently with this branch's near-identical App\Services\
IdempotencyGuard + its own IdempotencyKey model + migration
2026_09_11_000201_create_idempotency_keys_table.php. Two migrations both
creating the same idempotency_keys table would have collided.

Kept master's version as canonical (App\Support\IdempotencyStore, its
IdempotencyKey model, migration 000202) and deleted this branch's
duplicate IdempotencyGuard/migration. WebcastController now calls
IdempotencyStore::handle() instead, matching its actual contract rather
than assuming it matched IdempotencyGuard's interface:

- Idempotency-Key is now a REQUIRED header (400 if missing) for
  storeCredential()/revokeCredential(), matching the app-wide convention
  IdempotencyStore establishes -- previously optional in this branch's
  own guard.
- IdempotencyStore persists and replays exactly what the callback's
  JsonResponse contains, with no separate "public vs stored body" split
  the way this branch's own IdempotencyGuard supported. Since the
  webcast secret must never be persisted (spec: "nunca armazenar token
  em claro indefinidamente") but must still reach the caller that
  actually created it, storeCredential() now has the callback always
  return secret: null (what IdempotencyStore persists/replays) and
  overlays the real secret onto the outgoing response afterwards, only
  when this process is the one that actually ran WebcastCredential::
  issue() (tracked via a side-channel reference, not through the
  persisted response).
- Dropped the bespoke race-simulation test for the create-time unique-
  constraint collision (IdempotencyGuard-specific); that behavior is now
  IdempotencyStore's, already covered by tests/Feature/
  ManagedAccountsApiTest.php.

Also resolves routes/web.php (kept every branch's `require` line) and
docs/api/openapi.yaml (kept both /frontend/webcast* and
/frontend/managed-accounts path definitions, plus master's new
EXCLUDED_PREFIXES-based OpenApiSpecTest that no longer requires every
/api/frontend/* route to be documented -- webcast's entries are kept
documented anyway as they were before).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
matbrgz added a commit that referenced this pull request Sep 11, 2026
…76)

CRITICAL: Contest::getContestTime() computed elapsed time as
now()->diffInSeconds($this->start_time). Under Carbon 3 (this app's
pinned version), $a->diffInSeconds($b) returns $b's timestamp minus
$a's -- signed, not absolute -- so this returned a NEGATIVE value for
the entire duration a contest was running, instead of positive elapsed
seconds since start.

This corrupted every consumer across the app: Run.contest_time,
Run.judged_time, Task.completed_time, and Clarification.answered_time
were all negative (13 call sites in SubmitController, JudgeController,
StaffController, SiteController, AutoJudgeService,
ReconcileStuckRunsCommand, and the Api\* equivalents). Worse,
Score::updateScore() derives solved_time = floor(contest_time / 60),
and Leaderboard::getScoreboard() ranks by total_time ascending -- so a
LATER solve produced a MORE NEGATIVE (i.e. numerically smaller)
total_time and ranked BETTER, inverting the scoreboard's core ranking
for every contest this app has ever run.

tests/Unit/ContestModelTest.php had a test that explicitly asserted
the negative result as correct ("The method returns the time
difference (negative when contest has started)"), which is why this
went uncaught -- the test was calibrated to the bug rather than the
intended behavior.

Fix: swap the receiver/argument
($this->start_time->diffInSeconds(now())) so elapsed time is
correctly signed positive. Updated the test that encoded the wrong
expectation, and added ScoreLeaderboardRankingTest -- an end-to-end
test through the real Contest::getContestTime() -> Score::updateScore()
-> Leaderboard::getScoreboard() pipeline (not literal/fixed total_time
values, which is how every other existing scoreboard test avoided
tripping over this) proving an earlier solver now ranks ahead of a
later one. Verified this new test fails against the pre-fix code
(-30 instead of positive) and passes after the fix.

Found while independently reviewing PR #73 (webcast export), which
had already discovered this bug and worked around it locally in its
own BocaWebcastZipBuilder rather than fixing the shared root cause --
that workaround should be simplified once this lands.


Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn

Co-authored-by: Claude Sonnet 5 <[email protected]>
…s PR #73 review round 2

Merges in #74 (similarity backend), #75 (IdempotencyStore payload-hash key
ordering), and #76 (Contest::getContestTime() sign fix). Only conflict was
routes/web.php's `require` lines (kept all of them).

A. Removes BocaWebcastZipBuilder::timeFile()'s local workaround for
   Contest::getContestTime()'s Carbon 3 signed-diff bug, now that #76 fixes
   the root cause directly on the model. timeFile() just calls
   $contest->getContestTime() again -- no more parallel implementation of
   the same elapsed-time calculation. The value produced is unchanged (the
   workaround already computed the correct positive figure), so no test
   expectations needed correcting, just the redundant code removed.

B. Ten further review findings, all fixed:

1. Webcast\ScoreboardController::show() now null-checks $credential->
   contest before use -- a still-active credential whose contest was
   soft-deleted (Contest uses SoftDeletes; ContestController::destroy()
   never cascades) previously reached Leaderboard::getScoreboard(null) and
   threw a TypeError instead of a clean 401.
2. BocaWebcastZipBuilder::teams() uses ?? instead of ?: for the fallback
   team name -- ?: silently replaced a team literally named "0" with the
   placeholder, since "0" is falsy in PHP.
3. AuthenticateWebcastCredential now eager-loads `contest` on the
   credential lookup (the one route a credential is meant to be polled
   on repeatedly).
4. WebcastController::storeCredential() no longer runs a redundant
   Rule::exists('contests','id') validation query alongside the
   Contest::find() + null-check that already answers the same question
   (and already correctly excludes soft-deleted contests).
5. WebcastController::export() now uses response()->download($path)->
   deleteFileAfterSend(true) instead of a hand-rolled streamDownload()+
   readfile()+register_shutdown_function() -- Symfony's BinaryFileResponse
   already calls ignore_user_abort(true) and unlinks the temp file in a
   finally block around the transfer loop, so a client-cancelled download
   still gets cleaned up via the framework's own mechanism.
6. WebcastController::index() now uses Eloquent's paginate() instead of
   hand-rolled page/perPage/lastPage/forPage bookkeeping, matching the
   convention Api\Frontend\ManagedAccountsController (#47) already
   established for the same "session-admin JSON list" shape.
7. Removed the dead hash_equals() re-check in AuthenticateWebcastCredential
   -- a row can only be returned by `WHERE token_hash = $hash`, so
   comparing them again could never evaluate false; it was presented as a
   timing-safety measure but wasn't one.
8. Left a comment on the storeCredential() secret-redaction workaround
   describing the pattern and a possible shared fix (an optional redact
   closure on IdempotencyStore::handle()) as a follow-up, since that
   would touch the shared class #47's endpoint also depends on.
9. BocaWebcastZipBuilder::resultCode() simplified in_array($run->status,
   ['judged'], true) to the direct $run->status !== 'judged' comparison.

Regression tests added for #1 (soft-deleted contest -> 401), #2 (team
named "0"), and #3 (relationLoaded('contest') on the credential lookup,
tested directly against the query shape rather than by counting queries
over a full request, which would also pick up Leaderboard::getScoreboard()
's own unrelated internal Contest::findOrFail() call).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn
@matbrgz
matbrgz merged commit 7470f29 into master Sep 11, 2026
@matbrgz
matbrgz deleted the feature/issue-44-webcast-export branch September 11, 2026 12:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant