Repository navigation
Conversation
Before this change every tool resolved `owner`/`repo` straight from its
arguments and read or wrote it. The authenticated account was used only to
attribute writes, and the single `getRepository` call in the tree was a
lookup, not a check. Any account that could authenticate to `/plugin-mcp/`
could therefore read any repository on the instance, private ones included,
and `list_repositories` answered for the named owner rather than for the
caller.
`RepositoryAuthorization` puts each tool back under GitBucket's own rules,
using `hasGuestRole` / `hasDeveloperRole` from `RepositoryService` rather than
a reimplementation:
- a public repository is readable by any authenticated account;
- a private one only with at least the guest role;
- writes require the developer role;
- a repository that exists but is unreadable and one that does not exist are
reported identically, so a refusal cannot confirm a private repository's
existence;
- issue creation follows the repository's own `issuesOption`, reproducing the
table in `IssueCreationService.isIssueEditable` (ALL requires a public
repository, PUBLIC the guest role, PRIVATE the developer role, DISABLE
nobody, and an unknown value is refused rather than treated as open). The
table is reproduced rather than called because the native predicate needs a
`Context` the tool layer does not have; the role predicates underneath are
still GitBucket's;
- a denial carries its own JSON-RPC error code instead of InternalError,
because a refusal is not a server failure.
Mutation arguments now fail closed. The inherited helpers go through Jackson's
`asText("")` and `asInt(-1)`, so `{"body":{}}` became an empty string and
erased a description, and `1.9`, `4294967297`, `"1"` and `true` all resolved
to identifier 1 and sent the edit to a different object. `StrictArgs` requires
a JSON string for text and an integral in-range positive number for an
identifier, and refuses before any write. An omitted field and an explicitly
empty one stay distinct, because clearing a description is a legitimate edit
and cannot double as the error signal.
Timestamps are published as ISO 8601 instants in UTC. Every date previously
went through `java.util.Date.toString`, which renders in the JVM's default
zone with locale-dependent month and day names: unparseable for a client and
incomparable with GitBucket's own ISO 8601 output.
Commit identities keep GitBucket's stored meaning rather than their column
names: `commitIdTo` is the head, `commitIdFrom` is the merge base and not the
base branch tip, and both are values stored at the last pull request update,
which the payload states. Merged state comes from the merge comment, the same
record `ApiPullRequest` reads; the `mergedCommitIds` column is only written by
the web merge route, so a pull request merged through the REST API has it
empty.
Five operations are added: `whoami`, `get_thread_comments`,
`update_pull_request`, `update_own_comment` and `mark_ready_for_review`.
`update_pull_request` preserves the field it is not given and reads the row
back to compare. `update_own_comment` edits only the caller's own comments and
refuses an admin editing another author's text rather than silently elevating.
`mark_ready_for_review` uses GitBucket's native one-way `update_draft`
operation and reproduces its authorization exactly, including the part that is
easy to miss: read access to the base repository plus the developer role on
the pull request's head repository, which for a fork is a different
repository. Its `expected_head_sha` precondition is checked before the write
and the stored head returned after it, which is check-then-write and not
compare-and-swap; the payload says so rather than overstating it.
`serverInfo.version` is read from the shipped plugin descriptor instead of a
hardcoded literal that had already drifted from it.
Tests: 137, covering the authorization matrix, the argument contract, the
timestamp format and the tools' own `execute` with GitBucket's storage and
role predicates replaced, asserting on a recorded write log so that a refusal
which nevertheless wrote fails instead of passing silently. Compiled and run
against both GitBucket 4.46.0 and 4.48.0.
The groundwork for OAuth 2.1 bearer authentication: the documents a client reads before it authenticates, and the two primitives everything later depends on. No request handling and no persistence yet, so all of it is exercised without a server. GitBucket is not an OAuth authorization server. It ships personal access tokens and session authenticators, but no authorization endpoint, token endpoint, client registry or key set; its OAuth support is as a client, for signing users in from an external provider. docs/authentication.md records that finding, the two ways out of it, and why this plugin becomes the authorization server rather than requiring a second service that would then need to map its own subjects onto GitBucket accounts. `OAuthConfig` derives every published identifier — issuer, endpoints, and the resource a token is bound to — from one externally configured base URL, and from nothing else. Not from `Host`, not from `X-Forwarded-Host`: those are set by whoever is talking to the server, or to the proxy in front of it, and a resource identifier that follows a request header is not an audience binding. A deployment that has not configured it does not serve OAuth, and the refusal names the property to set rather than failing silently. A context path is carried through, so a GitBucket under /gitbucket does not advertise endpoints at the server root. The metadata describes only what exists. `code_challenge_methods_supported` is S256 alone — the absence of `plain` is the point, since a client that can be talked into the plain method has no protection at all. Only `authorization_code` and `refresh_token` are advertised. No `registration_endpoint`, because dynamic registration is not implemented; the client ID is an HTTPS metadata URL instead. No OIDC scopes and no userinfo endpoint, because neither is implemented, and advertising a capability that is absent produces a client that fails later and further from the cause. The `WWW-Authenticate` reason is a closed set of server-authored values rather than a string. The first version sanitised caller text, and its own test caught the flaw: stripping quotes and newlines stops header and auth-param injection but still copies an attacker's words into a response header, a proxy log, and whatever parses either. Removing the argument removes the question. The token refusal is also deliberately uninformative — unknown, expired, revoked and wrong-audience give one answer, because the differences only help someone probing with tokens they should not hold. Scopes are `mcp:read` and `mcp:write`, with write implying read. A scope per tool looks precise and is unusable: twenty consent lines nobody reads and nobody refuses. Unknown requested scopes are narrowed away rather than rejected, and the granted set is returned to the client so the narrowing is visible. 31 tests: configuration validation including context paths and the http refusal, both discovery documents, the challenge in every refusal mode, PKCE against the RFC 7636 appendix B vector, and the scope lattice. Total 171, passing against GitBucket 4.46.0 and 4.48.0.
The previous commit hand-rolled PKCE and the authorization server metadata. Both are now the library's, and the boundary between the two is written down rather than left to be inferred from the imports. GitBucket already carries `com.nimbusds:oauth2-oidc-sdk` on its runtime classpath, for its own OpenID Connect sign-in: 11.33 in 4.46.0, 11.38.2 in 4.47.0 and 4.48.0. So it is a compileOnly dependency, pinned to 11.33 — the oldest supported release's version, so only API present across the whole tested range is used — and nothing is bundled. No duplicate classes in the shadow JAR, no version skew with the host, no growth in the artifact. Apache 2.0, the same licence as this project. The SDK now supplies the S256 computation and the verifier syntax rules (`CodeVerifier`, `CodeChallenge`) and the RFC 8414 document's field names and JSON shape (`AuthorizationServerMetadata`). This repository supplies the policy — S256 and nothing else, and the claim that each advertised value is true — plus everything the SDK does not model: the RFC 9728 protected resource document, which has no type in the shipped version, and the `WWW-Authenticate` challenge. `docs/authentication.md` carries the full table, and no part of the right-hand column is described anywhere as library-provided. `Secrets` collects credential generation and storage in one place: `SecureRandom` for 256 bits of entropy, SHA-256 for what goes in the database, and a constant-time comparison. SHA-256 rather than a password hash because these are random 256-bit values with no dictionary to slow down, and a per-request adaptive hash on the token path is a denial-of-service surface. Two controls establish the delegation rather than asserting it: the adapter's challenge is compared against the SDK's own computation for the same verifier, and the metadata document is parsed back with the SDK's parser, so it is well-formed RFC 8414 metadata rather than JSON with the right key names. Compatibility is now measured at three points instead of two. Compiled and the unit suite executed against the runtime classpaths of GitBucket 4.46.0, 4.47.0 and 4.48.0, each with the oauth2-oidc-sdk version that release ships. 174 tests, passing on all three. Those three are what has been run; versions between or beyond them are untested rather than known-good, and the document says so. The external authorization server option is also restated correctly. It can be done safely — an explicit administrator-established binding on (issuer, subject), not an email match — and it is rejected on operational grounds instead: a second service to run and keep available, and a binding table to populate by hand before anyone can connect, for a plugin whose premise is that no separate service is required.
Three objects with three lifetimes, so three tables: a grant is the consent and outlives both credentials, a code lives for a minute and is consumed once, an access token lives for an hour and there may be several per grant. Plus a fourth for refresh tokens, for a reason the tests found rather than the design anticipated. The schema is a Liquibase changelog, so the same definition produces correct types on H2 and PostgreSQL, which are the two backends GitBucket deployments use. Storage is plain JDBC rather than Slick: every security-relevant operation here is a conditional write whose row count is the answer, and that guarantee depends on it being one statement. Written as SQL it is visible; generated, it would be something to re-derive from the query builder each time the question came up. Single use and rotation are atomic. Redeeming a code is an UPDATE matching CONSUMED = false, so two simultaneous exchanges produce exactly one token and one refusal, with no window in which both callers see an unused code. Rotation is the same shape. Both are tested with two real connections and a thread pool, because a sequential test cannot tell an atomic conditional update from a check-then-write. Refresh tokens are a chain, not a column. The first version kept the current refresh hash on the grant row and could not tell a replayed old token from a string that was never issued — it answered "unknown" to the one case that should end the session. The concurrency test is what found it: the losing thread got NotFound where it should have got a revocation. Superseded rows are now kept and marked, so every token a grant ever had stays recognisable, and a replay three rotations deep still revokes. Revocation has one primitive and one guarantee. Revoking consent, revoking either credential and detecting a replayed code or refresh token all end at revokeGrant, because they all mean the same thing. Access tokens are not deleted; they are checked against their grant on every request, so a revoked grant stops them at the next authorization check with no second write to race with. The guarantee is stated at that check: after revocation no later check passes. It says nothing about an operation already past its check and executing, which finishes. Expiry is enforced by comparing against the clock on every read, so the purge is hygiene rather than a security control: if it never runs the tables grow and the system stays correct. There is a test for exactly that. A code is not a bearer credential. Redemption verifies the client, the exact redirect URI, the resource and possession of the PKCE verifier, each with its own refusal. Credentials are stored as SHA-256 and never in the clear, which a test checks by dumping every table and searching for the issued values. 30 cases against a real H2 database created by applying the changelog itself, so the migration is exercised by every one of them and its idempotence is checked directly. 204 tests total, passing against GitBucket 4.46.0, 4.47.0 and 4.48.0.
Completes the flow: GitBucket session, consent, code, tokens, Bearer authentication, tool execution, revocation. Authorization runs on GitBucket's own session, so the plugin never sees a password and the account that consents is whoever GitBucket says is signed in. The pending request is held in the HTTP session rather than in hidden form fields: a hidden code_challenge is a value the browser could be made to change between the consent screen and the decision, and the point of PKCE is that the challenge is fixed when authorization starts. The form carries an opaque key and a CSRF token, and the pending entry is removed on any decision so a resubmitted form cannot mint a second code. Errors before a validated redirect_uri are shown, not redirected. Sending a protocol error to an unvalidated URI is how an authorization server becomes an open redirector. After the client's metadata has been fetched and the exact redirect matched, errors go back to the client as RFC 6749 requires, each carrying iss so a response cannot be taken from one server and replayed to a client expecting another. Bearer authentication never falls back. One header, one scheme, one answer: a token that does not resolve is an error, not a reason to look at the browser session — which would let a stale or stolen token act as whoever happens to be signed in — nor at Basic, which would let a client downgrade out of its own scope restrictions. The account is resolved at the point of use rather than trusted from the grant row, so an account removed or disabled since consent stops working immediately without waiting for revocation. Basic authentication is unchanged and holds every scope, because those credentials are the account rather than a delegation of part of it. Scope is an abstract member on ToolDef, so a new mutating tool that forgets to declare does not compile instead of inheriting the weaker requirement. That is not a claim: adding the member broke an inherited test that built a ToolDef without one. One value feeds both the advertised policy and the dispatcher's check, so the two cannot drift. Insufficient scope answers 403 with an insufficient_scope challenge, distinct from the 401 for a bad credential: a client told to authenticate again for a scope problem will loop. The CIMD fetcher is fenced. HTTPS only; every resolved address checked against loopback, link-local, private, carrier-grade and multicast ranges; redirects refused outright rather than followed, since an allowed host bouncing to a forbidden one is the usual bypass; connect, read and byte limits. The address of the established connection is re-checked after connecting. The resolver is injectable, so the policy is tested rather than the sandbox's DNS. Two defects found by the tests rather than by review: Rotation classified a replay by asking two questions — which grant, then was it rotated — and a concurrent winner could commit between them, so the loser reported an expiry where a replay had happened. One read now answers both. The concurrency control then showed what the race actually produces: the loser detects reuse and revokes the family, and the winner finds its own grant revoked a moment later, so neither caller gets a usable credential. That is the documented policy applied consistently rather than a bug, so the test now asserts it and docs/authentication.md says it: a client must serialise its refreshes. The storage invariant is asserted separately — the chain never forks, exactly one row ends up rotated. A real migration is registered, not a cosmetic version. Schema 1.0 carries the Liquibase changelog for the four tables; the plugin version is separate and unchanged. anonymousAccessiblePaths covers discovery, token and revocation, and deliberately not authorize, which must know who is signed in. 229 tests, stable across three consecutive runs on GitBucket 4.46.0, 4.47.0 and 4.48.0.
The CIMD fetcher refuses every address a server-side fetch should not reach, loopback included. That is correct for a public deployment and makes one legitimate case impossible: a developer running an MCP client on the same machine as GitBucket cannot complete an authorization at all, because the client's metadata document is on 127.0.0.1. `gitbucket.mcp.oauth.allowLoopbackClients` opens loopback and nothing else. Private, link-local, carrier-grade and multicast ranges stay forbidden with it on, which is asserted rather than described. It is off by default, so a deployment that never sets it behaves exactly as before. The alternative was a test-only branch compiled into the production path, which is worse: the fetcher the tests exercise would not be the fetcher that runs, and the escape would exist with no name an operator could find. Co-Authored-By: Claude Opus 5 <[email protected]>
The overlapping-connection test proves two callers cannot both get a usable credential, but it cannot say which of the two orderings produced that, and it conflates three separate properties. Two deterministic schedules now exercise the orderings explicitly, alongside the genuine race rather than in place of it. Schedule A is a replay after the first exchange has completed: the committed family revocation is asserted, and so is the fact that the access token the completed exchange handed out is refused at a fresh authorization check. A response that has already been sent is not undone, and the guarantee is stated where it holds. Schedule B is revocation landing between a completed exchange and the next use of its credential, which is the same guarantee approached from the other side. Three things are kept apart deliberately. The database transition — one refresh credential cannot produce two independently valid successors or fork the chain — is asserted on stored state. Replay handling is asserted on a correctly bound second presentation. The HTTP result is neither of those: it is whatever the caller was told at the time, and a successful response followed by revocation is consistent rather than contradictory. Nothing here adds a grace window or softens replay handling. The consequence for clients is an interoperability requirement of the policy and is written down as one: a client must serialise its refreshes. That is a statement about the client's own behaviour, not a claim that the server can tell the legitimate caller from a replay — it cannot, which is exactly why reuse ends the family. Co-Authored-By: Claude Opus 5 <[email protected]>
The schema was declared, committed and covered by thirty tests, and on a running GitBucket it never ran. Two independent causes, each sufficient on its own, and both silent: the plugin loaded, every route answered, and the missing table first appeared as a 500 on the first authorization. The changelog was a Liquibase document. GitBucket runs plugin migrations through Solidbase, which wraps the file in its own <databaseChangeLog> and supplies the change set's id and author, so the root element has to be a bare <changeSet>. A file carrying its own root parses as a nested changelog, the migration is skipped, and Solidbase records the previous version. The tests did not catch it because they applied the changelog through Liquibase directly, which is a different code path and accepts the Liquibase form. They now build their schema the way GitBucket does — Solidbase, over the plugin's own declared versions — and assert the recorded version afterwards, which is the value GitBucket itself checks at startup. The versions were also declared on the wrong class. GitBucket loads the class literally named `Plugin` from the root package; this repository has carried both that class and `com.newsrx.mcpplugin.MCPPlugin` since before this branch, and the two had drifted. `Plugin` now extends `MCPPlugin`, so there is one declaration and they cannot diverge again, and a new suite tests the entry point by loading it by name: its plugin id, that its last declared version carries a migration, and that the anonymous paths include discovery, token and revocation but not authorize. Co-Authored-By: Claude Opus 5 <[email protected]>
Presenting a valid refresh token with the wrong client id rotated it and revoked the grant. The reasoning was that an attacker holding a valid refresh token is the dangerous reading — but it has the consequence backwards. The client id is not a secret and not a credential: anyone who learns a refresh token can send it with any client id they like, and the server would then end the session the legitimate client is still using. The check meant to detect a stolen credential handed an unauthenticated caller a way to destroy a working one. The bindings are now checked before anything is written. A presentation that fails one is refused and changes nothing: the token still rotates once afterwards for the client it belongs to, and the grant stays alive. Only a correctly bound presentation reaches the conditional UPDATE, which remains the single atomic claim on the rotation, so two lawful callers still resolve to exactly one winner. Replay handling is unchanged. A correctly bound token presented twice still revokes the family, which is the case the policy exists for; the read that classifies the failure still happens after the failed claim, never before, so a concurrent winner cannot make a replay look like an expiry. The test asserting the old behaviour is replaced rather than relaxed: the lawful token must still work after the wrongly-bound attempt, and a binding failure against an already rotated token must leave the successor the legitimate client holds untouched. Co-Authored-By: Claude Opus 5 <[email protected]>
The README claimed a 4.42–4.46 range nobody had run and a tool count that was five short; the authentication document described the refresh policy in terms that ran together three different guarantees. Both now say what is true. Compatibility is the three versions actually exercised, with the `oauth2-oidc-sdk` each one ships, and an explicit statement that anything outside the table is untested rather than broken. The tool tables list all nineteen tools with the scope each requires, which is also the policy the dispatcher enforces, so a reader can see what a read-only grant can do. The refresh section separates the database transition, replay handling and the HTTP result, and states the client-side serialisation requirement as an interoperability consequence of the policy rather than as something the server can arbitrate — it cannot tell the legitimate caller from a replay, which is why reuse ends the family. Binding failures are documented as what they are: refused, and inert. A storage section covers the migration, including the two mistakes that produced a schema which never appeared: Solidbase's bare `<changeSet>` root, and the fact that GitBucket reads the root-package `Plugin` class and nothing else. What has not been tested is given the same prominence as what has. Driving the protocol over raw HTTP is not evidence that any particular commercial client will connect, and portable change elements are not an executed PostgreSQL upgrade. Co-Authored-By: Claude Opus 5 <[email protected]>
Two harnesses that run against a disposable GitBucket with the plugin installed, because the offline suites replace GitBucket's storage and role predicates and therefore cannot establish GitBucket's own role computation, its SQL, or the HTTP transport. `integration.py` exercises every tool across each repository visibility and each collaborator role, and compares the plugin's answer with GitBucket's own REST API, web routes and Git rather than with an expectation written down beside it. `oauth_controls.py` drives the OAuth flow through the production endpoints and the real tool dispatcher: discovery read anonymously, consent approved, denied and CSRF-rejected, code exchange with each binding failure and a replay, refresh rotation with its binding failures and replay, Bearer credentials that must not fall back to Basic or to a browser session, a read-only consent refusing a mutating tool to a GitBucket administrator, adequate scope still refused by the repository's own permissions and issue settings, and a removed account's outstanding token going dead. Effects are observed independently of what the endpoint replied. A refusal that must change nothing is followed by the lawful operation, which has to succeed; a replay that must revoke is followed by a fresh authorization check, which has to fail. Issue counts come from GitBucket's REST API before and after, so a tool that answered well and wrote anyway is caught. Neither harness may be pointed at an instance that holds anything real. Both refuse to start unless the instance is blank, and both create accounts and repositories and deliberately attempt refused writes. Co-Authored-By: Claude Opus 5 <[email protected]>
A mutation that made `AuthenticatedCaller.permits` answer `true` for every request left the whole unit suite green. Scope enforcement was covered only by the live gate, so the one decision every tool call passes through had no offline control at all. Seven cases make that decision observable: a read grant refusing a write, a write grant satisfying a read because write implies read, an empty grant permitting nothing, an unknown scope string not becoming a scope, a Basic caller holding every scope and carrying no grant, an OAuth caller carrying its grant id so a revoked grant can be found, and the registry checked so that a mutating tool cannot quietly declare the read scope. The abstract `requiredScope` member already makes a new tool fail to compile without answering the question. What it cannot do is stop the wrong answer, which is why the last case names the mutating tools explicitly. `Account` is built without `accountId`: 4.46.0 has no such field and 4.48.0 gives it a default, so naming it would pin the suite to one release. Co-Authored-By: Claude Opus 5 <[email protected]>
The gate asserted that `initialize` reports `0.1.2-SNAPSHOT`. That literal is one fork's version number, so on any other lineage the check fails for a reason that has nothing to do with the plugin — and, worse, a literal is exactly the defect the descriptor lookup exists to prevent. Production reads the version from `gitbucket-plugin.properties`; a test comparing it with a constant written by hand cannot tell that apart from a hardcoded answer. `MCP_PLUGIN_JAR` now names the exact JAR installed on the instance, and the expected version is read out of that artifact's packaged descriptor. Both `initialize` and `whoami` are compared against it, so the two paths that report a version are shown to read the same source. It is required, not optional. An unset or unreadable path is exit 2, like every other precondition here: a check that quietly skips is the defect this harness has already been corrected for twice. Co-Authored-By: Claude Opus 5 <[email protected]>
The Liquibase tests establish what the changelog does to a database. They say nothing about whether GitBucket ever runs it: what executes is what the loaded `Plugin` class declares and what Solidbase finds packaged in the JAR, so a migration can be written, committed, tested and still never run. This gate starts real GitBucket processes and asks the operator's questions. The previous plugin runs and serves no authorization-server metadata; the candidate replaces it through the ordinary plugin mechanism; the migration executes; a repository and issue created under the previous plugin are still there; the Basic connection still works and is still unscoped; a grant issued after the upgrade survives a restart; and a revocation performed before a restart is still in force after it. That last one is what distinguishes persistence from a cache — a revocation held in memory would come back to life, and the credential would start working again. `--db-url` runs the whole sequence against PostgreSQL instead of the bundled H2, which is the only way that path is tested rather than generated. Two pieces of hygiene it needs in order to mean anything: it refuses to start when something is already serving the port, because a leftover server answers health checks and would be mistaken for the artifact under test; and it stops every process it started, including when it aborts, so a failed run cannot poison the next one. The processes run with a non-UTC default time zone deliberately. A UTC host is the configuration that once hid a timestamp defect here. Co-Authored-By: Claude Opus 5 <[email protected]>
The authentication document said the storage tests ran on H2 and that PostgreSQL was expected to work but untested. It has now been run: the upgrade gate drove a blank PostgreSQL 16 database through the pre-OAuth plugin to this one, and the four tables and the recorded module version were read back from the database afterwards. That paragraph is replaced rather than softened. Also recorded: the five single-line mutations of production source, each of which turns the suite red on the controls written for that guard, and the fact that the first of them originally left the suite green — which is how the scope gate turned out to have no offline control. What remains untested is now one thing rather than two: connecting a particular commercial MCP client. Raw HTTP passing says nothing about whether a given connector accepts this server. Co-Authored-By: Claude Opus 5 <[email protected]>
The SSRF fence checked an address and then handed a host *name* to
HttpURLConnection, which resolved it again on its own. The two resolutions
are independent and only the second decides where the request goes, so a name
answering with a public address for the check and a loopback address for the
connection was fetched from loopback with the loopback escape switched off.
The second check that was supposed to catch this could not: it read
`conn.getURL.getHost`, which is the URL's host name rather than the peer, and
it ran after `getResponseCode` — after the request had been sent, which for a
server-side request forgery is the entire injury.
Reproduced against the real transport before changing anything: with the
policy resolver answering 203.0.113.10 and the server on loopback, the fetch
returned Right(OAuthClient(...)) and the loopback listener recorded one HTTP
request. Afterwards, the same scenario returns Unreachable and the listener
records none.
The address is now chosen once, by the code that validated it, and the socket
is connected to exactly that address. Neither HttpURLConnection nor
java.net.http.HttpClient can be told which address to use — both resolve the
URL host themselves, and HttpURLConnection's SSLSocketFactory only looks like
a hook, because the JDK asks it for an *unconnected* socket and then connects
that socket by name. So the request is made over a socket opened here.
Certificate verification is not hand-written. The socket is layered with the
original host name and setEndpointIdentificationAlgorithm("HTTPS"), so the JDK
performs its usual name check against the name, not against the pinned
address. Pinning decides where the bytes go and gives up nothing about who
must be at the other end. SNI carries the name too. No proxy is consulted: a
proxied request goes wherever the proxy decides, which would make destination
control an illusion.
Two address ranges were also reading as public. fc00::/7, IPv6 unique local,
is not covered by isSiteLocalAddress, which only knows the deprecated
fec0::/10 — so fd00::1 was a permitted target. An IPv4 address wrapped in IPv6
notation was not unwrapped either, so ::ffff:10.0.0.1 passed.
PinnedFetchSpec drives the production fetch over real sockets, and its witness
is what the listeners saw rather than what the fetch returned. Its TLS
material is a throwaway self-signed key pair trusted only by that suite.
Co-Authored-By: Claude Opus 5 <[email protected]>
Two places gave revocation authority to presentations that had not earned it. Authorization codes checked `consumed` before the client, redirect, resource and PKCE bindings. Reproduced on all four: after a lawful exchange, a replay carrying a wrong client id, a wrong redirect, a wrong resource or a wrong verifier returned AlreadyUsed, revoked the grant, and turned the legitimate caller's access token into Revoked. Possession of a spent code is not evidence, and an unauthenticated caller must not be able to end a session with one. The sharpest case is the verifier: whoever captured the code but not the PKCE secret could still destroy what it bought. The bindings are now checked first, and each refusal leaves the grant alive. A correctly bound replay still revokes, so the policy is intact rather than merely harder to reach. The opposite defect sat two lines further down. A conditional UPDATE that matched no row returned AlreadyUsed without revoking, so the loser of a genuine race bypassed reuse detection entirely: reproduced with two connections, one redeemed, the other got AlreadyUsed, and the grant stayed live. A lost claim is now classified by re-reading the row, and a correctly bound loser gets the same documented policy as any other replay. Re-reading rather than assuming keeps a claim that failed for some other reason from being reported as a replay. Expiry is separated from replay in both paths. An expired code is refused without revoking, because being slow is not being stolen. The same confusion existed for refresh tokens, and was worse. A superseded token whose own expiry had passed was classified as a replay and revoked the family — so an old credential, useless to whoever held it, could still destroy the successor the legitimate client was using. Rotation failure now consults expiry first: dead of old age is refused, spent-but-alive still revokes. Controls sit immediately before, exactly at and after the expiry instant, and one checks that purging does not delete the unexpired superseded rows replay detection depends on. Co-Authored-By: Claude Opus 5 <[email protected]>
The grant records the resource it was minted for, and nothing compared that with the resource this server actually is. Storing it made it a fact in a table, not a binding. Reproduced over HTTP before changing anything, with itest/resource_gate.py: one server, started as localhost, issues a grant; the same server restarts as 127.0.0.1, a different canonical resource; the unexpired token is presented again. It was accepted, whoami answered, and create_issue *stored an issue* — the stored count went from 1 to 2 under an audience the grant was never issued for. The refresh token rotated under the other resource as well. A token outlives the request that created it, so this is not hypothetical: a reconfigured deployment, or a neighbouring one sharing a database, hands over a perfectly valid unexpired credential for somewhere else. The bearer path now refuses a grant whose resource is not this server's, before any tool is chosen, and reports it exactly like any other unusable token so the refusal reveals nothing. Rotation takes the audience as a binding alongside the client id — both the resource this server is, and the resource the client asked for when it asked — checked before anything is written, so a mismatch consumes nothing and revokes nothing. The gate also restores the original configuration afterwards and checks that the refused credentials still work, so a refusal is a refusal and not a quiet destruction. Co-Authored-By: Claude Opus 5 <[email protected]>
The authentication document already stated the right policy in three of the places the implementation got wrong — a binding failure is not a replay, expiry does not revoke, the audience binds the token. Saying so was not enough, so the wording now also says where the line falls: on spent codes as well as unused ones, on superseded refresh tokens that have since expired, and at the point a credential is used rather than where it was minted. The CIMD section no longer claims the destination is re-checked after connecting. It describes what the fetcher now does and why a post-connect check could never have worked. oauth_controls.py gains the matching HTTP controls: each of the four wrong bindings against a spent code, and then the proof that none of them revoked anything — the access token issued by the lawful exchange still works. The correctly bound replay follows, and its revocation is still committed. Co-Authored-By: Claude Opus 5 <[email protected]>
The response parser was written here, and it was wrong in the two ways a hand-written one is prone to. `copy` returned normally when the peer closed with declared body bytes still outstanding, so a body short of its Content-Length read as complete. `parseChunkSize` turned every parse failure into 0L, which to its caller is the terminating zero chunk, so `NOTHEX` ended the body successfully. Both turned a truncated prefix into a valid client registration. A JSON document that parses is not evidence that the HTTP message carrying it finished (RFC 9112 6.3, 7.1, 8). Reproduced against the delivered artifact before changing anything, with the reviewer's wire fixture driving the real fetch: Content-Length set to the body plus 100 with the peer closing after the JSON, and a complete JSON chunk followed by NOTHEX — both returned Right(OAuthClient(...)). Afterwards they return ConnectionClosedException and MalformedChunkCodingException, and the two lawful twins are still accepted. Message parsing is now Apache HttpClient's rather than expanded by hand. It is on GitBucket's runtime classpath in all three supported releases (httpclient 4.5.14, httpcore 4.4.16), so it is compileOnly and nothing is bundled -- the same arrangement as the Nimbus SDK. Destination pinning survives the change and is the reason this client was chosen: its DnsResolver is consulted for the route, so answering with the one address that passed the check is what decides where the socket goes. Certificate verification is still the JVM's, against the host name, through the default HTTPS socket factory and the default hostname verifier. Redirects are disabled, no proxy is consulted, and the timeouts are unchanged. The size cap now refuses rather than truncates. A cap that silently returns a prefix is the same defect one step removed. Six controls drive the production fetch against a fixture that writes an exact byte sequence. Each malformed case has its lawful twin, and the twins earned their place immediately: the first version of these controls passed while a plain-http client id was being refused before any request was made, so nothing reached the wire. The twins failed, which is how that was caught. The malformed cases now assert a transport-level refusal specifically, so "rejected by validation" can no longer masquerade as "rejected by framing". Co-Authored-By: Claude Opus 5 <[email protected]>
The resource gate asserted `st >= 400` at its two refresh sites, so an HTTP 500 counted as a denial. Reproduced with the reviewer's fault injection, which replaces exactly those two responses with 500 and leaves every other call real: both injected failures printed, both counted as PASS, the gate reported 15 passed 0 failed and exited 0. Two of its negative checks had observed nothing at all. RFC 6749 5.2 gives the token endpoint one shape for a rejected grant: 400 with a documented `error` code, or 401 when the client itself was not accepted. Anything else is the server failing to answer, and a failure to answer is not a refusal. `refused_grant` requires the status, an object, and one of the documented codes, and aborts the gate otherwise -- a gate that cannot read authorization must not report it. Thirteen controls drive that helper at the same call sites: 500, 502, 503, a 404 from a missing route, a 200, a refusal status carrying a string or nothing, and a documented status carrying an undocumented or absent error code. Four lawful twins keep it from being merely strict -- invalid_grant, invalid_target, invalid_client, and a documented error alongside extra fields. After the fix the injected run aborts, naming the status and body it was given and saying it cannot read authorization from them. The ordinary run is still 15 passed, 0 failed, which also establishes that the server really does answer the documented codes at both sites. Co-Authored-By: Claude Opus 5 <[email protected]>
Two bounds were lost when message parsing moved to Apache HttpClient, and neither loss shows up against a response the server has already finished sending -- which is why the earlier controls did not catch them. Body overflow drained the tail. readBounded threw at the 64 KiB cap, but the entity stream was closed in a finally, and closing a half-read entity makes the client consume the rest of the framed body first. A peer that keeps supplying that tail within the read timeout holds the fetch open for as long as it chooses, which is the opposite of what a cap is for. Reproduced against the delivered artifact with the reviewer's fixture: the fetch did not return until the fixture released it, after 622,592 bytes had been sent, and the overflow error had been replaced by a framing exception. The request is now aborted when the body is not read to its end, so the connection is discarded with nothing drained. Afterwards the same fixture reports the fetch returning on its own, with the overflow error intact. The byte count before release is socket buffering and is not asserted. Header bounds went to unlimited. The previous reader bounded line length, total header text and header count; BasicHttpClientConnectionManager applies no message constraints by default, so a single 1 MiB header was accepted. MaxLineLength and MaxHeaderCount are now set explicitly -- 8 KiB and 100, whose product bounds the block -- through the stack's own ConnectionConfig rather than by parsing headers here again. Four controls: an overflow fixture that stays open after the cap and must not hold the fetch, an oversized header line, too many headers, and a lawful twin with an ordinary number of ordinary headers so the bounds are not refusing for the wrong reason. The overflow control asserts that the fetch finished before the fixture was released; a response already completed by the server cannot detect that regression at all. Pinning, TLS hostname and certificate verification, redirect refusal, proxy exclusion and the timeouts are unchanged, and their controls still pass. Co-Authored-By: Claude Opus 5 <[email protected]>
The helper accepted any documented refusal -- a cross product of two statuses and seven error codes -- and the two call sites inspected only the status. So an `invalid_client` or an `invalid_request` counted as proof that the resource binding had been checked, when neither says anything about the resource. Reproduced with the reviewer's substitution, which replaces only those two refresh observations with (401, invalid_client) and leaves every other call real: the gate reported 15 passed, 0 failed and exited 0. Both scenarios are entitled to exactly (400, invalid_grant), because OAuthEndpoints.refreshFailure answers that for every rotation failure. That uniformity is a production property and is deliberate -- a refusal must not disclose which binding was wrong -- so it stays as it is. What follows for this gate is that the one response establishing the resource binding was consulted is that exact pair, and nothing else. `refused_grant` now takes the pair the scenario expects, defaulting to it, and the call sites compare the pair rather than the status. Nine controls reject the lawful-but-wrong refusals -- invalid_client at both statuses, invalid_request, invalid_target, unauthorized_client, invalid_scope, unsupported_grant_type -- alongside the existing 5xx, missing-route and malformed-body cases. Twins keep it honest: the entitled pair still passes, and a scenario may name a different expectation explicitly, which is how the two code-path cases now read. Co-Authored-By: Claude Opus 5 <[email protected]>
`list_repositories` reported issue_count 0 and pr_count 0 for every repository, while `get_repository` reported real values for the same one. The cause is not serialization. GitBucket's `getUserRepositories` builds each RepositoryInfo through `createRepositoryInfo`, which uses the constructor its own source documents as "Creates instance without issue, pull request, and milestone count" -- those fields are literally 0 because nothing counted them. `getRepository` takes the other path and runs the query. So the listing was publishing placeholders as measurements, and a reader could not tell a repository with no issues from one whose issues were never counted. Reproduced on a disposable instance before changing anything: a repository with four open issues listed as issue_count 0 and detailed as issue_count 4, with GitBucket's own API agreeing with the detail. The listing now enumerates cheaply, filters by what the caller may read, and reads counts through GitBucket's own `getRepository` for those repositories only. The cost moves rather than grows: the enumeration no longer performs a Git read for every repository including ones the caller cannot see, and a detail read is performed for each one it can. No cache, no parallel statistics and no HTTP loop. The same wiring bug had a third effect nobody had reported. `without_forked` was being passed as `getUserRepositories`'s second argument, which is `withoutPhysicalInfo` -- and under that flag GitBucket returns **-1** as the fork count. So `without_forked=true` published fork_count -1 as though it were measured. Reproduced, and gone now that nothing from the enumeration is published. `without_forked` is implemented against the real relationship, the one GitBucket's own API uses for its `fork` field: a repository is a fork when it has an origin. A fork *count* says how many forks exist of a lineage and never meant that this repository is one, so `is_fork` is published separately. Counter meanings are documented in the README and repeated in every response, because "issue_count" sounds like a total and is actually open issues excluding pull requests. itest/repo_list_gate.py, 40 checks, compares the listing with GitBucket's REST API rather than with the plugin's other answers -- two answers that disagree cannot both be checked against each other. Its fixture holds a repository with open and closed issues and a pull request, one that is legitimately empty, a private one, and a real fork, under outsider, developer, admin and owner callers. The empty repository matters: a gate whose every expectation is nonzero cannot tell a correct zero from a placeholder, which was the defect. Co-Authored-By: Claude Opus 5 <[email protected]>
The listing reads twice -- once to enumerate, once per repository for the counts -- and `canRead` was applied only to the first. Between them a repository can become private, and the detail read then returns the description and counts that exist only in the private state. Publishing those under the earlier decision discloses them. Reproduced on the delivered candidate artifact with the reviewer's deterministic control, production unmodified: an outsider's listing returned is_private true, the private-only description and issue_count 17 / pr_count 9, while the same production GetRepositoryTool refused the detail for the same caller and repository. Two tools disagreeing about the same repository is the disclosure, whichever way round it is. The fresh RepositoryInfo is now authorized with the same native rule before it is serialized. A repository that stopped being readable in between is omitted and the published count is of what was published, so the two stay consistent. This claims no atomicity and cancels nothing: a decision taken before a change cannot be withdrawn after it. It refuses to attach an old decision to newly read data, which is a different thing. The early filter keeps its own job -- repositories the caller never had access to are not read in detail at all -- because it still decides what is worth enriching; it simply cannot speak for a record it has not seen. Five named controls through the production `execute`: the privacy transition publishing nothing, the detail tool refusing the same transitioned repository, stable public data still published with its counts, stable private data still published to guest, developer and administrator, and a role that was sufficient at enumeration and gone by the detail read. The last is the same shape from the other direction -- the caller's access disappears rather than the repository's visibility changing. The stubs model GitBucket's role predicates but not its ownership rule, so an owner has no role in them. The owner's access to their own private repository is covered against real GitBucket in itest/repo_list_gate.py instead of being asserted against a fixture that does not implement it. Removing only this guard compiles and fails exactly one control, the one written for it, with the lawful cases still green. Co-Authored-By: Claude Opus 5 <[email protected]>
It was called "a role that was sufficient at enumeration and is gone at the detail read", which claims more than it does. The fixture removes the guest role *between two complete `execute` invocations*; within each one the role is constant. It never places the removal between the enumeration and the detail read of a single call, so the name described a control that was not there. Renamed to say what happens, and the comment now states the boundary this control does not reach and credits the one that does: a reviewer's within-invocation control, which drops the role during the detail read itself. No production change, and the assertions are untouched. A test whose name overstates it is worse than no test, because the gap it leaves is invisible. Co-Authored-By: Claude Opus 5 <[email protected]>
Five documents had drifted from the code they describe. Each item below was read out of the source, not out of another document. **The consent screen has no scope selector.** README said "You choose read-only or read and write". The client chooses, in its authorization request; the screen lists exactly those scopes and offers one decision over the set, Authorize or Cancel. A client asking for nothing is granted the weaker scope. What is granted is the set the server recorded when the request arrived, held in the user's session -- not the value posted back with the form, which is why a resubmitted form cannot mint a second code. Documented in README and, with the mechanism, in the Scopes section of docs/authentication.md. No UI was added: the fix is to the description. **A commercial client has connected, and that claim is now bounded.** docs/authentication.md said connecting one was still not established. It is, so the operations observed are listed -- reads, issue creation, a comment added, read back, edited by appending and read back again -- together with the three things they do not establish: refresh and revocation (both connections were used inside their grants), the permission matrix (two accounts are not visibility x role x issuesOption), and anything about this tree, because the instance those clients reached runs an earlier build. Its listing still answers without `is_fork` or the `*_semantics` keys and still reports zero issues for repositories that have them, which identifies the build precisely. **CONTRIBUTING described a tree that has not existed for some time** -- a 14-tool layout, test files with per-file counts, and the pre-OAuth runner under scripts/ as the way to test. The structure now matches the real tree, the test instructions point at `./gradlew test` and the gates under itest/, and "Adding a new tool" has the step it was missing: `requiredScope` is an abstract member, so omitting it does not compile, and the entry says why that is deliberate and that the scope is a ceiling rather than a substitute for the repository guard. **Counts in prose went stale, so they are gone.** itest/README claimed 63 self-test controls against a suite that runs 85, and README claimed 240 tests against 290. Both now describe what is covered and let the run print its own total. The per-gate floors are stated instead, from each gate's own source (200, 35, 22, 15), because those are facts about the gates rather than a running tally. The self-test description also no longer calls every control negative: the lawful twins are the half that notices a guard which refuses everything. **itest/README had no section for the audience gate** and described the OAuth helpers under the repository-listing heading. Both fixed; resource_gate.py now has its commands and the reason only a restart can show that property. **DEPLOY.md was a dated development report.** It named a shared corporate address, carried default credentials as prod advice, and its claims had expired -- 14 tools, Basic auth as the only path, compatibility 4.42.0-4.46.0. It is now a generic runbook: build, install, verify which artifact is actually running via the packaged descriptor, and what to check before deploying anywhere shared. The original is retained in the private review record, where a report about one instance belongs. Nothing here changes production behaviour or adds a capability. Co-Authored-By: Claude Opus 5 <[email protected]>
`MCP_PLUGIN_JAR=$DIR/gitbucket-mcp-plugin-*.jar python3 itest/integration.py` cannot work. The shell does not expand a glob inside an assignment word, so the variable carries the asterisk literally and the gate stops at its own precondition — exit 2, *does not name a readable file* — before it reaches HTTP. Reproduced against a directory holding the real JAR, then fixed. It was in **two** documents: `itest/README.md` and `README.md`. Both now give one concrete path, and `itest/README.md` also gives the form to use when the name is not known ahead of time — resolve the glob, then require that it matched exactly one existing file. A resolve that finds two JARs has to stop; silently taking the first is how the wrong artifact gets measured. Both now also keep the copy being pointed at **outside** the directory GitBucket scans. GitBucket copies what it loads into `plugins/.installed/` and rebuilds that directory on every scan, so a path into it is not a stable thing to name. The gate's own precondition was already correct and is unchanged; what was wrong was the command the documents gave for it. Co-Authored-By: Claude Opus 5 <[email protected]>
DEPLOY.md said `serverInfo.version` was the way to confirm which artifact is running. It reports the **declared** version, and that does not identify a build: every artifact in this contribution declares `0.1.0`, including ones with different contents and different behaviour. Two of them sat side by side here — a delivered build and a deliberately mutated one — with the same `pluginVersion` and different hashes. So the file now says to compare the **hash** of the JAR placed in the plugins directory against the hash of the build that was chosen, and keeps the handshake, `serverInfo.version` and `/health` for what they are good for: smoke checks that something is up and answering. Reading the descriptor rather than a literal is still worth having, and the gate still does it — it is just not an identity. **Replacement needed stating rather than assuming.** Leave two JARs declaring one plugin id in that directory and GitBucket loads one of them, and neither a restart nor a new filename decides which. From its own scan logic: candidates are ordered by version descending; that version is parsed from the **file name**, not the descriptor; a name the pattern does not match counts as `0.0.0`, so `…-0.1.0-new.jar` sorts *below* the `…-0.1.0.jar` it was meant to supersede; and the first candidate for an id wins while the rest are skipped, logged as `Plugin <id> is duplicated. <jar> is available.` Delete the previous JAR instead of renaming around it, and read that log line as the signal that one was left behind. `plugins/.installed/` is documented for what it is: GitBucket's own copy of what it loaded, rebuilt on each scan — a witness, never a place to install to. One shell block was mis-fenced as `bash` while being a JVM flag, so it could not parse as shell. Fenced plainly now. **And one inference removed.** docs/authentication.md said both client connections were used inside the lifetime of their grants, while also saying the second connection's authentication path is not recorded. Those cannot both hold: an unclassified connection is not known to have a grant. The honest statement is the one kept — refresh, rotation, replay and revocation were not observed on either connection — with the reason separated: for the ChatGPT connection that is a fact about a grant, and for the other it is simply that nothing of the kind was seen. Co-Authored-By: Claude Opus 5 <[email protected]>
|
| GitGuardian id | GitGuardian status | Secret | Commit | Filename | |
|---|---|---|---|---|---|
| - | - | Authentication Tuple | b33a24b | itest/repo_list_gate.py | View secret |
| - | - | Base64 Basic Authentication | 13e1db2 | itest/oauth_controls.py | View secret |
🛠 Guidelines to remediate hardcoded secrets
- Understand the implications of revoking this secret by investigating where it is used in your code.
- Replace and store your secrets safely. Learn here the best practices.
- Revoke and rotate these secrets.
- If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.
To avoid such incidents in the future consider
- following these best practices for managing and storing secrets including API keys and other credentials
- install secret detection on pre-commit to catch secret before it leaves your machine and ease remediation.
🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.
|
Please approve the pending fork workflows. I investigated both GitGuardian findings: they are synthetic credentials used by the disposable integration-test harness. Please review them as test credentials. No scanner suppression or history rewrite has been applied. |
What does this PR do?
Add opt-in OAuth authorization for MCP clients while preserving current GitBucket account and repository permissions. Includes PKCE S256, client metadata discovery with a bounded/pinned fetcher, hashed credentials, persistent grants, refresh rotation/reuse detection and revocation. Bearer errors never fall back to Basic or sessions; read-only consent cannot invoke writes, including for admins.
Also adds identity/thread reads, strict mutation arguments, editing own comments, PR updates/ready-for-review, UTC timestamps, accurate repository counters/fork filtering and fresh-record authorization. README, deployment, authentication and contribution docs are updated.
Validation
29 commits based on d16d35b; head 4251948. Clean contribution history; upstream authorship/licence preserved. The release version is left to the maintainer. See docs/authentication.md and itest/README.md for contracts, controls and limitations.
Checklist