From 8d521ec93e41fcdfd5964a55e12959457eb5c1fb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 18:13:00 +0000 Subject: [PATCH 01/29] Enforce GitBucket repository permissions on every MCP tool 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. --- .../com/newsrx/mcpplugin/MCPController.scala | 11 +- .../newsrx/mcpplugin/PluginDescriptor.scala | 28 + .../com/newsrx/mcpplugin/mcp/StrictArgs.scala | 118 +++ .../com/newsrx/mcpplugin/mcp/Timestamps.scala | 37 + .../com/newsrx/mcpplugin/mcp/ToolDef.scala | 8 +- .../com/newsrx/mcpplugin/tools/Authz.scala | 136 +++ .../mcpplugin/tools/IdentityTools.scala | 50 ++ .../newsrx/mcpplugin/tools/IssueTools.scala | 92 ++- .../mcpplugin/tools/PullRequestTools.scala | 341 +++++++- .../mcpplugin/tools/RepositoryTools.scala | 13 +- .../RepositoryAuthorizationSpec.scala | 259 ++++++ .../com/newsrx/mcpplugin/StrictArgsSpec.scala | 144 ++++ .../com/newsrx/mcpplugin/TimestampsSpec.scala | 74 ++ .../newsrx/mcpplugin/ToolRegistrySpec.scala | 113 +++ .../mcpplugin/tools/ToolExecutionSpec.scala | 778 ++++++++++++++++++ 15 files changed, 2183 insertions(+), 19 deletions(-) create mode 100644 src/main/scala/com/newsrx/mcpplugin/PluginDescriptor.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/mcp/StrictArgs.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/mcp/Timestamps.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/tools/Authz.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/RepositoryAuthorizationSpec.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/StrictArgsSpec.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/TimestampsSpec.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/tools/ToolExecutionSpec.scala diff --git a/src/main/scala/com/newsrx/mcpplugin/MCPController.scala b/src/main/scala/com/newsrx/mcpplugin/MCPController.scala index 75405e5..25e48e6 100644 --- a/src/main/scala/com/newsrx/mcpplugin/MCPController.scala +++ b/src/main/scala/com/newsrx/mcpplugin/MCPController.scala @@ -2,7 +2,7 @@ package com.newsrx.mcpplugin import com.fasterxml.jackson.databind.node.ObjectNode import com.newsrx.mcpplugin.mcp.{JsonRpc, ToolRegistry} -import com.newsrx.mcpplugin.tools.SessionSupport +import com.newsrx.mcpplugin.tools.{AuthorizationError, SessionSupport} import gitbucket.core.controller.ControllerBase import gitbucket.core.model.Account import gitbucket.core.service.{AccountService, RepositoryService, SystemSettingsService} @@ -123,6 +123,11 @@ class MCPController val result = tool.execute(args, account, request, mapper) JsonRpc.successResponse(mapper, req.id, result) } catch { + // A denial is its own outcome, not an internal failure: reporting it + // as InternalError would tell a caller the server broke when in fact + // the server refused. + case e: AuthorizationError => + JsonRpc.errorResponse(mapper, req.id, JsonRpc.McpError - 2, e.getMessage) case e: NoSuchElementException => JsonRpc.errorResponse(mapper, req.id, JsonRpc.McpError - 1, e.getMessage) case e: IllegalArgumentException => @@ -157,7 +162,9 @@ class MCPController val serverInfo = mapper.createObjectNode() serverInfo.put("name", "gitbucket-mcp-plugin") - serverInfo.put("version", "0.1.0") + // Reported from the descriptor that ships in the JAR instead of a second + // hardcoded literal: the two disagreed in v0.1.1. + serverInfo.put("version", PluginDescriptor.get("pluginVersion")) root.set[ObjectNode]("capabilities", capabilities) root.set[ObjectNode]("serverInfo", serverInfo) diff --git a/src/main/scala/com/newsrx/mcpplugin/PluginDescriptor.scala b/src/main/scala/com/newsrx/mcpplugin/PluginDescriptor.scala new file mode 100644 index 0000000..96e4fc7 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/PluginDescriptor.scala @@ -0,0 +1,28 @@ +package com.newsrx.mcpplugin + +import java.util.Properties +import scala.util.Using + +/** + * The plugin descriptor as it ships inside the JAR. + * + * Read from the classpath rather than written into the code a second time, so + * this cannot drift from the descriptor GitBucket itself loads. It remains + * self-reported: it identifies what the running JAR says about itself, not + * what produced its bytes. + * + * Owned by the plugin's root package rather than by `tools`, because both the + * controller and the tool layer read it. Scoped to this package so it stays + * an internal detail of the plugin. + */ +private[mcpplugin] object PluginDescriptor { + private val props: Properties = { + val p = new Properties() + Option(getClass.getClassLoader.getResourceAsStream("gitbucket-plugin.properties")).foreach { in => + Using.resource(in)(p.load) + } + p + } + + def get(key: String): String = Option(props.getProperty(key)).getOrElse("") +} diff --git a/src/main/scala/com/newsrx/mcpplugin/mcp/StrictArgs.scala b/src/main/scala/com/newsrx/mcpplugin/mcp/StrictArgs.scala new file mode 100644 index 0000000..2b673ca --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/mcp/StrictArgs.scala @@ -0,0 +1,118 @@ +package com.newsrx.mcpplugin.mcp + +import com.fasterxml.jackson.databind.JsonNode + +/** + * Argument reading for operations that change stored data. + * + * `MCPController.handleToolCall` hands `arguments` to a tool without checking + * it against the advertised schema, so whatever a client sends is what the + * tool sees. The inherited helpers in [[ToolDef]] go through Jackson's + * `asText("")`, which answers `""` for an object, an array or a null and + * stringifies numbers and booleans. For a read that is merely sloppy. For a + * write it is destructive in two distinct ways: + * + * - `{"body": {}}` becomes an empty string, so a malformed request silently + * erases a description and the read-back then faithfully confirms the + * text the caller never asked for; + * - `{"expected_head_sha": {}}` becomes `""`, which the old `strOpt` then + * discarded as absent, turning a supplied precondition into no + * precondition at all. + * + * These helpers fail closed instead. Absent stays absent; a supplied value + * must be a JSON string, because an empty string is a legitimate edit and + * cannot therefore double as the error signal; everything else is refused + * before any write happens. + */ +object StrictArgs { + + /** + * A supplied JSON string, or `None` when the key is absent. + * + * `""` is returned as `Some("")`: clearing a body is a real edit, and the + * caller's intent to clear it must survive the trip. Any non-string value, + * JSON `null` included, is an error rather than a silent default. + */ + def textOpt(args: JsonNode, key: String): Option[String] = + Option(args.get(key)) match { + case None => None + case Some(node) if node.isTextual => Some(node.asText()) + case Some(node) => + throw new IllegalArgumentException( + s"argument '$key' must be a JSON string, received ${typeName(node)}" + ) + } + + /** A supplied, non-empty JSON string. Absent and empty are both refused. */ + def requiredText(args: JsonNode, key: String): String = + textOpt(args, key) match { + case Some(value) if value.nonEmpty => value + case Some(_) => + throw new IllegalArgumentException(s"argument '$key' must not be empty") + case None => + throw new IllegalArgumentException(s"missing required argument: $key") + } + + /** + * A supplied commit id, validated as 40 hexadecimal characters. + * + * A precondition that cannot be parsed is refused rather than dropped: the + * caller asked for a guarded write, and performing an unguarded one in its + * place would be the opposite of what was requested. Abbreviated ids are + * refused too, because a prefix comparison against a stored full id would + * quietly never match. + */ + def commitIdOpt(args: JsonNode, key: String): Option[String] = + textOpt(args, key).map { value => + if (value.length != 40 || !value.forall(isHexDigit)) { + throw new IllegalArgumentException( + s"argument '$key' must be a full 40-character hexadecimal commit id" + ) + } + value + } + + /** + * A supplied object identifier: a JSON integral number inside Int range and + * strictly positive. + * + * The inherited `ToolDef.int` goes through `asInt(-1)` and admits anything + * that comes back non-negative. Measured on Jackson 2.15.2, `1.9`, + * `4294967297`, `"1"` and `true` all arrive as 1, so a malformed target + * silently became pull request or comment number 1 and the mutation went to + * the wrong object. `isIntegralNumber` rejects the fractional and textual + * and boolean forms, `canConvertToInt` rejects the out-of-range ones, and + * GitBucket's issue, pull request and comment ids start at 1, so zero and + * negatives are outside the domain rather than merely odd. + */ + def identifier(args: JsonNode, key: String): Int = + Option(args.get(key)) match { + case None => + throw new IllegalArgumentException(s"missing required argument: $key") + case Some(node) if !node.isIntegralNumber => + throw new IllegalArgumentException( + s"argument '$key' must be a JSON integer, received ${typeName(node)}" + ) + case Some(node) if !node.canConvertToInt => + throw new IllegalArgumentException( + s"argument '$key' is outside the supported range: ${node.asText()}" + ) + case Some(node) if node.asInt() < 1 => + throw new IllegalArgumentException( + s"argument '$key' must be a positive identifier, received ${node.asInt()}" + ) + case Some(node) => node.asInt() + } + + private def isHexDigit(c: Char): Boolean = + (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') + + private def typeName(node: JsonNode): String = + if (node.isNull) "null" + else if (node.isObject) "an object" + else if (node.isArray) "an array" + else if (node.isBoolean) "a boolean" + else if (node.isFloatingPointNumber) "a fractional number" + else if (node.isNumber) "a number" + else node.getNodeType.toString.toLowerCase +} diff --git a/src/main/scala/com/newsrx/mcpplugin/mcp/Timestamps.scala b/src/main/scala/com/newsrx/mcpplugin/mcp/Timestamps.scala new file mode 100644 index 0000000..4231fa3 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/mcp/Timestamps.scala @@ -0,0 +1,37 @@ +package com.newsrx.mcpplugin.mcp + +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import java.util.Date + +/** + * Timestamps as a client can actually read them. + * + * Every date this gateway published used to go through `java.util.Date. + * toString`, which produces `"Fri Oct 23 15:38:41 EEST 2026"`. Three things + * are wrong with that for a machine-facing payload: + * + * - it is rendered in the server JVM's default time zone, so the same instant + * reads differently on two hosts and the string carries an abbreviation + * (`EEST`) that is ambiguous and not parseable back to an offset; + * - the month and day names are locale-dependent; + * - it cannot be compared with GitBucket's own REST API, which publishes ISO + * 8601 in UTC, so a consumer holding both answers cannot tell whether they + * agree. + * + * Measured, not assumed: the live gate's own `merged_at` comparison refused to + * run against a JVM in `Europe/Kiev` because it could not turn `EEST` into an + * offset. Earlier runs happened to be on a UTC host, which is exactly why this + * stayed invisible. + * + * All timestamps are therefore published as ISO 8601 instants in UTC, to the + * second, matching GitBucket's own API: `2026-10-23T12:38:41Z`. + */ +object Timestamps { + + private val iso = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") + + /** An instant in UTC, ISO 8601, second precision. */ + def iso8601(date: Date): String = + iso.format(date.toInstant.atZone(ZoneOffset.UTC)) +} diff --git a/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala b/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala index 66ce626..8c205d2 100644 --- a/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala +++ b/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala @@ -131,6 +131,9 @@ object ToolRegistry { new ClosePullRequestTool, new ReopenPullRequestTool, new GetPrDiffTool, + new GetThreadCommentsTool, + new UpdatePullRequestTool, + new MarkReadyForReviewTool, // Issue tools new ListIssuesTool, new GetIssueTool, @@ -138,9 +141,12 @@ object ToolRegistry { new CloseIssueTool, new ReopenIssueTool, new AddIssueCommentTool, + new UpdateOwnCommentTool, // Repository tools new ListRepositoriesTool, - new GetRepositoryTool + new GetRepositoryTool, + // Identity + new WhoAmITool ) } diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/Authz.scala b/src/main/scala/com/newsrx/mcpplugin/tools/Authz.scala new file mode 100644 index 0000000..73bdb86 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/tools/Authz.scala @@ -0,0 +1,136 @@ +package com.newsrx.mcpplugin.tools + +import gitbucket.core.model.Account +import gitbucket.core.service.RepositoryService +import gitbucket.core.service.RepositoryService.RepositoryInfo +// The Session type GitBucket's services declare, not `slick.jdbc.JdbcBackend.Session`. +// The latter is the Session of the `JdbcBackend` *object*; the services use the +// profile's path-dependent `backend.Session`. An object Session conforms to it +// when passed, which is why production compiled, but a method declared with the +// narrower type overrides nothing — that is what broke the stubs in the tests. +import gitbucket.core.model.Profile.profile.blockingApi.Session + +/** + * Raised when the authenticated caller may not perform the requested + * operation on the named repository. Distinct from `NoSuchElementException` + * so the controller can map it to its own JSON-RPC error code. + */ +class AuthorizationError(message: String) extends RuntimeException(message) + +/** + * Repository authorization for MCP tool execution. + * + * Authentication alone is not authorization. Before this trait existed, every + * tool resolved `owner`/`repo` straight from the request arguments and read or + * wrote it, so any account that could authenticate to the MCP endpoint could + * reach any repository on the instance, private ones included. These guards + * put each tool back under the same rules GitBucket's own controllers apply. + * + * The rules are GitBucket's, not reimplemented here: the role predicates come + * from `gitbucket.core.service.RepositoryService` (4.48.0, + * `hasGuestRole`/`hasDeveloperRole`/`hasOwnerRole`), and the read rule matches + * what GitBucket's `ReferrerAuthenticator` enforces — a public repository is + * readable by any authenticated account, a private one only by an account with + * at least the guest role. + */ +trait RepositoryAuthorization { self: RepositoryService => + + /** + * The repository, if the caller may read it. + * + * A repository that exists but is not readable and one that does not exist + * are reported the same way on purpose: answering "forbidden" for a private + * repository would confirm its existence to a caller who may not see it. + */ + protected def readableRepository(owner: String, repo: String, account: Account)(implicit + s: Session + ): RepositoryInfo = + getRepository(owner, repo) match { + case Some(info) if canRead(info, account) => info + case _ => + throw new NoSuchElementException(s"repository $owner/$repo not found or not readable") + } + + /** The repository, if the caller may write to it (developer role or above). */ + protected def writableRepository(owner: String, repo: String, account: Account)(implicit + s: Session + ): RepositoryInfo = { + val info = readableRepository(owner, repo, account) + if (!hasDeveloperRole(owner, repo, Some(account))) { + throw new AuthorizationError( + s"${account.userName} does not have write access to $owner/$repo" + ) + } + info + } + + /** True when `account` may read `info`. */ + protected def canRead(info: RepositoryInfo, account: Account)(implicit s: Session): Boolean = + !info.repository.isPrivate || + hasGuestRole(info.repository.userName, info.repository.repositoryName, Some(account)) + + /** + * Whether `account` may open an issue in `info`, under the repository's own + * issue policy. + * + * Read access is not the rule GitBucket applies here. `IssueCreationService. + * isIssueEditable` (4.48.0) branches on `options.issuesOption`, and the + * native creation route consults it before writing. Reading alone therefore + * admitted three cases the server itself refuses: a guest of a PRIVATE-issue + * repository, any reader of a DISABLE repository, and an authenticated + * outsider of a PUBLIC-issue repository. + * + * The branch table is reproduced rather than reused because the native + * predicate needs a `Context` the tool layer does not have. The role + * predicates underneath are still GitBucket's. + */ + protected def canCreateIssue(info: RepositoryInfo, account: Account)(implicit s: Session): Boolean = { + val owner = info.repository.userName + val name = info.repository.repositoryName + info.repository.options.issuesOption match { + // ALL: an authenticated caller, but only where the repository is public. + case "ALL" => !info.repository.isPrivate + case "PUBLIC" => hasGuestRole(owner, name, Some(account)) + case "PRIVATE" => hasDeveloperRole(owner, name, Some(account)) + case "DISABLE" => false + // An unknown setting is refused rather than guessed: a future or + // corrupted value must not open the route by default. + case _ => false + } + } + + /** + * The repository, if the caller may open an issue in it. + * + * Readability is checked first and reported as a missing repository, so a + * policy refusal cannot confirm that a private repository exists. + */ + protected def issuableRepository(owner: String, repo: String, account: Account)(implicit + s: Session + ): RepositoryInfo = { + val info = readableRepository(owner, repo, account) + if (!canCreateIssue(info, account)) { + throw new AuthorizationError( + s"${account.userName} may not open an issue in $owner/$repo under its " + + s"issues policy (${info.repository.options.issuesOption})" + ) + } + info + } + + /** + * Developer role on an arbitrary repository, used where the authorized + * repository is not the one named in the arguments. GitBucket's own + * `update_draft` route checks the *head* repository of a pull request, not + * the base one, and this exists so that check can be reproduced exactly + * rather than approximated. + */ + protected def requireDeveloperRole(owner: String, repo: String, account: Account)(implicit + s: Session + ): Unit = + if (!hasDeveloperRole(owner, repo, Some(account))) { + throw new AuthorizationError( + s"${account.userName} does not have developer access to $owner/$repo" + ) + } +} diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala new file mode 100644 index 0000000..82f1be8 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala @@ -0,0 +1,50 @@ +package com.newsrx.mcpplugin.tools + +import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} +import com.fasterxml.jackson.databind.node.ObjectNode +import com.newsrx.mcpplugin.PluginDescriptor +import com.newsrx.mcpplugin.mcp.ToolDef +import gitbucket.core.model.Account +import javax.servlet.http.HttpServletRequest + +/** + * Who the server validated this call as. + * + * A client cannot otherwise learn the identity its own credentials resolve + * to: a pull request's `author` is whoever opened it, and a separately + * configured REST credential says nothing about the account behind the MCP + * connector's header. Without this tool an agent can only guess, and a guess + * about identity is exactly what must not appear in a review report. + * + * The account here is the one `MCPController.authenticate` already validated + * for this request, so this is a read of server state, not a second check. + */ +class WhoAmITool extends ToolDef { + val name = "whoami" + val description = + "Return the GitBucket account this MCP connection is authenticated as, plus the self-reported plugin descriptor" + + def inputSchema(mapper: ObjectMapper) = objectSchema(mapper, required = Seq()) + + def execute(args: JsonNode, account: Account, request: HttpServletRequest, mapper: ObjectMapper): JsonNode = { + val n = mapper.createObjectNode() + n.put("login", account.userName) + n.put("full_name", account.fullName) + n.put("email", account.mailAddress) + n.put("is_admin", account.isAdmin) + n.put("is_group_account", account.isGroupAccount) + n.put("is_removed", account.isRemoved) + + val plugin = mapper.createObjectNode() + plugin.put("plugin_id", PluginDescriptor.get("pluginId")) + plugin.put("plugin_name", PluginDescriptor.get("pluginName")) + plugin.put("plugin_version", PluginDescriptor.get("pluginVersion")) + plugin.put("plugin_provider", PluginDescriptor.get("pluginProvider")) + // The descriptor is a string inside the JAR. It is not a build attestation + // and must not be used to identify which source revision produced the JAR. + plugin.put("self_reported", true) + n.set[ObjectNode]("plugin", plugin) + + jsonContent(mapper, n) + } +} diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala index 0c19b24..ef8e41e 100644 --- a/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala +++ b/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala @@ -2,7 +2,7 @@ package com.newsrx.mcpplugin.tools import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.fasterxml.jackson.databind.node.ObjectNode -import com.newsrx.mcpplugin.mcp.ToolDef +import com.newsrx.mcpplugin.mcp.{StrictArgs, Timestamps, ToolDef} import gitbucket.core.model.{Account, Issue} import gitbucket.core.service.{AccountService, IssuesService, LabelsService, MilestonesService, PrioritiesService, RepositoryService} import gitbucket.core.service.IssuesService.IssueSearchCondition @@ -18,6 +18,7 @@ private[tools] trait IssueService with PrioritiesService with MilestonesService with SessionSupport + with RepositoryAuthorization private[tools] object IssueJson { def issueNode(mapper: ObjectMapper, issue: Issue): ObjectNode = { @@ -28,8 +29,8 @@ private[tools] object IssueJson { n.put("state", if (issue.closed) "closed" else "open") n.put("author", issue.openedUserName) n.put("is_pr", issue.isPullRequest) - n.put("created_at", issue.registeredDate.toString) - n.put("updated_at", issue.updatedDate.toString) + n.put("created_at", Timestamps.iso8601(issue.registeredDate)) + n.put("updated_at", Timestamps.iso8601(issue.updatedDate)) n } } @@ -56,6 +57,7 @@ class ListIssuesTool extends ToolDef with IssueService { val limit = math.min(intOpt(args, "limit", 30), 100) implicit val session = blockingSession(request) + readableRepository(owner, repo, account) val condition = new IssueSearchCondition( labels = Set.empty, milestone = None, priority = None, @@ -97,6 +99,7 @@ class GetIssueTool extends ToolDef with IssueService { val number = int(args, "number") implicit val session = blockingSession(request) + readableRepository(owner, repo, account) getIssue(owner, repo, number.toString) match { case None => @@ -131,6 +134,10 @@ class CreateIssueTool extends ToolDef with IssueService { val body = strOpt(args, "body") implicit val session = blockingSession(request) + // Read access is not the rule: GitBucket branches on the repository's + // `issuesOption` before writing, and reading alone admitted cases the + // server itself refuses. + issuableRepository(owner, repo, account) val issueId = insertIssue(owner, repo, loginUser = account.userName, @@ -172,6 +179,7 @@ class CloseIssueTool extends ToolDef with IssueService { val reason = strOpt(args, "reason") implicit val session = blockingSession(request) + writableRepository(owner, repo, account) getIssue(owner, repo, number.toString).getOrElse( throw new NoSuchElementException(s"issue #$number not found in $owner/$repo") @@ -204,6 +212,7 @@ class ReopenIssueTool extends ToolDef with IssueService { val number = int(args, "number") implicit val session = blockingSession(request) + writableRepository(owner, repo, account) getIssue(owner, repo, number.toString).getOrElse( throw new NoSuchElementException(s"issue #$number not found in $owner/$repo") @@ -238,6 +247,7 @@ class AddIssueCommentTool extends ToolDef with IssueService { val body = str(args, "body") implicit val session = blockingSession(request) + writableRepository(owner, repo, account) getIssue(owner, repo, number.toString).getOrElse( throw new NoSuchElementException(s"issue #$number not found in $owner/$repo") @@ -253,3 +263,79 @@ class AddIssueCommentTool extends ToolDef with IssueService { jsonContent(mapper, result) } } + +// ── update_own_comment ────────────────────────────────────────────────────── + +/** + * Edit a comment the caller wrote. + * + * Authorship is enforced here rather than assumed: GitBucket lets a + * repository administrator edit anyone's comment, but a gateway that silently + * exercised that power would make an agent's edits indistinguishable from a + * person's. This tool edits the caller's own comments only, and an admin + * calling it on someone else's comment is refused rather than quietly + * elevated. The saved text is read back and compared before success is + * reported. + */ +class UpdateOwnCommentTool extends ToolDef with IssueService { + val name = "update_own_comment" + val description = "Edit a comment written by the authenticated account, with exact read-back of the stored text" + + def inputSchema(mapper: ObjectMapper) = objectSchema( + mapper, + required = Seq("owner", "repo", "comment_id", "body"), + "owner" -> strNode(mapper, "Repository owner"), + "repo" -> strNode(mapper, "Repository name"), + "comment_id" -> intNode(mapper, "Comment id, as returned by get_thread_comments"), + "body" -> strNode(mapper, "Replacement comment text") + ) + + def execute(args: JsonNode, account: Account, request: HttpServletRequest, mapper: ObjectMapper): JsonNode = { + val owner = str(args, "owner") + val repo = str(args, "repo") + val commentId = StrictArgs.identifier(args, "comment_id") + // Strict: a malformed body must not be coerced into empty text and + // overwrite a real comment. An empty replacement is refused outright, + // since blanking a comment is a deletion wearing an edit's clothes. + val body = StrictArgs.requiredText(args, "body") + + implicit val session = blockingSession(request) + readableRepository(owner, repo, account) + + val comment = getComment(owner, repo, commentId.toString).getOrElse( + throw new NoSuchElementException(s"comment $commentId not found in $owner/$repo") + ) + + if (comment.commentedUserName != account.userName) { + throw new AuthorizationError( + s"comment $commentId was written by ${comment.commentedUserName}; " + + s"${account.userName} may edit only their own comments through this gateway" + ) + } + if (comment.action != "comment") { + throw new IllegalArgumentException( + s"comment $commentId is a '${comment.action}' record, not editable comment text" + ) + } + + updateComment(owner, repo, comment.issueId, commentId, body) + + val saved = getComment(owner, repo, commentId.toString).getOrElse( + throw new IllegalStateException(s"comment $commentId disappeared during update") + ) + if (saved.content != body) { + throw new IllegalStateException( + s"comment $commentId was not stored exactly as supplied" + ) + } + + val n = mapper.createObjectNode() + n.put("comment_id", commentId) + n.put("issue_number", comment.issueId) + n.put("author", saved.commentedUserName) + n.put("body", saved.content) + n.put("body_saved_exactly", true) + n.put("updated_at", Timestamps.iso8601(saved.updatedDate)) + jsonContent(mapper, n) + } +} diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala index 2d9d891..0cfb981 100644 --- a/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala +++ b/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala @@ -2,8 +2,8 @@ package com.newsrx.mcpplugin.tools import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.fasterxml.jackson.databind.node.ObjectNode -import com.newsrx.mcpplugin.mcp.ToolDef -import gitbucket.core.model.{Account, Issue, PullRequest} +import com.newsrx.mcpplugin.mcp.{StrictArgs, Timestamps, ToolDef} +import gitbucket.core.model.{Account, Issue, IssueComment, PullRequest} import gitbucket.core.service.{AccountService, ActivityService, CommitsService, IssuesService, LabelsService, MergeService, MilestonesService, PrioritiesService, PullRequestService, RepositoryService, RequestCache, SystemSettingsService, WebHookPullRequestReviewCommentService, WebHookPullRequestService, WebHookService} import gitbucket.core.service.IssuesService.IssueSearchCondition import gitbucket.core.util.JGitUtil.DiffInfo @@ -28,21 +28,81 @@ private[tools] trait PrService with RequestCache with SystemSettingsService with SessionSupport + with RepositoryAuthorization private[tools] object PrJson { - def prNode(mapper: ObjectMapper, issue: Issue, pr: PullRequest): ObjectNode = { + + /** + * A pull request as this gateway reports it. + * + * Commit identities carry GitBucket's stored meaning, verified against + * 4.48.0 rather than guessed from the column names: + * + * - `PullRequest.commitIdTo` is the head commit, resolved by + * `JGitUtil.updatePullRequest` from `refs/pull//head`; + * - `PullRequest.commitIdFrom` is the *merge base* between the base branch + * and the head branch, not the current tip of the base branch. + * + * Calling `commitIdFrom` a "base SHA" would therefore be wrong, so it is + * published as `merge_base_sha`. Both are values stored when the pull + * request was last updated; neither is a live read of a branch tip now, and + * `commit_ids_are_stored_snapshot` says so in the payload rather than only + * in this comment. + * + * `mergedComment` is what GitBucket itself treats as the merge record: the + * issue comment whose action is `merge`, fetched with + * `IssuesService.getMergedComment`. It is passed in rather than read here + * because this object holds no session. + */ + def prNode( + mapper: ObjectMapper, + issue: Issue, + pr: PullRequest, + mergedComment: Option[(IssueComment, Account)] + ): ObjectNode = { val n = mapper.createObjectNode() n.put("number", issue.issueId) n.put("title", issue.title) n.put("body", issue.content.getOrElse("")) n.put("state", if (issue.closed) "closed" else "open") n.put("author", issue.openedUserName) + n.put("base_owner", pr.userName) + n.put("base_repo", pr.repositoryName) n.put("base_branch", pr.branch) - n.put("head_branch", pr.requestBranch) n.put("head_user", pr.requestUserName) + n.put("head_repo", pr.requestRepositoryName) + n.put("head_branch", pr.requestBranch) + n.put("head_sha", pr.commitIdTo) + n.put("merge_base_sha", pr.commitIdFrom) + n.put("commit_ids_are_stored_snapshot", true) n.put("is_draft", pr.isDraft) - n.put("created_at", issue.registeredDate.toString) - n.put("updated_at", issue.updatedDate.toString) + // Merged state comes from the merge *comment*, which is the record + // GitBucket's own API reads (`ApiPullRequest.apply` takes + // `mergedComment` and sets `merged = mergedComment.isDefined`). + // + // This used to be derived from `PullRequest.mergedCommitIds`, and that was + // wrong. Measured on a live 4.48.0 instance: after a merge through + // `PUT /api/v3/.../pulls/:id/merge`, GitBucket answered `merged: true` + // with a `merged_at`, while the column was still empty and this gateway + // answered `merged: false`. Only the web merge route writes that column + // (`PullRequestsController` line 367, for the revert feature); the API + // route does not. A closed pull request that was never merged still + // reports merged=false, which `state` alone cannot say. + n.put("merged", mergedComment.isDefined) + mergedComment.foreach { case (comment, account) => + n.put("merged_at", Timestamps.iso8601(comment.registeredDate)) + n.put("merged_by", account.userName) + } + // The commit ids of the merge, when GitBucket recorded them. Absent on a + // merge performed through the API, so a consumer must not read their + // absence as "not merged" — `merged` is the field that answers that. + pr.mergedCommitIds.map(_.trim).filter(_.nonEmpty).foreach { ids => + val arr = mapper.createArrayNode() + ids.split(",").map(_.trim).filter(_.nonEmpty).foreach(arr.add) + n.set[ObjectNode]("merged_commit_ids", arr) + } + n.put("created_at", Timestamps.iso8601(issue.registeredDate)) + n.put("updated_at", Timestamps.iso8601(issue.updatedDate)) n } } @@ -77,10 +137,12 @@ class ListPullRequestsTool extends ToolDef with PrService { visibility = None, groups = Set.empty, others = Nil ) + readableRepository(owner, repo, account) + val prs = searchPullRequestByApi(condition, 0, limit, (owner, repo)) val arr = mapper.createArrayNode() prs.foreach { t => - arr.add(PrJson.prNode(mapper, t._1, t._4)) + arr.add(PrJson.prNode(mapper, t._1, t._4, getMergedComment(owner, repo, t._1.issueId))) } val root = mapper.createObjectNode() @@ -110,12 +172,13 @@ class GetPullRequestTool extends ToolDef with PrService { val number = int(args, "number") implicit val session = blockingSession(request) + readableRepository(owner, repo, account) getPullRequest(owner, repo, number) match { case None => throw new NoSuchElementException(s"pull request #$number not found in $owner/$repo") case Some((issue, pr)) => - val node = PrJson.prNode(mapper, issue, pr) + val node = PrJson.prNode(mapper, issue, pr, getMergedComment(owner, repo, number)) node.put("comment_count", getComments(owner, repo, number).size) jsonContent(mapper, node) } @@ -144,6 +207,7 @@ class AddPrCommentTool extends ToolDef with PrService { val body = str(args, "body") implicit val session = blockingSession(request) + writableRepository(owner, repo, account) getPullRequest(owner, repo, number).getOrElse( throw new NoSuchElementException(s"pull request #$number not found in $owner/$repo") @@ -182,6 +246,7 @@ class ClosePullRequestTool extends ToolDef with PrService { val reason = strOpt(args, "reason") implicit val session = blockingSession(request) + writableRepository(owner, repo, account) getPullRequest(owner, repo, number).getOrElse( throw new NoSuchElementException(s"pull request #$number not found in $owner/$repo") @@ -214,6 +279,7 @@ class ReopenPullRequestTool extends ToolDef with PrService { val number = int(args, "number") implicit val session = blockingSession(request) + writableRepository(owner, repo, account) getPullRequest(owner, repo, number).getOrElse( throw new NoSuchElementException(s"pull request #$number not found in $owner/$repo") @@ -246,6 +312,7 @@ class GetPrDiffTool extends ToolDef with PrService { val number = int(args, "number") implicit val session = blockingSession(request) + readableRepository(owner, repo, account) val (_, pr) = getPullRequest(owner, repo, number).getOrElse( throw new NoSuchElementException(s"pull request #$number not found in $owner/$repo") @@ -275,3 +342,261 @@ class GetPrDiffTool extends ToolDef with PrService { jsonContent(mapper, root) } } + +// ── get_thread_comments ───────────────────────────────────────────────────── + +/** + * The comment bodies of one issue or pull request thread. + * + * `get_pull_request` and `get_issue` report only a `comment_count`, which is + * not a read: an agent asked to act on review remarks cannot see them. This + * returns the text, with the ids and authors needed to answer in the right + * place, and a bounded page so a long thread cannot be pulled in one call. + */ +class GetThreadCommentsTool extends ToolDef with PrService { + val name = "get_thread_comments" + val description = "Read the comments of an issue or pull request thread, with ids, authors and bounded pagination" + + val MaxLimit = 50 + + def inputSchema(mapper: ObjectMapper) = objectSchema( + mapper, + required = Seq("owner", "repo", "number"), + "owner" -> strNode(mapper, "Repository owner"), + "repo" -> strNode(mapper, "Repository name"), + "number" -> intNode(mapper, "Issue or pull request number"), + "offset" -> intNode(mapper, "Comments to skip, oldest first (default: 0)"), + "limit" -> intNode(mapper, s"Maximum comments to return (default: 30, max: $MaxLimit)") + ) + + def execute(args: JsonNode, account: Account, request: HttpServletRequest, mapper: ObjectMapper): JsonNode = { + val owner = str(args, "owner") + val repo = str(args, "repo") + val number = int(args, "number") + val offset = math.max(intOpt(args, "offset", 0), 0) + val limit = math.min(math.max(intOpt(args, "limit", 30), 1), MaxLimit) + + implicit val session = blockingSession(request) + readableRepository(owner, repo, account) + + if (getIssue(owner, repo, number.toString).isEmpty) { + throw new NoSuchElementException(s"issue or pull request #$number not found in $owner/$repo") + } + + // GitBucket records state changes ("close", "reopen", "merge", …) as + // comments too. Those carry no author text, so they are reported with + // their action rather than silently dropped: a thread with the deletions + // hidden would misrepresent what happened. + val all = getComments(owner, repo, number) + val page = all.slice(offset, offset + limit) + + val arr = mapper.createArrayNode() + page.foreach { c => + val n = mapper.createObjectNode() + n.put("comment_id", c.commentId) + n.put("author", c.commentedUserName) + n.put("action", c.action) + n.put("body", c.content) + n.put("created_at", Timestamps.iso8601(c.registeredDate)) + n.put("updated_at", Timestamps.iso8601(c.updatedDate)) + arr.add(n) + } + + val root = mapper.createObjectNode() + root.put("number", number) + root.put("total_count", all.size) + root.put("offset", offset) + root.put("returned", page.size) + root.put("has_more", offset + page.size < all.size) + root.put("next_offset", offset + page.size) + root.set[ObjectNode]("comments", arr) + jsonContent(mapper, root) + } +} + +// ── update_pull_request ───────────────────────────────────────────────────── + +/** + * Change a pull request's title or body, and nothing else. + * + * GitBucket's `updateIssue` takes both title and content and writes both, so + * an omitted argument would blank the other field. The current value is read + * first and passed through unchanged, and the saved row is read back and + * compared, because this installation has already answered 200 to a REST + * PATCH whose field it then ignored. Branches are never touched. + */ +class UpdatePullRequestTool extends ToolDef with PrService { + val name = "update_pull_request" + val description = "Update the title and/or body of a pull request, preserving the field that is not supplied" + + def inputSchema(mapper: ObjectMapper) = objectSchema( + mapper, + required = Seq("owner", "repo", "number"), + "owner" -> strNode(mapper, "Repository owner"), + "repo" -> strNode(mapper, "Repository name"), + "number" -> intNode(mapper, "Pull request number"), + "title" -> strNode(mapper, "New title; omit to keep the current one"), + "body" -> strNode(mapper, "New body; omit to keep the current one") + ) + + def execute(args: JsonNode, account: Account, request: HttpServletRequest, mapper: ObjectMapper): JsonNode = { + val owner = str(args, "owner") + val repo = str(args, "repo") + // Strict identifier: the inherited `int` coerces 1.9, 4294967297, "1" and + // true all to 1, which would send the edit to pull request 1. + val number = StrictArgs.identifier(args, "number") + // Read through the strict helpers, not the coercing ones: a malformed + // `body` must not become an empty string and erase the description. + // An omitted field and a supplied empty string are different requests, + // so only a JSON string counts as supplied. + val newTitle = StrictArgs.textOpt(args, "title") + val newBody = StrictArgs.textOpt(args, "body") + + if (newTitle.isEmpty && newBody.isEmpty) { + throw new IllegalArgumentException("supply at least one of: title, body") + } + // Empty-title policy: a pull request must keep a title, so an empty one is + // refused. An empty body is accepted, because clearing a description is a + // normal edit and there is no equivalent reason to forbid it. + if (newTitle.contains("")) { + throw new IllegalArgumentException("argument 'title' must not be empty") + } + + implicit val session = blockingSession(request) + writableRepository(owner, repo, account) + + val (issue, _) = getPullRequest(owner, repo, number).getOrElse( + throw new NoSuchElementException(s"pull request #$number not found in $owner/$repo") + ) + + val title = newTitle.getOrElse(issue.title) + val content = newBody.orElse(issue.content) + + updateIssue(owner, repo, number, title, content) + + // Read back and compare the stored bytes. A write that reports success + // without this proves nothing about what was saved. + val (saved, savedPr) = getPullRequest(owner, repo, number).getOrElse( + throw new IllegalStateException(s"pull request #$number disappeared during update") + ) + val titleOk = saved.title == title + val bodyOk = saved.content.getOrElse("") == content.getOrElse("") + + val root = PrJson.prNode(mapper, saved, savedPr, getMergedComment(owner, repo, number)) + root.put("title_saved_exactly", titleOk) + root.put("body_saved_exactly", bodyOk) + if (!titleOk || !bodyOk) { + throw new IllegalStateException( + s"update of pull request #$number was not stored exactly: " + + s"title_saved_exactly=$titleOk body_saved_exactly=$bodyOk" + ) + } + jsonContent(mapper, root) + } +} + +// ── mark_ready_for_review ─────────────────────────────────────────────────── + +/** + * Take a draft pull request out of draft, using GitBucket's own operation. + * + * `PullRequestService.updateDraftToPullRequest` (4.48.0) writes `isDraft = + * false` and nothing else. It is one-way: it never sets a pull request back to + * draft, so repeating this call preserves the ready state rather than toggling + * it. GitBucket's `update_draft` route fires no hook or event, and this does + * not add one. + * + * Authorization reproduces that route exactly, including the part that is easy + * to get wrong: 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 from the one named in the arguments. + * + * Race guarantee, stated precisely: `expected_head_sha` is compared against + * the stored head before the transition and the stored head is returned after + * it, both inside the request's transaction, but this is a check followed by a + * write and not an atomic compare-and-swap. A push that lands between them is + * not prevented. Do not describe it as compare-and-swap. + */ +class MarkReadyForReviewTool extends ToolDef with PrService { + val name = "mark_ready_for_review" + val description = "Take an open, unmerged draft pull request out of draft using GitBucket's native operation" + + def inputSchema(mapper: ObjectMapper) = objectSchema( + mapper, + required = Seq("owner", "repo", "number"), + "owner" -> strNode(mapper, "Repository owner of the base repository"), + "repo" -> strNode(mapper, "Base repository name"), + "number" -> intNode(mapper, "Pull request number"), + "expected_head_sha" -> strNode( + mapper, + "Full 40-character commit id. If given, refuse when the stored head differs. " + + "Checked before the write, not atomically with it." + ) + ) + + def execute(args: JsonNode, account: Account, request: HttpServletRequest, mapper: ObjectMapper): JsonNode = { + val owner = str(args, "owner") + val repo = str(args, "repo") + val number = StrictArgs.identifier(args, "number") + // A supplied precondition is validated, never discarded: silently + // dropping a malformed one would perform the unguarded write the caller + // explicitly asked to avoid. + val expected = StrictArgs.commitIdOpt(args, "expected_head_sha") + + implicit val session = blockingSession(request) + + // Base repository must be readable by the caller; the write permission + // that matters lives on the head repository, checked below. + readableRepository(owner, repo, account) + + val (issue, pr) = getPullRequest(owner, repo, number).getOrElse( + throw new NoSuchElementException(s"pull request #$number not found in $owner/$repo") + ) + + requireDeveloperRole(pr.requestUserName, pr.requestRepositoryName, account) + + if (issue.closed) { + throw new IllegalArgumentException( + s"pull request #$number is closed; only an open pull request can be marked ready" + ) + } + // Merged is read from the merge comment, the same record GitBucket's own + // API reads. `mergedCommitIds` is not written by the API merge route, so + // testing it here would have let a merged pull request through whenever it + // had somehow been reopened. + if (getMergedComment(owner, repo, number).isDefined) { + throw new IllegalArgumentException( + s"pull request #$number is merged; only an unmerged pull request can be marked ready" + ) + } + expected.foreach { want => + if (!want.equalsIgnoreCase(pr.commitIdTo)) { + throw new IllegalArgumentException( + s"stale expected_head_sha: pull request #$number records head ${pr.commitIdTo}, caller expected $want" + ) + } + } + + val wasDraft = pr.isDraft + // Already-ready is not an error: the requested end state is the same, and + // the native operation is one-way, so calling it again changes nothing. + if (wasDraft) { + updateDraftToPullRequest(owner, repo, number) + } + + val (afterIssue, afterPr) = getPullRequest(owner, repo, number).getOrElse( + throw new IllegalStateException(s"pull request #$number disappeared during the transition") + ) + + val root = PrJson.prNode(mapper, afterIssue, afterPr, getMergedComment(owner, repo, number)) + root.put("was_draft", wasDraft) + root.put("changed", wasDraft && !afterPr.isDraft) + root.put("race_guarantee", "checked-then-written; not compare-and-swap") + if (afterPr.isDraft) { + throw new IllegalStateException( + s"pull request #$number is still a draft after the native transition" + ) + } + jsonContent(mapper, root) + } +} diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala index f2af37b..50db8d0 100644 --- a/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala +++ b/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala @@ -11,6 +11,7 @@ private[tools] trait RepoService extends RepositoryService with AccountService with SessionSupport + with RepositoryAuthorization // ── list_repositories ─────────────────────────────────────────────────────── @@ -31,7 +32,11 @@ class ListRepositoriesTool extends ToolDef with RepoService { implicit val session = blockingSession(request) - val repos = getUserRepositories(owner, withoutForked) + // `getUserRepositories` answers for `owner`, not for the caller: without + // this filter the listing hands every private repository of any account to + // anyone who can authenticate. Each entry is kept only if the caller may + // read it under GitBucket's own rule. + val repos = getUserRepositories(owner, withoutForked).filter(canRead(_, account)) val arr = mapper.createArrayNode() repos.foreach { info => val r = info.repository @@ -73,10 +78,8 @@ class GetRepositoryTool extends ToolDef with RepoService { implicit val session = blockingSession(request) - getRepository(owner, repo) match { - case None => - throw new NoSuchElementException(s"repository $owner/$repo not found") - case Some(info) => + readableRepository(owner, repo, account) match { + case info => val r = info.repository val n = mapper.createObjectNode() n.put("name", r.repositoryName) diff --git a/src/test/scala/com/newsrx/mcpplugin/RepositoryAuthorizationSpec.scala b/src/test/scala/com/newsrx/mcpplugin/RepositoryAuthorizationSpec.scala new file mode 100644 index 0000000..6187c4e --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/RepositoryAuthorizationSpec.scala @@ -0,0 +1,259 @@ +package com.newsrx.mcpplugin + +import com.newsrx.mcpplugin.tools.{AuthorizationError, RepositoryAuthorization} +import gitbucket.core.model.{Account, Repository, RepositoryOptions} +import gitbucket.core.service.{AccountService, RepositoryService} +import gitbucket.core.service.RepositoryService.RepositoryInfo +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import gitbucket.core.model.Profile.profile.blockingApi.Session + +/** + * Fixtures for exercising authorization without a database. + * + * The role predicates are GitBucket's and are stubbed here, so these controls + * verify that the guard consults them and obeys their verdict, and that the + * refusal shape is right. They do not re-verify GitBucket's own role + * computation; that needs a live instance and is listed in the runbook. + */ +object AuthzFixtures { + private val epoch = new java.util.Date(0L) + + private val options = RepositoryOptions( + issuesOption = "PUBLIC", + externalIssuesUrl = None, + wikiOption = "PUBLIC", + externalWikiUrl = None, + allowFork = true, + mergeOptions = "merge-commit", + defaultMergeOption = "merge-commit", + safeMode = false + ) + + def repository(owner: String, name: String, isPrivate: Boolean): Repository = + Repository( + userName = owner, + repositoryName = name, + isPrivate = isPrivate, + description = None, + defaultBranch = "main", + registeredDate = epoch, + updatedDate = epoch, + lastActivityDate = epoch, + originUserName = None, + originRepositoryName = None, + parentUserName = None, + parentRepositoryName = None, + options = options + ) + + /** + * Named `repoInfo`, not `info`: a ScalaTest suite already inherits an + * `info: Informer`, and wildcard-importing a fixture helper of the same + * name loses to the inherited member, so the call resolved to `Informer` + * and reported "unknown parameter name isPrivate". + */ + def repoInfo(owner: String, name: String, isPrivate: Boolean): RepositoryInfo = + RepositoryInfo( + owner = owner, + name = name, + repository = repository(owner, name, isPrivate), + issueCount = 0, + pullCount = 0, + forkedCount = 0, + milestoneCount = 0, + branchList = Seq("main"), + tags = Nil, + managers = Nil + ) + + def account(name: String, admin: Boolean = false): Account = + Account( + userName = name, + fullName = name, + mailAddress = s"$name@example.com", + password = "", + isAdmin = admin, + url = None, + registeredDate = epoch, + updatedDate = epoch, + lastLoginDate = None, + image = None, + isGroupAccount = false, + isRemoved = false, + description = None + ) +} + +/** + * A world of repositories and roles, with GitBucket's data access replaced. + * + * `guests` and `developers` name the accounts holding each role, so a test can + * state a permission matrix directly. The session is never dereferenced: every + * method that would touch it is overridden. + */ +class StubAuthz( + repositories: Map[(String, String), RepositoryInfo], + guests: Set[(String, String, String)] = Set.empty, + developers: Set[(String, String, String)] = Set.empty +) extends RepositoryService + // `RepositoryService` has a self-type of `AccountService`, so it must be + // mixed in even though none of its queries run here. + with AccountService + with RepositoryAuthorization { + + override def getRepository(userName: String, repositoryName: String)(implicit + s: Session + ): Option[RepositoryInfo] = + repositories.get((userName, repositoryName)) + + override def hasGuestRole(owner: String, repository: String, loginAccount: Option[Account])(implicit + s: Session + ): Boolean = + loginAccount.exists { a => + a.isAdmin || guests.contains((owner, repository, a.userName)) || + developers.contains((owner, repository, a.userName)) + } + + override def hasDeveloperRole(owner: String, repository: String, loginAccount: Option[Account])(implicit + s: Session + ): Boolean = + loginAccount.exists(a => a.isAdmin || developers.contains((owner, repository, a.userName))) + + // Exposed so the controls can call the protected guards directly. + def readable(owner: String, repo: String, account: Account)(implicit s: Session): RepositoryInfo = + readableRepository(owner, repo, account) + + def writable(owner: String, repo: String, account: Account)(implicit s: Session): RepositoryInfo = + writableRepository(owner, repo, account) + + def visible(info: RepositoryInfo, account: Account)(implicit s: Session): Boolean = + canRead(info, account) + + def requireDeveloper(owner: String, repo: String, account: Account)(implicit s: Session): Unit = + requireDeveloperRole(owner, repo, account) +} + +@RunWith(classOf[JUnitRunner]) +class RepositoryAuthorizationSpec extends AnyFunSuite with Matchers { + + import AuthzFixtures._ + + private implicit val session: Session = null + + private val publicRepo = repoInfo("example-org", "public-repo", isPrivate = false) + private val privateRepo = repoInfo("example-org", "private-repo", isPrivate = true) + private val repos = Map( + ("example-org", "public-repo") -> publicRepo, + ("example-org", "private-repo") -> privateRepo + ) + + private val outsider = account("outsider") + private val guest = account("guest") + private val developer = account("developer") + private val admin = account("admin", admin = true) + + private def world = new StubAuthz( + repos, + guests = Set(("example-org", "private-repo", "guest")), + developers = Set(("example-org", "private-repo", "developer"), ("example-org", "public-repo", "developer")) + ) + + // ── read ────────────────────────────────────────────────────────────────── + + test("a public repository is readable by any authenticated account") { + world.readable("example-org", "public-repo", outsider).name shouldBe "public-repo" + } + + test("a private repository is not readable without a role") { + a[NoSuchElementException] should be thrownBy world.readable("example-org", "private-repo", outsider) + } + + test("a private repository is readable with the guest role") { + world.readable("example-org", "private-repo", guest).name shouldBe "private-repo" + } + + test("an admin can read a private repository") { + world.readable("example-org", "private-repo", admin).name shouldBe "private-repo" + } + + test("an inaccessible private repository is indistinguishable from a missing one") { + // The point of the control: a caller who may not see the repository must + // not be able to infer that it exists from a different error. + val denied = the[NoSuchElementException] thrownBy world.readable("example-org", "private-repo", outsider) + val missing = the[NoSuchElementException] thrownBy world.readable("example-org", "no-such-repo", outsider) + denied.getClass shouldBe missing.getClass + denied.getMessage.replace("private-repo", "X") shouldBe + missing.getMessage.replace("no-such-repo", "X") + } + + test("a denial does not leak the private flag or any repository detail") { + val denied = the[NoSuchElementException] thrownBy world.readable("example-org", "private-repo", outsider) + denied.getMessage.toLowerCase should not include "private=true" + denied.getMessage.toLowerCase should not include "forbidden" + } + + // ── write ───────────────────────────────────────────────────────────────── + + test("a guest cannot write to a repository they can read") { + // Read access and write access are separate verdicts; conflating them is + // how a reader would gain the ability to comment or close. + world.readable("example-org", "private-repo", guest).name shouldBe "private-repo" + an[AuthorizationError] should be thrownBy world.writable("example-org", "private-repo", guest) + } + + test("a developer can write") { + world.writable("example-org", "private-repo", developer).name shouldBe "private-repo" + } + + test("an outsider writing to a public repository is refused as a write, not as a read") { + // The repository is readable, so the failure must be the write verdict. + world.readable("example-org", "public-repo", outsider).name shouldBe "public-repo" + an[AuthorizationError] should be thrownBy world.writable("example-org", "public-repo", outsider) + } + + test("a write to an unreadable repository is refused before the write verdict") { + // Order matters: answering AuthorizationError here would confirm that the + // private repository exists. + a[NoSuchElementException] should be thrownBy world.writable("example-org", "private-repo", outsider) + } + + // ── listing filter ──────────────────────────────────────────────────────── + + test("canRead filters a listing to what the caller may see") { + val w = world + val all = Seq(publicRepo, privateRepo) + all.filter(w.visible(_, outsider)).map(_.name) shouldBe Seq("public-repo") + all.filter(w.visible(_, guest)).map(_.name) should contain theSameElementsAs Seq( + "public-repo", + "private-repo" + ) + all.filter(w.visible(_, admin)).map(_.name) should have size 2 + } + + // ── explicit developer check on a named repository ──────────────────────── + + test("requireDeveloperRole applies to the repository it is given, not the one being read") { + // The readiness transition needs the developer role on the *head* + // repository of a fork, which is a different repository from the base. + val w = world + noException should be thrownBy w.requireDeveloper("example-org", "private-repo", developer) + an[AuthorizationError] should be thrownBy w.requireDeveloper("example-org", "private-repo", guest) + } + + // ── sensitivity ─────────────────────────────────────────────────────────── + + // An earlier version of this file ended with a "sensitivity" case that built + // a variant whose read rule ignored privacy and then asserted that the + // outsider got in. It was removed: a passing test whose assertion is that + // unauthorized access succeeds reads as a sanctioned behaviour, and it + // demonstrated nothing about the tools, only about a subclass written for + // the occasion. + // + // What it was reaching for is now done against the real code, by mutating + // the production source rather than a test double: see + // `ToolExecutionSpec`, which drives the tools' own `execute`, and the + // mutation record in `docs/validation-runbook.md`. +} diff --git a/src/test/scala/com/newsrx/mcpplugin/StrictArgsSpec.scala b/src/test/scala/com/newsrx/mcpplugin/StrictArgsSpec.scala new file mode 100644 index 0000000..7038436 --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/StrictArgsSpec.scala @@ -0,0 +1,144 @@ +package com.newsrx.mcpplugin + +import com.fasterxml.jackson.databind.ObjectMapper +import com.newsrx.mcpplugin.mcp.StrictArgs +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers + +/** + * Controls for the argument contract of the mutating tools. + * + * These run offline with no GitBucket instance: the code under test is pure + * Jackson handling, and it is the same code the tools call. Each case below + * corresponds to a way the previous coercing helpers would have destroyed or + * weakened a write. + */ +@RunWith(classOf[JUnitRunner]) +class StrictArgsSpec extends AnyFunSuite with Matchers { + + private val mapper = new ObjectMapper() + + private def args(json: String) = mapper.readTree(json) + + // ── omitted vs intentionally empty ──────────────────────────────────────── + + test("an omitted key is absent, not empty") { + StrictArgs.textOpt(args("""{"title":"t"}"""), "body") shouldBe None + } + + test("an explicitly empty string is supplied, not absent") { + // The distinction that matters: clearing a body must reach the tool as a + // request to clear it, while omitting it must leave the stored text alone. + StrictArgs.textOpt(args("""{"body":""}"""), "body") shouldBe Some("") + } + + test("a normal string round-trips unchanged") { + StrictArgs.textOpt(args("""{"body":"hello"}"""), "body") shouldBe Some("hello") + } + + // ── wrong JSON types are refused before any write ───────────────────────── + + test("an object body is refused instead of becoming empty text") { + // The regression this whole helper exists for: `asText("")` turned `{}` + // into "" and the tool then erased a real description. + val thrown = the[IllegalArgumentException] thrownBy + StrictArgs.textOpt(args("""{"body":{}}"""), "body") + thrown.getMessage should include("must be a JSON string") + thrown.getMessage should include("an object") + } + + test("an array body is refused") { + an[IllegalArgumentException] should be thrownBy + StrictArgs.textOpt(args("""{"body":[1,2]}"""), "body") + } + + test("a numeric body is refused rather than stringified") { + an[IllegalArgumentException] should be thrownBy + StrictArgs.textOpt(args("""{"body":42}"""), "body") + } + + test("a boolean body is refused rather than stringified") { + an[IllegalArgumentException] should be thrownBy + StrictArgs.textOpt(args("""{"body":true}"""), "body") + } + + test("an explicit null body is refused, not treated as absent") { + // Treating null as absent would silently turn "clear this" or a client + // bug into "change nothing", which is a different operation either way. + an[IllegalArgumentException] should be thrownBy + StrictArgs.textOpt(args("""{"body":null}"""), "body") + } + + // ── Unicode and newlines survive ────────────────────────────────────────── + + test("unicode and newlines are preserved byte for byte") { + val text = "перший рядок\nдругий\t— ok ✅\r\nкінець" + val node = mapper.createObjectNode() + node.put("body", text) + StrictArgs.textOpt(node, "body") shouldBe Some(text) + } + + // ── requiredText ────────────────────────────────────────────────────────── + + test("requiredText refuses an absent key") { + // The exception is bound to a value first: chaining `getMessage` into the + // infix `thrownBy` expression does not parse. + val thrown = the[IllegalArgumentException] thrownBy + StrictArgs.requiredText(args("""{}"""), "body") + thrown.getMessage should include("missing required argument") + } + + test("requiredText refuses an empty string") { + // Blanking a comment is a deletion wearing an edit's clothes. + val thrown = the[IllegalArgumentException] thrownBy + StrictArgs.requiredText(args("""{"body":""}"""), "body") + thrown.getMessage should include("must not be empty") + } + + test("requiredText refuses a wrong type") { + an[IllegalArgumentException] should be thrownBy + StrictArgs.requiredText(args("""{"body":{}}"""), "body") + } + + test("requiredText accepts real text") { + StrictArgs.requiredText(args("""{"body":"text"}"""), "body") shouldBe "text" + } + + // ── commit id precondition ──────────────────────────────────────────────── + + test("an absent precondition stays absent") { + StrictArgs.commitIdOpt(args("""{}"""), "expected_head_sha") shouldBe None + } + + test("a full 40-character hexadecimal id is accepted") { + val sha = "0123456789abcdef0123456789abcdef01234567" + sha.length shouldBe 40 + StrictArgs.commitIdOpt(args(s"""{"expected_head_sha":"$sha"}"""), "expected_head_sha") shouldBe Some(sha) + } + + test("an abbreviated id is refused rather than compared as a prefix") { + // A prefix never equals a stored full id, so accepting one would make the + // precondition always fail — or, worse, be quietly dropped. + an[IllegalArgumentException] should be thrownBy + StrictArgs.commitIdOpt(args("""{"expected_head_sha":"1f822ae"}"""), "expected_head_sha") + } + + test("a non-hexadecimal id of the right length is refused") { + val forty = "z" * 40 + an[IllegalArgumentException] should be thrownBy + StrictArgs.commitIdOpt(args(s"""{"expected_head_sha":"$forty"}"""), "expected_head_sha") + } + + test("an empty precondition is refused, not discarded") { + // The old `strOpt` dropped "" and performed an unguarded write. + an[IllegalArgumentException] should be thrownBy + StrictArgs.commitIdOpt(args("""{"expected_head_sha":""}"""), "expected_head_sha") + } + + test("an object precondition is refused, not discarded") { + an[IllegalArgumentException] should be thrownBy + StrictArgs.commitIdOpt(args("""{"expected_head_sha":{}}"""), "expected_head_sha") + } +} diff --git a/src/test/scala/com/newsrx/mcpplugin/TimestampsSpec.scala b/src/test/scala/com/newsrx/mcpplugin/TimestampsSpec.scala new file mode 100644 index 0000000..b22f34a --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/TimestampsSpec.scala @@ -0,0 +1,74 @@ +package com.newsrx.mcpplugin + +import com.newsrx.mcpplugin.mcp.Timestamps +import java.util.{Date, TimeZone} +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers + +/** + * Controls for the published timestamp format. + * + * The regression these exist for: every date went through + * `java.util.Date.toString`, which renders in the JVM's default zone with + * locale-dependent names ("Fri Oct 23 15:38:41 EEST 2026"). It read as a + * plausible timestamp, so a non-empty-string assertion passed, while being + * unparseable for a client and incomparable with GitBucket's own ISO 8601 + * output. The live gate refused to compare it once it ran on a host in + * Europe/Kiev. + * + * The default zone is changed inside these cases on purpose: a formatter that + * depends on it must fail here. + */ +@RunWith(classOf[JUnitRunner]) +class TimestampsSpec extends AnyFunSuite with Matchers { + + private def withZone[A](id: String)(body: => A): A = { + val previous = TimeZone.getDefault + try { + TimeZone.setDefault(TimeZone.getTimeZone(id)) + body + } finally TimeZone.setDefault(previous) + } + + private val epoch = new Date(0L) + private val instant = new Date(1792759121000L) // 2026-10-23T12:38:41Z + + test("the epoch formats as an ISO 8601 instant in UTC") { + Timestamps.iso8601(epoch) shouldBe "1970-01-01T00:00:00Z" + } + + test("a known instant formats to the second, with a Z suffix") { + Timestamps.iso8601(instant) shouldBe "2026-10-23T12:38:41Z" + } + + test("the output does not depend on the JVM's default time zone") { + // The whole point: Date.toString would answer differently in each of + // these, which is what made the field unusable. + val renderings = Seq("UTC", "Europe/Kiev", "America/Los_Angeles", "Asia/Kolkata", "Pacific/Chatham") + .map(z => withZone(z)(Timestamps.iso8601(instant))) + renderings.distinct shouldBe Seq("2026-10-23T12:38:41Z") + } + + test("the output does not depend on the JVM's default locale") { + val previous = java.util.Locale.getDefault + try { + java.util.Locale.setDefault(java.util.Locale.forLanguageTag("uk-UA")) + Timestamps.iso8601(instant) shouldBe "2026-10-23T12:38:41Z" + java.util.Locale.setDefault(java.util.Locale.forLanguageTag("ja-JP")) + Timestamps.iso8601(instant) shouldBe "2026-10-23T12:38:41Z" + } finally java.util.Locale.setDefault(previous) + } + + test("every output matches the shape GitBucket's own API publishes") { + val pattern = """^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$""".r + Seq(epoch, instant, new Date(), new Date(253402300799000L)).foreach { d => + withClue(s"$d: ") { pattern.findFirstIn(Timestamps.iso8601(d)) should not be empty } + } + } + + test("a date before the epoch still formats as an instant") { + Timestamps.iso8601(new Date(-1000L)) shouldBe "1969-12-31T23:59:59Z" + } +} diff --git a/src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala b/src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala new file mode 100644 index 0000000..dee141a --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala @@ -0,0 +1,113 @@ +package com.newsrx.mcpplugin + +import com.fasterxml.jackson.databind.ObjectMapper +import com.newsrx.mcpplugin.mcp.ToolRegistry +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import scala.jdk.CollectionConverters._ + +/** + * Offline controls for what the registry publishes. These run without a + * GitBucket instance or a database, so they check the surface a client + * discovers, not the behaviour of a tool against real data. Behavioural + * controls for authorization, read-back and the ready transition need a live + * instance and are listed in README.md under "Checks not executed here". + */ +@RunWith(classOf[JUnitRunner]) +class ToolRegistrySpec extends AnyFunSuite with Matchers { + + private val mapper = new ObjectMapper() + + test("every registered tool has a unique name and a non-empty description") { + val tools = ToolRegistry.all(mapper) + val names = tools.map(_.name) + names.distinct.size shouldBe names.size + tools.foreach { t => + withClue(s"tool ${t.name}: ") { + t.name.trim should not be empty + t.description.trim should not be empty + } + } + } + + test("the operations this increment adds are discoverable") { + val names = ToolRegistry.all(mapper).map(_.name).toSet + // Named individually rather than by count, so adding an unrelated tool + // cannot make this pass while one of these is missing. + names should contain allOf ( + "whoami", + "get_thread_comments", + "update_pull_request", + "update_own_comment", + "mark_ready_for_review" + ) + } + + test("the pre-existing tools are still published") { + val names = ToolRegistry.all(mapper).map(_.name).toSet + names should contain allOf ( + "list_pull_requests", "get_pull_request", "add_pr_comment", + "close_pull_request", "reopen_pull_request", "get_pr_diff", + "list_issues", "get_issue", "create_issue", + "close_issue", "reopen_issue", "add_issue_comment", + "list_repositories", "get_repository" + ) + } + + test("every input schema is an object schema with a required array") { + ToolRegistry.all(mapper).foreach { t => + val schema = t.inputSchema(mapper) + withClue(s"tool ${t.name}: ") { + schema.get("type").asText() shouldBe "object" + schema.has("properties") shouldBe true + schema.get("required").isArray shouldBe true + } + } + } + + test("every declared required argument exists among the schema properties") { + ToolRegistry.all(mapper).foreach { t => + val schema = t.inputSchema(mapper) + val props = schema.get("properties").fieldNames().asScala.toSet + val required = schema.get("required").elements().asScala.map(_.asText()).toSet + withClue(s"tool ${t.name}: ") { + (required diff props) shouldBe empty + } + } + } + + test("whoami takes no required arguments") { + val tool = ToolRegistry.find("whoami", mapper).getOrElse(fail("whoami is not registered")) + tool.inputSchema(mapper).get("required").size() shouldBe 0 + } + + test("mark_ready_for_review offers expected_head_sha but does not demand it") { + val tool = ToolRegistry + .find("mark_ready_for_review", mapper) + .getOrElse(fail("mark_ready_for_review is not registered")) + val schema = tool.inputSchema(mapper) + schema.get("properties").has("expected_head_sha") shouldBe true + val required = schema.get("required").elements().asScala.map(_.asText()).toSet + required should not contain "expected_head_sha" + } + + test("update_pull_request requires neither title nor body in its schema") { + // Either one alone is a valid edit, so the schema cannot demand both; the + // "at least one" rule is enforced in execute and is not expressible here. + val tool = ToolRegistry + .find("update_pull_request", mapper) + .getOrElse(fail("update_pull_request is not registered")) + val required = tool.inputSchema(mapper).get("required").elements().asScala.map(_.asText()).toSet + required shouldBe Set("owner", "repo", "number") + } + + test("the shipped descriptor carries the version the server reports") { + // v0.1.1 shipped with a descriptor saying 0.1.0 and a separate hardcoded + // literal in the controller. The version now has one source; this fails if + // the descriptor is missing from the test classpath or left empty. + PluginDescriptor.get("pluginVersion").trim should not be empty + PluginDescriptor.get("pluginId") shouldBe "mcp-plugin" + } +} diff --git a/src/test/scala/com/newsrx/mcpplugin/tools/ToolExecutionSpec.scala b/src/test/scala/com/newsrx/mcpplugin/tools/ToolExecutionSpec.scala new file mode 100644 index 0000000..5118af3 --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/tools/ToolExecutionSpec.scala @@ -0,0 +1,778 @@ +package com.newsrx.mcpplugin.tools + +import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} +import com.newsrx.mcpplugin.AuthzFixtures +import gitbucket.core.model.{Account, Issue, IssueComment, PullRequest, Repository, RepositoryOptions} +import gitbucket.core.service.RepositoryService.RepositoryInfo +import gitbucket.core.model.Profile.profile.blockingApi.Session +import javax.servlet.http.HttpServletRequest +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import scala.collection.mutable + +/** + * Operation-level controls: the real tools, their real `execute`, with + * GitBucket's storage replaced. + * + * The helper suites exercise the guard and the argument parser in isolation, + * which does not witness whether a tool actually calls them. These controls + * do. Every case below goes through the production `execute` of the production + * tool class, and every storage write is recorded, so "refused" can be told + * apart from "refused after writing". + * + * This file lives in `com.newsrx.mcpplugin.tools` because the service traits + * the tools are built from (`RepoService`, `IssueService`, `PrService`) are + * `private[tools]`. Extending them rather than re-assembling the service list + * keeps the stubs honest: a tool that gains a dependency gains it here too. + * + * Scope, stated plainly: GitBucket's role predicates and its persistence are + * stubbed, so these controls establish tool wiring, policy branching and + * before/after state. They do not re-verify GitBucket's own role computation + * or its SQL. The live-instance matrix stays in `docs/validation-runbook.md`. + */ +private[tools] object ExecFixtures { + val epoch = new java.util.Date(0L) + + def options(issuesOption: String): RepositoryOptions = RepositoryOptions( + issuesOption = issuesOption, + externalIssuesUrl = None, + wikiOption = "PUBLIC", + externalWikiUrl = None, + allowFork = true, + mergeOptions = "merge-commit", + defaultMergeOption = "merge-commit", + safeMode = false + ) + + def repoInfo( + owner: String, + name: String, + isPrivate: Boolean = false, + issuesOption: String = "PUBLIC" + ): RepositoryInfo = + RepositoryInfo( + owner = owner, + name = name, + repository = Repository( + userName = owner, + repositoryName = name, + isPrivate = isPrivate, + description = None, + defaultBranch = "main", + registeredDate = epoch, + updatedDate = epoch, + lastActivityDate = epoch, + originUserName = None, + originRepositoryName = None, + parentUserName = None, + parentRepositoryName = None, + options = options(issuesOption) + ), + issueCount = 0, + pullCount = 0, + forkedCount = 0, + milestoneCount = 0, + branchList = Seq("main"), + tags = Nil, + managers = Nil + ) + + def account(name: String, admin: Boolean = false): Account = AuthzFixtures.account(name, admin) + + def issue( + owner: String, + repo: String, + number: Int, + title: String = "title", + body: Option[String] = Some("body"), + closed: Boolean = false + ): Issue = + Issue( + userName = owner, + repositoryName = repo, + issueId = number, + openedUserName = "author", + milestoneId = None, + priorityId = None, + title = title, + content = body, + closed = closed, + registeredDate = epoch, + updatedDate = epoch, + isPullRequest = true + ) + + def pullRequest( + baseOwner: String, + baseRepo: String, + number: Int, + headOwner: String, + headRepo: String, + head: String = "a" * 40, + isDraft: Boolean = true, + merged: Option[String] = None + ): PullRequest = + PullRequest( + userName = baseOwner, + repositoryName = baseRepo, + issueId = number, + branch = "main", + requestUserName = headOwner, + requestRepositoryName = headRepo, + requestBranch = "feature", + commitIdFrom = "b" * 40, + commitIdTo = head, + isDraft = isDraft, + mergedCommitIds = merged + ) + + def comment(id: Int, author: String, body: String, action: String = "comment"): IssueComment = + IssueComment( + userName = "example-org", + repositoryName = "repo", + issueId = 7, + commentId = id, + action = action, + commentedUserName = author, + content = body, + registeredDate = epoch, + updatedDate = epoch + ) +} + +/** Stored state plus a write log, so a refusal that still wrote is visible. */ +private[tools] class ToolWorld { + val repositories = mutable.Map.empty[(String, String), RepositoryInfo] + val userRepositories = mutable.Map.empty[String, List[RepositoryInfo]] + val guests = mutable.Set.empty[(String, String, String)] + val developers = mutable.Set.empty[(String, String, String)] + val pullRequests = mutable.Map.empty[(String, String, Int), (Issue, PullRequest)] + val comments = mutable.Map.empty[Int, IssueComment] + /** GitBucket's merge record: the issue comment whose action is `merge`. */ + val merges = mutable.Map.empty[(String, String, Int), (IssueComment, Account)] + val writes = mutable.ArrayBuffer.empty[String] +} + +/** Repository reads and role predicates. */ +private[tools] trait StubCommon extends RepoService { + def world: ToolWorld + + // Never dereferenced: everything that would touch a session is overridden. + // Typed by inference as Null so this conforms to whatever + // `Database.getSession` returns, without naming that type here. + override protected def blockingSession(implicit request: HttpServletRequest) = null + + override def getRepository(userName: String, repositoryName: String)(implicit + s: Session + ): Option[RepositoryInfo] = + world.repositories.get((userName, repositoryName)) + + override def getUserRepositories(userName: String, withoutPhysicalInfo: Boolean)(implicit + s: Session + ): List[RepositoryInfo] = + world.userRepositories.getOrElse(userName, Nil) + + override def hasGuestRole(owner: String, repository: String, loginAccount: Option[Account])(implicit + s: Session + ): Boolean = + loginAccount.exists { a => + a.isAdmin || world.guests.contains((owner, repository, a.userName)) || + world.developers.contains((owner, repository, a.userName)) + } + + override def hasDeveloperRole(owner: String, repository: String, loginAccount: Option[Account])(implicit + s: Session + ): Boolean = + loginAccount.exists(a => a.isAdmin || world.developers.contains((owner, repository, a.userName))) +} + +/** Issue storage, with every write recorded. */ +private[tools] trait StubIssues extends IssueService with StubCommon { + override def getIssue(owner: String, repository: String, issueId: String)(implicit + s: Session + ): Option[Issue] = + if (issueId.nonEmpty && issueId.forall(_.isDigit)) + world.pullRequests.get((owner, repository, issueId.toInt)).map(_._1) + else None + + override def getComment(owner: String, repository: String, commentId: String)(implicit + s: Session + ): Option[IssueComment] = + if (commentId.nonEmpty && commentId.forall(_.isDigit)) world.comments.get(commentId.toInt) else None + + override def getComments(owner: String, repository: String, issueId: Int)(implicit + s: Session + ): List[IssueComment] = + world.comments.values.filter(c => c.userName == owner && c.repositoryName == repository && c.issueId == issueId) + .toList + .sortBy(_.commentId) + + override def getMergedComment(owner: String, repository: String, issueId: Int)(implicit + s: Session + ): Option[(IssueComment, Account)] = + world.merges.get((owner, repository, issueId)) + + override def updateComment(owner: String, repository: String, issueId: Int, commentId: Int, content: String)( + implicit s: Session + ): Int = { + world.writes += s"updateComment($owner/$repository#$issueId comment=$commentId)" + world.comments.get(commentId).foreach(c => world.comments(commentId) = c.copy(content = content)) + 1 + } + + override def updateIssue(owner: String, repository: String, issueId: Int, title: String, content: Option[String])( + implicit s: Session + ): Int = { + world.writes += s"updateIssue($owner/$repository#$issueId)" + world.pullRequests.get((owner, repository, issueId)).foreach { case (i, p) => + world.pullRequests((owner, repository, issueId)) = (i.copy(title = title, content = content), p) + } + 1 + } + + override def insertIssue( + owner: String, + repository: String, + loginUser: String, + title: String, + content: Option[String], + milestoneId: Option[Int], + priorityId: Option[Int], + isPullRequest: Boolean + )(implicit s: Session): Int = { + world.writes += s"insertIssue($owner/$repository by $loginUser)" + 42 + } +} + +/** Pull request storage, with the draft transition recorded. */ +private[tools] trait StubPullRequests extends PrService with StubIssues { + override def getPullRequest(owner: String, repository: String, issueId: Int)(implicit + s: Session + ): Option[(Issue, PullRequest)] = + world.pullRequests.get((owner, repository, issueId)) + + override def updateDraftToPullRequest(owner: String, repository: String, issueId: Int)(implicit + s: Session + ): Unit = { + world.writes += s"updateDraftToPullRequest($owner/$repository#$issueId)" + world.pullRequests.get((owner, repository, issueId)).foreach { case (i, p) => + world.pullRequests((owner, repository, issueId)) = (i, p.copy(isDraft = false)) + } + } +} + +// The production tools, with storage replaced and nothing else. +private[tools] class TestCreateIssueTool(val world: ToolWorld) extends CreateIssueTool with StubIssues +private[tools] class TestUpdateOwnCommentTool(val world: ToolWorld) extends UpdateOwnCommentTool with StubIssues +private[tools] class TestUpdatePullRequestTool(val world: ToolWorld) + extends UpdatePullRequestTool + with StubPullRequests +private[tools] class TestMarkReadyTool(val world: ToolWorld) extends MarkReadyForReviewTool with StubPullRequests +private[tools] class TestGetPullRequestTool(val world: ToolWorld) extends GetPullRequestTool with StubPullRequests +private[tools] class TestListRepositoriesTool(val world: ToolWorld) extends ListRepositoriesTool with StubCommon + +@RunWith(classOf[JUnitRunner]) +class ToolExecutionSpec extends AnyFunSuite with Matchers { + + import ExecFixtures._ + + private val mapper = new ObjectMapper() + private val request: HttpServletRequest = null + + private def args(json: String): JsonNode = mapper.readTree(json) + + /** Tools answer `{"content":[{"type":"text","text":""}]}`. */ + private def payload(result: JsonNode): JsonNode = + mapper.readTree(result.get("content").get(0).get("text").asText()) + + // ── P1: create_issue follows the repository's issue policy ──────────────── + + private def issueWorld(issuesOption: String, isPrivate: Boolean): ToolWorld = { + val w = new ToolWorld + w.repositories(("example-org", "repo")) = repoInfo("example-org", "repo", isPrivate, issuesOption) + w.guests += (("example-org", "repo", "guest")) + w.developers += (("example-org", "repo", "developer")) + w + } + + private def createIssue(w: ToolWorld, who: Account): JsonNode = + new TestCreateIssueTool(w).execute( + args("""{"owner":"example-org","repo":"repo","title":"t","body":"b"}"""), + who, + request, + mapper + ) + + test("ALL on a public repository admits an authenticated outsider") { + val w = issueWorld("ALL", isPrivate = false) + payload(createIssue(w, account("outsider"))).get("number").asInt() shouldBe 42 + w.writes should have size 1 + } + + test("ALL on a private repository refuses even a developer, and writes nothing") { + // GitBucket's ALL branch is `!isPrivate && loggedIn`: privacy, not role, + // is what closes this one. + val w = issueWorld("ALL", isPrivate = true) + an[AuthorizationError] should be thrownBy createIssue(w, account("developer")) + w.writes shouldBe empty + } + + test("PUBLIC admits a guest but refuses an outsider, and the refusal writes nothing") { + val w = issueWorld("PUBLIC", isPrivate = false) + noException should be thrownBy createIssue(w, account("guest")) + w.writes should have size 1 + an[AuthorizationError] should be thrownBy createIssue(w, account("outsider")) + w.writes should have size 1 + } + + test("PRIVATE admits a developer but refuses a guest, and the refusal writes nothing") { + // The case the previous head got wrong: a guest passed the read guard and + // reached insertIssue. + val w = issueWorld("PRIVATE", isPrivate = true) + an[AuthorizationError] should be thrownBy createIssue(w, account("guest")) + w.writes shouldBe empty + noException should be thrownBy createIssue(w, account("developer")) + w.writes should have size 1 + } + + test("DISABLE refuses everyone including an admin, and writes nothing") { + val w = issueWorld("DISABLE", isPrivate = false) + an[AuthorizationError] should be thrownBy createIssue(w, account("developer")) + an[AuthorizationError] should be thrownBy createIssue(w, account("admin", admin = true)) + w.writes shouldBe empty + } + + test("an unknown issues setting is refused rather than treated as open") { + val w = issueWorld("SOMETHING_NEW", isPrivate = false) + an[AuthorizationError] should be thrownBy createIssue(w, account("developer")) + w.writes shouldBe empty + } + + test("an unreadable private repository is reported as missing, not as a policy refusal") { + // Order matters: an AuthorizationError here would confirm to a stranger + // that the private repository exists. + val w = issueWorld("PRIVATE", isPrivate = true) + a[NoSuchElementException] should be thrownBy createIssue(w, account("stranger")) + w.writes shouldBe empty + } + + // ── P2: malformed identifiers refuse, and write nothing ─────────────────── + + private def prWorld: ToolWorld = { + val w = new ToolWorld + w.repositories(("example-org", "repo")) = repoInfo("example-org", "repo") + w.developers += (("example-org", "repo", "developer")) + w.pullRequests(("example-org", "repo", 1)) = (issue("example-org", "repo", 1), pullRequest("example-org", "repo", 1, "example-org", "repo")) + w.pullRequests(("example-org", "repo", 5)) = (issue("example-org", "repo", 5), pullRequest("example-org", "repo", 5, "example-org", "repo")) + w + } + + private val malformedIds = Seq( + "1.9" -> "a fractional number", + "4294967297" -> "range", + "\"1\"" -> "JSON integer", + "true" -> "JSON integer", + "null" -> "JSON integer", + "{}" -> "JSON integer", + "[]" -> "JSON integer", + "0" -> "positive" + ) + + test("update_pull_request refuses every malformed identifier and never writes") { + // Through the inherited helper each of these arrived as pull request 1, so + // the edit would have landed on a real and unrelated pull request. + malformedIds.foreach { case (literal, fragment) => + val w = prWorld + val thrown = the[IllegalArgumentException] thrownBy { + new TestUpdatePullRequestTool(w).execute( + args(s"""{"owner":"example-org","repo":"repo","number":$literal,"title":"hijacked"}"""), + account("developer"), + request, + mapper + ) + } + withClue(s"identifier $literal: ") { + thrown.getMessage should include(fragment) + w.writes shouldBe empty + w.pullRequests(("example-org", "repo", 1))._1.title shouldBe "title" + } + } + } + + test("mark_ready_for_review refuses a malformed identifier and leaves draft state untouched") { + val w = prWorld + an[IllegalArgumentException] should be thrownBy new TestMarkReadyTool(w).execute( + args("""{"owner":"example-org","repo":"repo","number":1.9}"""), + account("developer"), + request, + mapper + ) + w.writes shouldBe empty + w.pullRequests(("example-org", "repo", 1))._2.isDraft shouldBe true + } + + test("update_own_comment refuses a malformed identifier before reading the comment") { + val w = commentWorld + an[IllegalArgumentException] should be thrownBy new TestUpdateOwnCommentTool(w).execute( + args("""{"owner":"example-org","repo":"repo","comment_id":"10","body":"x"}"""), + account("author"), + request, + mapper + ) + w.writes shouldBe empty + w.comments(10).content shouldBe "original" + } + + test("a well-formed identifier still reaches the right object") { + val w = prWorld + val result = payload( + new TestUpdatePullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"repo","number":5,"title":"new"}"""), + account("developer"), + request, + mapper + ) + ) + result.get("number").asInt() shouldBe 5 + w.writes should contain("updateIssue(example-org/repo#5)") + w.pullRequests(("example-org", "repo", 1))._1.title shouldBe "title" + } + + // ── omitted-field preservation, observed in stored state ────────────────── + + test("updating only the title preserves the stored body") { + val w = prWorld + new TestUpdatePullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"repo","number":1,"title":"renamed"}"""), + account("developer"), + request, + mapper + ) + val (stored, _) = w.pullRequests(("example-org", "repo", 1)) + stored.title shouldBe "renamed" + stored.content shouldBe Some("body") + } + + test("updating only the body preserves the stored title") { + val w = prWorld + new TestUpdatePullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"repo","number":1,"body":"rewritten"}"""), + account("developer"), + request, + mapper + ) + val (stored, _) = w.pullRequests(("example-org", "repo", 1)) + stored.title shouldBe "title" + stored.content shouldBe Some("rewritten") + } + + test("an explicit empty body clears it while the title survives") { + val w = prWorld + new TestUpdatePullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"repo","number":1,"body":""}"""), + account("developer"), + request, + mapper + ) + val (stored, _) = w.pullRequests(("example-org", "repo", 1)) + stored.title shouldBe "title" + stored.content shouldBe Some("") + } + + test("a malformed object body refuses and leaves the stored body untouched") { + // The coercing helper turned `{}` into "" and erased a real description. + val w = prWorld + an[IllegalArgumentException] should be thrownBy new TestUpdatePullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"repo","number":1,"body":{}}"""), + account("developer"), + request, + mapper + ) + w.writes shouldBe empty + w.pullRequests(("example-org", "repo", 1))._1.content shouldBe Some("body") + } + + test("a reader without the developer role cannot update, and nothing is written") { + val w = prWorld + w.guests += (("example-org", "repo", "reader")) + an[AuthorizationError] should be thrownBy new TestUpdatePullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"repo","number":1,"title":"x"}"""), + account("reader"), + request, + mapper + ) + w.writes shouldBe empty + } + + // ── own-comment authorship, through the real tool ───────────────────────── + + private def commentWorld: ToolWorld = { + val w = new ToolWorld + w.repositories(("example-org", "repo")) = repoInfo("example-org", "repo") + w.comments(10) = comment(10, "author", "original") + w.comments(11) = comment(11, "author", "", action = "close") + w + } + + private def editComment(w: ToolWorld, who: Account, id: Int, body: String = "edited"): JsonNode = + new TestUpdateOwnCommentTool(w).execute( + args(s"""{"owner":"example-org","repo":"repo","comment_id":$id,"body":"$body"}"""), + who, + request, + mapper + ) + + test("the author can edit their own comment and the stored text matches exactly") { + val w = commentWorld + payload(editComment(w, account("author"), 10)).get("body_saved_exactly").asBoolean() shouldBe true + w.comments(10).content shouldBe "edited" + } + + test("another account cannot edit someone else's comment, and nothing is written") { + val w = commentWorld + an[AuthorizationError] should be thrownBy editComment(w, account("other"), 10) + w.writes shouldBe empty + w.comments(10).content shouldBe "original" + } + + test("an admin is refused another author's comment rather than silently elevated") { + // GitBucket would let a repository admin edit it. The gateway deliberately + // does not, so an agent's edits stay attributable. + val w = commentWorld + an[AuthorizationError] should be thrownBy editComment(w, account("admin", admin = true), 10) + w.writes shouldBe empty + w.comments(10).content shouldBe "original" + } + + test("a state-change record is refused as non-editable text") { + val w = commentWorld + an[IllegalArgumentException] should be thrownBy editComment(w, account("author"), 11) + w.writes shouldBe empty + } + + test("an empty replacement is refused rather than blanking the comment") { + val w = commentWorld + an[IllegalArgumentException] should be thrownBy editComment(w, account("author"), 10, body = "") + w.writes shouldBe empty + w.comments(10).content shouldBe "original" + } + + // ── the readiness transition, including the fork repository choice ──────── + + private def forkWorld( + isDraft: Boolean = true, + closed: Boolean = false, + merged: Option[String] = None, + mergeComment: Boolean = false + ): ToolWorld = { + val w = new ToolWorld + w.repositories(("example-org", "base")) = repoInfo("example-org", "base") + w.repositories(("fork", "head")) = repoInfo("fork", "head") + w.pullRequests(("example-org", "base", 3)) = ( + issue("example-org", "base", 3, closed = closed), + pullRequest("example-org", "base", 3, "fork", "head", isDraft = isDraft, merged = merged) + ) + if (mergeComment) { + w.merges(("example-org", "base", 3)) = + (comment(99, "merger", "merge it", action = "merge"), account("merger")) + } + w + } + + private def markReady(w: ToolWorld, who: Account, extra: String = ""): JsonNode = + new TestMarkReadyTool(w).execute( + args(s"""{"owner":"example-org","repo":"base","number":3$extra}"""), + who, + request, + mapper + ) + + test("the developer role is required on the head repository, not the base") { + // A developer of the base repository with no role on the fork is refused. + // This is the check GitBucket's own update_draft route performs, and + // getting it wrong would be invisible without distinct repositories. + val w = forkWorld() + w.developers += (("example-org", "base", "baseDev")) + an[AuthorizationError] should be thrownBy markReady(w, account("baseDev")) + w.writes shouldBe empty + w.pullRequests(("example-org", "base", 3))._2.isDraft shouldBe true + } + + test("a developer of the head repository can mark it ready") { + val w = forkWorld() + w.developers += (("fork", "head", "forkDev")) + val result = payload(markReady(w, account("forkDev"))) + result.get("is_draft").asBoolean() shouldBe false + result.get("was_draft").asBoolean() shouldBe true + result.get("changed").asBoolean() shouldBe true + w.writes should contain("updateDraftToPullRequest(example-org/base#3)") + } + + test("marking an already-ready pull request ready again changes nothing and writes nothing") { + val w = forkWorld(isDraft = false) + w.developers += (("fork", "head", "forkDev")) + val result = payload(markReady(w, account("forkDev"))) + result.get("is_draft").asBoolean() shouldBe false + result.get("changed").asBoolean() shouldBe false + w.writes shouldBe empty + } + + test("a stale expected head is refused and the draft state survives") { + val w = forkWorld() + w.developers += (("fork", "head", "forkDev")) + val thrown = the[IllegalArgumentException] thrownBy { + markReady(w, account("forkDev"), s""","expected_head_sha":"${"c" * 40}"""") + } + thrown.getMessage should include("stale expected_head_sha") + w.writes shouldBe empty + w.pullRequests(("example-org", "base", 3))._2.isDraft shouldBe true + } + + test("a matching expected head is accepted") { + val w = forkWorld() + w.developers += (("fork", "head", "forkDev")) + payload(markReady(w, account("forkDev"), s""","expected_head_sha":"${"a" * 40}"""")) + .get("is_draft") + .asBoolean() shouldBe false + } + + test("a malformed precondition is refused, not dropped into an unguarded write") { + val w = forkWorld() + w.developers += (("fork", "head", "forkDev")) + an[IllegalArgumentException] should be thrownBy { + markReady(w, account("forkDev"), ""","expected_head_sha":"aaaa"""") + } + w.writes shouldBe empty + w.pullRequests(("example-org", "base", 3))._2.isDraft shouldBe true + } + + test("a closed pull request is refused and nothing is written") { + val w = forkWorld(closed = true) + w.developers += (("fork", "head", "forkDev")) + an[IllegalArgumentException] should be thrownBy markReady(w, account("forkDev")) + w.writes shouldBe empty + } + + test("a merged pull request is refused and nothing is written") { + // Driven by the merge comment, which is what GitBucket reads. Measured on + // a live 4.48.0 instance: the API merge route leaves `mergedCommitIds` + // empty, so a column test would have let this through. + val w = forkWorld(mergeComment = true) + w.developers += (("fork", "head", "forkDev")) + val thrown = the[IllegalArgumentException] thrownBy markReady(w, account("forkDev")) + thrown.getMessage should include("is merged") + w.writes shouldBe empty + w.pullRequests(("example-org", "base", 3))._2.isDraft shouldBe true + } + + test("a merge comment with no recorded commit ids still counts as merged") { + // The exact live case: `merged_commit_ids` absent, `merged` true. + val w = forkWorld(isDraft = false, closed = true, mergeComment = true) + w.developers += (("fork", "head", "forkDev")) + val payloadNode = payload( + new TestGetPullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"base","number":3}"""), + account("forkDev"), + request, + mapper + ) + ) + payloadNode.get("merged").asBoolean() shouldBe true + payloadNode.get("merged_by").asText() shouldBe "merger" + payloadNode.has("merged_at") shouldBe true + payloadNode.has("merged_commit_ids") shouldBe false + payloadNode.get("state").asText() shouldBe "closed" + } + + test("recorded commit ids are published without being the test for merged") { + val w = forkWorld(isDraft = false, closed = true, merged = Some("aaa, bbb"), mergeComment = true) + w.developers += (("fork", "head", "forkDev")) + val n = payload( + new TestGetPullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"base","number":3}"""), + account("forkDev"), + request, + mapper + ) + ) + n.get("merged").asBoolean() shouldBe true + n.get("merged_commit_ids").get(0).asText() shouldBe "aaa" + n.get("merged_commit_ids").get(1).asText() shouldBe "bbb" + } + + test("a closed pull request with no merge comment reports merged=false") { + // `state` alone cannot say this: closed-without-merging and merged are + // both closed. + val w = forkWorld(isDraft = false, closed = true) + w.developers += (("fork", "head", "forkDev")) + val n = payload( + new TestGetPullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"base","number":3}"""), + account("forkDev"), + request, + mapper + ) + ) + n.get("state").asText() shouldBe "closed" + n.get("merged").asBoolean() shouldBe false + n.has("merged_by") shouldBe false + } + + test("a stale commit-id column alone does not make a pull request merged") { + // The inverse of the live defect: the column is set but no merge comment + // exists, so GitBucket would not call this merged either. + val w = forkWorld(merged = Some("deadbeef")) + w.developers += (("fork", "head", "forkDev")) + val result = payload(markReady(w, account("forkDev"))) + result.get("merged").asBoolean() shouldBe false + result.get("changed").asBoolean() shouldBe true + } + + test("the readiness transition leaves the title and body alone") { + val w = forkWorld() + w.developers += (("fork", "head", "forkDev")) + markReady(w, account("forkDev")) + val (stored, _) = w.pullRequests(("example-org", "base", 3)) + stored.title shouldBe "title" + stored.content shouldBe Some("body") + w.writes should not contain ("updateIssue(example-org/base#3)") + } + + // ── the read guard, inside real tools ───────────────────────────────────── + + test("get_pull_request refuses a private repository the caller cannot read") { + val w = new ToolWorld + w.repositories(("example-org", "secret")) = repoInfo("example-org", "secret", isPrivate = true) + w.pullRequests(("example-org", "secret", 1)) = + (issue("example-org", "secret", 1), pullRequest("example-org", "secret", 1, "example-org", "secret")) + a[NoSuchElementException] should be thrownBy new TestGetPullRequestTool(w).execute( + args("""{"owner":"example-org","repo":"secret","number":1}"""), + account("outsider"), + request, + mapper + ) + } + + test("list_repositories filters inside the tool, not merely inside the guard") { + val w = new ToolWorld + val open = repoInfo("example-org", "open") + val secret = repoInfo("example-org", "secret", isPrivate = true) + w.userRepositories("example-org") = List(open, secret) + w.repositories(("example-org", "open")) = open + w.repositories(("example-org", "secret")) = secret + + val outsiderView = payload( + new TestListRepositoriesTool(w).execute(args("""{"owner":"example-org"}"""), account("outsider"), request, mapper) + ) + outsiderView.get("count").asInt() shouldBe 1 + outsiderView.get("repositories").get(0).get("name").asText() shouldBe "open" + + w.guests += (("example-org", "secret", "guest")) + payload( + new TestListRepositoriesTool(w).execute(args("""{"owner":"example-org"}"""), account("guest"), request, mapper) + ).get("count").asInt() shouldBe 2 + } +} From 99728cf070cdd6cb1f349663e42d74d7983478d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 18:18:05 +0000 Subject: [PATCH 02/29] oauth: discovery metadata, PKCE and scopes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/authentication.md | 127 ++++++++ .../mcpplugin/oauth/ChallengeError.scala | 33 +++ .../com/newsrx/mcpplugin/oauth/Metadata.scala | 92 ++++++ .../newsrx/mcpplugin/oauth/OAuthConfig.scala | 77 +++++ .../com/newsrx/mcpplugin/oauth/Pkce.scala | 50 ++++ .../com/newsrx/mcpplugin/oauth/Scopes.scala | 62 ++++ .../mcpplugin/oauth/OAuthFoundationSpec.scala | 271 ++++++++++++++++++ 7 files changed, 712 insertions(+) create mode 100644 docs/authentication.md create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/ChallengeError.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/OAuthConfig.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/Scopes.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala diff --git a/docs/authentication.md b/docs/authentication.md new file mode 100644 index 0000000..8c85c01 --- /dev/null +++ b/docs/authentication.md @@ -0,0 +1,127 @@ +# Authentication + +The MCP endpoint accepts two authentication methods. Both resolve to a real +GitBucket account, and neither grants anything that account does not already +have. + +| Method | For | State | +| --- | --- | --- | +| HTTP Basic | clients that can send a username and password or personal access token, such as Claude Desktop | supported | +| OAuth 2.1 Bearer | clients that require a browser authorization flow, such as ChatGPT | this document | + +## Why the plugin is also the authorization server + +GitBucket 4.46–4.48 is **not** an OAuth authorization server. It ships +`AccessToken`/`AccessTokenService` — personal access tokens, stored as a hash — +and session authenticators, but no authorization endpoint, no token endpoint, +no client registry and no key set. Its OAuth support is as a *client*, for +signing users in from an external provider. Verified against the published +4.48.0 artifact rather than assumed. + +So an authorization server has to come from somewhere, and there are two +honest options. + +**An external authorization server** (Keycloak, Authentik, a hosted IdP). This +is a second service to deploy, operate and back up, with its own user store. +Worse, it reintroduces the problem this plugin exists to avoid: the external +server's subject is not a GitBucket account, so something has to map one to +the other, and the only cheap mapping — matching an email address — is exactly +the unverified link that turns an identity provider into a privilege +escalation. Rejected, but recorded here so the choice is visible rather than +implied. + +**The plugin acts as the authorization server**, authenticating the resource +owner with the GitBucket session the user already has. No new identity store, +no account linking, no second service. The resource owner is a GitBucket +account by construction, because the only way to reach the consent screen is +to be signed in to GitBucket. Chosen. + +The cost of that choice is honest too: this plugin then owns authorization +codes, tokens and consent records, and owns their security properties. The +rest of this document is about those properties. + +## Boundaries + +| Role | Where it lives | +| --- | --- | +| MCP resource server | the existing `/plugin-mcp/` endpoint, now also accepting `Authorization: Bearer` | +| Authorization server | this plugin, at its own endpoints | +| Resource owner authentication | GitBucket's own session — the plugin never sees a password | +| Account resolution | the signed-in GitBucket account, carried on the grant | +| Repository authorization | unchanged: GitBucket's `hasGuestRole` / `hasDeveloperRole`, per request | +| Persistent state | plugin-owned tables, created by a Solidbase migration | + +Effective access is the **intersection** of the granted scope and the account's +current GitBucket permissions. A token is never sufficient on its own: every +tool still runs the same repository guard it runs under Basic authentication, +so a grant issued yesterday cannot outlive a role removed today. + +## Registration: client ID metadata documents + +ChatGPT supports three registration mechanisms. This plugin implements one. + +- **CIMD** — the client's `client_id` is an HTTPS URL serving its own metadata. + Nothing is registered and nothing is stored. Implemented. +- **Dynamic client registration** (RFC 7591) — requires an open registration + endpoint and a client table. Not implemented: it is a larger attack surface + for a self-hosted server, and CIMD covers the client this work targets. +- **Pre-registration** — an administrator pastes a client ID and secret. + Not implemented. + +Fetching a metadata document means the server makes an outbound request to a +URL a caller supplied, which is a server-side request forgery primitive if it +is done carelessly. The fetcher is therefore bounded: HTTPS only, a response +size and time limit, no redirects followed to a different host, and private, +loopback and link-local address ranges refused after DNS resolution. + +## Tokens + +Access tokens are opaque, generated from a cryptographic random source and +stored as a SHA-256 hash, in the same spirit as GitBucket's own personal +access tokens. They are not self-contained. + +That is a deliberate trade. A signed self-contained token needs no storage and +no lookup, but it also cannot be revoked before it expires — revocation +latency becomes the token lifetime. An opaque token costs one indexed lookup +per request and gives **immediate** revocation, which is the property that +matters when a grant is withdrawn or an account is disabled. + +| Credential | Lifetime | Revocation | +| --- | --- | --- | +| authorization code | 60 seconds, single use | consumed atomically | +| access token | 1 hour | immediate | +| refresh token | 30 days, rotated on use | immediate; reuse of a rotated token revokes the whole grant | + +## Scopes + +| Scope | Grants | +| --- | --- | +| `mcp:read` | the read-only tools | +| `mcp:write` | the mutating tools, in addition to `mcp:read` | + +Every tool declares which one it needs, as an abstract member, so a tool that +forgets to declare does not compile rather than defaulting to the weaker +requirement. A read grant cannot mutate: the scope check happens before the +tool runs, and the repository guard still happens inside it. + +OIDC scopes (`openid`, `email`, `profile`) and a UserInfo endpoint are **not** +implemented, and the metadata does not advertise them. They are only needed +for workspace domain restrictions, and advertising a capability that is not +implemented is worse than not having it. + +## What the metadata says is what exists + +The discovery documents describe only implemented behaviour. In particular +`code_challenge_methods_supported` lists `S256` and nothing else, because the +plain method is not accepted; `grant_types_supported` lists only +`authorization_code` and `refresh_token`; and no `registration_endpoint` is +published, because dynamic registration is not implemented. + +## Configuration + +The canonical resource URL is configured explicitly. It is **not** derived +from the `Host` header or from `X-Forwarded-*`, because those are attacker- +controlled on a reverse-proxied deployment and a resource identifier that +moves with the request is not an audience binding. A deployment behind a proxy +or in a servlet context path sets the external URL once; everything else — +issuer, endpoints, the `resource` value in tokens — is derived from it. diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/ChallengeError.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/ChallengeError.scala new file mode 100644 index 0000000..353f873 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/ChallengeError.scala @@ -0,0 +1,33 @@ +package com.newsrx.mcpplugin.oauth + +/** + * The reasons this resource server refuses a bearer token (RFC 6750 §3.1). + * + * A closed set, with server-authored text. Error descriptions are the one + * place where caller-controlled bytes are most tempting to echo — "token + * `` is malformed" reads helpfully — and the one place where + * echoing them puts attacker text into a response header, a proxy log and + * whatever parses either. + * + * It is also deliberately uninformative about *why* a token failed. A caller + * learns that the token is not usable, not whether it was unknown, expired, + * bound to another resource or revoked; those differences are useful to + * someone probing with tokens they should not have. + */ +sealed abstract class ChallengeError(val code: String, val description: String, val status: Int) + +object ChallengeError { + + /** No credentials at all: not an error, just an invitation to authenticate. */ + case object None_ extends ChallengeError("", "", 401) + + case object InvalidRequest + extends ChallengeError("invalid_request", "malformed authorization header", 400) + + /** Covers unknown, expired, revoked and wrong-audience alike, on purpose. */ + case object InvalidToken + extends ChallengeError("invalid_token", "the access token is not valid", 401) + + case object InsufficientScope + extends ChallengeError("insufficient_scope", "the access token does not grant the required scope", 403) +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala new file mode 100644 index 0000000..9fb2646 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala @@ -0,0 +1,92 @@ +package com.newsrx.mcpplugin.oauth + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.node.ObjectNode + +/** + * The discovery documents, and the challenge that points at them. + * + * These describe only what is implemented. A metadata document is a promise a + * client acts on without asking again: advertising `plain` PKCE, a + * registration endpoint or an OIDC scope that does not work produces a client + * that fails later, further from the cause, with a worse error. + */ +object Metadata { + + /** + * RFC 9728 protected resource metadata, served at + * `/.well-known/oauth-protected-resource`. + */ + def protectedResource(mapper: ObjectMapper, config: OAuthConfig): ObjectNode = { + val n = mapper.createObjectNode() + n.put("resource", config.resource) + val servers = mapper.createArrayNode() + servers.add(config.issuer) + n.set[ObjectNode]("authorization_servers", servers) + val scopes = mapper.createArrayNode() + McpScope.all.foreach(s => scopes.add(s.name)) + n.set[ObjectNode]("scopes_supported", scopes) + val methods = mapper.createArrayNode() + methods.add("header") + n.set[ObjectNode]("bearer_methods_supported", methods) + n + } + + /** + * RFC 8414 authorization server metadata, served at + * `/.well-known/oauth-authorization-server`. + */ + def authorizationServer(mapper: ObjectMapper, config: OAuthConfig): ObjectNode = { + val n = mapper.createObjectNode() + n.put("issuer", config.issuer) + n.put("authorization_endpoint", config.authorizationEndpoint) + n.put("token_endpoint", config.tokenEndpoint) + n.put("revocation_endpoint", config.revocationEndpoint) + + array(mapper, n, "response_types_supported", Seq("code")) + array(mapper, n, "response_modes_supported", Seq("query")) + array(mapper, n, "grant_types_supported", Seq("authorization_code", "refresh_token")) + // S256 only. The absence of "plain" is the point, not an omission. + array(mapper, n, "code_challenge_methods_supported", Seq("S256")) + array(mapper, n, "scopes_supported", McpScope.all.map(_.name)) + // Public clients proving possession with PKCE; no client secret exists to + // present, so "none" is the honest value rather than a weaker default. + array(mapper, n, "token_endpoint_auth_methods_supported", Seq("none")) + array(mapper, n, "revocation_endpoint_auth_methods_supported", Seq("none")) + + // RFC 9207: the authorization response carries `iss`, so a client can tell + // which server answered and cannot be fed a response from another one. + n.put("authorization_response_iss_parameter_supported", true) + // The client_id is an HTTPS URL serving the client's own metadata; there + // is no registration step and therefore no registration_endpoint. + n.put("client_id_metadata_document_supported", true) + n + } + + /** + * The `WWW-Authenticate` value for a 401 from the resource server + * (RFC 9728 §5.1), which is how a client discovers where to authenticate + * when it did not look first. + * + * The reason is a [[ChallengeError]] rather than a string, so nothing a + * caller sent can reach a response header. Sanitising caller text would + * also work and is worse: it is a blacklist, it has to stay correct as the + * header grammar grows, and it still copies an attacker's words into a + * response other software may log or parse. + */ + def challenge(config: OAuthConfig, error: Option[ChallengeError] = None): String = { + val metadataUrl = s"${config.baseUrl}/.well-known/oauth-protected-resource" + val parts = Seq( + Some(s"""resource_metadata="$metadataUrl""""), + error.map(e => s"""error="${e.code}""""), + error.map(e => s"""error_description="${e.description}"""") + ).flatten + s"Bearer ${parts.mkString(", ")}" + } + + private def array(mapper: ObjectMapper, parent: ObjectNode, field: String, values: Seq[String]): Unit = { + val arr = mapper.createArrayNode() + values.foreach(arr.add) + parent.set[ObjectNode](field, arr) + } +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthConfig.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthConfig.scala new file mode 100644 index 0000000..9845cc3 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthConfig.scala @@ -0,0 +1,77 @@ +package com.newsrx.mcpplugin.oauth + +/** + * Where this server thinks it is. + * + * Every identifier an OAuth deployment publishes — the issuer, the endpoints, + * the `resource` a token is bound to — is derived from one externally + * configured base URL, and from nothing else. + * + * Specifically not from the request. `Host` and `X-Forwarded-Host` are set by + * whoever is talking to the server, and behind a reverse proxy they are set by + * whoever is talking to the proxy. A resource identifier that follows the + * request header is not an audience binding: a token minted for one `Host` + * would be accepted by the same server asked under another, which is the whole + * property audience binding exists to provide. So the base URL is + * configuration, it is validated once, and a deployment that has not set it + * does not serve OAuth at all rather than guessing. + */ +final case class OAuthConfig( + /** External base URL of this GitBucket, no trailing slash, e.g. `https://git.example.com`. */ + baseUrl: String, + accessTokenLifetimeSeconds: Int = 3600, + refreshTokenLifetimeSeconds: Int = 30 * 24 * 3600, + authorizationCodeLifetimeSeconds: Int = 60 +) { + /** The MCP resource identifier, and the `resource`/audience value in tokens. */ + val resource: String = s"$baseUrl/plugin-mcp/" + + /** This server is its own issuer; RFC 8414 derives the metadata path from it. */ + val issuer: String = baseUrl + + val authorizationEndpoint: String = s"$baseUrl/plugin-mcp/oauth/authorize" + val tokenEndpoint: String = s"$baseUrl/plugin-mcp/oauth/token" + val revocationEndpoint: String = s"$baseUrl/plugin-mcp/oauth/revoke" +} + +object OAuthConfig { + + /** Property and environment names a deployment can set. */ + val BaseUrlProperty = "gitbucket.mcp.oauth.baseUrl" + val BaseUrlEnv = "GITBUCKET_MCP_OAUTH_BASE_URL" + + /** + * Build a configuration from an explicitly supplied base URL. + * + * Returns the reason on the left rather than a boolean, because "OAuth is + * off because the base URL is `http://`" is something an administrator needs + * to be told, and a silently disabled authentication method is how a + * deployment ends up serving an endpoint nobody can authenticate to. + */ + def fromBaseUrl(raw: String): Either[String, OAuthConfig] = { + val trimmed = Option(raw).map(_.trim).getOrElse("") + if (trimmed.isEmpty) + Left(s"not configured: set $BaseUrlProperty or $BaseUrlEnv to this server's external base URL") + else if (!trimmed.startsWith("https://") && !isLoopback(trimmed)) + // Plain HTTP is refused except on loopback, where it is the only way to + // run the test suite. A bearer token on a cleartext connection is a + // bearer token for whoever is on the path. + Left(s"must be an https:// URL (or http://localhost for testing), got: $trimmed") + else if (trimmed.endsWith("/")) + Left(s"must not end with a slash, got: $trimmed") + else if (trimmed.contains("?") || trimmed.contains("#")) + Left(s"must not carry a query or fragment, got: $trimmed") + else + Right(OAuthConfig(trimmed)) + } + + private def isLoopback(url: String): Boolean = + url.startsWith("http://localhost") || url.startsWith("http://127.0.0.1") + + /** Read the configured base URL from the system property, then the environment. */ + def configuredBaseUrl(): Option[String] = + Option(System.getProperty(BaseUrlProperty)) + .orElse(Option(System.getenv(BaseUrlEnv))) + .map(_.trim) + .filter(_.nonEmpty) +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala new file mode 100644 index 0000000..321902b --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala @@ -0,0 +1,50 @@ +package com.newsrx.mcpplugin.oauth + +import java.nio.charset.StandardCharsets +import java.security.MessageDigest +import java.util.Base64 + +/** + * Proof Key for Code Exchange, S256 only (RFC 7636). + * + * The `plain` method is not accepted and is not advertised. It protects + * against nothing an attacker who can read the authorization response cannot + * also do, and offering it invites a downgrade: a client that can be talked + * into sending `code_challenge_method=plain` has no protection at all. + */ +object Pkce { + + /** RFC 7636 §4.1: 43–128 characters from the unreserved set. */ + private val VerifierPattern = "^[A-Za-z0-9\\-._~]{43,128}$".r + + /** A challenge is the base64url-no-padding SHA-256 of the verifier. */ + def challengeFor(verifier: String): String = { + val digest = MessageDigest.getInstance("SHA-256") + .digest(verifier.getBytes(StandardCharsets.US_ASCII)) + Base64.getUrlEncoder.withoutPadding.encodeToString(digest) + } + + def isWellFormedVerifier(verifier: String): Boolean = + verifier != null && VerifierPattern.pattern.matcher(verifier).matches() + + /** + * Whether `verifier` proves possession of the key behind `challenge`. + * + * The comparison is constant-time. A challenge is not a secret, so this is + * belt-and-braces rather than load-bearing, but the same helper is used for + * values that are secret and a single comparison routine is easier to keep + * right than two. + */ + def verify(verifier: String, challenge: String): Boolean = { + if (!isWellFormedVerifier(verifier) || challenge == null || challenge.isEmpty) false + else constantTimeEquals(challengeFor(verifier), challenge) + } + + def constantTimeEquals(a: String, b: String): Boolean = { + val x = a.getBytes(StandardCharsets.UTF_8) + val y = b.getBytes(StandardCharsets.UTF_8) + // MessageDigest.isEqual is constant-time for equal-length inputs and + // short-circuits only on length, which is not secret here. + MessageDigest.isEqual(x, y) + } +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/Scopes.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/Scopes.scala new file mode 100644 index 0000000..1bbf9ed --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/Scopes.scala @@ -0,0 +1,62 @@ +package com.newsrx.mcpplugin.oauth + +/** + * The scopes this authorization server issues. + * + * Two, deliberately. A scope list that mirrors the tool list looks precise and + * is unusable: a client has to request twenty of them, a user has to read + * twenty lines of consent, and nobody refuses one. The distinction that + * actually changes what can happen to a repository is read versus write. + */ +sealed abstract class McpScope(val name: String) { + + /** Whether a grant carrying `granted` is sufficient for this requirement. */ + def satisfiedBy(granted: Set[String]): Boolean +} + +object McpScope { + + /** Read-only tools. */ + case object Read extends McpScope("mcp:read") { + def satisfiedBy(granted: Set[String]): Boolean = + granted.contains(Read.name) || granted.contains(Write.name) + } + + /** + * Mutating tools. + * + * `mcp:write` implies `mcp:read`: a client that may change an issue can + * already read it back, and pretending otherwise would only teach clients to + * request both every time. + */ + case object Write extends McpScope("mcp:write") { + def satisfiedBy(granted: Set[String]): Boolean = granted.contains(Write.name) + } + + val all: Seq[McpScope] = Seq(Read, Write) + + private val byName: Map[String, McpScope] = all.map(s => s.name -> s).toMap + + def byScopeName(name: String): Option[McpScope] = byName.get(name) + + /** + * Parse a space-delimited scope string, keeping only scopes this server + * issues. + * + * RFC 6749 allows a server to issue a narrower scope than was requested, and + * that is what happens here: an unknown scope is dropped rather than + * refused, so a client asking for `mcp:read openid` gets `mcp:read` and a + * working connection instead of an error it cannot act on. The granted set + * is returned to the client in the token response, so the narrowing is + * visible rather than silent. + */ + def parseRequested(raw: String): Set[String] = + Option(raw).getOrElse("").split("\\s+").filter(_.nonEmpty).filter(byName.contains).toSet + + /** The default when a client requests no scope at all: the weaker one. */ + val default: Set[String] = Set(Read.name) + + /** Render a granted set in the canonical order, for a token response. */ + def render(granted: Set[String]): String = + all.map(_.name).filter(granted.contains).mkString(" ") +} diff --git a/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala b/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala new file mode 100644 index 0000000..0dd843d --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala @@ -0,0 +1,271 @@ +package com.newsrx.mcpplugin.oauth + +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers + +/** + * Controls for the parts of the OAuth layer that have no database and no + * request: configuration, discovery documents, the challenge header, PKCE and + * scopes. + * + * These are the pieces a client reads before it ever authenticates, so a + * mistake here is a mistake every client inherits. + */ +@RunWith(classOf[JUnitRunner]) +class OAuthFoundationSpec extends AnyFunSuite with Matchers { + + private val mapper = new ObjectMapper() + private val config = OAuthConfig("https://git.example.com") + + // ── configuration ───────────────────────────────────────────────────────── + + test("a well-formed https base URL is accepted and derives every identifier") { + val c = OAuthConfig.fromBaseUrl("https://git.example.com").toOption.get + c.issuer shouldBe "https://git.example.com" + c.resource shouldBe "https://git.example.com/plugin-mcp/" + c.authorizationEndpoint shouldBe "https://git.example.com/plugin-mcp/oauth/authorize" + c.tokenEndpoint shouldBe "https://git.example.com/plugin-mcp/oauth/token" + } + + test("a context path is carried into every derived identifier") { + // A GitBucket deployed under /gitbucket must not advertise endpoints at + // the server root. + val c = OAuthConfig.fromBaseUrl("https://example.com/gitbucket").toOption.get + c.resource shouldBe "https://example.com/gitbucket/plugin-mcp/" + c.authorizationEndpoint shouldBe "https://example.com/gitbucket/plugin-mcp/oauth/authorize" + } + + test("an unconfigured base URL is refused with a reason an administrator can act on") { + val reason = OAuthConfig.fromBaseUrl("").swap.toOption.get + reason should include(OAuthConfig.BaseUrlProperty) + reason should include(OAuthConfig.BaseUrlEnv) + OAuthConfig.fromBaseUrl(null).isLeft shouldBe true + } + + test("plain http is refused except on loopback") { + OAuthConfig.fromBaseUrl("http://git.example.com").isLeft shouldBe true + OAuthConfig.fromBaseUrl("http://localhost:8080").isRight shouldBe true + OAuthConfig.fromBaseUrl("http://127.0.0.1:8080").isRight shouldBe true + } + + test("a trailing slash, query or fragment is refused rather than normalised") { + // Silently trimming would mean the configured value and the published + // value differ, and the published one is what a token is bound to. + OAuthConfig.fromBaseUrl("https://git.example.com/").isLeft shouldBe true + OAuthConfig.fromBaseUrl("https://git.example.com?x=1").isLeft shouldBe true + OAuthConfig.fromBaseUrl("https://git.example.com#x").isLeft shouldBe true + } + + // ── protected resource metadata (RFC 9728) ──────────────────────────────── + + test("protected resource metadata names this resource and its authorization server") { + val n = Metadata.protectedResource(mapper, config) + n.get("resource").asText() shouldBe "https://git.example.com/plugin-mcp/" + n.get("authorization_servers").get(0).asText() shouldBe "https://git.example.com" + n.get("bearer_methods_supported").get(0).asText() shouldBe "header" + } + + test("protected resource metadata advertises exactly the scopes that exist") { + val n = Metadata.protectedResource(mapper, config) + val scopes = (0 until n.get("scopes_supported").size()).map(n.get("scopes_supported").get(_).asText()) + scopes should contain theSameElementsAs Seq("mcp:read", "mcp:write") + } + + // ── authorization server metadata (RFC 8414) ────────────────────────────── + + test("authorization server metadata carries the fields ChatGPT requires") { + val n = Metadata.authorizationServer(mapper, config) + Seq("issuer", "authorization_endpoint", "token_endpoint", "code_challenge_methods_supported") + .foreach(f => withClue(s"$f: ")(n.has(f) shouldBe true)) + n.get("issuer").asText() shouldBe config.issuer + } + + test("S256 is the only code challenge method advertised") { + // A metadata document that also lists "plain" invites a downgrade, and a + // client that sends it gets no protection at all. + val methods = Metadata.authorizationServer(mapper, config).get("code_challenge_methods_supported") + methods.size() shouldBe 1 + methods.get(0).asText() shouldBe "S256" + } + + test("only the implemented grant types are advertised") { + val n = Metadata.authorizationServer(mapper, config).get("grant_types_supported") + val grants = (0 until n.size()).map(n.get(_).asText()) + grants should contain theSameElementsAs Seq("authorization_code", "refresh_token") + grants should not contain "implicit" + grants should not contain "password" + grants should not contain "client_credentials" + } + + test("no registration endpoint is advertised, because none is implemented") { + val n = Metadata.authorizationServer(mapper, config) + n.has("registration_endpoint") shouldBe false + n.get("client_id_metadata_document_supported").asBoolean() shouldBe true + } + + test("issuer identification is advertised, which fixes ChatGPT's redirect URI") { + // RFC 9207 support is what lets ChatGPT use its shared redirect URI + // instead of a per-connection callback, so the claim must be true. + Metadata.authorizationServer(mapper, config) + .get("authorization_response_iss_parameter_supported").asBoolean() shouldBe true + } + + test("no OIDC scope or userinfo endpoint is advertised, because neither is implemented") { + val n = Metadata.authorizationServer(mapper, config) + n.has("userinfo_endpoint") shouldBe false + val scopes = n.get("scopes_supported") + (0 until scopes.size()).map(scopes.get(_).asText()) should not contain "openid" + } + + // ── the 401 challenge ───────────────────────────────────────────────────── + + test("the challenge points at the protected resource metadata") { + val c = Metadata.challenge(config) + c should startWith("Bearer ") + c should include("""resource_metadata="https://git.example.com/.well-known/oauth-protected-resource"""") + } + + test("the challenge carries the error code a client branches on") { + val c = Metadata.challenge(config, Some(ChallengeError.InvalidToken)) + c should include("""error="invalid_token"""") + c should include("""error_description="the access token is not valid"""") + } + + test("an insufficient-scope refusal is distinguishable from an invalid token") { + // A client that holds a valid read token and calls a write tool must be + // told to ask for more, not to authenticate again. + Metadata.challenge(config, Some(ChallengeError.InsufficientScope)) should + include("""error="insufficient_scope"""") + ChallengeError.InsufficientScope.status shouldBe 403 + ChallengeError.InvalidToken.status shouldBe 401 + } + + test("no caller-controlled text can reach the challenge header") { + // The reason is a closed set rather than a string, so there is no argument + // through which a caller's bytes could arrive. Every description is + // server-authored and free of the characters that would end a quoted + // string or a header line. + Seq(ChallengeError.InvalidRequest, ChallengeError.InvalidToken, + ChallengeError.InsufficientScope).foreach { e => + val c = Metadata.challenge(config, Some(e)) + withClue(s"${e.code}: ") { + c.count(_ == '"') shouldBe 6 // three quoted values, two quotes each + c should not include "\r" + c should not include "\n" + e.description should fullyMatch regex "[ -!#-\\[\\]-~]*" + } + } + } + + test("every refusal still points at the metadata, so a client can recover") { + Seq(None, Some(ChallengeError.InvalidToken), Some(ChallengeError.InsufficientScope)) + .foreach { e => + Metadata.challenge(config, e) should + include("""resource_metadata="https://git.example.com/.well-known/oauth-protected-resource"""") + } + } + + test("the token refusal reveals nothing about why the token failed") { + // Unknown, expired, revoked and wrong-audience are one answer on purpose: + // the differences are only useful to someone probing with tokens they + // should not hold. + ChallengeError.InvalidToken.description should not include "expired" + ChallengeError.InvalidToken.description should not include "revoked" + ChallengeError.InvalidToken.description should not include "unknown" + } + + // ── PKCE ────────────────────────────────────────────────────────────────── + + test("a verifier matches the challenge derived from it") { + val verifier = "a" * 43 + Pkce.verify(verifier, Pkce.challengeFor(verifier)) shouldBe true + } + + test("the challenge is base64url with no padding, as RFC 7636 requires") { + val challenge = Pkce.challengeFor("b" * 64) + challenge should not include "=" + challenge should not include "+" + challenge should not include "/" + challenge should fullyMatch regex "[A-Za-z0-9_-]+" + } + + test("the published RFC 7636 appendix B vector is reproduced") { + // An independent value, so this checks the implementation rather than + // checking it against itself. + Pkce.challengeFor("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") shouldBe + "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + } + + test("a wrong verifier is refused") { + Pkce.verify("c" * 43, Pkce.challengeFor("d" * 43)) shouldBe false + } + + test("a verifier outside the length range is refused") { + Pkce.isWellFormedVerifier("a" * 42) shouldBe false + Pkce.isWellFormedVerifier("a" * 43) shouldBe true + Pkce.isWellFormedVerifier("a" * 128) shouldBe true + Pkce.isWellFormedVerifier("a" * 129) shouldBe false + } + + test("a verifier with characters outside the unreserved set is refused") { + Pkce.isWellFormedVerifier(("a" * 42) + "+") shouldBe false + Pkce.isWellFormedVerifier(("a" * 42) + "/") shouldBe false + Pkce.isWellFormedVerifier(("a" * 42) + " ") shouldBe false + } + + test("a missing verifier or challenge is refused rather than treated as a match") { + Pkce.verify(null, "x") shouldBe false + Pkce.verify("a" * 43, null) shouldBe false + Pkce.verify("a" * 43, "") shouldBe false + } + + // ── scopes ──────────────────────────────────────────────────────────────── + + test("a read grant satisfies a read requirement and not a write one") { + val granted = Set("mcp:read") + McpScope.Read.satisfiedBy(granted) shouldBe true + McpScope.Write.satisfiedBy(granted) shouldBe false + } + + test("a write grant satisfies both, because writing implies reading back") { + val granted = Set("mcp:write") + McpScope.Read.satisfiedBy(granted) shouldBe true + McpScope.Write.satisfiedBy(granted) shouldBe true + } + + test("an empty grant satisfies nothing") { + McpScope.Read.satisfiedBy(Set.empty) shouldBe false + McpScope.Write.satisfiedBy(Set.empty) shouldBe false + } + + test("an unrelated scope grants nothing") { + val granted = Set("openid", "email", "admin") + McpScope.Read.satisfiedBy(granted) shouldBe false + McpScope.Write.satisfiedBy(granted) shouldBe false + } + + test("requested scopes are narrowed to what this server issues") { + McpScope.parseRequested("mcp:read openid profile") shouldBe Set("mcp:read") + McpScope.parseRequested("mcp:read mcp:write") shouldBe Set("mcp:read", "mcp:write") + McpScope.parseRequested("admin mcp:admin") shouldBe Set.empty + } + + test("odd whitespace in a scope string does not create a scope") { + McpScope.parseRequested(" mcp:read\t\tmcp:write ") shouldBe Set("mcp:read", "mcp:write") + McpScope.parseRequested("") shouldBe Set.empty + McpScope.parseRequested(null) shouldBe Set.empty + } + + test("a granted set renders in a stable order for the token response") { + McpScope.render(Set("mcp:write", "mcp:read")) shouldBe "mcp:read mcp:write" + McpScope.render(Set("mcp:read")) shouldBe "mcp:read" + McpScope.render(Set.empty) shouldBe "" + } + + test("the default grant is the weaker scope") { + McpScope.default shouldBe Set("mcp:read") + } +} From c79876fbcd34c0e88f8583f4d47157e10e20a4e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 20:27:49 +0000 Subject: [PATCH 03/29] oauth: delegate protocol types to the SDK GitBucket already ships MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- build.gradle | 7 ++ docs/authentication.md | 60 +++++++++++--- .../com/newsrx/mcpplugin/oauth/Metadata.scala | 55 ++++++++----- .../com/newsrx/mcpplugin/oauth/Pkce.scala | 78 ++++++++++--------- .../com/newsrx/mcpplugin/oauth/Secrets.scala | 52 +++++++++++++ .../mcpplugin/oauth/OAuthFoundationSpec.scala | 27 +++++++ 6 files changed, 215 insertions(+), 64 deletions(-) create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/Secrets.scala diff --git a/build.gradle b/build.gradle index f7eefc8..180f6f4 100644 --- a/build.gradle +++ b/build.gradle @@ -21,6 +21,11 @@ dependencies { compileOnly 'javax.servlet:javax.servlet-api:4.0.1' compileOnly 'com.fasterxml.jackson.core:jackson-databind:2.15.2' compileOnly 'com.github.takezoe:blocking-slick_2.13:0.0.14' + // Already on GitBucket's runtime classpath (it uses Nimbus for its own + // OpenID Connect sign-in), so this is compileOnly and is not bundled. + // Pinned to the version shipped by the oldest supported GitBucket, 4.46.0, + // so only API present across the tested range is used. + compileOnly 'com.nimbusds:oauth2-oidc-sdk:11.33' testImplementation 'org.scalatest:scalatest_2.13:3.2.18' testImplementation 'org.scalatestplus:junit-4-13_2.13:3.2.18.0' @@ -28,6 +33,8 @@ dependencies { testImplementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' testCompileOnly 'io.github.gitbucket:gitbucket_2.13:4.46.0' testCompileOnly 'javax.servlet:javax.servlet-api:4.0.1' + testCompileOnly 'com.nimbusds:oauth2-oidc-sdk:11.33' + testRuntimeOnly 'com.nimbusds:oauth2-oidc-sdk:11.33' testRuntimeOnly 'io.github.gitbucket:gitbucket_2.13:4.46.0' testRuntimeOnly 'javax.servlet:javax.servlet-api:4.0.1' testRuntimeOnly 'com.github.takezoe:blocking-slick_2.13:0.0.14' diff --git a/docs/authentication.md b/docs/authentication.md index 8c85c01..8ed66dd 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -11,24 +11,34 @@ have. ## Why the plugin is also the authorization server -GitBucket 4.46–4.48 is **not** an OAuth authorization server. It ships +GitBucket is **not** an OAuth authorization server. It ships `AccessToken`/`AccessTokenService` — personal access tokens, stored as a hash — and session authenticators, but no authorization endpoint, no token endpoint, no client registry and no key set. Its OAuth support is as a *client*, for signing users in from an external provider. Verified against the published -4.48.0 artifact rather than assumed. +artifacts rather than assumed. So an authorization server has to come from somewhere, and there are two honest options. **An external authorization server** (Keycloak, Authentik, a hosted IdP). This -is a second service to deploy, operate and back up, with its own user store. -Worse, it reintroduces the problem this plugin exists to avoid: the external -server's subject is not a GitBucket account, so something has to map one to -the other, and the only cheap mapping — matching an email address — is exactly -the unverified link that turns an identity provider into a privilege -escalation. Rejected, but recorded here so the choice is visible rather than -implied. +can be done safely: the mapping from the external subject to a GitBucket +account is an explicit, administrator-established binding on +`(issuer, subject)`, stored and verified, and an identity provider that +GitBucket already trusts for sign-in is a reasonable thing to trust for +authorization too. Matching on email is not the only option and is not what +makes this approach hard. + +What makes it hard is operational. It is a second service to deploy, operate, +upgrade and back up; it needs its own availability story, because the MCP +endpoint stops authenticating when it is down; and the binding table has to be +populated and maintained by hand for every user, which is work an +administrator does before anyone can connect. For a plugin whose premise is +"no separate service or proxy required", that cost falls on every deployment +to serve a case most of them do not have. Rejected on those grounds, and +recorded here so the choice is visible rather than implied. A deployment that +already runs an IdP and wants it to own MCP authorization is a reasonable +future option, not a contradiction of this one. **The plugin acts as the authorization server**, authenticating the resource owner with the GitBucket session the user already has. No new identity store, @@ -40,6 +50,30 @@ The cost of that choice is honest too: this plugin then owns authorization codes, tokens and consent records, and owns their security properties. The rest of this document is about those properties. +## What is a dependency and what is ours + +The protocol types come from **`com.nimbusds:oauth2-oidc-sdk`**, Apache-2.0, +which GitBucket already carries on its runtime classpath for its own OpenID +Connect sign-in. It is therefore a `compileOnly` dependency and is **not** +bundled into the plugin JAR: no duplicate classes, no version skew with the +host, no growth in the artifact. Pinned at 11.33, the version shipped by the +oldest supported GitBucket, so only API present across the whole tested range +is used. + +| Supplied by the library | Implemented here | +| --- | --- | +| PKCE: verifier syntax, S256 computation (`CodeVerifier`, `CodeChallenge`) | the policy that S256 is the only accepted method | +| RFC 8414 authorization server metadata: field names, JSON shape | the values in it, and the claim that each one is true | +| Authorization and token request parsing, error objects, token responses, revocation requests | which requests are honoured, and every decision about whether to honour one | +| `ClientID`, `Scope`, `State`, `AuthorizationCode`, `BearerAccessToken` types | the storage, lifetime, binding and rotation of everything they name | +| — | RFC 9728 protected resource metadata, which has no type in the shipped SDK version | +| — | the `WWW-Authenticate` challenge | +| — | consent, CSRF, GitBucket account resolution, scope enforcement, the CIMD fetcher and its SSRF controls, and the schema | + +Randomness and hashing are the JDK's `SecureRandom` and `MessageDigest`. No +cryptography is implemented here, and nothing in the table's right-hand column +is described anywhere in this repository as coming from the library. + ## Boundaries | Role | Where it lives | @@ -117,6 +151,14 @@ plain method is not accepted; `grant_types_supported` lists only `authorization_code` and `refresh_token`; and no `registration_endpoint` is published, because dynamic registration is not implemented. +## Tested versions + +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 (11.33 for 4.46.0, 11.38.2 for +the other two). Those three are what has been run; versions between or beyond +them are untested rather than known-good. + ## Configuration The canonical resource URL is configured explicitly. It is **not** derived diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala index 9fb2646..1b7c1a4 100644 --- a/src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/Metadata.scala @@ -2,6 +2,12 @@ package com.newsrx.mcpplugin.oauth import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode +import com.nimbusds.oauth2.sdk.{GrantType, ResponseMode, ResponseType, Scope => NimbusScope} +import com.nimbusds.oauth2.sdk.`as`.AuthorizationServerMetadata +import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod +import com.nimbusds.oauth2.sdk.id.Issuer +import java.net.URI +import scala.jdk.CollectionConverters._ /** * The discovery documents, and the challenge that points at them. @@ -10,6 +16,14 @@ import com.fasterxml.jackson.databind.node.ObjectNode * client acts on without asking again: advertising `plain` PKCE, a * registration endpoint or an OIDC scope that does not work produces a client * that fails later, further from the cause, with a worse error. + * + * Ownership, because it differs between the two documents. The authorization + * server document is built and serialized by + * `com.nimbusds.oauth2.sdk.as.AuthorizationServerMetadata`, so RFC 8414 field + * names and shapes are the library's. The protected resource document is + * written here by hand: RFC 9728 has no type in the oauth2-oidc-sdk version + * GitBucket ships, which is a small document and a deliberate exception + * rather than a preference for hand-rolled protocol code. */ object Metadata { @@ -35,32 +49,37 @@ object Metadata { /** * RFC 8414 authorization server metadata, served at * `/.well-known/oauth-authorization-server`. + * + * Built through Nimbus's `AuthorizationServerMetadata`, which owns the field + * names and the JSON shape. */ def authorizationServer(mapper: ObjectMapper, config: OAuthConfig): ObjectNode = { - val n = mapper.createObjectNode() - n.put("issuer", config.issuer) - n.put("authorization_endpoint", config.authorizationEndpoint) - n.put("token_endpoint", config.tokenEndpoint) - n.put("revocation_endpoint", config.revocationEndpoint) + val m = new AuthorizationServerMetadata(new Issuer(config.issuer)) + m.setAuthorizationEndpointURI(URI.create(config.authorizationEndpoint)) + m.setTokenEndpointURI(URI.create(config.tokenEndpoint)) + m.setRevocationEndpointURI(URI.create(config.revocationEndpoint)) - array(mapper, n, "response_types_supported", Seq("code")) - array(mapper, n, "response_modes_supported", Seq("query")) - array(mapper, n, "grant_types_supported", Seq("authorization_code", "refresh_token")) + m.setResponseTypes(List(ResponseType.CODE).asJava) + m.setResponseModes(List(ResponseMode.QUERY).asJava) + m.setGrantTypes(List(GrantType.AUTHORIZATION_CODE, GrantType.REFRESH_TOKEN).asJava) // S256 only. The absence of "plain" is the point, not an omission. - array(mapper, n, "code_challenge_methods_supported", Seq("S256")) - array(mapper, n, "scopes_supported", McpScope.all.map(_.name)) + m.setCodeChallengeMethods(List(Pkce.supportedMethod).asJava) + m.setScopes(new NimbusScope(McpScope.all.map(_.name): _*)) // Public clients proving possession with PKCE; no client secret exists to // present, so "none" is the honest value rather than a weaker default. - array(mapper, n, "token_endpoint_auth_methods_supported", Seq("none")) - array(mapper, n, "revocation_endpoint_auth_methods_supported", Seq("none")) - + m.setTokenEndpointAuthMethods(List(ClientAuthenticationMethod.NONE).asJava) + m.setRevocationEndpointAuthMethods(List(ClientAuthenticationMethod.NONE).asJava) // RFC 9207: the authorization response carries `iss`, so a client can tell // which server answered and cannot be fed a response from another one. - n.put("authorization_response_iss_parameter_supported", true) - // The client_id is an HTTPS URL serving the client's own metadata; there - // is no registration step and therefore no registration_endpoint. - n.put("client_id_metadata_document_supported", true) - n + m.setSupportsAuthorizationResponseIssuerParam(true) + + val node = mapper.readTree(m.toJSONObject.toJSONString).asInstanceOf[ObjectNode] + // SEP-3149. Not modelled by the SDK version GitBucket ships, so it is set + // on the serialized document; the client_id is an HTTPS URL serving the + // client's own metadata, and there is no registration step and therefore + // no registration_endpoint. + node.put("client_id_metadata_document_supported", true) + node } /** diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala index 321902b..89d704b 100644 --- a/src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/Pkce.scala @@ -1,50 +1,54 @@ package com.newsrx.mcpplugin.oauth -import java.nio.charset.StandardCharsets -import java.security.MessageDigest -import java.util.Base64 +import com.nimbusds.oauth2.sdk.pkce.{CodeChallenge, CodeChallengeMethod, CodeVerifier} /** - * Proof Key for Code Exchange, S256 only (RFC 7636). + * Proof Key for Code Exchange (RFC 7636), S256 only. * - * The `plain` method is not accepted and is not advertised. It protects - * against nothing an attacker who can read the authorization response cannot - * also do, and offering it invites a downgrade: a client that can be talked - * into sending `code_challenge_method=plain` has no protection at all. + * The computation and the verifier's syntax rules come from + * `com.nimbusds:oauth2-oidc-sdk`, which GitBucket already carries on its + * runtime classpath for its own OpenID Connect sign-in. This object is a thin + * adapter: it decides the policy — S256 and nothing else — and converts the + * library's exceptions into a boolean the caller can act on. The base64url + * SHA-256 is the library's, not ours. + * + * The `plain` method is not accepted and not advertised. It protects against + * nothing an attacker who can read the authorization response cannot also do, + * and offering it invites a downgrade: a client that can be talked into + * sending `code_challenge_method=plain` has no protection at all. */ object Pkce { - /** RFC 7636 §4.1: 43–128 characters from the unreserved set. */ - private val VerifierPattern = "^[A-Za-z0-9\\-._~]{43,128}$".r - - /** A challenge is the base64url-no-padding SHA-256 of the verifier. */ - def challengeFor(verifier: String): String = { - val digest = MessageDigest.getInstance("SHA-256") - .digest(verifier.getBytes(StandardCharsets.US_ASCII)) - Base64.getUrlEncoder.withoutPadding.encodeToString(digest) - } - - def isWellFormedVerifier(verifier: String): Boolean = - verifier != null && VerifierPattern.pattern.matcher(verifier).matches() + /** The S256 challenge for a verifier, as RFC 7636 §4.2 defines it. */ + def challengeFor(verifier: String): String = + CodeChallenge.compute(CodeChallengeMethod.S256, new CodeVerifier(verifier)).getValue /** - * Whether `verifier` proves possession of the key behind `challenge`. - * - * The comparison is constant-time. A challenge is not a secret, so this is - * belt-and-braces rather than load-bearing, but the same helper is used for - * values that are secret and a single comparison routine is easier to keep - * right than two. + * Whether `verifier` is syntactically a code verifier: 43–128 characters + * from the unreserved set. Nimbus enforces this in `CodeVerifier`'s + * constructor. */ - def verify(verifier: String, challenge: String): Boolean = { - if (!isWellFormedVerifier(verifier) || challenge == null || challenge.isEmpty) false - else constantTimeEquals(challengeFor(verifier), challenge) - } + def isWellFormedVerifier(verifier: String): Boolean = + try { new CodeVerifier(verifier); true } + catch { case _: IllegalArgumentException | _: NullPointerException => false } + + /** Whether `verifier` proves possession of the key behind `challenge`. */ + def verify(verifier: String, challenge: String): Boolean = + try { + if (challenge == null || challenge.isEmpty) false + else { + val computed = CodeChallenge.compute(CodeChallengeMethod.S256, new CodeVerifier(verifier)) + // Nimbus's CodeChallenge equality is a plain String comparison, so the + // constant-time one is ours. A challenge is not secret, which makes + // this belt-and-braces rather than load-bearing; the same routine is + // used below for values that are secret, and one comparison is easier + // to keep right than two. + Secrets.constantTimeEquals(computed.getValue, challenge) + } + } catch { + case _: IllegalArgumentException | _: NullPointerException => false + } - def constantTimeEquals(a: String, b: String): Boolean = { - val x = a.getBytes(StandardCharsets.UTF_8) - val y = b.getBytes(StandardCharsets.UTF_8) - // MessageDigest.isEqual is constant-time for equal-length inputs and - // short-circuits only on length, which is not secret here. - MessageDigest.isEqual(x, y) - } + /** The method this server accepts, for the metadata document. */ + val supportedMethod: CodeChallengeMethod = CodeChallengeMethod.S256 } diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/Secrets.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/Secrets.scala new file mode 100644 index 0000000..68e7310 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/Secrets.scala @@ -0,0 +1,52 @@ +package com.newsrx.mcpplugin.oauth + +import java.nio.charset.StandardCharsets +import java.security.{MessageDigest, SecureRandom} +import java.util.Base64 + +/** + * Generating and comparing the credentials this server issues. + * + * Nothing novel: `SecureRandom` for entropy and SHA-256 for storage, both + * from the JDK. The only decisions here are how much entropy and what gets + * persisted, and the answer to the second is never the credential itself. + */ +object Secrets { + + private val random = new SecureRandom() + + /** + * A new credential: 256 bits, base64url without padding. + * + * Authorization codes, access tokens and refresh tokens all use this. They + * have very different lifetimes but the same requirement — unguessable — + * and a shorter code would only save bytes in a URL nobody reads. + */ + def newCredential(): String = { + val bytes = new Array[Byte](32) + random.nextBytes(bytes) + Base64.getUrlEncoder.withoutPadding.encodeToString(bytes) + } + + /** + * What goes in the database. + * + * A credential is stored as its SHA-256, so a reader of the table cannot + * authenticate with what they find there. SHA-256 rather than a password + * hash on purpose: these are 256-bit random values, not passwords, so there + * is no dictionary to slow down, and a per-request bcrypt would be a + * denial-of-service surface on the hot path. + */ + def hash(credential: String): String = { + val digest = MessageDigest.getInstance("SHA-256") + .digest(credential.getBytes(StandardCharsets.UTF_8)) + digest.map("%02x".format(_)).mkString + } + + /** Constant-time comparison, for values where timing could leak a secret. */ + def constantTimeEquals(a: String, b: String): Boolean = + if (a == null || b == null) false + else MessageDigest.isEqual( + a.getBytes(StandardCharsets.UTF_8), + b.getBytes(StandardCharsets.UTF_8)) +} diff --git a/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala b/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala index 0dd843d..bdceb64 100644 --- a/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala +++ b/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthFoundationSpec.scala @@ -113,6 +113,19 @@ class OAuthFoundationSpec extends AnyFunSuite with Matchers { .get("authorization_response_iss_parameter_supported").asBoolean() shouldBe true } + test("the authorization server document parses back as RFC 8414 metadata") { + // Round-tripping through the SDK's parser is what establishes that the + // document is well-formed metadata rather than a JSON object that happens + // to have the right key names. + val json = Metadata.authorizationServer(mapper, config).toString + val parsed = com.nimbusds.oauth2.sdk.`as`.AuthorizationServerMetadata.parse(json) + parsed.getIssuer.getValue shouldBe config.issuer + parsed.getAuthorizationEndpointURI.toString shouldBe config.authorizationEndpoint + parsed.getTokenEndpointURI.toString shouldBe config.tokenEndpoint + parsed.getCodeChallengeMethods.size shouldBe 1 + parsed.supportsAuthorizationResponseIssuerParam() shouldBe true + } + test("no OIDC scope or userinfo endpoint is advertised, because neither is implemented") { val n = Metadata.authorizationServer(mapper, config) n.has("userinfo_endpoint") shouldBe false @@ -192,6 +205,20 @@ class OAuthFoundationSpec extends AnyFunSuite with Matchers { challenge should fullyMatch regex "[A-Za-z0-9_-]+" } + test("the challenge agrees with the library's own computation") { + // The SHA-256 and base64url are the SDK's; this asserts the adapter asks + // it rather than reimplementing it beside it. + val verifier = new com.nimbusds.oauth2.sdk.pkce.CodeVerifier("e" * 50) + val fromLibrary = com.nimbusds.oauth2.sdk.pkce.CodeChallenge + .compute(com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod.S256, verifier).getValue + Pkce.challengeFor(verifier.getValue) shouldBe fromLibrary + Pkce.verify(verifier.getValue, fromLibrary) shouldBe true + } + + test("the advertised method is the library's S256 constant") { + Pkce.supportedMethod shouldBe com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod.S256 + } + test("the published RFC 7636 appendix B vector is reproduced") { // An independent value, so this checks the implementation rather than // checking it against itself. From 1cd49dcd20b45c88cd6b490ac4befeab378c3630 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 20:38:42 +0000 Subject: [PATCH 04/29] oauth: grant, code, refresh and token storage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/main/resources/update/mcp-plugin_1.0.xml | 137 ++++++ .../newsrx/mcpplugin/oauth/OAuthStore.scala | 378 +++++++++++++++ .../mcpplugin/oauth/OAuthStoreSpec.scala | 447 ++++++++++++++++++ 3 files changed, 962 insertions(+) create mode 100644 src/main/resources/update/mcp-plugin_1.0.xml create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/oauth/OAuthStoreSpec.scala diff --git a/src/main/resources/update/mcp-plugin_1.0.xml b/src/main/resources/update/mcp-plugin_1.0.xml new file mode 100644 index 0000000..821fc8b --- /dev/null +++ b/src/main/resources/update/mcp-plugin_1.0.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala new file mode 100644 index 0000000..ceb8697 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala @@ -0,0 +1,378 @@ +package com.newsrx.mcpplugin.oauth + +import java.sql.{Connection, Timestamp} +import java.time.Instant + +/** + * What a token resolves to: a live consent, by a known account, for a known + * client and resource, carrying a scope set. + */ +final case class ResolvedGrant( + grantId: String, + userName: String, + clientId: String, + resource: String, + scopes: Set[String] +) + +/** Why an exchange or a token presentation was refused. */ +sealed trait GrantFailure +object GrantFailure { + case object NotFound extends GrantFailure + case object Expired extends GrantFailure + case object Revoked extends GrantFailure + case object AlreadyUsed extends GrantFailure + case object ClientMismatch extends GrantFailure + case object RedirectMismatch extends GrantFailure + case object ResourceMismatch extends GrantFailure + case object PkceFailed extends GrantFailure +} + +/** + * Persistence for OAuth grants, codes and tokens. + * + * Plain JDBC rather than Slick, deliberately. Every security-relevant + * operation here is a conditional write whose row count is the answer — + * "consume this code if it is still unconsumed and unexpired" — and the + * guarantee depends on that being one statement. Written as SQL it is + * visible; generated, it would be something to re-derive from the query + * builder every time the question comes up. + * + * The SQL is ANSI and uses no vendor features, so the same statements run on + * the H2 and PostgreSQL backends GitBucket supports. + */ +object OAuthStore { + + // ── grants ──────────────────────────────────────────────────────────────── + + /** + * Record a consent decision and return its id. + * + * A fresh grant per authorization rather than one updated in place: two + * concurrent authorizations by the same user for the same client are then + * two independent consents, and revoking one does not silently revoke the + * other. + */ + def createGrant(conn: Connection, userName: String, clientId: String, + resource: String, scopes: Set[String], now: Instant): String = { + val grantId = Secrets.newCredential() + val sql = + """INSERT INTO MCP_OAUTH_GRANT + |(GRANT_ID, USER_NAME, CLIENT_ID, RESOURCE, SCOPES, REVOKED, CREATED_AT, UPDATED_AT) + |VALUES (?, ?, ?, ?, ?, ?, ?, ?)""".stripMargin + using(conn.prepareStatement(sql)) { st => + st.setString(1, grantId) + st.setString(2, userName) + st.setString(3, clientId) + st.setString(4, resource) + st.setString(5, McpScope.render(scopes)) + st.setBoolean(6, false) + st.setTimestamp(7, Timestamp.from(now)) + st.setTimestamp(8, Timestamp.from(now)) + st.executeUpdate() + } + grantId + } + + def findGrant(conn: Connection, grantId: String): Option[ResolvedGrant] = + using(conn.prepareStatement( + "SELECT USER_NAME, CLIENT_ID, RESOURCE, SCOPES FROM MCP_OAUTH_GRANT WHERE GRANT_ID = ? AND REVOKED = ?")) { st => + st.setString(1, grantId) + st.setBoolean(2, false) + using(st.executeQuery()) { rs => + if (rs.next()) + Some(ResolvedGrant(grantId, rs.getString(1), rs.getString(2), rs.getString(3), + McpScope.parseRequested(rs.getString(4)))) + else None + } + } + + /** + * Revoke a grant. + * + * This is the single revocation primitive. Revoking consent, revoking a + * refresh token and detecting a replayed refresh token all end here, + * because they all mean the same thing: this consent is over. 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 without a + * second write to race with. + */ + def revokeGrant(conn: Connection, grantId: String, now: Instant): Boolean = + using(conn.prepareStatement( + "UPDATE MCP_OAUTH_GRANT SET REVOKED = ?, UPDATED_AT = ? WHERE GRANT_ID = ? AND REVOKED = ?")) { st => + st.setBoolean(1, true) + st.setTimestamp(2, Timestamp.from(now)) + st.setString(3, grantId) + st.setBoolean(4, false) + st.executeUpdate() == 1 + } + + /** Every live grant for an account, for a consent-management view. */ + def grantsFor(conn: Connection, userName: String): List[ResolvedGrant] = + using(conn.prepareStatement( + "SELECT GRANT_ID, CLIENT_ID, RESOURCE, SCOPES FROM MCP_OAUTH_GRANT WHERE USER_NAME = ? AND REVOKED = ? ORDER BY CREATED_AT")) { st => + st.setString(1, userName) + st.setBoolean(2, false) + using(st.executeQuery()) { rs => + val out = List.newBuilder[ResolvedGrant] + while (rs.next()) + out += ResolvedGrant(rs.getString(1), userName, rs.getString(2), rs.getString(3), + McpScope.parseRequested(rs.getString(4))) + out.result() + } + } + + // ── authorization codes ─────────────────────────────────────────────────── + + def issueCode(conn: Connection, grantId: String, codeChallenge: String, + redirectUri: String, expiresAt: Instant): String = { + val code = Secrets.newCredential() + using(conn.prepareStatement( + """INSERT INTO MCP_OAUTH_CODE (CODE_HASH, GRANT_ID, CODE_CHALLENGE, REDIRECT_URI, EXPIRES_AT, CONSUMED) + |VALUES (?, ?, ?, ?, ?, ?)""".stripMargin)) { st => + st.setString(1, Secrets.hash(code)) + st.setString(2, grantId) + st.setString(3, codeChallenge) + st.setString(4, redirectUri) + st.setTimestamp(5, Timestamp.from(expiresAt)) + st.setBoolean(6, false) + st.executeUpdate() + } + code + } + + /** + * Redeem an authorization code, once. + * + * The consumption is a conditional UPDATE whose row count decides the + * winner, so two simultaneous exchanges of the same code produce exactly + * one token and one `AlreadyUsed`. Checking a flag and then writing it + * would leave a window between the two in which both callers see an unused + * code; there is no such window here, on either backend, because the + * database serialises the update on the row. + * + * Everything the code was bound to is verified: the client that is asking, + * the redirect URI it claims, the resource it wants, and possession of the + * PKCE verifier. A code is not a bearer credential on its own. + */ + def redeemCode(conn: Connection, code: String, clientId: String, redirectUri: String, + resource: Option[String], codeVerifier: String, + now: Instant): Either[GrantFailure, ResolvedGrant] = { + val hash = Secrets.hash(code) + val row = using(conn.prepareStatement( + """SELECT c.GRANT_ID, c.CODE_CHALLENGE, c.REDIRECT_URI, c.EXPIRES_AT, c.CONSUMED, + | g.USER_NAME, g.CLIENT_ID, g.RESOURCE, g.SCOPES, g.REVOKED + | FROM MCP_OAUTH_CODE c JOIN MCP_OAUTH_GRANT g ON g.GRANT_ID = c.GRANT_ID + | WHERE c.CODE_HASH = ?""".stripMargin)) { st => + st.setString(1, hash) + using(st.executeQuery()) { rs => + if (!rs.next()) None + else Some((rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4).toInstant, + rs.getBoolean(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), + rs.getBoolean(10))) + } + } + + row match { + case None => Left(GrantFailure.NotFound) + case Some((grantId, challenge, storedRedirect, expiresAt, consumed, userName, grantClient, + grantResource, scopes, revoked)) => + if (revoked) Left(GrantFailure.Revoked) + else if (consumed) { + // A replayed code means the first one may have been stolen. RFC 6749 + // §10.5 and the OAuth 2.1 guidance both say to revoke what it bought. + revokeGrant(conn, grantId, now) + Left(GrantFailure.AlreadyUsed) + } + else if (!expiresAt.isAfter(now)) Left(GrantFailure.Expired) + else if (!Secrets.constantTimeEquals(clientId, grantClient)) Left(GrantFailure.ClientMismatch) + else if (!Secrets.constantTimeEquals(redirectUri, storedRedirect)) Left(GrantFailure.RedirectMismatch) + else if (resource.exists(r => !Secrets.constantTimeEquals(r, grantResource))) + Left(GrantFailure.ResourceMismatch) + else if (!Pkce.verify(codeVerifier, challenge)) Left(GrantFailure.PkceFailed) + else if (!consumeCode(conn, hash, now)) Left(GrantFailure.AlreadyUsed) + else Right(ResolvedGrant(grantId, userName, grantClient, grantResource, + McpScope.parseRequested(scopes))) + } + } + + /** The atomic step: true for exactly one caller. */ + private def consumeCode(conn: Connection, codeHash: String, now: Instant): Boolean = + using(conn.prepareStatement( + "UPDATE MCP_OAUTH_CODE SET CONSUMED = ? WHERE CODE_HASH = ? AND CONSUMED = ? AND EXPIRES_AT > ?")) { st => + st.setBoolean(1, true) + st.setString(2, codeHash) + st.setBoolean(3, false) + st.setTimestamp(4, Timestamp.from(now)) + st.executeUpdate() == 1 + } + + // ── access tokens ───────────────────────────────────────────────────────── + + def issueAccessToken(conn: Connection, grantId: String, expiresAt: Instant, now: Instant): String = { + val token = Secrets.newCredential() + using(conn.prepareStatement( + "INSERT INTO MCP_OAUTH_TOKEN (TOKEN_HASH, GRANT_ID, EXPIRES_AT, CREATED_AT) VALUES (?, ?, ?, ?)")) { st => + st.setString(1, Secrets.hash(token)) + st.setString(2, grantId) + st.setTimestamp(3, Timestamp.from(expiresAt)) + st.setTimestamp(4, Timestamp.from(now)) + st.executeUpdate() + } + token + } + + /** + * Resolve a presented access token. + * + * One query, joined to the grant, so revocation takes effect here rather + * than depending on a sweep having run. The guarantee this provides is + * about the *authorization check*: after a grant is revoked, no later check + * passes. It says nothing about an operation already past its check and + * executing — that one finishes. + */ + def resolveAccessToken(conn: Connection, token: String, now: Instant): Either[GrantFailure, ResolvedGrant] = + using(conn.prepareStatement( + """SELECT t.GRANT_ID, t.EXPIRES_AT, g.USER_NAME, g.CLIENT_ID, g.RESOURCE, g.SCOPES, g.REVOKED + | FROM MCP_OAUTH_TOKEN t JOIN MCP_OAUTH_GRANT g ON g.GRANT_ID = t.GRANT_ID + | WHERE t.TOKEN_HASH = ?""".stripMargin)) { st => + st.setString(1, Secrets.hash(token)) + using(st.executeQuery()) { rs => + if (!rs.next()) Left(GrantFailure.NotFound) + else if (rs.getBoolean(7)) Left(GrantFailure.Revoked) + else if (!rs.getTimestamp(2).toInstant.isAfter(now)) Left(GrantFailure.Expired) + else Right(ResolvedGrant(rs.getString(1), rs.getString(3), rs.getString(4), + rs.getString(5), McpScope.parseRequested(rs.getString(6)))) + } + } + + // ── refresh tokens ──────────────────────────────────────────────────────── + + def setRefreshToken(conn: Connection, grantId: String, expiresAt: Instant, now: Instant): String = { + val refresh = Secrets.newCredential() + insertRefresh(conn, Secrets.hash(refresh), grantId, expiresAt, now) + refresh + } + + private def insertRefresh(conn: Connection, hash: String, grantId: String, + expiresAt: Instant, now: Instant): Unit = + using(conn.prepareStatement( + "INSERT INTO MCP_OAUTH_REFRESH (TOKEN_HASH, GRANT_ID, EXPIRES_AT, ROTATED, CREATED_AT) VALUES (?, ?, ?, ?, ?)")) { st => + st.setString(1, hash) + st.setString(2, grantId) + st.setTimestamp(3, Timestamp.from(expiresAt)) + st.setBoolean(4, false) + st.setTimestamp(5, Timestamp.from(now)) + st.executeUpdate() + } + + /** + * Rotate a refresh token: the presented one stops working as the new one + * starts. + * + * Rotation is a conditional UPDATE marking the presented row, so concurrent + * refreshes resolve to exactly one winner. The loser is not merely refused. + * A token that is present but already rotated is either a race or a stolen + * copy being replayed, and from the server's side those are + * indistinguishable, so the grant is revoked — which is what OAuth 2.1 asks + * for, and why a well-behaved client must not refresh twice in parallel. + * + * The superseded rows are kept rather than deleted. That is the point: a + * grant that remembered only its current refresh hash could not tell a + * replayed old token from a string that was never issued, and would answer + * "unknown" to the one case that should end the session. An earlier version + * of this code did exactly that, and the concurrency test above is what + * found it. + */ + def rotateRefreshToken(conn: Connection, presented: String, clientId: String, + expiresAt: Instant, now: Instant): Either[GrantFailure, (ResolvedGrant, String)] = { + val presentedHash = Secrets.hash(presented) + + val rotated = using(conn.prepareStatement( + "UPDATE MCP_OAUTH_REFRESH SET ROTATED = ? WHERE TOKEN_HASH = ? AND ROTATED = ? AND EXPIRES_AT > ?")) { st => + st.setBoolean(1, true) + st.setString(2, presentedHash) + st.setBoolean(3, false) + st.setTimestamp(4, Timestamp.from(now)) + st.executeUpdate() == 1 + } + + val grantId = refreshGrantId(conn, presentedHash) + + if (!rotated) { + grantId match { + // Present but not rotatable: already used, or expired. A replay ends + // the grant; an expiry does not, because it is the client being slow + // rather than a credential being somewhere it should not be. + case Some(id) if isRotated(conn, presentedHash) => + revokeGrant(conn, id, now) + Left(GrantFailure.AlreadyUsed) + case Some(_) => Left(GrantFailure.Expired) + case None => Left(GrantFailure.NotFound) + } + } else { + grantId.flatMap(findGrant(conn, _)) match { + case None => + // The row rotated but its grant is gone or revoked. + Left(GrantFailure.Revoked) + case Some(grant) if !Secrets.constantTimeEquals(clientId, grant.clientId) => + revokeGrant(conn, grant.grantId, now) + Left(GrantFailure.ClientMismatch) + case Some(grant) => + val replacement = Secrets.newCredential() + insertRefresh(conn, Secrets.hash(replacement), grant.grantId, expiresAt, now) + Right((grant, replacement)) + } + } + } + + private def refreshGrantId(conn: Connection, hash: String): Option[String] = + using(conn.prepareStatement("SELECT GRANT_ID FROM MCP_OAUTH_REFRESH WHERE TOKEN_HASH = ?")) { st => + st.setString(1, hash) + using(st.executeQuery())(rs => if (rs.next()) Some(rs.getString(1)) else None) + } + + private def isRotated(conn: Connection, hash: String): Boolean = + using(conn.prepareStatement("SELECT ROTATED FROM MCP_OAUTH_REFRESH WHERE TOKEN_HASH = ?")) { st => + st.setString(1, hash) + using(st.executeQuery())(rs => rs.next() && rs.getBoolean(1)) + } + + /** RFC 7009: revoke by either credential type; both end the grant. */ + def revokeByToken(conn: Connection, token: String, now: Instant): Boolean = { + val hash = Secrets.hash(token) + val byAccess = using(conn.prepareStatement( + "SELECT GRANT_ID FROM MCP_OAUTH_TOKEN WHERE TOKEN_HASH = ?")) { st => + st.setString(1, hash) + using(st.executeQuery())(rs => if (rs.next()) Some(rs.getString(1)) else None) + } + byAccess.orElse(refreshGrantId(conn, hash)) + .exists(revokeGrant(conn, _, now)) + } + + // ── housekeeping ────────────────────────────────────────────────────────── + + /** + * Delete expired codes and tokens. + * + * Hygiene, not a security control: nothing here is what makes an expired + * credential stop working, because every read already compares against the + * clock. If this never runs, the tables grow and the system stays correct. + */ + def purgeExpired(conn: Connection, now: Instant): Int = { + val cutoff = Timestamp.from(now) + val codes = using(conn.prepareStatement("DELETE FROM MCP_OAUTH_CODE WHERE EXPIRES_AT < ?")) { st => + st.setTimestamp(1, cutoff); st.executeUpdate() + } + val tokens = using(conn.prepareStatement("DELETE FROM MCP_OAUTH_TOKEN WHERE EXPIRES_AT < ?")) { st => + st.setTimestamp(1, cutoff); st.executeUpdate() + } + val refresh = using(conn.prepareStatement("DELETE FROM MCP_OAUTH_REFRESH WHERE EXPIRES_AT < ?")) { st => + st.setTimestamp(1, cutoff); st.executeUpdate() + } + codes + tokens + refresh + } + + private def using[A <: AutoCloseable, B](resource: A)(body: A => B): B = + try body(resource) finally resource.close() +} diff --git a/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthStoreSpec.scala b/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthStoreSpec.scala new file mode 100644 index 0000000..1fba730 --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/oauth/OAuthStoreSpec.scala @@ -0,0 +1,447 @@ +package com.newsrx.mcpplugin.oauth + +import java.sql.{Connection, DriverManager} +import java.time.Instant +import java.util.concurrent.{Callable, Executors, TimeUnit} +import liquibase.{Contexts, LabelExpression, Liquibase} +import liquibase.database.DatabaseFactory +import liquibase.database.jvm.JdbcConnection +import liquibase.resource.ClassLoaderResourceAccessor +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers +import scala.jdk.CollectionConverters._ + +/** + * The grant store, against a real database, with the real schema. + * + * H2 in memory, created by applying the plugin's own Liquibase changelog — + * so the migration is exercised by every case here rather than being a file + * nobody runs until deployment. The same changelog is what runs on + * PostgreSQL; this suite establishes the logic, not the PostgreSQL DDL, and + * that distinction is kept in the documentation. + * + * The concurrency cases use two real connections and a thread pool. A + * sequential test cannot tell an atomic conditional update from a + * check-then-write, which is exactly the property that matters for + * single-use codes and rotating refresh tokens. + */ +@RunWith(classOf[JUnitRunner]) +class OAuthStoreSpec extends AnyFunSuite with Matchers { + + private val now = Instant.parse("2026-01-01T12:00:00Z") + private val later = now.plusSeconds(60) + private val resource = "https://git.example.com/plugin-mcp/" + private val clientId = "https://client.example.com/.well-known/mcp-client" + private val redirect = "https://chatgpt.com/connector_platform_oauth_redirect" + private val verifier = "v" * 64 + private val challenge = Pkce.challengeFor(verifier) + + private var counter = 0 + + /** A fresh, independently named in-memory database per test. */ + private def freshDb(): String = { + counter += 1 + val name = s"mcpoauth$counter" + val url = s"jdbc:h2:mem:$name;DB_CLOSE_DELAY=-1" + val conn = DriverManager.getConnection(url) + try { + val database = DatabaseFactory.getInstance + .findCorrectDatabaseImplementation(new JdbcConnection(conn)) + // `liquibase` as a local name would shadow the package, so the types + // below could not be resolved. + val lb = new Liquibase("update/mcp-plugin_1.0.xml", + new ClassLoaderResourceAccessor(), database) + lb.update(new Contexts(), new LabelExpression()) + } finally conn.close() + url + } + + private def withDb[A](body: Connection => A): A = { + val url = freshDb() + val conn = DriverManager.getConnection(url) + try body(conn) finally conn.close() + } + + private def seedGrant(conn: Connection, scopes: Set[String] = Set("mcp:read")): String = + OAuthStore.createGrant(conn, "alice", clientId, resource, scopes, now) + + // ── the migration itself ────────────────────────────────────────────────── + + test("the plugin's changelog creates its tables on a blank database") { + withDb { conn => + val md = conn.getMetaData + val tables = { + val rs = md.getTables(null, null, "%", Array("TABLE")) + val b = Set.newBuilder[String] + while (rs.next()) b += rs.getString("TABLE_NAME").toUpperCase + b.result() + } + tables should contain allOf ("MCP_OAUTH_GRANT", "MCP_OAUTH_CODE", "MCP_OAUTH_TOKEN", + "MCP_OAUTH_REFRESH") + } + } + + test("the changelog is idempotent, as an upgrade path requires") { + val url = freshDb() + val conn = DriverManager.getConnection(url) + try { + val database = DatabaseFactory.getInstance + .findCorrectDatabaseImplementation(new JdbcConnection(conn)) + // Running it a second time must not fail or duplicate anything. + noException should be thrownBy new Liquibase("update/mcp-plugin_1.0.xml", + new ClassLoaderResourceAccessor(), database) + .update(new Contexts(), new LabelExpression()) + OAuthStore.grantsFor(conn, "alice") shouldBe empty + } finally conn.close() + } + + // ── bindings: a code is not a bearer credential ─────────────────────────── + + test("a code redeems once, to the grant it was issued for") { + withDb { conn => + val grantId = seedGrant(conn) + val code = OAuthStore.issueCode(conn, grantId, challenge, redirect, later) + val result = OAuthStore.redeemCode(conn, code, clientId, redirect, Some(resource), verifier, now) + result.map(_.userName) shouldBe Right("alice") + result.map(_.scopes) shouldBe Right(Set("mcp:read")) + result.map(_.grantId) shouldBe Right(grantId) + } + } + + test("a code presented by another client is refused") { + withDb { conn => + val code = OAuthStore.issueCode(conn, seedGrant(conn), challenge, redirect, later) + OAuthStore.redeemCode(conn, code, "https://evil.example.com/meta", redirect, + Some(resource), verifier, now) shouldBe Left(GrantFailure.ClientMismatch) + } + } + + test("a code redeemed against a different redirect URI is refused") { + withDb { conn => + val code = OAuthStore.issueCode(conn, seedGrant(conn), challenge, redirect, later) + OAuthStore.redeemCode(conn, code, clientId, "https://evil.example.com/cb", + Some(resource), verifier, now) shouldBe Left(GrantFailure.RedirectMismatch) + } + } + + test("a code redeemed for a different resource is refused") { + withDb { conn => + val code = OAuthStore.issueCode(conn, seedGrant(conn), challenge, redirect, later) + OAuthStore.redeemCode(conn, code, clientId, redirect, + Some("https://other.example.com/plugin-mcp/"), verifier, now) shouldBe + Left(GrantFailure.ResourceMismatch) + } + } + + test("a code redeemed without the PKCE verifier is refused") { + withDb { conn => + val code = OAuthStore.issueCode(conn, seedGrant(conn), challenge, redirect, later) + OAuthStore.redeemCode(conn, code, clientId, redirect, Some(resource), "w" * 64, now) shouldBe + Left(GrantFailure.PkceFailed) + OAuthStore.redeemCode(conn, code, clientId, redirect, Some(resource), "", now) shouldBe + Left(GrantFailure.PkceFailed) + } + } + + test("an expired code is refused") { + withDb { conn => + val code = OAuthStore.issueCode(conn, seedGrant(conn), challenge, redirect, now.minusSeconds(1)) + OAuthStore.redeemCode(conn, code, clientId, redirect, Some(resource), verifier, now) shouldBe + Left(GrantFailure.Expired) + } + } + + test("an unknown code is refused without revealing anything else") { + withDb { conn => + OAuthStore.redeemCode(conn, "not-a-code", clientId, redirect, Some(resource), verifier, now) shouldBe + Left(GrantFailure.NotFound) + } + } + + // ── replay ──────────────────────────────────────────────────────────────── + + test("replaying a code fails and revokes what the first redemption bought") { + withDb { conn => + val grantId = seedGrant(conn) + val code = OAuthStore.issueCode(conn, grantId, challenge, redirect, later) + OAuthStore.redeemCode(conn, code, clientId, redirect, Some(resource), verifier, now).isRight shouldBe true + val token = OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.resolveAccessToken(conn, token, now).isRight shouldBe true + + // A second presentation means the code may have been stolen; the grant + // it bought is no longer trustworthy. + OAuthStore.redeemCode(conn, code, clientId, redirect, Some(resource), verifier, now) shouldBe + Left(GrantFailure.AlreadyUsed) + OAuthStore.resolveAccessToken(conn, token, now) shouldBe Left(GrantFailure.Revoked) + OAuthStore.findGrant(conn, grantId) shouldBe None + } + } + + // ── concurrency ─────────────────────────────────────────────────────────── + + test("two simultaneous redemptions of one code produce exactly one grant") { + val url = freshDb() + val setup = DriverManager.getConnection(url) + val grantId = try seedGrant(setup) finally () + val code = try OAuthStore.issueCode(setup, grantId, challenge, redirect, later) finally setup.close() + + val pool = Executors.newFixedThreadPool(2) + try { + val task = new Callable[Either[GrantFailure, ResolvedGrant]] { + def call(): Either[GrantFailure, ResolvedGrant] = { + val c = DriverManager.getConnection(url) + try OAuthStore.redeemCode(c, code, clientId, redirect, Some(resource), verifier, now) + finally c.close() + } + } + val results = pool.invokeAll(List(task, task).asJava, 30, TimeUnit.SECONDS) + .asScala.map(_.get()).toList + withClue(s"results=$results: ") { + results.count(_.isRight) shouldBe 1 + results.count(_ == Left(GrantFailure.AlreadyUsed)) shouldBe 1 + } + } finally pool.shutdownNow() + } + + test("two simultaneous refreshes produce exactly one new token") { + val url = freshDb() + val setup = DriverManager.getConnection(url) + val refresh = try { + val grantId = seedGrant(setup) + OAuthStore.setRefreshToken(setup, grantId, now.plusSeconds(3600), now) + } finally setup.close() + + val pool = Executors.newFixedThreadPool(2) + try { + val task = new Callable[Either[GrantFailure, (ResolvedGrant, String)]] { + def call(): Either[GrantFailure, (ResolvedGrant, String)] = { + val c = DriverManager.getConnection(url) + try OAuthStore.rotateRefreshToken(c, refresh, clientId, now.plusSeconds(3600), now) + finally c.close() + } + } + val results = pool.invokeAll(List(task, task).asJava, 30, TimeUnit.SECONDS) + .asScala.map(_.get()).toList + withClue(s"results=$results: ") { + results.count(_.isRight) shouldBe 1 + results.count(_ == Left(GrantFailure.AlreadyUsed)) shouldBe 1 + } + } finally pool.shutdownNow() + } + + // ── refresh rotation ────────────────────────────────────────────────────── + + test("rotation replaces the refresh token and the old one stops working") { + withDb { conn => + val grantId = seedGrant(conn) + val first = OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + val Right((grant, second)) = + OAuthStore.rotateRefreshToken(conn, first, clientId, now.plusSeconds(3600), now) + grant.userName shouldBe "alice" + second should not be first + // The second one works; the first is now a replay. + OAuthStore.rotateRefreshToken(conn, second, clientId, now.plusSeconds(3600), now).isRight shouldBe true + } + } + + test("replaying a rotated refresh token revokes the whole grant") { + withDb { conn => + val grantId = seedGrant(conn) + val first = OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.rotateRefreshToken(conn, first, clientId, now.plusSeconds(3600), now).isRight shouldBe true + val token = OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now) + + OAuthStore.rotateRefreshToken(conn, first, clientId, now.plusSeconds(3600), now) shouldBe + Left(GrantFailure.AlreadyUsed) + OAuthStore.findGrant(conn, grantId) shouldBe None + OAuthStore.resolveAccessToken(conn, token, now) shouldBe Left(GrantFailure.Revoked) + } + } + + test("an unknown refresh token fails without revoking anything") { + withDb { conn => + val grantId = seedGrant(conn) + OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.rotateRefreshToken(conn, "never-issued", clientId, now.plusSeconds(3600), now) shouldBe + Left(GrantFailure.NotFound) + OAuthStore.findGrant(conn, grantId).isDefined shouldBe true + } + } + + test("a refresh token presented by another client revokes the grant") { + withDb { conn => + val grantId = seedGrant(conn) + val refresh = OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.rotateRefreshToken(conn, refresh, "https://evil.example.com/meta", + now.plusSeconds(3600), now) shouldBe Left(GrantFailure.ClientMismatch) + OAuthStore.findGrant(conn, grantId) shouldBe None + } + } + + test("an expired refresh token is refused without revoking the grant") { + // Expiry is the client being slow, not a credential being somewhere it + // should not be, so it must not end a consent the user still holds. + withDb { conn => + val grantId = seedGrant(conn) + val refresh = OAuthStore.setRefreshToken(conn, grantId, now.minusSeconds(1), now) + OAuthStore.rotateRefreshToken(conn, refresh, clientId, now.plusSeconds(3600), now) shouldBe + Left(GrantFailure.Expired) + OAuthStore.findGrant(conn, grantId).isDefined shouldBe true + } + } + + test("every token in a rotation chain stays recognisable as a replay") { + // Three rotations deep, the first token must still revoke rather than + // read as a string that was never issued. + withDb { conn => + val grantId = seedGrant(conn) + val t1 = OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + val Right((_, t2)) = OAuthStore.rotateRefreshToken(conn, t1, clientId, now.plusSeconds(3600), now) + val Right((_, t3)) = OAuthStore.rotateRefreshToken(conn, t2, clientId, now.plusSeconds(3600), now) + OAuthStore.rotateRefreshToken(conn, t3, clientId, now.plusSeconds(3600), now).isRight shouldBe true + + OAuthStore.rotateRefreshToken(conn, t1, clientId, now.plusSeconds(3600), now) shouldBe + Left(GrantFailure.AlreadyUsed) + OAuthStore.findGrant(conn, grantId) shouldBe None + } + } + + // ── revocation ──────────────────────────────────────────────────────────── + + test("revoking a grant invalidates every access token it issued, at once") { + withDb { conn => + val grantId = seedGrant(conn) + val tokens = (1 to 3).map(_ => OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now)) + tokens.foreach(t => OAuthStore.resolveAccessToken(conn, t, now).isRight shouldBe true) + + OAuthStore.revokeGrant(conn, grantId, now) shouldBe true + tokens.foreach(t => OAuthStore.resolveAccessToken(conn, t, now) shouldBe Left(GrantFailure.Revoked)) + } + } + + test("revoking by access token ends the grant, not just that token") { + withDb { conn => + val grantId = seedGrant(conn) + val a = OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now) + val b = OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.revokeByToken(conn, a, now) shouldBe true + OAuthStore.resolveAccessToken(conn, b, now) shouldBe Left(GrantFailure.Revoked) + } + } + + test("revoking by refresh token ends the grant") { + withDb { conn => + val grantId = seedGrant(conn) + val refresh = OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + val access = OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.revokeByToken(conn, refresh, now) shouldBe true + OAuthStore.resolveAccessToken(conn, access, now) shouldBe Left(GrantFailure.Revoked) + } + } + + test("revoking an unknown token reports nothing revoked") { + withDb { conn => OAuthStore.revokeByToken(conn, "never-issued", now) shouldBe false } + } + + test("revoking twice is harmless and still reports the first one as the revocation") { + withDb { conn => + val grantId = seedGrant(conn) + OAuthStore.revokeGrant(conn, grantId, now) shouldBe true + OAuthStore.revokeGrant(conn, grantId, now) shouldBe false + } + } + + test("a revoked grant cannot be refreshed back into life") { + withDb { conn => + val grantId = seedGrant(conn) + val refresh = OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.revokeGrant(conn, grantId, now) + OAuthStore.rotateRefreshToken(conn, refresh, clientId, now.plusSeconds(3600), now).isLeft shouldBe true + } + } + + // ── access tokens ───────────────────────────────────────────────────────── + + test("an expired access token is refused even though its grant is live") { + withDb { conn => + val grantId = seedGrant(conn) + val token = OAuthStore.issueAccessToken(conn, grantId, now.minusSeconds(1), now) + OAuthStore.resolveAccessToken(conn, token, now) shouldBe Left(GrantFailure.Expired) + OAuthStore.findGrant(conn, grantId).isDefined shouldBe true + } + } + + test("an unknown access token is refused") { + withDb { conn => + OAuthStore.resolveAccessToken(conn, "never-issued", now) shouldBe Left(GrantFailure.NotFound) + } + } + + test("a token carries the scopes of its grant, not of the request") { + withDb { conn => + val grantId = seedGrant(conn, Set("mcp:read", "mcp:write")) + val token = OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now) + OAuthStore.resolveAccessToken(conn, token, now).map(_.scopes) shouldBe + Right(Set("mcp:read", "mcp:write")) + } + } + + test("two users' grants are isolated from each other") { + withDb { conn => + val alice = OAuthStore.createGrant(conn, "alice", clientId, resource, Set("mcp:write"), now) + val bob = OAuthStore.createGrant(conn, "bob", clientId, resource, Set("mcp:write"), now) + val bobToken = OAuthStore.issueAccessToken(conn, bob, now.plusSeconds(3600), now) + + OAuthStore.revokeGrant(conn, alice, now) + // Revoking Alice's consent must not touch Bob's, and Bob's token must + // still resolve to Bob. + OAuthStore.resolveAccessToken(conn, bobToken, now).map(_.userName) shouldBe Right("bob") + OAuthStore.grantsFor(conn, "alice") shouldBe empty + OAuthStore.grantsFor(conn, "bob").map(_.grantId) shouldBe List(bob) + } + } + + // ── credentials are not stored in the clear ─────────────────────────────── + + test("no credential is recoverable from the tables") { + withDb { conn => + val grantId = seedGrant(conn) + val code = OAuthStore.issueCode(conn, grantId, challenge, redirect, later) + val access = OAuthStore.issueAccessToken(conn, grantId, now.plusSeconds(3600), now) + val refresh = OAuthStore.setRefreshToken(conn, grantId, now.plusSeconds(3600), now) + + def dump(table: String): String = { + val st = conn.createStatement() + try { + val rs = st.executeQuery(s"SELECT * FROM $table") + val md = rs.getMetaData + val sb = new StringBuilder + while (rs.next()) (1 to md.getColumnCount).foreach(i => sb.append(String.valueOf(rs.getObject(i)))) + sb.toString + } finally st.close() + } + val all = dump("MCP_OAUTH_GRANT") + dump("MCP_OAUTH_CODE") + dump("MCP_OAUTH_TOKEN") + + dump("MCP_OAUTH_REFRESH") + all should not include code + all should not include access + all should not include refresh + // The hashes are there, which is what makes a lookup possible at all. + all should include(Secrets.hash(access)) + } + } + + // ── housekeeping is not a security control ──────────────────────────────── + + test("expiry is enforced by the clock, not by the purge having run") { + withDb { conn => + val grantId = seedGrant(conn) + val token = OAuthStore.issueAccessToken(conn, grantId, now.minusSeconds(1), now) + // Nothing has been purged, and it is already refused. + OAuthStore.resolveAccessToken(conn, token, now) shouldBe Left(GrantFailure.Expired) + OAuthStore.purgeExpired(conn, now) should be >= 1 + OAuthStore.resolveAccessToken(conn, token, now) shouldBe Left(GrantFailure.NotFound) + } + } +} From 9a007342d45d93e4cdfea0e6b6440d8c90fdb1ea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 21:01:07 +0000 Subject: [PATCH 05/29] oauth: the HTTP path, bearer authentication and scope enforcement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- docs/authentication.md | 12 + .../com/newsrx/mcpplugin/MCPController.scala | 134 +++++-- .../com/newsrx/mcpplugin/MCPPlugin.scala | 31 +- .../com/newsrx/mcpplugin/mcp/ToolDef.scala | 14 + .../mcpplugin/oauth/AuthenticatedCaller.scala | 39 ++ .../mcpplugin/oauth/ClientMetadata.scala | 199 ++++++++++ .../newsrx/mcpplugin/oauth/ConsentView.scala | 75 ++++ .../mcpplugin/oauth/OAuthEndpoints.scala | 339 ++++++++++++++++++ .../newsrx/mcpplugin/oauth/OAuthStore.scala | 29 +- .../mcpplugin/tools/IdentityTools.scala | 2 + .../newsrx/mcpplugin/tools/IssueTools.scala | 8 + .../mcpplugin/tools/PullRequestTools.scala | 10 + .../mcpplugin/tools/RepositoryTools.scala | 3 + .../com/newsrx/mcpplugin/ToolDefSpec.scala | 3 + .../newsrx/mcpplugin/ToolRegistrySpec.scala | 43 +++ .../mcpplugin/oauth/ClientMetadataSpec.scala | 210 +++++++++++ .../mcpplugin/oauth/OAuthStoreSpec.scala | 73 +++- 17 files changed, 1169 insertions(+), 55 deletions(-) create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/AuthenticatedCaller.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/ClientMetadata.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/ConsentView.scala create mode 100644 src/main/scala/com/newsrx/mcpplugin/oauth/OAuthEndpoints.scala create mode 100644 src/test/scala/com/newsrx/mcpplugin/oauth/ClientMetadataSpec.scala diff --git a/docs/authentication.md b/docs/authentication.md index 8ed66dd..8431a16 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -126,6 +126,18 @@ matters when a grant is withdrawn or an account is disabled. | access token | 1 hour | immediate | | refresh token | 30 days, rotated on use | immediate; reuse of a rotated token revokes the whole grant | +Reuse detection applies to races as well as to theft, because the server +cannot tell them apart. If a client presents the same refresh token twice at +once, one request rotates it and the other sees a token that has already been +rotated — which is exactly what a stolen copy looks like — so the grant is +revoked and **neither** request comes away with a usable credential. A client +must therefore serialise its refreshes. This is what OAuth 2.1 asks for, and +it is tested against two real connections rather than assumed. + +Expiry is treated differently on purpose. An expired refresh token is refused +but does **not** revoke the grant: that is the client being slow, not a +credential being somewhere it should not be. + ## Scopes | Scope | Grants | diff --git a/src/main/scala/com/newsrx/mcpplugin/MCPController.scala b/src/main/scala/com/newsrx/mcpplugin/MCPController.scala index 25e48e6..e52d663 100644 --- a/src/main/scala/com/newsrx/mcpplugin/MCPController.scala +++ b/src/main/scala/com/newsrx/mcpplugin/MCPController.scala @@ -2,6 +2,7 @@ package com.newsrx.mcpplugin import com.fasterxml.jackson.databind.node.ObjectNode import com.newsrx.mcpplugin.mcp.{JsonRpc, ToolRegistry} +import com.newsrx.mcpplugin.oauth._ import com.newsrx.mcpplugin.tools.{AuthorizationError, SessionSupport} import gitbucket.core.controller.ControllerBase import gitbucket.core.model.Account @@ -15,27 +16,28 @@ class MCPController with AccountService with RepositoryService with SystemSettingsService - with SessionSupport { + with SessionSupport + with OAuthEndpoints { // ── Routes ──────────────────────────────────────────────────────────────── post("/plugin-mcp/") { contentType = "application/json; charset=UTF-8" - withAuth { account => - handleJsonRpc(account) + withAuth { caller => + handleJsonRpc(caller) } } // Some MCP clients POST without trailing slash post("/plugin-mcp") { contentType = "application/json; charset=UTF-8" - withAuth { account => - handleJsonRpc(account) + withAuth { caller => + handleJsonRpc(caller) } } get("/plugin-mcp/sse") { - withAuth { account => + withAuth { caller => contentType = "text/event-stream; charset=UTF-8" response.setHeader("Cache-Control", "no-cache") response.setHeader("X-Accel-Buffering", "no") @@ -53,7 +55,7 @@ class MCPController // ── JSON-RPC dispatch ───────────────────────────────────────────────────── - private def handleJsonRpc(account: Account): String = { + private def handleJsonRpc(caller: AuthenticatedCaller): String = { val body = request.body if (body.isEmpty) { return JsonRpc.errorResponse(mapper, None, JsonRpc.InvalidRequest, "empty request body") @@ -79,7 +81,7 @@ class MCPController JsonRpc.successResponse(mapper, req.id, ToolRegistry.listResult(mapper)) case "tools/call" => - handleToolCall(account, req) + handleToolCall(caller, req) case "resources/list" => // Resources not implemented — return empty list @@ -102,7 +104,7 @@ class MCPController } } - private def handleToolCall(account: Account, req: JsonRpc.Request): String = { + private def handleToolCall(caller: AuthenticatedCaller, req: JsonRpc.Request): String = { val params = req.params.getOrElse(mapper.createObjectNode()) val toolName = Option(params.get("name")).map(_.asText("")).getOrElse("") if (toolName.isEmpty) { @@ -117,10 +119,22 @@ class MCPController mapper, req.id, JsonRpc.MethodNotFound, s"unknown tool: $toolName" ) + case Some(tool) if !caller.permits(tool.requiredScope) => + // Distinct from an authentication failure, and distinct in the HTTP + // status too: the credential is good, the consent is not wide enough. + // A client that is told "authenticate again" for this will loop. + oauthConfig.foreach { config => + response.setHeader("WWW-Authenticate", + Metadata.challenge(config, Some(ChallengeError.InsufficientScope))) + } + response.setStatus(HttpServletResponse.SC_FORBIDDEN) + JsonRpc.errorResponse(mapper, req.id, JsonRpc.McpError - 3, + s"insufficient_scope: $toolName requires ${tool.requiredScope.name}") + case Some(tool) => val args = Option(params.get("arguments")).getOrElse(mapper.createObjectNode()) try { - val result = tool.execute(args, account, request, mapper) + val result = tool.execute(args, caller.account, request, mapper) JsonRpc.successResponse(mapper, req.id, result) } catch { // A denial is its own outcome, not an internal failure: reporting it @@ -174,35 +188,89 @@ class MCPController // ── Authentication ──────────────────────────────────────────────────────── - private def withAuth(f: Account => String): String = { - authenticate() match { - case None => - response.setHeader("WWW-Authenticate", "Basic realm=\"GitBucket MCP\"") - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED) + private def withAuth(f: AuthenticatedCaller => String): String = { + authenticateCaller() match { + case Right(caller) => f(caller) + case Left(error) => contentType = "application/json; charset=UTF-8" - JsonRpc.errorResponse( - mapper, None, JsonRpc.McpError, "authentication required" - ) - case Some(account) => - f(account) + response.setStatus(error.status) + response.setHeader("WWW-Authenticate", challengeHeader(error)) + JsonRpc.errorResponse(mapper, None, + if (error == ChallengeError.None_) JsonRpc.McpError else JsonRpc.McpError - 4, + if (error == ChallengeError.None_) "authentication required" else error.description) + } + } + + /** + * The challenge offered when authentication fails. + * + * Both schemes are offered when OAuth is configured, so a Basic client is + * not pushed into a browser flow it cannot perform and an OAuth client can + * still discover where to authorize. + */ + private def challengeHeader(error: ChallengeError): String = { + val basic = "Basic realm=\"GitBucket MCP\"" + oauthConfig match { + case Some(config) => + val bearer = Metadata.challenge(config, + if (error == ChallengeError.None_) None else Some(error)) + s"$bearer, $basic" + case None => basic } } - /** Extract and validate Basic auth credentials. */ - private def authenticate(): Option[Account] = - Option(request.getHeader("Authorization")).flatMap { header => - if (!header.startsWith("Basic ")) return None - try { - val decoded = new String(Base64.getDecoder.decode(header.drop(6).trim), "UTF-8") - val colon = decoded.indexOf(':') - if (colon < 0) return None - val username = decoded.substring(0, colon) - val password = decoded.substring(colon + 1) + /** + * Resolve the caller from the Authorization header. + * + * One header, one scheme, one answer. A Bearer token that does not resolve + * is an error and never a reason to look somewhere else: falling back to + * the browser session would mean a stale or stolen token silently acting as + * whoever happens to be signed in, and falling back to Basic would let a + * client downgrade itself out of its own scope restrictions. + */ + private def authenticateCaller(): Either[ChallengeError, AuthenticatedCaller] = + Option(request.getHeader("Authorization")).map(_.trim).filter(_.nonEmpty) match { + case None => Left(ChallengeError.None_) + case Some(header) if header.regionMatches(true, 0, "Bearer ", 0, 7) => + bearerCaller(header.substring(7).trim) + case Some(header) if header.regionMatches(true, 0, "Basic ", 0, 6) => + basicCaller(header.substring(6).trim) + case Some(_) => Left(ChallengeError.InvalidRequest) + } + + private def bearerCaller(token: String): Either[ChallengeError, AuthenticatedCaller] = + oauthConfig match { + case None => Left(ChallengeError.InvalidToken) + case Some(_) if token.isEmpty => Left(ChallengeError.InvalidRequest) + case Some(_) => + OAuthStore.resolveAccessToken(oauthConn, token, now()) match { + case Left(_) => Left(ChallengeError.InvalidToken) + case Right(grant) => + implicit val s = Database.getSession(request) + // The account is resolved now, not trusted from the grant row: an + // account removed or disabled since consent must stop working + // here, without waiting for the grant to be revoked. + getAccountByUserName(grant.userName, includeRemoved = false) match { + case Some(account) => Right(AuthenticatedCaller.oauth(account, grant)) + case None => Left(ChallengeError.InvalidToken) + } + } + } + + private def basicCaller(encoded: String): Either[ChallengeError, AuthenticatedCaller] = + try { + val decoded = new String(Base64.getDecoder.decode(encoded), "UTF-8") + val colon = decoded.indexOf(':') + if (colon < 0) Left(ChallengeError.InvalidRequest) + else { implicit val session = Database.getSession(request) val settings = loadSystemSettings() - authenticate(settings, username, password) - } catch { - case _: Exception => None + authenticate(settings, decoded.substring(0, colon), decoded.substring(colon + 1)) match { + case Some(account) => Right(AuthenticatedCaller.basic(account)) + case None => Left(ChallengeError.InvalidToken) + } } + } catch { + case _: Exception => Left(ChallengeError.InvalidRequest) } } diff --git a/src/main/scala/com/newsrx/mcpplugin/MCPPlugin.scala b/src/main/scala/com/newsrx/mcpplugin/MCPPlugin.scala index 7868b40..aa4eb63 100644 --- a/src/main/scala/com/newsrx/mcpplugin/MCPPlugin.scala +++ b/src/main/scala/com/newsrx/mcpplugin/MCPPlugin.scala @@ -2,6 +2,7 @@ package com.newsrx.mcpplugin import gitbucket.core.plugin.{Plugin, PluginRegistry} import gitbucket.core.service.SystemSettingsService.SystemSettings +import io.github.gitbucket.solidbase.migration.LiquibaseMigration import io.github.gitbucket.solidbase.model.Version import javax.servlet.ServletContext @@ -9,7 +10,35 @@ class MCPPlugin extends Plugin { override val pluginId = "mcp-plugin" override val pluginName = "MCP Plugin" override val description = "MCP (Model Context Protocol) server for GitBucket" - override val versions = List(new Version("0.1.0")) + // Schema versions, which are not the plugin version. 1.0 is the first one + // to carry a migration: the OAuth grant, code, refresh and token tables. + // Nothing is added here to change what an admin page displays — a version + // without a real schema change would make Solidbase look for a migration + // that does not exist. + override val versions = List( + new Version("0.1.0"), + new Version("1.0", new LiquibaseMigration("update/mcp-plugin_1.0.xml")) + ) + + /** + * Paths that must work without a GitBucket session. + * + * Discovery is read before a client has any credential at all, and the + * token and revocation endpoints are called by the client rather than by a + * browser. `/plugin-mcp/oauth/authorize` is deliberately absent: it is the + * one endpoint that must know who is signed in. + */ + override def anonymousAccessiblePaths( + registry: PluginRegistry, + context: ServletContext, + settings: SystemSettings + ): Seq[String] = Seq( + "/.well-known/oauth-protected-resource", + "/.well-known/oauth-authorization-server", + "/plugin-mcp/oauth/token", + "/plugin-mcp/oauth/revoke", + "/plugin-mcp/health" + ) override def controllers( registry: PluginRegistry, diff --git a/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala b/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala index 8c205d2..5b31cfc 100644 --- a/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala +++ b/src/main/scala/com/newsrx/mcpplugin/mcp/ToolDef.scala @@ -2,6 +2,7 @@ package com.newsrx.mcpplugin.mcp import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.fasterxml.jackson.databind.node.ObjectNode +import com.newsrx.mcpplugin.oauth.McpScope import gitbucket.core.model.Account import javax.servlet.http.HttpServletRequest @@ -10,6 +11,19 @@ trait ToolDef { def name: String def description: String + /** + * The OAuth scope a caller needs to invoke this tool. + * + * Abstract rather than defaulting to [[McpScope.Read]]: a default would be + * the weaker requirement, so a new mutating tool that forgot to declare + * would be callable with a read-only grant and nothing would say so. This + * way it does not compile. + * + * It is one value feeding two places — the advertised policy in + * `tools/list` and the check in the dispatcher — so the two cannot drift. + */ + def requiredScope: McpScope + /** JSON Schema for the `arguments` object. */ def inputSchema(mapper: ObjectMapper): ObjectNode diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/AuthenticatedCaller.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/AuthenticatedCaller.scala new file mode 100644 index 0000000..1789ea2 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/AuthenticatedCaller.scala @@ -0,0 +1,39 @@ +package com.newsrx.mcpplugin.oauth + +import gitbucket.core.model.Account + +/** + * Who is calling, and what they were allowed to ask for. + * + * Both authentication methods end here, which is the point: everything + * downstream sees one shape and cannot accidentally treat an OAuth caller as + * unrestricted by forgetting to look at a scope field that only one branch + * populates. + */ +final case class AuthenticatedCaller( + account: Account, + scopes: Set[String], + /** Present only for OAuth callers; a Basic caller holds no grant. */ + grantId: Option[String] +) { + def permits(required: McpScope): Boolean = required.satisfiedBy(scopes) +} + +object AuthenticatedCaller { + + /** + * A caller who presented the account's own password or personal access + * token. + * + * These credentials are the account, not a delegation of part of it, so + * there is no narrower scope to apply and every scope is held. This is what + * keeps the existing Basic connection working exactly as it did: adding + * OAuth must not quietly restrict a client that was never scoped. + */ + def basic(account: Account): AuthenticatedCaller = + AuthenticatedCaller(account, McpScope.all.map(_.name).toSet, None) + + /** A caller presenting an access token, limited to what was consented to. */ + def oauth(account: Account, grant: ResolvedGrant): AuthenticatedCaller = + AuthenticatedCaller(account, grant.scopes, Some(grant.grantId)) +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/ClientMetadata.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/ClientMetadata.scala new file mode 100644 index 0000000..167685e --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/ClientMetadata.scala @@ -0,0 +1,199 @@ +package com.newsrx.mcpplugin.oauth + +import java.io.{BufferedInputStream, InputStream} +import java.net.{HttpURLConnection, InetAddress, URI, URL} +import java.nio.charset.StandardCharsets +import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} +import scala.jdk.CollectionConverters._ + +/** A client described by its own metadata document (SEP-3149, CIMD). */ +final case class OAuthClient( + clientId: String, + clientName: String, + redirectUris: Set[String] +) { + /** Exact match. A prefix or a host comparison is how redirect validation gets broken. */ + def permits(redirectUri: String): Boolean = redirectUris.contains(redirectUri) +} + +sealed trait ClientMetadataError { def message: String } +object ClientMetadataError { + final case class Rejected(message: String) extends ClientMetadataError + final case class Unreachable(message: String) extends ClientMetadataError + final case class Malformed(message: String) extends ClientMetadataError +} + +/** + * Fetching a client's metadata document. + * + * The client id *is* a URL the caller supplies, and the server then makes a + * request to it. That is a server-side request forgery primitive unless it is + * fenced, and the fence is the interesting part of this file: a GitBucket is + * usually inside a network with things worth reaching. + * + * The rules, each because of a specific way this goes wrong: + * + * - HTTPS only, so the document cannot be substituted on the wire; + * - every resolved address is checked against loopback, link-local, private + * and multicast ranges, so `https://internal.example/` and + * `https://169.254.169.254/` are refused rather than fetched; + * - redirects are not followed at all, so an allowed host cannot bounce the + * request to a refused one — the common bypass of a check done only on the + * first URL; + * - connect and read timeouts, and a hard cap on bytes read, so a slow or + * endless response occupies one request slot briefly instead of a thread + * forever. + * + * Checking the address and then connecting is a time-of-check/time-of-use gap + * in principle: DNS can change between the two. Closing it properly needs a + * socket-level hook that `HttpURLConnection` does not offer, so the address of + * the established connection is verified again after connecting, which closes + * it in practice for the JDK client. + */ +object ClientMetadata { + + private val ConnectTimeoutMs = 5000 + private val ReadTimeoutMs = 5000 + private val MaxBytes = 64 * 1024 + + /** Parse and validate a client id without fetching anything. */ + def validateClientId(clientId: String): Either[ClientMetadataError, URI] = + try { + val uri = new URI(clientId) + if (uri.getScheme == null || uri.getScheme.toLowerCase != "https") + Left(ClientMetadataError.Rejected("client_id must be an https URL")) + else if (uri.getHost == null || uri.getHost.isEmpty) + Left(ClientMetadataError.Rejected("client_id must name a host")) + else if (uri.getFragment != null) + Left(ClientMetadataError.Rejected("client_id must not carry a fragment")) + else if (uri.getUserInfo != null) + Left(ClientMetadataError.Rejected("client_id must not carry user information")) + else Right(uri) + } catch { + case _: Exception => Left(ClientMetadataError.Rejected("client_id is not a valid URL")) + } + + /** True when this address must never be the target of a server-side fetch. */ + def isForbiddenAddress(addr: InetAddress): Boolean = + addr.isLoopbackAddress || addr.isLinkLocalAddress || addr.isSiteLocalAddress || + addr.isAnyLocalAddress || addr.isMulticastAddress || + // 100.64.0.0/10, carrier-grade NAT, not covered by isSiteLocalAddress. + (addr.getAddress.length == 4 && + (addr.getAddress()(0) & 0xff) == 100 && + ((addr.getAddress()(1) & 0xff) >= 64) && ((addr.getAddress()(1) & 0xff) <= 127)) + + /** How a host name becomes addresses; injectable so the policy is testable. */ + type Resolver = String => Array[InetAddress] + + val systemResolver: Resolver = InetAddress.getAllByName + + private def checkHost(host: String, resolve: Resolver): Either[ClientMetadataError, Unit] = + try { + val addresses = resolve(host) + if (addresses.isEmpty) Left(ClientMetadataError.Unreachable(s"cannot resolve $host")) + // Every address, not the first: a host that resolves to one public and + // one private address must not be reachable by retry. + else if (addresses.exists(isForbiddenAddress)) + Left(ClientMetadataError.Rejected(s"$host resolves to a non-public address")) + else Right(()) + } catch { + case _: Exception => Left(ClientMetadataError.Unreachable(s"cannot resolve $host")) + } + + /** + * Fetch and parse a client metadata document. + * + * `open` is injectable so the fetch policy can be tested without a network: + * the SSRF rules are enforced before it is called, and the byte cap after. + */ + def fetch(mapper: ObjectMapper, clientId: String, + open: URL => HttpURLConnection = defaultOpen, + resolve: Resolver = systemResolver): Either[ClientMetadataError, OAuthClient] = + for { + uri <- validateClientId(clientId) + _ <- checkHost(uri.getHost, resolve) + body <- read(uri.toURL, open, resolve) + client <- parse(mapper, clientId, body) + } yield client + + private def read(url: URL, open: URL => HttpURLConnection, + resolve: Resolver): Either[ClientMetadataError, String] = { + var conn: HttpURLConnection = null + try { + conn = open(url) + conn.setRequestMethod("GET") + conn.setConnectTimeout(ConnectTimeoutMs) + conn.setReadTimeout(ReadTimeoutMs) + conn.setInstanceFollowRedirects(false) + conn.setRequestProperty("Accept", "application/json") + val status = conn.getResponseCode + if (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) + Left(ClientMetadataError.Rejected("client metadata must not redirect")) + else if (status != 200) + Left(ClientMetadataError.Unreachable(s"client metadata returned HTTP $status")) + else { + // The connection is established here, so this is the address actually + // used rather than the one resolved a moment ago. + val connected = Option(conn.getURL).map(_.getHost).getOrElse("") + checkHost(connected, resolve) match { + case Left(e) => Left(e) + case Right(_) => Right(readCapped(conn.getInputStream)) + } + } + } catch { + case e: Exception => Left(ClientMetadataError.Unreachable( + s"client metadata could not be fetched: ${e.getClass.getSimpleName}")) + } finally if (conn != null) conn.disconnect() + } + + private def readCapped(in: InputStream): String = { + val buffered = new BufferedInputStream(in) + try { + val out = new java.io.ByteArrayOutputStream() + val buf = new Array[Byte](8192) + var total = 0 + var n = buffered.read(buf) + while (n >= 0 && total < MaxBytes) { + val take = math.min(n, MaxBytes - total) + out.write(buf, 0, take) + total += take + n = buffered.read(buf) + } + new String(out.toByteArray, StandardCharsets.UTF_8) + } finally buffered.close() + } + + def parse(mapper: ObjectMapper, clientId: String, body: String): Either[ClientMetadataError, OAuthClient] = + try { + val node: JsonNode = mapper.readTree(body) + if (node == null || !node.isObject) + Left(ClientMetadataError.Malformed("client metadata is not a JSON object")) + else { + val declaredId = Option(node.get("client_id")).filter(_.isTextual).map(_.asText()) + // A document that names a different client_id is describing someone + // else, and treating it as this client's is how one client's redirect + // list ends up authorising another's. + if (declaredId.exists(_ != clientId)) + Left(ClientMetadataError.Rejected("client metadata declares a different client_id")) + else { + val uris = Option(node.get("redirect_uris")).filter(_.isArray) + .map(_.elements().asScala.filter(_.isTextual).map(_.asText()).toSet) + .getOrElse(Set.empty[String]) + .filter(u => u.startsWith("https://") || u.startsWith("http://localhost")) + if (uris.isEmpty) + Left(ClientMetadataError.Malformed("client metadata declares no usable redirect_uris")) + else + Right(OAuthClient( + clientId = clientId, + clientName = Option(node.get("client_name")).filter(_.isTextual) + .map(_.asText()).filter(_.nonEmpty).getOrElse(clientId), + redirectUris = uris)) + } + } + } catch { + case _: Exception => Left(ClientMetadataError.Malformed("client metadata is not valid JSON")) + } + + private def defaultOpen(url: URL): HttpURLConnection = + url.openConnection().asInstanceOf[HttpURLConnection] +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/ConsentView.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/ConsentView.scala new file mode 100644 index 0000000..86d8088 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/ConsentView.scala @@ -0,0 +1,75 @@ +package com.newsrx.mcpplugin.oauth + +/** + * The consent screen. + * + * Rendered here rather than through a template because every value on it + * comes from somewhere untrusted — the client's own metadata document, and + * query parameters — and the escaping has to be unmissable. A template would + * put the escaping decision one indirection away from the data. + * + * The client name is attacker-controlled: whoever publishes the metadata + * document chooses it. It is escaped, and it is shown next to the client id + * so a name claiming to be something it is not can be seen for what it is. + */ +object ConsentView { + + def escape(raw: String): String = + Option(raw).getOrElse("") + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """) + .replace("'", "'") + + private def scopeLine(scope: String): String = scope match { + case "mcp:read" => "Read your repositories, issues and pull requests" + case "mcp:write" => "Create and change issues, comments and pull requests" + case other => escape(other) + } + + def render(client: OAuthClient, userName: String, scopes: Set[String], + redirectUri: String, state: Option[String], csrfToken: String, + formAction: String): String = { + val items = McpScope.all.map(_.name).filter(scopes.contains).map { s => + s"""
  • ${escape(s)} — ${escape(scopeLine(s))}
  • """ + }.mkString("\n") + + s""" + | + | + | + |Authorize application + | + | + | + |

    Authorize application

    + |
    + |
    ${escape(client.clientName)}
    + |
    ${escape(client.clientId)}
    + |
    + |

    Signed in as ${escape(userName)}. This application is asking to:

    + |
      + |$items + |
    + |

    It will act as you, and only within what your GitBucket account may already do.

    + |
    + | + | + | + | + | + | + | + |
    + | + |""".stripMargin + } +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthEndpoints.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthEndpoints.scala new file mode 100644 index 0000000..61a0193 --- /dev/null +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthEndpoints.scala @@ -0,0 +1,339 @@ +package com.newsrx.mcpplugin.oauth + +import com.fasterxml.jackson.databind.ObjectMapper +import gitbucket.core.controller.ControllerBase +import gitbucket.core.servlet.Database +import java.sql.Connection +import java.time.Instant +import javax.servlet.http.HttpSession + +/** A started authorization, held in the user's session until they decide. */ +private[oauth] final case class PendingAuthorization( + clientId: String, + clientName: String, + redirectUri: String, + scopes: Set[String], + state: Option[String], + codeChallenge: String, + resource: Option[String] +) + +/** + * The authorization server's HTTP surface. + * + * Mixed into the MCP controller so it shares one route table and one database + * session, which is what lets a code be consumed and its token issued inside + * the same transaction. + * + * The pending request lives in the user's HTTP session rather than in hidden + * form fields. A hidden `code_challenge` would be a value the browser could + * be made to change between the consent screen and the decision, and the + * whole point of PKCE is that the challenge is fixed when authorization + * starts. The form carries only an opaque key and a CSRF token. + */ +trait OAuthEndpoints extends ControllerBase { + self: { def mapper: ObjectMapper } => + + private val PendingPrefix = "mcp-oauth-pending:" + private val CsrfAttribute = "mcp-oauth-csrf" + + /** Resolved once per request; absent means OAuth is not configured. */ + protected def oauthConfig: Option[OAuthConfig] = + OAuthConfig.configuredBaseUrl().flatMap(OAuthConfig.fromBaseUrl(_).toOption) + + protected def oauthConn: Connection = Database.getSession(request).conn + + protected def now(): Instant = Instant.now() + + /** Overridable so tests can drive the fetcher without a network. */ + protected def fetchClient(clientId: String): Either[ClientMetadataError, OAuthClient] = + ClientMetadata.fetch(mapper, clientId) + + // ── discovery ───────────────────────────────────────────────────────────── + + get("/.well-known/oauth-protected-resource") { + withConfig { config => + contentType = "application/json; charset=UTF-8" + mapper.writeValueAsString(Metadata.protectedResource(mapper, config)) + } + } + + get("/.well-known/oauth-authorization-server") { + withConfig { config => + contentType = "application/json; charset=UTF-8" + mapper.writeValueAsString(Metadata.authorizationServer(mapper, config)) + } + } + + // ── authorize ───────────────────────────────────────────────────────────── + + get("/plugin-mcp/oauth/authorize") { + withConfig { config => + context.loginAccount match { + // Not signed in: GitBucket's own login, then back here. The plugin + // never sees a password, and the account that consents is whoever + // GitBucket says is signed in. + case None => + redirect(s"/signin?redirect=${urlEncode(request.getRequestURI + queryString)}") + case Some(account) => + startAuthorization(config, account.userName) + } + } + } + + post("/plugin-mcp/oauth/authorize") { + withConfig { config => + context.loginAccount match { + case None => halt(401, "not signed in") + case Some(account) => completeAuthorization(config, account.userName) + } + } + } + + private def startAuthorization(config: OAuthConfig, userName: String): Any = { + val clientId = param("client_id") + val redirectUri = param("redirect_uri") + val responseType = param("response_type") + val challenge = param("code_challenge") + val method = param("code_challenge_method") + val resource = optionalParam("resource") + val state = optionalParam("state") + + // Errors before a validated redirect_uri cannot be sent to the client: + // redirecting to an unvalidated URI is how an authorization server + // becomes an open redirector. + if (clientId.isEmpty || redirectUri.isEmpty) + return badRequest("client_id and redirect_uri are required") + + fetchClient(clientId) match { + case Left(err) => badRequest(s"client_id rejected: ${err.message}") + case Right(client) if !client.permits(redirectUri) => + badRequest("redirect_uri is not registered for this client") + case Right(client) => + // From here the redirect URI is trusted, so protocol errors go back + // to the client as RFC 6749 requires. + if (responseType != "code") + errorRedirect(config, redirectUri, state, "unsupported_response_type") + else if (method != "S256") + errorRedirect(config, redirectUri, state, "invalid_request") + else if (challenge.isEmpty) + errorRedirect(config, redirectUri, state, "invalid_request") + else if (resource.exists(_ != config.resource)) + errorRedirect(config, redirectUri, state, "invalid_target") + else { + val requested = McpScope.parseRequested(param("scope")) + val scopes = if (requested.isEmpty) McpScope.default else requested + val key = Secrets.newCredential() + val pending = PendingAuthorization(client.clientId, client.clientName, redirectUri, + scopes, state, challenge, resource) + httpSession.setAttribute(PendingPrefix + key, pending) + contentType = "text/html; charset=UTF-8" + ConsentView.render(client, userName, scopes, redirectUri, state, + csrfToken(), s"${config.baseUrl}/plugin-mcp/oauth/authorize?k=${urlEncode(key)}") + } + } + } + + private def completeAuthorization(config: OAuthConfig, userName: String): Any = { + val key = param("k") + val attribute = PendingPrefix + key + val pending = Option(httpSession.getAttribute(attribute)).collect { + case p: PendingAuthorization => p + } + + // One use: the pending request is removed whatever the decision, so a + // resubmitted form cannot mint a second code. + httpSession.removeAttribute(attribute) + + pending match { + case None => badRequest("no authorization in progress") + case Some(p) => + if (!Secrets.constantTimeEquals(param("csrf_token"), csrfToken())) + badRequest("invalid CSRF token") + else if (param("decision") != "allow") + errorRedirect(config, p.redirectUri, p.state, "access_denied") + else { + val conn = oauthConn + val issuedAt = now() + val grantId = OAuthStore.createGrant(conn, userName, p.clientId, config.resource, + p.scopes, issuedAt) + val code = OAuthStore.issueCode(conn, grantId, p.codeChallenge, p.redirectUri, + issuedAt.plusSeconds(config.authorizationCodeLifetimeSeconds)) + val params = Seq( + Some("code=" + urlEncode(code)), + // RFC 9207: name the server that answered, so a response cannot be + // taken from one authorization server and replayed to a client + // that expected another. + Some("iss=" + urlEncode(config.issuer)), + p.state.map(s => "state=" + urlEncode(s)) + ).flatten.mkString("&") + redirect(appendQuery(p.redirectUri, params)) + } + } + } + + // ── token ───────────────────────────────────────────────────────────────── + + post("/plugin-mcp/oauth/token") { + withConfig { config => + contentType = "application/json; charset=UTF-8" + response.setHeader("Cache-Control", "no-store") + val conn = oauthConn + param("grant_type") match { + case "authorization_code" => exchangeCode(config, conn) + case "refresh_token" => exchangeRefresh(config, conn) + case "" => tokenError(400, "invalid_request", "grant_type is required") + case other => tokenError(400, "unsupported_grant_type", s"unsupported grant_type") + } + } + } + + private def exchangeCode(config: OAuthConfig, conn: Connection): String = { + val code = param("code") + val clientId = param("client_id") + val redirectUri = param("redirect_uri") + val verifier = param("code_verifier") + val resource = optionalParam("resource") + if (code.isEmpty || clientId.isEmpty || redirectUri.isEmpty || verifier.isEmpty) + return tokenError(400, "invalid_request", "code, client_id, redirect_uri and code_verifier are required") + if (resource.exists(_ != config.resource)) + return tokenError(400, "invalid_target", "resource does not match this server") + + OAuthStore.redeemCode(conn, code, clientId, redirectUri, Some(config.resource), verifier, now()) match { + case Left(failure) => codeFailure(failure) + case Right(grant) => issueTokens(config, conn, grant) + } + } + + private def exchangeRefresh(config: OAuthConfig, conn: Connection): String = { + val refresh = param("refresh_token") + val clientId = param("client_id") + if (refresh.isEmpty || clientId.isEmpty) + return tokenError(400, "invalid_request", "refresh_token and client_id are required") + + val moment = now() + OAuthStore.rotateRefreshToken(conn, refresh, clientId, + moment.plusSeconds(config.refreshTokenLifetimeSeconds), moment) match { + case Left(failure) => refreshFailure(failure) + case Right((grant, replacement)) => + val access = OAuthStore.issueAccessToken(conn, grant.grantId, + moment.plusSeconds(config.accessTokenLifetimeSeconds), moment) + tokenResponse(config, access, Some(replacement), grant.scopes) + } + } + + private def issueTokens(config: OAuthConfig, conn: Connection, grant: ResolvedGrant): String = { + val moment = now() + val access = OAuthStore.issueAccessToken(conn, grant.grantId, + moment.plusSeconds(config.accessTokenLifetimeSeconds), moment) + val refresh = OAuthStore.setRefreshToken(conn, grant.grantId, + moment.plusSeconds(config.refreshTokenLifetimeSeconds), moment) + tokenResponse(config, access, Some(refresh), grant.scopes) + } + + private def tokenResponse(config: OAuthConfig, access: String, refresh: Option[String], + scopes: Set[String]): String = { + val n = mapper.createObjectNode() + n.put("access_token", access) + n.put("token_type", "Bearer") + n.put("expires_in", config.accessTokenLifetimeSeconds) + // Returned so a narrowed grant is visible to the client rather than + // discovered later as a refusal. + n.put("scope", McpScope.render(scopes)) + refresh.foreach(n.put("refresh_token", _)) + mapper.writeValueAsString(n) + } + + /** + * A failed code exchange. + * + * `invalid_grant` for everything the caller could have got wrong about the + * code itself, which is what RFC 6749 §5.2 specifies and also avoids + * telling a prober which part they got right. A binding failure is still a + * binding failure in the store — it does not consume the code and does not + * revoke — so the uniform wire error does not become a uniform effect. + */ + private def codeFailure(failure: GrantFailure): String = failure match { + case GrantFailure.ResourceMismatch => tokenError(400, "invalid_target", "resource does not match") + case _ => tokenError(400, "invalid_grant", "the authorization code is not valid") + } + + private def refreshFailure(failure: GrantFailure): String = + tokenError(400, "invalid_grant", "the refresh token is not valid") + + private def tokenError(status: Int, code: String, description: String): String = { + response.setStatus(status) + val n = mapper.createObjectNode() + n.put("error", code) + n.put("error_description", description) + mapper.writeValueAsString(n) + } + + // ── revoke ──────────────────────────────────────────────────────────────── + + post("/plugin-mcp/oauth/revoke") { + withConfig { _ => + contentType = "application/json; charset=UTF-8" + val token = param("token") + if (token.nonEmpty) OAuthStore.revokeByToken(oauthConn, token, now()) + // RFC 7009 §2.2: an unknown token is a successful revocation. Saying + // otherwise turns this endpoint into an oracle for whether a token + // exists. + response.setStatus(200) + "{}" + } + } + + // ── helpers ─────────────────────────────────────────────────────────────── + + private def withConfig(f: OAuthConfig => Any): Any = oauthConfig match { + case Some(config) => f(config) + case None => + response.setStatus(404) + contentType = "application/json; charset=UTF-8" + """{"error":"oauth_not_configured"}""" + } + + protected def httpSession: HttpSession = request.getSession(true) + + /** A per-session CSRF token, created on first use. */ + protected def csrfToken(): String = { + val s = httpSession + Option(s.getAttribute(CsrfAttribute)).map(_.toString).getOrElse { + val token = Secrets.newCredential() + s.setAttribute(CsrfAttribute, token) + token + } + } + + private def param(name: String): String = + Option(request.getParameter(name)).map(_.trim).getOrElse("") + + private def optionalParam(name: String): Option[String] = + Option(request.getParameter(name)).map(_.trim).filter(_.nonEmpty) + + private def queryString: String = + Option(request.getQueryString).filter(_.nonEmpty).map("?" + _).getOrElse("") + + private def badRequest(message: String): Any = { + response.setStatus(400) + contentType = "text/plain; charset=UTF-8" + message + } + + private def errorRedirect(config: OAuthConfig, redirectUri: String, + state: Option[String], error: String): Any = { + val params = Seq( + Some("error=" + urlEncode(error)), + Some("iss=" + urlEncode(config.issuer)), + state.map(s => "state=" + urlEncode(s)) + ).flatten.mkString("&") + redirect(appendQuery(redirectUri, params)) + } + + private def appendQuery(uri: String, query: String): String = + if (uri.contains("?")) s"$uri&$query" else s"$uri?$query" + + private def urlEncode(value: String): String = + java.net.URLEncoder.encode(value, "UTF-8") +} diff --git a/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala index ceb8697..ece066e 100644 --- a/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala +++ b/src/main/scala/com/newsrx/mcpplugin/oauth/OAuthStore.scala @@ -297,21 +297,26 @@ object OAuthStore { st.executeUpdate() == 1 } - val grantId = refreshGrantId(conn, presentedHash) + // One read, not two. Asking for the grant id and then asking whether the + // row was rotated leaves a gap in which a concurrent winner can commit + // between the two answers, and the loser then classifies a replay as an + // expiry. That gap made the concurrency control intermittently + // disagree with itself, which is how it was found. + val row = refreshRow(conn, presentedHash) if (!rotated) { - grantId match { + row match { // Present but not rotatable: already used, or expired. A replay ends // the grant; an expiry does not, because it is the client being slow // rather than a credential being somewhere it should not be. - case Some(id) if isRotated(conn, presentedHash) => + case Some((id, true)) => revokeGrant(conn, id, now) Left(GrantFailure.AlreadyUsed) - case Some(_) => Left(GrantFailure.Expired) + case Some((_, false)) => Left(GrantFailure.Expired) case None => Left(GrantFailure.NotFound) } } else { - grantId.flatMap(findGrant(conn, _)) match { + row.map(_._1).flatMap(findGrant(conn, _)) match { case None => // The row rotated but its grant is gone or revoked. Left(GrantFailure.Revoked) @@ -326,17 +331,15 @@ object OAuthStore { } } - private def refreshGrantId(conn: Connection, hash: String): Option[String] = - using(conn.prepareStatement("SELECT GRANT_ID FROM MCP_OAUTH_REFRESH WHERE TOKEN_HASH = ?")) { st => + /** The grant a refresh token belongs to, and whether it has been rotated. */ + private def refreshRow(conn: Connection, hash: String): Option[(String, Boolean)] = + using(conn.prepareStatement("SELECT GRANT_ID, ROTATED FROM MCP_OAUTH_REFRESH WHERE TOKEN_HASH = ?")) { st => st.setString(1, hash) - using(st.executeQuery())(rs => if (rs.next()) Some(rs.getString(1)) else None) + using(st.executeQuery())(rs => if (rs.next()) Some((rs.getString(1), rs.getBoolean(2))) else None) } - private def isRotated(conn: Connection, hash: String): Boolean = - using(conn.prepareStatement("SELECT ROTATED FROM MCP_OAUTH_REFRESH WHERE TOKEN_HASH = ?")) { st => - st.setString(1, hash) - using(st.executeQuery())(rs => rs.next() && rs.getBoolean(1)) - } + private def refreshGrantId(conn: Connection, hash: String): Option[String] = + refreshRow(conn, hash).map(_._1) /** RFC 7009: revoke by either credential type; both end the grant. */ def revokeByToken(conn: Connection, token: String, now: Instant): Boolean = { diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala index 82f1be8..e5ad18f 100644 --- a/src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala +++ b/src/main/scala/com/newsrx/mcpplugin/tools/IdentityTools.scala @@ -3,6 +3,7 @@ package com.newsrx.mcpplugin.tools import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.fasterxml.jackson.databind.node.ObjectNode import com.newsrx.mcpplugin.PluginDescriptor +import com.newsrx.mcpplugin.oauth.McpScope import com.newsrx.mcpplugin.mcp.ToolDef import gitbucket.core.model.Account import javax.servlet.http.HttpServletRequest @@ -21,6 +22,7 @@ import javax.servlet.http.HttpServletRequest */ class WhoAmITool extends ToolDef { val name = "whoami" + val requiredScope = McpScope.Read val description = "Return the GitBucket account this MCP connection is authenticated as, plus the self-reported plugin descriptor" diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala index ef8e41e..6bf7acf 100644 --- a/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala +++ b/src/main/scala/com/newsrx/mcpplugin/tools/IssueTools.scala @@ -2,6 +2,7 @@ package com.newsrx.mcpplugin.tools import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.fasterxml.jackson.databind.node.ObjectNode +import com.newsrx.mcpplugin.oauth.McpScope import com.newsrx.mcpplugin.mcp.{StrictArgs, Timestamps, ToolDef} import gitbucket.core.model.{Account, Issue} import gitbucket.core.service.{AccountService, IssuesService, LabelsService, MilestonesService, PrioritiesService, RepositoryService} @@ -39,6 +40,7 @@ private[tools] object IssueJson { class ListIssuesTool extends ToolDef with IssueService { val name = "list_issues" + val requiredScope = McpScope.Read val description = "List issues in a GitBucket repository (excludes pull requests)" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -83,6 +85,7 @@ class ListIssuesTool extends ToolDef with IssueService { class GetIssueTool extends ToolDef with IssueService { val name = "get_issue" + val requiredScope = McpScope.Read val description = "Get details of a specific issue" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -116,6 +119,7 @@ class GetIssueTool extends ToolDef with IssueService { class CreateIssueTool extends ToolDef with IssueService { val name = "create_issue" + val requiredScope = McpScope.Write val description = "Create a new issue in a GitBucket repository" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -161,6 +165,7 @@ class CreateIssueTool extends ToolDef with IssueService { class CloseIssueTool extends ToolDef with IssueService { val name = "close_issue" + val requiredScope = McpScope.Write val description = "Close an issue" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -196,6 +201,7 @@ class CloseIssueTool extends ToolDef with IssueService { class ReopenIssueTool extends ToolDef with IssueService { val name = "reopen_issue" + val requiredScope = McpScope.Write val description = "Reopen a closed issue" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -229,6 +235,7 @@ class ReopenIssueTool extends ToolDef with IssueService { class AddIssueCommentTool extends ToolDef with IssueService { val name = "add_issue_comment" + val requiredScope = McpScope.Write val description = "Add a comment to an issue" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -279,6 +286,7 @@ class AddIssueCommentTool extends ToolDef with IssueService { */ class UpdateOwnCommentTool extends ToolDef with IssueService { val name = "update_own_comment" + val requiredScope = McpScope.Write val description = "Edit a comment written by the authenticated account, with exact read-back of the stored text" def inputSchema(mapper: ObjectMapper) = objectSchema( diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala index 0cfb981..2dcc8f9 100644 --- a/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala +++ b/src/main/scala/com/newsrx/mcpplugin/tools/PullRequestTools.scala @@ -2,6 +2,7 @@ package com.newsrx.mcpplugin.tools import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.fasterxml.jackson.databind.node.ObjectNode +import com.newsrx.mcpplugin.oauth.McpScope import com.newsrx.mcpplugin.mcp.{StrictArgs, Timestamps, ToolDef} import gitbucket.core.model.{Account, Issue, IssueComment, PullRequest} import gitbucket.core.service.{AccountService, ActivityService, CommitsService, IssuesService, LabelsService, MergeService, MilestonesService, PrioritiesService, PullRequestService, RepositoryService, RequestCache, SystemSettingsService, WebHookPullRequestReviewCommentService, WebHookPullRequestService, WebHookService} @@ -111,6 +112,7 @@ private[tools] object PrJson { class ListPullRequestsTool extends ToolDef with PrService { val name = "list_pull_requests" + val requiredScope = McpScope.Read val description = "List pull requests in a GitBucket repository" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -156,6 +158,7 @@ class ListPullRequestsTool extends ToolDef with PrService { class GetPullRequestTool extends ToolDef with PrService { val name = "get_pull_request" + val requiredScope = McpScope.Read val description = "Get details of a specific pull request" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -189,6 +192,7 @@ class GetPullRequestTool extends ToolDef with PrService { class AddPrCommentTool extends ToolDef with PrService { val name = "add_pr_comment" + val requiredScope = McpScope.Write val description = "Add a comment to a pull request" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -228,6 +232,7 @@ class AddPrCommentTool extends ToolDef with PrService { class ClosePullRequestTool extends ToolDef with PrService { val name = "close_pull_request" + val requiredScope = McpScope.Write val description = "Close a pull request without merging" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -263,6 +268,7 @@ class ClosePullRequestTool extends ToolDef with PrService { class ReopenPullRequestTool extends ToolDef with PrService { val name = "reopen_pull_request" + val requiredScope = McpScope.Write val description = "Reopen a closed pull request" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -296,6 +302,7 @@ class ReopenPullRequestTool extends ToolDef with PrService { class GetPrDiffTool extends ToolDef with PrService { val name = "get_pr_diff" + val requiredScope = McpScope.Read val description = "Get the list of files changed in a pull request" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -355,6 +362,7 @@ class GetPrDiffTool extends ToolDef with PrService { */ class GetThreadCommentsTool extends ToolDef with PrService { val name = "get_thread_comments" + val requiredScope = McpScope.Read val description = "Read the comments of an issue or pull request thread, with ids, authors and bounded pagination" val MaxLimit = 50 @@ -427,6 +435,7 @@ class GetThreadCommentsTool extends ToolDef with PrService { */ class UpdatePullRequestTool extends ToolDef with PrService { val name = "update_pull_request" + val requiredScope = McpScope.Write val description = "Update the title and/or body of a pull request, preserving the field that is not supplied" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -519,6 +528,7 @@ class UpdatePullRequestTool extends ToolDef with PrService { */ class MarkReadyForReviewTool extends ToolDef with PrService { val name = "mark_ready_for_review" + val requiredScope = McpScope.Write val description = "Take an open, unmerged draft pull request out of draft using GitBucket's native operation" def inputSchema(mapper: ObjectMapper) = objectSchema( diff --git a/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala b/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala index 50db8d0..449c4e4 100644 --- a/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala +++ b/src/main/scala/com/newsrx/mcpplugin/tools/RepositoryTools.scala @@ -2,6 +2,7 @@ package com.newsrx.mcpplugin.tools import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import com.fasterxml.jackson.databind.node.ObjectNode +import com.newsrx.mcpplugin.oauth.McpScope import com.newsrx.mcpplugin.mcp.ToolDef import gitbucket.core.model.Account import gitbucket.core.service.{AccountService, RepositoryService} @@ -17,6 +18,7 @@ private[tools] trait RepoService class ListRepositoriesTool extends ToolDef with RepoService { val name = "list_repositories" + val requiredScope = McpScope.Read val description = "List repositories accessible to a GitBucket user" def inputSchema(mapper: ObjectMapper) = objectSchema( @@ -63,6 +65,7 @@ class ListRepositoriesTool extends ToolDef with RepoService { class GetRepositoryTool extends ToolDef with RepoService { val name = "get_repository" + val requiredScope = McpScope.Read val description = "Get details of a specific GitBucket repository" def inputSchema(mapper: ObjectMapper) = objectSchema( diff --git a/src/test/scala/com/newsrx/mcpplugin/ToolDefSpec.scala b/src/test/scala/com/newsrx/mcpplugin/ToolDefSpec.scala index 4612ab0..8f502d3 100644 --- a/src/test/scala/com/newsrx/mcpplugin/ToolDefSpec.scala +++ b/src/test/scala/com/newsrx/mcpplugin/ToolDefSpec.scala @@ -132,6 +132,9 @@ class ToolDefSpec extends AnyFunSuite with Matchers { private object TestTool extends ToolDef { val name = "test_tool" val description = "tool for testing helpers" + // Every tool must declare the scope it needs; the member is abstract so + // that a new one cannot silently inherit the weaker requirement. + val requiredScope = com.newsrx.mcpplugin.oauth.McpScope.Read def inputSchema(mapper: ObjectMapper) = objectSchema(mapper, Seq("x"), "x" -> strNode(mapper, "required string")) diff --git a/src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala b/src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala index dee141a..947a83a 100644 --- a/src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala +++ b/src/test/scala/com/newsrx/mcpplugin/ToolRegistrySpec.scala @@ -1,6 +1,7 @@ package com.newsrx.mcpplugin import com.fasterxml.jackson.databind.ObjectMapper +import com.newsrx.mcpplugin.oauth.McpScope import com.newsrx.mcpplugin.mcp.ToolRegistry import org.junit.runner.RunWith import org.scalatestplus.junit.JUnitRunner @@ -110,4 +111,46 @@ class ToolRegistrySpec extends AnyFunSuite with Matchers { PluginDescriptor.get("pluginVersion").trim should not be empty PluginDescriptor.get("pluginId") shouldBe "mcp-plugin" } + + // ── scope policy ────────────────────────────────────────────────────────── + + test("every registered tool declares the scope it requires") { + // The member is abstract, so this cannot fail at runtime — it is here to + // state the invariant the compiler is enforcing, and to fail loudly if a + // default is ever introduced. + ToolRegistry.all(mapper).foreach { t => + withClue(s"${t.name}: ")(Seq(McpScope.Read, McpScope.Write) should contain(t.requiredScope)) + } + } + + test("the read and write split is exactly the published one") { + val byScope = ToolRegistry.all(mapper).groupBy(_.requiredScope).map { + case (k, v) => k -> v.map(_.name).toSet + } + byScope(McpScope.Read) shouldBe Set("whoami", "list_repositories", "get_repository", + "list_issues", "get_issue", "list_pull_requests", "get_pull_request", "get_pr_diff", + "get_thread_comments") + byScope(McpScope.Write) shouldBe Set("create_issue", "close_issue", "reopen_issue", + "add_issue_comment", "update_own_comment", "add_pr_comment", "close_pull_request", + "reopen_pull_request", "update_pull_request", "mark_ready_for_review") + } + + test("no tool whose name reads as a mutation is classified read-only") { + // A cheap independent check on the table above: if someone adds + // `delete_issue` and marks it Read, this notices without the list being + // updated. + val mutating = Seq("create", "close", "reopen", "update", "add", "delete", "merge", "mark") + ToolRegistry.all(mapper) + .filter(t => mutating.exists(t.name.startsWith)) + .foreach(t => withClue(s"${t.name}: ")(t.requiredScope shouldBe McpScope.Write)) + } + + test("a write grant satisfies every tool; a read grant satisfies only the read tools") { + val read = Set("mcp:read") + val write = Set("mcp:write") + val all = ToolRegistry.all(mapper) + all.count(_.requiredScope.satisfiedBy(write)) shouldBe all.size + all.count(_.requiredScope.satisfiedBy(read)) shouldBe 9 + all.count(_.requiredScope.satisfiedBy(Set.empty[String])) shouldBe 0 + } } diff --git a/src/test/scala/com/newsrx/mcpplugin/oauth/ClientMetadataSpec.scala b/src/test/scala/com/newsrx/mcpplugin/oauth/ClientMetadataSpec.scala new file mode 100644 index 0000000..94995e0 --- /dev/null +++ b/src/test/scala/com/newsrx/mcpplugin/oauth/ClientMetadataSpec.scala @@ -0,0 +1,210 @@ +package com.newsrx.mcpplugin.oauth + +import com.fasterxml.jackson.databind.ObjectMapper +import java.net.{HttpURLConnection, InetAddress, URL} +import org.junit.runner.RunWith +import org.scalatestplus.junit.JUnitRunner +import org.scalatest.funsuite.AnyFunSuite +import org.scalatest.matchers.should.Matchers + +/** + * The client metadata fetcher, and the fence around it. + * + * The client id is a URL the caller supplies and the server then requests, so + * these are the controls that keep it from becoming a way to reach things + * inside the network a GitBucket usually sits in. + */ +@RunWith(classOf[JUnitRunner]) +class ClientMetadataSpec extends AnyFunSuite with Matchers { + + private val mapper = new ObjectMapper() + private val clientId = "https://client.example.com/.well-known/mcp-client" + + private def doc(body: String) = ClientMetadata.parse(mapper, clientId, body) + + /** A resolver, so the policy is tested rather than this sandbox's DNS. */ + private def resolvesTo(ip: String): ClientMetadata.Resolver = + (_: String) => Array(InetAddress.getByName(ip)) + + private val publicHost = resolvesTo("93.184.216.34") + + // ── what counts as a client id ──────────────────────────────────────────── + + test("an https client id with a host is accepted") { + ClientMetadata.validateClientId(clientId).isRight shouldBe true + } + + test("a non-https client id is refused") { + Seq("http://client.example.com/m", "file:///etc/passwd", "gopher://x/1", + "ftp://client.example.com/m").foreach { id => + withClue(s"$id: ")(ClientMetadata.validateClientId(id).isLeft shouldBe true) + } + } + + test("a client id carrying credentials or a fragment is refused") { + // user:pass@ can make a URL read as one host and resolve as another. + ClientMetadata.validateClientId("https://user:pw@client.example.com/m").isLeft shouldBe true + ClientMetadata.validateClientId("https://client.example.com/m#x").isLeft shouldBe true + } + + test("a malformed client id is refused rather than thrown") { + Seq("", "not a url", "https://", "https:// space").foreach { id => + withClue(s"[$id]: ")(ClientMetadata.validateClientId(id).isLeft shouldBe true) + } + } + + // ── the SSRF fence ──────────────────────────────────────────────────────── + + test("loopback, link-local, private and carrier-grade addresses are forbidden targets") { + Seq("127.0.0.1", "127.0.0.53", "::1", + "169.254.169.254", // cloud instance metadata + "10.0.0.1", "172.16.0.1", "192.168.1.1", + "100.64.0.1", "100.127.255.254", + "0.0.0.0", "224.0.0.1").foreach { ip => + withClue(s"$ip: ")( + ClientMetadata.isForbiddenAddress(InetAddress.getByName(ip)) shouldBe true) + } + } + + test("ordinary public addresses are permitted targets") { + Seq("93.184.216.34", "8.8.8.8", "2606:2800:220:1:248:1893:25c8:1946").foreach { ip => + withClue(s"$ip: ")( + ClientMetadata.isForbiddenAddress(InetAddress.getByName(ip)) shouldBe false) + } + } + + test("a host resolving to any forbidden address is refused, not just the first") { + // A split-horizon name that answers with one public and one private + // address must not be reachable by retrying. + var opened = false + val mixed: ClientMetadata.Resolver = (_: String) => + Array(InetAddress.getByName("93.184.216.34"), InetAddress.getByName("10.0.0.5")) + ClientMetadata.fetch(mapper, clientId, (_: URL) => { opened = true; null }, mixed).isLeft shouldBe true + opened shouldBe false + } + + test("a fetch succeeds through the real path when every rule is satisfied") { + val body = s"""{"client_id":"$clientId","client_name":"Example","redirect_uris":["https://a.example.com/cb"]}""" + ClientMetadata.fetch(mapper, clientId, (_: URL) => stub(200, body), publicHost) + .map(_.clientName) shouldBe Right("Example") + } + + test("a client id resolving to a forbidden address is refused before any request") { + var opened = false + val result = ClientMetadata.fetch(mapper, clientId, + (_: URL) => { opened = true; null }, resolvesTo("127.0.0.1")) + result shouldBe Left(ClientMetadataError.Rejected( + "client.example.com resolves to a non-public address")) + withClue("the fetcher must refuse before opening a connection: ")(opened shouldBe false) + } + + test("a redirect is refused rather than followed") { + // The classic bypass: an allowed host answers 302 to a forbidden one. + Seq(301, 302, 303, 307, 308).foreach { status => + val result = ClientMetadata.fetch(mapper, clientId, (_: URL) => stub(status, ""), publicHost) + withClue(s"$status: ") { + result shouldBe Left(ClientMetadataError.Rejected("client metadata must not redirect")) + } + } + } + + test("a non-200 response is reported as unreachable, not parsed") { + ClientMetadata.fetch(mapper, clientId, (_: URL) => stub(404, "{}"), publicHost).isLeft shouldBe true + ClientMetadata.fetch(mapper, clientId, (_: URL) => stub(500, "{}"), publicHost).isLeft shouldBe true + } + + test("the response body is capped, so an endless document cannot be read forever") { + val huge = """{"client_id":"""" + clientId + """","redirect_uris":["https://a.example.com/cb"],"pad":"""" + + ("x" * (300 * 1024)) + """"}""" + // Truncated at the cap, so it no longer parses: refused, not consumed. + val result = ClientMetadata.fetch(mapper, clientId, (_: URL) => stub(200, huge), publicHost) + result.isLeft shouldBe true + } + + // ── what a document has to say ──────────────────────────────────────────── + + test("a well-formed document yields the client's name and redirect URIs") { + val result = doc(s"""{"client_id":"$clientId","client_name":"Example Client", + |"redirect_uris":["https://chatgpt.com/connector_platform_oauth_redirect"]}""".stripMargin) + result.map(_.clientName) shouldBe Right("Example Client") + result.map(_.redirectUris) shouldBe Right(Set("https://chatgpt.com/connector_platform_oauth_redirect")) + } + + test("a document declaring a different client_id is refused") { + // Otherwise one client's redirect list could authorise another's. + doc(s"""{"client_id":"https://evil.example.com/m","redirect_uris":["https://a.example.com/cb"]}""") shouldBe + Left(ClientMetadataError.Rejected("client metadata declares a different client_id")) + } + + test("a document with no usable redirect URI is refused") { + doc(s"""{"client_id":"$clientId"}""").isLeft shouldBe true + doc(s"""{"client_id":"$clientId","redirect_uris":[]}""").isLeft shouldBe true + // Non-https redirects are dropped, which leaves none. + doc(s"""{"client_id":"$clientId","redirect_uris":["http://evil.example.com/cb"]}""").isLeft shouldBe true + } + + test("a document that is not JSON, or not an object, is refused") { + Seq("", "not json", "[1,2,3]", "\"a string\"", "null").foreach { body => + withClue(s"[$body]: ")(doc(body).isLeft shouldBe true) + } + } + + test("the client name falls back to the client id rather than being empty") { + doc(s"""{"client_id":"$clientId","client_name":"","redirect_uris":["https://a.example.com/cb"]}""") + .map(_.clientName) shouldBe Right(clientId) + } + + // ── redirect matching ───────────────────────────────────────────────────── + + test("a redirect URI must match exactly") { + val client = OAuthClient(clientId, "C", Set("https://chatgpt.com/connector/oauth/abc")) + client.permits("https://chatgpt.com/connector/oauth/abc") shouldBe true + // Every one of these is a near-miss a prefix or host check would admit. + client.permits("https://chatgpt.com/connector/oauth/abc/..") shouldBe false + client.permits("https://chatgpt.com/connector/oauth/abcd") shouldBe false + client.permits("https://chatgpt.com/connector/oauth/abc?x=1") shouldBe false + client.permits("https://chatgpt.com/connector/oauth/abc#x") shouldBe false + client.permits("https://evil.example.com/connector/oauth/abc") shouldBe false + client.permits("https://chatgpt.com.evil.example.com/connector/oauth/abc") shouldBe false + } + + // ── consent rendering of untrusted values ───────────────────────────────── + + test("a client name cannot inject markup into the consent screen") { + val hostile = """""" + val client = OAuthClient("https://evil.example.com/m\" onload=\"x", hostile, + Set("https://evil.example.com/cb")) + val html = ConsentView.render(client, "alice", Set("mcp:read"), + "https://evil.example.com/cb", Some("s\">"), "csrf", "/plugin-mcp/oauth/authorize?k=1") + html should not include "