feat(quota): ingest CI usage reported by external CI systems #103
No reviewers
Labels
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
codefloe/forgejo-codefloe!103
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/quota-ci-external-ingest"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Implements #95, phase 3a of the CI build minutes quota work, on top of #100 (the ledger) and #102 (enforcement).
Phase 1 made Forgejo Actions minutes countable and phase 2 made them enforceable.
This phase lets a CI system that is not Forgejo Actions report the minutes it spent, so they land in the same ledger, show up in the same totals, and count against the same
time:rules.This is the ingest half only.
The pre-flight check that lets a reporter ask permission before starting is #98.
What changed
Reporter identity
A reporter is a named external system with a token, registered purely in configuration:
The section name is the reporter's name and becomes the
sourceof every ledger record it writes, so usage stays attributable per system whiletime:ci:externalsums them.Only the hash is configured, so a leaked
app.inidoes not hand out the credential.A name that cannot be stored as a source, a
TOKEN_HASHthat is not a SHA-256, or a section trying to claim the built-inactionssource is dropped with a log line rather than failing startup.Nothing in the forge knows that any particular system exists: a second external CI is configuration, not code.
The integration tests register two differently named reporters through the same mechanism to prove it.
Authentication
Reporter credentials are deliberately not user tokens: this endpoint writes billing data, and no user should be able to reach it by holding a personal token.
/api/v1/quota/ciis mounted beside the rest of the API inrouters/init.go, with a stack of its own: security headers,APIContexter, and reporter authentication.That is what keeps the two kinds of credential apart in both directions.
Run through the shared API stack, a reporter's token would be read as a malformed access token and refused before any handler saw it; run through its own, it cannot authenticate a user, is never offered to the user authentication, and buys nothing anywhere else in the API.
A leaked reporter token reaches this endpoint and no further, including on an instance with
REQUIRE_SIGNIN_VIEW = true.Endpoint
POST /api/v1/quota/ci/usagesourceis not in the body. It is the authenticated reporter, so no reporter can write usage in another's name.repo; a repository this instance does not have is a 404.stopped, so a report delivered days late still bills the month it belongs to.secondsis optional and derived from the interval when omitted, for a reporter that bills something other than wall clock time.(source, external_ref), the unique index from phase 1. A repeat of a report that was already booked answers 200 and charges nothing, so a reporter can drain a retry queue safely.AddRecordnow hands back the record already holding a reference instead of a bare "did it write" flag, which is what makes that distinction possible.Two workers racing the unique index reach the same answer: the transaction that loses re-reads the row it collided with rather than reporting an error, so the "a retry is always accepted" contract holds under concurrency.
The comparison is over what a report claims — class, started, stopped, seconds — and not over the owner and repository the forge resolved from it, so a repository transferred or recreated between a report and its retry does not wedge that retry in the producer's queue.
Files changed
modules/setting/codefloe_quota_ci.go— read[quota.ci.reporter.<name>]sections intoQuotaCI.Reporters, validating the name and the token hashmodules/setting/codefloe_quota_ci_test.go— new: reporter loading, including every way a section is refusedmodels/codefloe/quota_ci/quota_ci.go—AddRecordreturns the existing record on a repeat;SameBillingAscompares what two reports claimmodels/codefloe/quota_ci/quota_ci_test.go— follow the new signaturemodules/structs/codefloe_quota_ci.go—QuotaCIUsageReport, the request bodyservices/codefloe/quota_ci/ingest.go— new: validate a report, resolve the repository and owner, book it, and tell a replay from a contradictionservices/codefloe/quota_ci/info.go— render records through the ingest half's helper rather than repeating itrouters/api/v1/codefloe/quota_ci_reporter.go— new: the reporter router and its authenticationrouters/api/v1/codefloe/quota_ci.go— theReportQuotaCIUsagehandlerrouters/init.go— mount/api/v1/quota/ciwhen the ledger is onservices/auth/method/codefloe_token.go— new: export the existing bearer-token parser rather than writing a second onerouters/api/v1/swagger/codefloe_quota_ci.go,templates/swagger/v1_json.tmpl— the response and body definitionstests/integration/api_quota_ci_usage_test.go— new: attribution, per-reporter sources, idempotency, mismatch, late periods, unknown repositories, validation, that an unauthenticated caller, an unknown token, a user token and a query-string token are all refused, and that underREQUIRE_SIGNIN_VIEWa reporter can still report while its token reads nothingBehaviour change
Nothing changes for an instance that configures no reporter: the route is only mounted when
[quota.ci] ENABLEDis on, and without a matching token every request to it is a 401.Once a reporter is registered, its minutes appear in the owner's CI usage under its own source and under
time:ci:external, and are therefore counted by anytime:ci:externalortime:ci:allrule the owner is held to. Operators writing such rules should know that turning a reporter on can push an owner over a limit that was previously only about Forgejo Actions.Crow CI side
Tracked in the Crow repository: report duration per finished pipeline step to this endpoint, and queue failed pushes durably, relying on
external_reffor safety. Nothing here knows Crow exists.c96b2b75ffb1a4107879Review
Build is clean at
b1a4107879and the setting/model unit tests pass (go test -tags sqlite ./models/codefloe/quota_ci/).Findings ordered by severity.
Blocking
1. Reporter token bypasses
REQUIRE_SIGNIN_VIEWon every API route (routers/api/shared/middleware.go:170)The
!IsQuotaCIReporter(ctx)exemption lives in the sharedverifyAuthWithOptionsstack, andQuotaCIReporterAuthflags any request carrying a valid reporter token regardless of path.On an instance with
REQUIRE_SIGNIN_VIEW = true,GET /api/v1/repos/search(or/repos/{owner}/{public-repo},/users/{u}) with no credentials is 403, but the same request withAuthorization: Bearer <reporter-token>sets the flag, drops the header, skips the 403 and is served as an anonymous reader with 200.A leaked CI secret enumerates the instance, and the docstring's "everything else in the API still sees an unauthenticated caller" is exactly the problem on such an instance.
Fix: scope the exemption to the reporter route, or mount
/api/v1/quota/cias its own router with a minimal stack (context.APIContexter()+ reporter auth), the wayrouters/api/actionsis mounted inrouters/init.go.That also removes the
shared -> v1/codefloeimport inversion, theAuthorizationheader deletion, and thesudo()inheritance in item 12.Should fix before merge
2. Two reporters sharing a
TOKEN_HASHload silently, last match wins (modules/setting/codefloe_quota_ci.go:118,routers/api/v1/codefloe/quota_ci_reporter.go:95)loadQuotaCIReportersdedupes on name only andquotaCIReporterForkeeps the last matching reporter.Copy
[quota.ci.reporter.crow]to[quota.ci.reporter.woodpecker]without changing the hash and every report crow sends is booked withsource = woodpecker, flipping if the sections are reordered, with no log line.Reject a repeated hash the same way a repeated name is rejected.
3. Concurrent identical reports race the unique index and answer 500 (
models/codefloe/quota_ci/quota_ci.go:141)GetthenInsertinAddRecordis not atomic; two workers draining one queue both see no row, the second insert hitsUNIQUE(record_ref)andReportQuotaCIUsageanswers 500 from the default branch.Nothing is double-charged, but the "retry is always 200" contract is broken.
Catch the unique violation and re-read the existing row, or retry the transaction once.
4. Query-string PAT still authenticates alongside the reporter token (
routers/api/v1/codefloe/quota_ci_reporter.go:45)Deleting the header does not stop
?access_token=/?token=(DISABLE_QUERY_AUTH_TOKENdefaults to false), so one request can be both a reporter and a signed-in user, contradicting the "has no user behind it and never will" invariant.Either refuse a reporter request that also carries user credentials, or clear the query token too.
5. No test covers the sign-in exemption or non-reporter routes (
tests/integration/api_quota_ci_usage_test.go:255)Add:
RequireSignInView=true+ reporter token gives 201 onPOST /quota/ci/usageand 403 onGET /api/v1/repos/user2/repo1(fails today per item 1), and reporter token againstGET /api/v1/useris 401.Without these, an upstream merge that reorders
Middlewares()and movesQuotaCIReporterAuthafterapiAuthenticationpasses CI while the reporter token starts being parsed as a malformed PAT.Plausible
6. Retry after a repo transfer or recreate is refused with 409 (
services/codefloe/quota_ci/ingest.go:56)SameBillingAscomparesOwnerIDandRepoID, which the reporter never sends and which are re-resolved fromreport.Repoat retry time.A client that timed out after the server committed, then re-sends after the repo was transferred, gets
ErrReportMismatchand the item is stuck in its queue.The doc comment says the comparison is "over what a report claims, not over what the ledger derived", which argues for comparing only class/started/stopped/seconds; at minimum the 409 message should say which field differed.
Cleanups
7.
seenmap and the duplicate-name branch are unreachable (modules/setting/codefloe_quota_ci.go:106):configProviderLoadOptions()does not setAllowNonUniqueSections, so go-ini merges repeated sections andChildSections()never yields a name twice.Replace it with the duplicate-hash check from item 2.
8.
bearerTokenduplicatestokenFromAuthorizationBearerinservices/auth/method/util.go:34(routers/api/v1/codefloe/quota_ci_reporter.go:107).Export the existing helper and call it.
9.
validNameandmaxNameLength = 40are a character-for-character copy ofisValidQuotaCIReporterName(services/codefloe/quota_ci/ingest.go:159).Both guard the same two columns; one exported helper in
modules/utilormodules/structs(whichsettingcan import) serves setting, model and service, and can also ownSourceActions/ClassDefaultthatquotaCISourceActionsre-literals.10. The
IsErrRepoNotExistre-wrap is redundant (services/codefloe/quota_ci/ingest.go:134):ErrRepoNotExist.Unwrap()already returnsutil.ErrNotExist, so the handler maps it to 404 without the branch.11.
binding:"Required"ontime.Timeis inert (modules/structs/codefloe_quota_ci.go:99): go-chi/binding routes struct fields intovalidateStructand skips their own rules.Only the
IsZerocheck inrecordFromcatches a missing timestamp, so the outcome is right today, but the tags and swagger promise validation that does not exist.12. The reporter route inherits
sudo()and sits in a single-route group (routers/api/v1/api.go:576): a CI system forwarding aSudoheader gets 403 "Only administrators allowed to sudo." instead of 201.Resolved by the separate mount in item 1; otherwise a single
m.Post("/quota/ci/usage", codefloe.ReqQuotaCIReporter(), bind(...), codefloe.ReportQuotaCIUsage)reads as one line.b1a4107879bc3f833b18Reworked at
bc3f833b18. Item 1 is fixed by the separate mount you suggested, which subsumes 4 and 12 and removes theshared -> v1/codefloeimport inversion.routers/api/shared/middleware.goandrouters/api/v1/api.goare back to untouched; the only upstream file the PR still edits isrouters/init.go, +7 lines.1. Sign-in bypass — fixed
/api/v1/quota/ciis now mounted inrouters/init.gonext to/api/v1, with a stack ofsecurityHeaders() + context.APIContexter() + reqQuotaCIReporter()and nothing else. chi routes the more specific static prefix, so/api/v1/*keeps everything else.QuotaCIReporterAuthandIsQuotaCIReporterare gone; the reporter is authenticated inside its own router and the shared stack never sees the credential.The scoping is now stronger than the 403 you asked for: on
REQUIRE_SIGNIN_VIEW = truea reporter token against/api/v1/repos/user2/repo1,/api/v1/repos/searchand/api/v1/users/user2gets 401, because the shared stack reads it as the malformed access token it is rather than skipping anything. Covered byTestAPIQuotaCIUsageReportRequireSignInView.2. Shared
TOKEN_HASH— fixedloadQuotaCIReportersnow keys on the normalised digest and drops a section that repeats one already claimed, logging which reporter owns it. The first section wins, so copying[quota.ci.reporter.crow]loses the copy rather than the original. Case is normalised first, so an upper-case repeat is still caught. Test: "two reporters may not share a token".3. Insert race — fixed
AddRecordsplits intoinsertRecordplus a fallback: when the transaction fails it re-reads(source, external_ref)and, if the row is there, returns it. The error is only reported when nothing was booked. This deliberately does not classify driver-specific unique violations — if the record exists after a failed transaction, some other committed transaction wrote it and folded its seconds, so the state is right and the retry contract holds. Test: "concurrent bookings of one reference charge once".4. Query-string PAT — fixed by 1
The reporter router runs no user authentication at all, so
?access_token=and?token=cannot produce a doer on those routes. Test: "a query string token does not authenticate a reporter" (401).5. Tests — added
TestAPIQuotaCIUsageReportRequireSignInView(report still works, three read endpoints refused) and "a reporter token buys nothing elsewhere in the API" (GET /api/v1/user→ 401). The regression you describe — a reordering ofMiddlewares()— can no longer happen, since the reporter route does not go throughMiddlewares().6. Retry after transfer — fixed, and I took your first suggestion
SameBillingAsis replaced byBillingDifference, which compares onlyclass,started,stoppedandsecondsand returns the name of the first field that differs; the 409 is now... already booked for different work: seconds.OwnerID/RepoIDare out, so a transfer or recreate between a report and its retry no longer wedges the queue.One consequence worth naming: the record echoed back on a replay is now looked up by the stored
RepoID, not the repository the retry named, so the response says what the ledger actually holds. Tests inTestQuotaCIBillingDifference.7. Unreachable
seenmap — removedConfirmed:
configProviderLoadOptions()does not setAllowNonUniqueSections, so go-ini merges repeated section names. Replaced by the digest map from item 2.8. Duplicate bearer parsing — deduplicated, but not by exporting in place
Exporting
tokenFromAuthorizationBearermeans renaming it and every call site acrossaccess_token.go,action_task_token.go,authorized_integration.goandbasic.go— a wide diff in upstream files, which this fork pays for at every merge. Instead there is a three-line fork-ownedservices/auth/method/codefloe_token.goexporting a wrapper, and the reporter calls it. Same single source of truth for the parsing, no upstream file touched. Say the word if you would rather have the rename.9. Duplicated name validator — one helper
Now
setting.IsValidQuotaCIName, called by both the reporter loader and the class check inrecordFrom, withmaxQuotaCINameLengthbeside it. I put it inmodules/settingrather thanmodules/utilbecause that is where the shape is defined and both callers already depend on setting; a generically-named string predicate inutilwould have had to invent a meaning it does not have.quotaCISourceActionsstays a literal:settingcannot importmodels/codefloe/quota_ci(that package'smodels/dbdependency importssetting). The reserved-name check moved out of the validator into the loader, which is the only place it means anything.10. Redundant re-wrap — removed
GetRepositoryByOwnerAndNameis now returned directly, with a comment noting thatErrRepoNotExistunwraps toutil.ErrNotExist.11. Inert
binding:"Required"— tags droppedConfirmed in
binding.go:355: a struct-kinded field recurses intovalidateStructandcontinues, so the rules never run. The tags never reached the swagger spec either (QuotaCIUsageReporthas norequiredarray before or after). The handler now decodes the body itself and every check lives inrecordFrom, which is the only place that was doing the work anyway. A body that is not a usage report is a 422.12.
sudo()inheritance — fixed by 1The reporter router does not include
sudo(), so a forwardedSudoheader is ignored rather than answered with 403.Verified:
golangci-lint run ./...clean, deadcode output unchanged,go test -tags sqlite ./models/codefloe/... ./modules/setting/... ./services/... ./routers/api/...pass, andTestAPIQuotaCI*/TestQuota*pass on sqlite. Full CI is running.