codefloe/forgejo-codefloe
Watch
4
12
Fork
You've already forked forgejo-codefloe
0

feat(quota): ingest CI usage reported by external CI systems #103

Merged
pat-s merged 1 commit from feat/quota-ci-external-ingest into v16.0/forgejo-codefloe 2026-08-29 13:43:27 +00:00
Owner

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:

[quota.ci.reporter.crow]
TOKEN_HASH = <hex sha256 of the token>

The section name is the reporter's name and becomes the source of every ledger record it writes, so usage stays attributable per system while time:ci:external sums them.
Only the hash is configured, so a leaked app.ini does not hand out the credential.
A name that cannot be stored as a source, a TOKEN_HASH that is not a SHA-256, or a section trying to claim the built-in actions source 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/ci is mounted beside the rest of the API in routers/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/usage

{
  "repo": "owner/name",
  "external_ref": "pipeline/4711/step/3",
  "started": "2026-08-28T10:00:00Z",
  "stopped": "2026-08-28T10:07:31Z",
  "seconds": 451,
  "class": "linux"
}
  • source is not in the body. It is the authenticated reporter, so no reporter can write usage in another's name.
  • The owner is resolved from repo; a repository this instance does not have is a 404.
  • The period comes from stopped, so a report delivered days late still bills the month it belongs to.
  • seconds is optional and derived from the interval when omitted, for a reporter that bills something other than wall clock time.
  • The write is idempotent on (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.
  • A repeat that reuses a reference for different work is refused with 409 rather than silently kept or overwritten: that is a reporter bug, and hiding it behind a number nobody can explain later is worse than saying so.

AddRecord now 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 into QuotaCI.Reporters, validating the name and the token hash
  • modules/setting/codefloe_quota_ci_test.go — new: reporter loading, including every way a section is refused
  • models/codefloe/quota_ci/quota_ci.go — AddRecord returns the existing record on a repeat; SameBillingAs compares what two reports claim
  • models/codefloe/quota_ci/quota_ci_test.go — follow the new signature
  • modules/structs/codefloe_quota_ci.go — QuotaCIUsageReport, the request body
  • services/codefloe/quota_ci/ingest.go — new: validate a report, resolve the repository and owner, book it, and tell a replay from a contradiction
  • services/codefloe/quota_ci/info.go — render records through the ingest half's helper rather than repeating it
  • routers/api/v1/codefloe/quota_ci_reporter.go — new: the reporter router and its authentication
  • routers/api/v1/codefloe/quota_ci.go — the ReportQuotaCIUsage handler
  • routers/init.go — mount /api/v1/quota/ci when the ledger is on
  • services/auth/method/codefloe_token.go — new: export the existing bearer-token parser rather than writing a second one
  • routers/api/v1/swagger/codefloe_quota_ci.go, templates/swagger/v1_json.tmpl — the response and body definitions
  • tests/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 under REQUIRE_SIGNIN_VIEW a reporter can still report while its token reads nothing

Behaviour change

Nothing changes for an instance that configures no reporter: the route is only mounted when [quota.ci] ENABLED is 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 any time:ci:external or time:ci:all rule 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_ref for safety. Nothing here knows Crow exists.

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: ```ini [quota.ci.reporter.crow] TOKEN_HASH = <hex sha256 of the token> ``` The section name is the reporter's name and becomes the `source` of every ledger record it writes, so usage stays attributable per system while `time:ci:external` sums them. Only the hash is configured, so a leaked `app.ini` does not hand out the credential. A name that cannot be stored as a source, a `TOKEN_HASH` that is not a SHA-256, or a section trying to claim the built-in `actions` source 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/ci` is mounted beside the rest of the API in `routers/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/usage` ```json { "repo": "owner/name", "external_ref": "pipeline/4711/step/3", "started": "2026-08-28T10:00:00Z", "stopped": "2026-08-28T10:07:31Z", "seconds": 451, "class": "linux" } ``` - `source` is not in the body. It is the authenticated reporter, so no reporter can write usage in another's name. - The owner is resolved from `repo`; a repository this instance does not have is a 404. - The period comes from `stopped`, so a report delivered days late still bills the month it belongs to. - `seconds` is optional and derived from the interval when omitted, for a reporter that bills something other than wall clock time. - The write is idempotent on `(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. - A repeat that reuses a reference for **different** work is refused with 409 rather than silently kept or overwritten: that is a reporter bug, and hiding it behind a number nobody can explain later is worse than saying so. `AddRecord` now 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 into `QuotaCI.Reporters`, validating the name and the token hash - `modules/setting/codefloe_quota_ci_test.go` — new: reporter loading, including every way a section is refused - `models/codefloe/quota_ci/quota_ci.go` — `AddRecord` returns the existing record on a repeat; `SameBillingAs` compares what two reports claim - `models/codefloe/quota_ci/quota_ci_test.go` — follow the new signature - `modules/structs/codefloe_quota_ci.go` — `QuotaCIUsageReport`, the request body - `services/codefloe/quota_ci/ingest.go` — new: validate a report, resolve the repository and owner, book it, and tell a replay from a contradiction - `services/codefloe/quota_ci/info.go` — render records through the ingest half's helper rather than repeating it - `routers/api/v1/codefloe/quota_ci_reporter.go` — new: the reporter router and its authentication - `routers/api/v1/codefloe/quota_ci.go` — the `ReportQuotaCIUsage` handler - `routers/init.go` — mount `/api/v1/quota/ci` when the ledger is on - `services/auth/method/codefloe_token.go` — new: export the existing bearer-token parser rather than writing a second one - `routers/api/v1/swagger/codefloe_quota_ci.go`, `templates/swagger/v1_json.tmpl` — the response and body definitions - `tests/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 under `REQUIRE_SIGNIN_VIEW` a reporter can still report while its token reads nothing ## Behaviour change Nothing changes for an instance that configures no reporter: the route is only mounted when `[quota.ci] ENABLED` is 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 any `time:ci:external` or `time:ci:all` rule 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_ref` for safety. Nothing here knows Crow exists.
pat-s force-pushed feat/quota-ci-external-ingest from c96b2b75ff
Some checks failed
testing / test-unit (pull_request) Has been cancelled
testing / test-e2e (pull_request) Has been cancelled
testing / test-remote-cacher (redis) (pull_request) Has been cancelled
testing / test-remote-cacher (valkey) (pull_request) Has been cancelled
testing / test-remote-cacher (garnet) (pull_request) Has been cancelled
testing / test-mysql (pull_request) Has been cancelled
testing / test-pgsql (pull_request) Has been cancelled
testing / test-sqlite (pull_request) Has been cancelled
testing / frontend-checks (pull_request) Has been cancelled
testing / backend-checks (pull_request) Has been cancelled
to b1a4107879
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m45s
testing / backend-checks (pull_request) Successful in 6m14s
testing / test-unit (pull_request) Successful in 10m10s
testing / test-remote-cacher (redis) (pull_request) Successful in 3m38s
testing / test-remote-cacher (garnet) (pull_request) Successful in 3m38s
testing / test-remote-cacher (valkey) (pull_request) Successful in 3m47s
testing / test-e2e (pull_request) Successful in 26m39s
testing / test-mysql (pull_request) Successful in 29m24s
testing / test-sqlite (pull_request) Successful in 44m44s
testing / test-pgsql (pull_request) Successful in 47m47s
2026-08-29 10:53:58 +00:00
Compare
Author
Owner

Review

Build is clean at b1a4107879 and 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_VIEW on every API route (routers/api/shared/middleware.go:170)

The !IsQuotaCIReporter(ctx) exemption lives in the shared verifyAuthWithOptions stack, and QuotaCIReporterAuth flags 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 with Authorization: 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/ci as its own router with a minimal stack (context.APIContexter() + reporter auth), the way routers/api/actions is mounted in routers/init.go.
That also removes the shared -> v1/codefloe import inversion, the Authorization header deletion, and the sudo() inheritance in item 12.

Should fix before merge

2. Two reporters sharing a TOKEN_HASH load silently, last match wins (modules/setting/codefloe_quota_ci.go:118, routers/api/v1/codefloe/quota_ci_reporter.go:95)

loadQuotaCIReporters dedupes on name only and quotaCIReporterFor keeps 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 with source = 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)

Get then Insert in AddRecord is not atomic; two workers draining one queue both see no row, the second insert hits UNIQUE(record_ref) and ReportQuotaCIUsage answers 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_TOKEN defaults 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 on POST /quota/ci/usage and 403 on GET /api/v1/repos/user2/repo1 (fails today per item 1), and reporter token against GET /api/v1/user is 401.
Without these, an upstream merge that reorders Middlewares() and moves QuotaCIReporterAuth after apiAuthentication passes 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)

SameBillingAs compares OwnerID and RepoID, which the reporter never sends and which are re-resolved from report.Repo at retry time.
A client that timed out after the server committed, then re-sends after the repo was transferred, gets ErrReportMismatch and 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. seen map and the duplicate-name branch are unreachable (modules/setting/codefloe_quota_ci.go:106): configProviderLoadOptions() does not set AllowNonUniqueSections, so go-ini merges repeated sections and ChildSections() never yields a name twice.
Replace it with the duplicate-hash check from item 2.

8. bearerToken duplicates tokenFromAuthorizationBearer in services/auth/method/util.go:34 (routers/api/v1/codefloe/quota_ci_reporter.go:107).
Export the existing helper and call it.

9. validName and maxNameLength = 40 are a character-for-character copy of isValidQuotaCIReporterName (services/codefloe/quota_ci/ingest.go:159).
Both guard the same two columns; one exported helper in modules/util or modules/structs (which setting can import) serves setting, model and service, and can also own SourceActions/ClassDefault that quotaCISourceActions re-literals.

10. The IsErrRepoNotExist re-wrap is redundant (services/codefloe/quota_ci/ingest.go:134): ErrRepoNotExist.Unwrap() already returns util.ErrNotExist, so the handler maps it to 404 without the branch.

11. binding:"Required" on time.Time is inert (modules/structs/codefloe_quota_ci.go:99): go-chi/binding routes struct fields into validateStruct and skips their own rules.
Only the IsZero check in recordFrom catches 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 a Sudo header 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.

## Review Build is clean at `b1a4107879` and 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_VIEW` on every API route** (`routers/api/shared/middleware.go:170`) The `!IsQuotaCIReporter(ctx)` exemption lives in the shared `verifyAuthWithOptions` stack, and `QuotaCIReporterAuth` flags 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 with `Authorization: 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/ci` as its own router with a minimal stack (`context.APIContexter()` + reporter auth), the way `routers/api/actions` is mounted in `routers/init.go`. That also removes the `shared -> v1/codefloe` import inversion, the `Authorization` header deletion, and the `sudo()` inheritance in item 12. ### Should fix before merge **2. Two reporters sharing a `TOKEN_HASH` load silently, last match wins** (`modules/setting/codefloe_quota_ci.go:118`, `routers/api/v1/codefloe/quota_ci_reporter.go:95`) `loadQuotaCIReporters` dedupes on name only and `quotaCIReporterFor` keeps 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 with `source = 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`) `Get` then `Insert` in `AddRecord` is not atomic; two workers draining one queue both see no row, the second insert hits `UNIQUE(record_ref)` and `ReportQuotaCIUsage` answers 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_TOKEN` defaults 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 on `POST /quota/ci/usage` and 403 on `GET /api/v1/repos/user2/repo1` (fails today per item 1), and reporter token against `GET /api/v1/user` is 401. Without these, an upstream merge that reorders `Middlewares()` and moves `QuotaCIReporterAuth` after `apiAuthentication` passes 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`) `SameBillingAs` compares `OwnerID` and `RepoID`, which the reporter never sends and which are re-resolved from `report.Repo` at retry time. A client that timed out after the server committed, then re-sends after the repo was transferred, gets `ErrReportMismatch` and 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.** `seen` map and the duplicate-name branch are unreachable (`modules/setting/codefloe_quota_ci.go:106`): `configProviderLoadOptions()` does not set `AllowNonUniqueSections`, so go-ini merges repeated sections and `ChildSections()` never yields a name twice. Replace it with the duplicate-hash check from item 2. **8.** `bearerToken` duplicates `tokenFromAuthorizationBearer` in `services/auth/method/util.go:34` (`routers/api/v1/codefloe/quota_ci_reporter.go:107`). Export the existing helper and call it. **9.** `validName` and `maxNameLength = 40` are a character-for-character copy of `isValidQuotaCIReporterName` (`services/codefloe/quota_ci/ingest.go:159`). Both guard the same two columns; one exported helper in `modules/util` or `modules/structs` (which `setting` can import) serves setting, model and service, and can also own `SourceActions`/`ClassDefault` that `quotaCISourceActions` re-literals. **10.** The `IsErrRepoNotExist` re-wrap is redundant (`services/codefloe/quota_ci/ingest.go:134`): `ErrRepoNotExist.Unwrap()` already returns `util.ErrNotExist`, so the handler maps it to 404 without the branch. **11.** `binding:"Required"` on `time.Time` is inert (`modules/structs/codefloe_quota_ci.go:99`): go-chi/binding routes struct fields into `validateStruct` and skips their own rules. Only the `IsZero` check in `recordFrom` catches 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 a `Sudo` header 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.
pat-s force-pushed feat/quota-ci-external-ingest from b1a4107879
All checks were successful
testing / frontend-checks (pull_request) Successful in 1m45s
testing / backend-checks (pull_request) Successful in 6m14s
testing / test-unit (pull_request) Successful in 10m10s
testing / test-remote-cacher (redis) (pull_request) Successful in 3m38s
testing / test-remote-cacher (garnet) (pull_request) Successful in 3m38s
testing / test-remote-cacher (valkey) (pull_request) Successful in 3m47s
testing / test-e2e (pull_request) Successful in 26m39s
testing / test-mysql (pull_request) Successful in 29m24s
testing / test-sqlite (pull_request) Successful in 44m44s
testing / test-pgsql (pull_request) Successful in 47m47s
to bc3f833b18
All checks were successful
testing / frontend-checks (pull_request) Successful in 56s
testing / backend-checks (pull_request) Successful in 4m59s
testing / test-unit (pull_request) Successful in 5m27s
testing / test-remote-cacher (garnet) (pull_request) Successful in 2m48s
testing / test-remote-cacher (valkey) (pull_request) Successful in 2m48s
testing / test-remote-cacher (redis) (pull_request) Successful in 2m48s
testing / test-e2e (pull_request) Successful in 23m1s
testing / test-mysql (pull_request) Successful in 26m8s
testing / test-sqlite (pull_request) Successful in 47m23s
issue-labels / backporting (pull_request_target) Has been skipped
milestone / set (pull_request_target) Has been skipped
testing / test-pgsql (pull_request) Successful in 48m28s
2026-08-29 12:41:42 +00:00
Compare
Author
Owner

Reworked at bc3f833b18. Item 1 is fixed by the separate mount you suggested, which subsumes 4 and 12 and removes the shared -> v1/codefloe import inversion. routers/api/shared/middleware.go and routers/api/v1/api.go are back to untouched; the only upstream file the PR still edits is routers/init.go, +7 lines.

1. Sign-in bypass — fixed

/api/v1/quota/ci is now mounted in routers/init.go next to /api/v1, with a stack of securityHeaders() + context.APIContexter() + reqQuotaCIReporter() and nothing else. chi routes the more specific static prefix, so /api/v1/* keeps everything else. QuotaCIReporterAuth and IsQuotaCIReporter are 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 = true a reporter token against /api/v1/repos/user2/repo1, /api/v1/repos/search and /api/v1/users/user2 gets 401, because the shared stack reads it as the malformed access token it is rather than skipping anything. Covered by TestAPIQuotaCIUsageReportRequireSignInView.

2. Shared TOKEN_HASH — fixed

loadQuotaCIReporters now 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

AddRecord splits into insertRecord plus 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 of Middlewares() — can no longer happen, since the reporter route does not go through Middlewares().

6. Retry after transfer — fixed, and I took your first suggestion

SameBillingAs is replaced by BillingDifference, which compares only class, started, stopped and seconds and returns the name of the first field that differs; the 409 is now ... already booked for different work: seconds. OwnerID/RepoID are 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 in TestQuotaCIBillingDifference.

7. Unreachable seen map — removed

Confirmed: configProviderLoadOptions() does not set AllowNonUniqueSections, 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 tokenFromAuthorizationBearer means renaming it and every call site across access_token.go, action_task_token.go, authorized_integration.go and basic.go — a wide diff in upstream files, which this fork pays for at every merge. Instead there is a three-line fork-owned services/auth/method/codefloe_token.go exporting 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 in recordFrom, with maxQuotaCINameLength beside it. I put it in modules/setting rather than modules/util because that is where the shape is defined and both callers already depend on setting; a generically-named string predicate in util would have had to invent a meaning it does not have.

quotaCISourceActions stays a literal: setting cannot import models/codefloe/quota_ci (that package's models/db dependency imports setting). 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

GetRepositoryByOwnerAndName is now returned directly, with a comment noting that ErrRepoNotExist unwraps to util.ErrNotExist.

11. Inert binding:"Required" — tags dropped

Confirmed in binding.go:355: a struct-kinded field recurses into validateStruct and continues, so the rules never run. The tags never reached the swagger spec either (QuotaCIUsageReport has no required array before or after). The handler now decodes the body itself and every check lives in recordFrom, 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 1

The reporter router does not include sudo(), so a forwarded Sudo header 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, and TestAPIQuotaCI* / TestQuota* pass on sqlite. Full CI is running.

Reworked at `bc3f833b18`. Item 1 is fixed by the separate mount you suggested, which subsumes 4 and 12 and removes the `shared -> v1/codefloe` import inversion. `routers/api/shared/middleware.go` and `routers/api/v1/api.go` are back to untouched; the only upstream file the PR still edits is `routers/init.go`, +7 lines. ### 1. Sign-in bypass — fixed `/api/v1/quota/ci` is now mounted in `routers/init.go` next to `/api/v1`, with a stack of `securityHeaders() + context.APIContexter() + reqQuotaCIReporter()` and nothing else. chi routes the more specific static prefix, so `/api/v1/*` keeps everything else. `QuotaCIReporterAuth` and `IsQuotaCIReporter` are 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 = true` a reporter token against `/api/v1/repos/user2/repo1`, `/api/v1/repos/search` and `/api/v1/users/user2` gets **401**, because the shared stack reads it as the malformed access token it is rather than skipping anything. Covered by `TestAPIQuotaCIUsageReportRequireSignInView`. ### 2. Shared `TOKEN_HASH` — fixed `loadQuotaCIReporters` now 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 `AddRecord` splits into `insertRecord` plus 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 of `Middlewares()` — can no longer happen, since the reporter route does not go through `Middlewares()`. ### 6. Retry after transfer — fixed, and I took your first suggestion `SameBillingAs` is replaced by `BillingDifference`, which compares only `class`, `started`, `stopped` and `seconds` and returns the name of the first field that differs; the 409 is now `... already booked for different work: seconds`. `OwnerID`/`RepoID` are 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 in `TestQuotaCIBillingDifference`. ### 7. Unreachable `seen` map — removed Confirmed: `configProviderLoadOptions()` does not set `AllowNonUniqueSections`, 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 `tokenFromAuthorizationBearer` means renaming it and every call site across `access_token.go`, `action_task_token.go`, `authorized_integration.go` and `basic.go` — a wide diff in upstream files, which this fork pays for at every merge. Instead there is a three-line fork-owned `services/auth/method/codefloe_token.go` exporting 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 in `recordFrom`, with `maxQuotaCINameLength` beside it. I put it in `modules/setting` rather than `modules/util` because that is where the shape is defined and both callers already depend on setting; a generically-named string predicate in `util` would have had to invent a meaning it does not have. `quotaCISourceActions` stays a literal: `setting` cannot import `models/codefloe/quota_ci` (that package's `models/db` dependency imports `setting`). 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 `GetRepositoryByOwnerAndName` is now returned directly, with a comment noting that `ErrRepoNotExist` unwraps to `util.ErrNotExist`. ### 11. Inert `binding:"Required"` — tags dropped Confirmed in `binding.go:355`: a struct-kinded field recurses into `validateStruct` and `continue`s, so the rules never run. The tags never reached the swagger spec either (`QuotaCIUsageReport` has no `required` array before or after). The handler now decodes the body itself and every check lives in `recordFrom`, 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 1 The reporter router does not include `sudo()`, so a forwarded `Sudo` header 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, and `TestAPIQuotaCI*` / `TestQuota*` pass on sqlite. Full CI is running.
pat-s merged commit e9e785fb96 into v16.0/forgejo-codefloe 2026-08-29 13:43:27 +00:00
pat-s deleted branch feat/quota-ci-external-ingest 2026-08-29 13:43:27 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
codefloe/forgejo-codefloe!103
No description provided.