diff --git a/.claude/skills/secure-coding-plugin/SKILL.md b/.claude/skills/secure-coding-plugin/SKILL.md index 3094995..26e3f0f 100644 --- a/.claude/skills/secure-coding-plugin/SKILL.md +++ b/.claude/skills/secure-coding-plugin/SKILL.md @@ -5,6 +5,7 @@ description: Use when adding or reviewing configuration, web-service inputs, aut # Secure coding for this plugin - Require authenticated SonarQube users and check `Create Projects` on every action that enumerates or imports repositories. +- Fail closed when the current-user permission response is absent or malformed. Verify local connector authorization behavior on the target instance before deployment. - Treat all browser input as untrusted. Bound batch size and string lengths; validate organization and repository identifiers before API calls. - Validate configured Gitea URL as absolute HTTP(S) with host and no userinfo, query, or fragment. The URL is trusted administrator configuration and may target a private Gitea host; never accept a request-specific outbound URL. - Disable redirects to avoid forwarding the Gitea token; do not expose outbound arbitrary URL input. @@ -27,3 +28,4 @@ description: Use when adding or reviewing configuration, web-service inputs, aut ## Not verified - Exact WebService framework CSRF behavior for custom POST actions must be validated on 25.9 during integration testing. +- Local connector caller identity and `api/users/current` permission shape require a live 25.9 check. diff --git a/.claude/skills/sonarqube-plugin-development/SKILL.md b/.claude/skills/sonarqube-plugin-development/SKILL.md index c361b55..0faa2a0 100644 --- a/.claude/skills/sonarqube-plugin-development/SKILL.md +++ b/.claude/skills/sonarqube-plugin-development/SKILL.md @@ -9,6 +9,7 @@ description: Use when adding or changing Java plugin entry points, extension reg - Use only `org.sonar.api.*` public API. Never import `org.sonar.server.*`, DAO classes, or implementation packages. - Define settings through `PropertyDefinition`; secured values must use a `.secured` key and PASSWORD type. - Add web services using `WebService` and `@ServerSide`; authorize each action explicitly. +- Inspect the pinned API JAR before importing any auth type. `org.sonar.api.user.UserSession` and `org.sonar.api.permissions.GlobalPermission` are absent from API 13.0.0.3026. The current implementation reads current-user permissions through the public `Request.localConnector()` interface and must be checked against the target server's response. - Set key, display name, version and minimum plugin API version in packaging metadata. The manifest `Sonar-Version` is an API version, not a SonarQube product release. Keep the minimum tested server release separately. - Use SLF4J supplied by the host; never package logging implementations or log credentials. - Verify extension APIs against the exact API artifact/Javadoc when changing the target release. @@ -25,7 +26,9 @@ description: Use when adding or changing Java plugin entry points, extension reg - SonarQube Community Build Plugin basics: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/developing-a-plugin/plugin-basics (consulted 2026-10-28) - SonarSource API compatibility matrix: https://github.com/SonarSource/sonar-plugin-api (consulted 2026-10-28) - SonarQube target dependency metadata: https://central.sonatype.com/artifact/org.sonarsource.sonarqube/sonar-core/25.9.0.112764 (consulted 2026-10-28) +- Pinned API source artifact: https://repo.maven.apache.org/maven2/org/sonarsource/api/plugin/sonar-plugin-api/13.0.0.3026/sonar-plugin-api-13.0.0.3026-sources.jar (consulted 2026-10-28) - SonarQube project creation REST API: https://docs.sonarsource.com/sonarqube-community-build/project-administration/creating-project/automating-creation (consulted 2026-10-28) ## Not verified - Full target-tag SonarQube source checkout was not available; API pin follows target dependency metadata and the published 25.8/25.10 compatibility table. +- The target server's `api/users/current` permissions response and local connector caller context were not tested live. diff --git a/CHANGELOG.md b/CHANGELOG.md index 808c47e..32279fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,4 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- Replace unavailable plugin API permission classes with a public local connector check and return existing-project status from the repository service. + [Unreleased]: http://localhost:3000/owner/bifrost/compare/v0.1.0...HEAD diff --git a/Dockerfile b/Dockerfile index b2c3243..7569dc2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,7 +8,7 @@ COPY .mvn ./.mvn COPY mvnw mvnw COPY mvnw.cmd mvnw.cmd ARG REVISION= -RUN version="$REVISION"; if [ -z "$version" ]; then version="$(sh scripts/version.sh)"; fi; \ +RUN set -eu; version="$REVISION"; if [ -z "$version" ]; then version="$(sh scripts/version.sh)"; fi; \ sh scripts/render-readme.sh "$version"; \ mvn -B -Drevision="$version" package diff --git a/Makefile b/Makefile index a61526d..3598e2e 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ test: @version=$$(sh scripts/version.sh); sh scripts/render-readme.sh "$$version"; sh ./mvnw -B -Drevision="$$version" test docker-build: - docker build --target export --output type=local,dest=dist . + @version=$$(sh scripts/version.sh); docker build --build-arg REVISION="$$version" --target export --output type=local,dest=dist . package: build diff --git a/README.md b/README.md index 5f2426b..8409b11 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Proof of concept plugin that lists Gitea repositories and creates SonarQube Comm - Generated build version: `@PLUGIN_VERSION@`. - Maven is used because SonarSource publishes the supported plugin packaging extension for Maven. -The source and deployment scaffolding are present. This environment did not have Java or Maven installed, and Docker could not connect to its engine. The JAR, tests, live Gitea calls, and browser behavior have not been verified here. +The Docker build completed with Java 17, all eight unit tests passed, and the exported JAR manifest contains the expected plugin key, class, version, name, and minimum plugin API version. Live Gitea calls, SonarQube startup, and browser behavior have not been verified here. ## Tree @@ -57,10 +57,10 @@ On Windows, run `mvnw.cmd -B -Drevision=1.2.3 verify`. To force a version manual Docker builds the plugin using a pinned Maven/JDK image and exports the JAR without a local JDK or Maven installation: ```sh -docker build --target export --output type=local,dest=dist . +docker build --build-arg REVISION="$(sh scripts/version.sh)" --target export --output type=local,dest=dist . ``` -Pass a version with `--build-arg REVISION=1.2.3`. The build stage uses `scripts/version.sh` when `REVISION` is empty. +Pass a version with `--build-arg REVISION=1.2.3`. The Docker context excludes Git metadata, so pass the output of `scripts/version.sh` from the host to preserve tag-based versions. A direct Docker build without `REVISION` uses the no-Git fallback. ## Install and configure @@ -144,8 +144,9 @@ When the SonarQube target changes, update version-sensitive skill claims only af - The manifest `Sonar-Version` denotes the minimum plugin API version. The separate `sonar.minimumVersion` property records the target product release because the documented manifest field does not encode a SonarQube product version. - The UTF-8 plugin display name is set to ASCII `Bifrost` because manifest encoding has not yet been confirmed by inspecting a built JAR. - The page uses public same-origin REST endpoints `api/projects/create` and `api/project_links/create`. Endpoint parameter and permission behavior should be verified on a live 25.9 instance. -- Existing-project detection uses the current user's `api/projects/search` visibility. Projects the user cannot browse may appear unimported; duplicate creation is still rejected by SonarQube and reported. +- Existing-project detection uses `api/components/show` through the public `LocalConnector` for each repository. Projects the user cannot browse may return a permission error; the importer stops that organization list rather than guessing that those projects are missing. +- Create Projects permission is checked against `api/users/current` through `LocalConnector`. Its response shape and preservation of the caller context need verification on a live 25.9 instance. - The global page menu is not conditionally hidden by Create Projects permission because the public page API documents only administrator gating. Every data and import web service checks Create Projects; direct same-origin project creation is also enforced by SonarQube. Menu hiding is a UI limitation. - The Gitea token scope and response fields may vary by Gitea version. The local Compose default is Gitea 1.23.8; no external instance was supplied. -- The Maven launcher is a small pinned-distribution bootstrap, not the upstream Maven Wrapper JAR implementation. It requires network access for initial Maven download and has not been validated in this environment. +- The Maven launcher is a small pinned-distribution bootstrap, not the upstream Maven Wrapper JAR implementation. It requires network access for initial Maven download; the Docker build used Maven directly. - Release scripts and workflow are scaffolding and have not been exercised against a real Gitea runner or protected branch. diff --git a/scripts/render-readme.sh b/scripts/render-readme.sh index 34c32e8..790ebc6 100644 --- a/scripts/render-readme.sh +++ b/scripts/render-readme.sh @@ -3,14 +3,5 @@ set -eu version=${1:-$(sh scripts/version.sh)} printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$' || { echo 'Invalid plugin version.' >&2; exit 2; } mkdir -p target -python_bin=${PYTHON:-python3} -"$python_bin" - "$version" <<'PY' -import sys -from pathlib import Path - -version = sys.argv[1] -source = Path("README.md").read_text(encoding="utf-8") -if "@PLUGIN_VERSION@" not in source: - raise SystemExit("README.md is missing the plugin version marker.") -Path("target/README.md").write_text(source.replace("@PLUGIN_VERSION@", version), encoding="utf-8") -PY +grep -q '@PLUGIN_VERSION@' README.md || { echo 'README.md is missing the plugin version marker.' >&2; exit 2; } +sed "s/@PLUGIN_VERSION@/$version/g" README.md > target/README.md diff --git a/src/main/java/cc/tordais/sonar/bifrost/BifrostPlugin.java b/src/main/java/cc/tordais/sonar/bifrost/BifrostPlugin.java index 70d3bfd..80a40d2 100644 --- a/src/main/java/cc/tordais/sonar/bifrost/BifrostPlugin.java +++ b/src/main/java/cc/tordais/sonar/bifrost/BifrostPlugin.java @@ -8,7 +8,7 @@ import org.sonar.api.Plugin; public final class BifrostPlugin implements Plugin { @Override public void define(Context context) { - context.addExtensions(BifrostProperties.definitions().toArray()); + context.addExtensions(BifrostProperties.definitions()); context.addExtensions(ImportPage.class, BifrostWebService.class); } } diff --git a/src/main/java/cc/tordais/sonar/bifrost/page/ImportPage.java b/src/main/java/cc/tordais/sonar/bifrost/page/ImportPage.java index 14b5ba3..0c7666b 100644 --- a/src/main/java/cc/tordais/sonar/bifrost/page/ImportPage.java +++ b/src/main/java/cc/tordais/sonar/bifrost/page/ImportPage.java @@ -2,6 +2,7 @@ package cc.tordais.sonar.bifrost.page; import org.sonar.api.web.page.Page; import org.sonar.api.web.page.PageDefinition; +import org.sonar.api.web.page.Context; public final class ImportPage implements PageDefinition { @Override diff --git a/src/main/java/cc/tordais/sonar/bifrost/ws/BifrostWebService.java b/src/main/java/cc/tordais/sonar/bifrost/ws/BifrostWebService.java index 8f1765d..e9fffc8 100644 --- a/src/main/java/cc/tordais/sonar/bifrost/ws/BifrostWebService.java +++ b/src/main/java/cc/tordais/sonar/bifrost/ws/BifrostWebService.java @@ -9,23 +9,22 @@ import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.Optional; import org.sonar.api.config.Configuration; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; +import org.sonar.api.server.ws.LocalConnector; import org.sonar.api.server.ServerSide; -import org.sonar.api.user.UserSession; -import org.sonar.api.permissions.GlobalPermission; @ServerSide public final class BifrostWebService implements WebService { private static final int MAX_IMPORT_ITEMS = 100; private final Configuration configuration; - private final UserSession userSession; - public BifrostWebService(Configuration configuration, UserSession userSession) { + public BifrostWebService(Configuration configuration) { this.configuration = configuration; - this.userSession = userSession; } @Override @@ -38,19 +37,19 @@ public final class BifrostWebService implements WebService { } private void orgs(Request request, Response response) throws Exception { - requirePermission(); + requirePermission(request); GiteaClient client = client(); OrganizationPolicy policy = policy(); List tokenOrganizations = client.organizations(); List visible = new java.util.ArrayList<>(policy.visibleOrganizations(tokenOrganizations)); if (configuration.getBoolean(BifrostProperties.INCLUDE_PERSONAL).orElse(false)) visible.add(client.currentUsername()); - var json = response.newJsonWriter().beginObject().beginArray("organizations"); + var json = response.newJsonWriter().beginObject().name("organizations").beginArray(); for (String organization : visible) json.value(organization); json.endArray().endObject().close(); } private void repos(Request request, Response response) throws Exception { - requirePermission(); + requirePermission(request); String organization = request.mandatoryParam("org"); GiteaClient client = client(); String username = configuration.getBoolean(BifrostProperties.INCLUDE_PERSONAL).orElse(false) ? client.currentUsername() : ""; @@ -58,15 +57,15 @@ public final class BifrostWebService implements WebService { throw new IllegalArgumentException("The requested organization is not allowed by the plugin configuration."); } List repositories = organization.equals(username) && !username.isEmpty() ? client.personalRepositories() : client.repositories(organization); - var json = response.newJsonWriter().beginObject().beginArray("repositories"); + var json = response.newJsonWriter().beginObject().name("repositories").beginArray(); for (GiteaRepository repository : repositories) { - json.beginObject().prop("org", repository.organization()).prop("name", repository.name()).prop("defaultBranch", repository.defaultBranch()).prop("url", repository.htmlUrl()).endObject(); + json.beginObject().prop("org", repository.organization()).prop("name", repository.name()).prop("defaultBranch", repository.defaultBranch()).prop("url", repository.htmlUrl()).prop("alreadyImported", projectExists(request, ProjectKey.of(repository.organization(), repository.name()))).endObject(); } json.endArray().endObject().close(); } private void validateImport(Request request, Response response) throws Exception { - requirePermission(); + requirePermission(request); String payload = request.param("selection"); if (payload == null || payload.length() > 30_000) throw new IllegalArgumentException("The import selection is missing or too large."); List items = ImportSelection.parse(payload); @@ -95,7 +94,7 @@ public final class BifrostWebService implements WebService { String previous = keys.putIfAbsent(ProjectKey.of(item.organization(), item.repository()), identity); if (previous != null && !previous.equals(identity)) throw new IllegalArgumentException("The selection contains repositories that produce the same SonarQube project key."); } - var json = response.newJsonWriter().beginObject().prop("validated", items.size()).beginArray("repositories"); + var json = response.newJsonWriter().beginObject().prop("validated", items.size()).name("repositories").beginArray(); for (ImportSelection item : items) { GiteaRepository repository = catalog.get(item.organization()).stream().filter(repo -> repo.name().equals(item.repository())).findFirst().orElseThrow(); json.beginObject().prop("org", repository.organization()).prop("repo", repository.name()).prop("name", repository.name()).prop("url", repository.htmlUrl()).prop("defaultBranch", repository.defaultBranch()).endObject(); @@ -116,12 +115,42 @@ public final class BifrostWebService implements WebService { return new OrganizationPolicy(allMode, organizations); } - private void requirePermission() { - if (!userSession.hasPermission(GlobalPermission.PROVISION_PROJECTS)) { + private void requirePermission(Request request) throws IOException { + LocalConnector.LocalResponse current = request.localConnector().call(new LocalApiRequest("api/users/current", Map.of())); + if (current.getStatus() != 200) throw new IllegalStateException("The current SonarQube user could not be verified."); + var user = new com.fasterxml.jackson.databind.ObjectMapper().readTree(current.getBytes()); + var permissions = user.path("permissions").path("global"); + boolean allowed = false; + for (var permission : permissions) { + if ("provisioning".equals(permission.asText()) || "admin".equals(permission.asText())) allowed = true; + } + if (!allowed) { throw new IllegalStateException("You need the Create Projects permission to use Bifrost."); } } + private boolean projectExists(Request request, String key) { + LocalConnector.LocalResponse result = request.localConnector().call(new LocalApiRequest("api/components/show", Map.of("component", key))); + if (result.getStatus() == 200) return true; + if (result.getStatus() == 404) return false; + throw new IllegalStateException("SonarQube could not check whether a project already exists (HTTP " + result.getStatus() + ")."); + } + + private record LocalApiRequest(String path, Map parameters) implements LocalConnector.LocalRequest { + public String getPath() { return path; } + public String getMediaType() { return "application/json"; } + public String getMethod() { return "GET"; } + public boolean hasParam(String key) { return parameters.containsKey(key); } + public String getParam(String key) { return parameters.get(key); } + public List getMultiParam(String key) { return parameters.containsKey(key) ? List.of(parameters.get(key)) : List.of(); } + public Optional getHeader(String name) { return Optional.empty(); } + public Map getParameterMap() { + var result = new java.util.HashMap(); + parameters.forEach((key, value) -> result.put(key, new String[] {value})); + return result; + } + } + private record ImportSelection(String organization, String repository) { static List parse(String json) throws IOException { var mapper = new com.fasterxml.jackson.databind.ObjectMapper(); diff --git a/src/main/resources/static/import.js b/src/main/resources/static/import.js index 5fe9078..6f8a4d8 100644 --- a/src/main/resources/static/import.js +++ b/src/main/resources/static/import.js @@ -100,12 +100,6 @@ return request("/api/bifrost/repos?org=" + encodeURIComponent(org)).then(function (data) { return data.repositories || []; }); })).then(function (groups) { repositories = groups.flat(); - const keys = repositories.map(function (repo) { return keyOf(repo.org, repo.name); }); - if (!keys.length) return { projects: [] }; - return request("/api/projects/search?projects=" + encodeURIComponent(keys.join(","))).then(function (data) { - const known = new Set((data.components || []).map(function (component) { return component.key; })); - repositories.forEach(function (repo) { repo.alreadyImported = known.has(keyOf(repo.org, repo.name)); }); - }); }).then(function () { status.textContent = repositories.length + " repositories displayed."; render(); diff --git a/src/test/java/cc/tordais/sonar/bifrost/gitea/GiteaClientTest.java b/src/test/java/cc/tordais/sonar/bifrost/gitea/GiteaClientTest.java index 8368ee5..218743d 100644 --- a/src/test/java/cc/tordais/sonar/bifrost/gitea/GiteaClientTest.java +++ b/src/test/java/cc/tordais/sonar/bifrost/gitea/GiteaClientTest.java @@ -27,7 +27,7 @@ class GiteaClientTest { assertThat(exchange.getRequestHeaders().getFirst("Authorization")).isEqualTo("token test-secret"); int page = Integer.parseInt(exchange.getRequestURI().getRawQuery().split("[=&]")[1]); requests.incrementAndGet(); - String body = page == 1 ? "[" + "{\"username\":\"org" + "\"},".repeat(49) + "{\"username\":\"last\"}]" : "[]"; + String body = page == 1 ? "[" + "{\"username\":\"org\"},".repeat(49) + "{\"username\":\"last\"}]" : "[]"; byte[] bytes = body.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.sendResponseHeaders(200, bytes.length);