Repository navigation
feat(webcast): issue #44 backend -- BOCA export + revocable credentials - #73
Merged
Merged
Conversation
… 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
4 tasks done
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, perdocs/specs/44-webcast.md):GET/POST/DELETE /api/frontend/webcast*(web session + CSRF,['auth','admin'],routes/frontend_api_webcast.phprequired from the bottom ofroutes/web.php) for contest selection, credential issuance/listing/revocation, backed by a newwebcast_credentialstable. Raw secrets are generated withStr::random(40), stored only assha256, and only ever appear once, in the create response.Idempotency-Keymechanism (idempotency_keystable +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).App\Services\BocaWebcastZipBuilder) producingcontest/runs/version/time/icpcwith 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).App\Http\Middleware\AuthenticateWebcastCredential,Authorization: Bearer <secret>, sha256 lookup +hash_equals) registered in its own route group (routes/webcast_consumer.php, wired viabootstrap/app.php'swithRouting(then: ...)) entirely outside both thewebandapigroups — no session, no CSRF, no Sanctum. It exposes exactly one route, the unfrozen scoreboard for the credential's own contest, and never callsAuth::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_exportstaysfalseby default (config('webcast.export_enabled'), envWEBCAST_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-reviewagainst the diff and fixed what it found before opening this PR:BocaWebcastZipBuilderno longer aborts the entire export with aRuntimeExceptionwhen a non-team account has a run in the contest (e.g. an admin's test run viaPOST /api/runs, which has nouser_typerestriction) — such runs are now silently excluded instead of taking down the whole export.IdempotencyGuard::handle()now catches aQueryExceptionfrom a create-time race on the sameIdempotency-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-fetchedContestis non-null after validation (a TOCTOU window if the contest were deleted between theRule::existscheck and theContest::find()call) — it now raises a clean 422 instead of risking aTypeError.Also noted, deliberately not fixed (out of scope): this app has no
personal_access_tokensmigration despiteHelium\UserusingHasApiTokensandroutes/api.phpgating everything behindauth:sanctum— any request presenting a genuineAuthorization: Bearerheader 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 intests/Feature/WebcastCredentialAuthTest.phpand 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/pintclean on all new/changed files.docs/api/openapi.yamlupdated (all new routes are under/api/*, soOpenApiSpecTest's drift guard requires them documented even though none use Sanctum).Not done here (explicitly open)
BocaWebcastZipBuilder::teams()should be revisited once that lands.🤖 Generated with Claude Code
https://claude.ai/code/session_011u3o4QCgpcqH51edYyRPMn