fix: align plugin with public API and pass Docker verification

This commit is contained in:
Arnaud Dartois committed 2026-10-29 09:13:09 +01:00
1 parent 537391fe49
commit b1b35832d1
12 files changed
+65 -40

No files matched your search

@@ -5,6 +5,7 @@ description: Use when adding or reviewing configuration, web-service inputs, aut
# Secure coding for this plugin # Secure coding for this plugin
- Require authenticated SonarQube users and check `Create Projects` on every action that enumerates or imports repositories. - 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. - 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. - 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. - 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 ## Not verified
- Exact WebService framework CSRF behavior for custom POST actions must be validated on 25.9 during integration testing. - 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.
@@ -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. - 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. - 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. - 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. - 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. - 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. - 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) - 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) - 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) - 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) - SonarQube project creation REST API: https://docs.sonarsource.com/sonarqube-community-build/project-administration/creating-project/automating-creation (consulted 2026-10-28)
## Not verified ## 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. - 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.
+4
View File
@@ -7,4 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [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 [Unreleased]: http://localhost:3000/owner/bifrost/compare/v0.1.0...HEAD
+1 -1
View File
@@ -8,7 +8,7 @@ COPY .mvn ./.mvn
COPY mvnw mvnw COPY mvnw mvnw
COPY mvnw.cmd mvnw.cmd COPY mvnw.cmd mvnw.cmd
ARG REVISION= 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"; \ sh scripts/render-readme.sh "$version"; \
mvn -B -Drevision="$version" package mvn -B -Drevision="$version" package
+1 -1
View File
@@ -7,7 +7,7 @@ test:
@version=$$(sh scripts/version.sh); sh scripts/render-readme.sh "$$version"; sh ./mvnw -B -Drevision="$$version" test @version=$$(sh scripts/version.sh); sh scripts/render-readme.sh "$$version"; sh ./mvnw -B -Drevision="$$version" test
docker-build: 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 package: build
+6 -5
View File
@@ -11,7 +11,7 @@ Proof of concept plugin that lists Gitea repositories and creates SonarQube Comm
- Generated build version: `@PLUGIN_VERSION@`. - Generated build version: `@PLUGIN_VERSION@`.
- Maven is used because SonarSource publishes the supported plugin packaging extension for Maven. - 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 ## 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: Docker builds the plugin using a pinned Maven/JDK image and exports the JAR without a local JDK or Maven installation:
```sh ```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 ## 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 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 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. - 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 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 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. - Release scripts and workflow are scaffolding and have not been exercised against a real Gitea runner or protected branch.
+2 -11
View File
@@ -3,14 +3,5 @@ set -eu
version=${1:-$(sh scripts/version.sh)} 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; } 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 mkdir -p target
python_bin=${PYTHON:-python3} grep -q '@PLUGIN_VERSION@' README.md || { echo 'README.md is missing the plugin version marker.' >&2; exit 2; }
"$python_bin" - "$version" <<'PY' sed "s/@PLUGIN_VERSION@/$version/g" README.md > target/README.md
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
@@ -8,7 +8,7 @@ import org.sonar.api.Plugin;
public final class BifrostPlugin implements Plugin { public final class BifrostPlugin implements Plugin {
@Override @Override
public void define(Context context) { public void define(Context context) {
context.addExtensions(BifrostProperties.definitions().toArray()); context.addExtensions(BifrostProperties.definitions());
context.addExtensions(ImportPage.class, BifrostWebService.class); context.addExtensions(ImportPage.class, BifrostWebService.class);
} }
} }
@@ -2,6 +2,7 @@ package cc.tordais.sonar.bifrost.page;
import org.sonar.api.web.page.Page; import org.sonar.api.web.page.Page;
import org.sonar.api.web.page.PageDefinition; import org.sonar.api.web.page.PageDefinition;
import org.sonar.api.web.page.Context;
public final class ImportPage implements PageDefinition { public final class ImportPage implements PageDefinition {
@Override @Override
@@ -9,23 +9,22 @@ import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.config.Configuration; import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.LocalConnector;
import org.sonar.api.server.ServerSide; import org.sonar.api.server.ServerSide;
import org.sonar.api.user.UserSession;
import org.sonar.api.permissions.GlobalPermission;
@ServerSide @ServerSide
public final class BifrostWebService implements WebService { public final class BifrostWebService implements WebService {
private static final int MAX_IMPORT_ITEMS = 100; private static final int MAX_IMPORT_ITEMS = 100;
private final Configuration configuration; private final Configuration configuration;
private final UserSession userSession;
public BifrostWebService(Configuration configuration, UserSession userSession) { public BifrostWebService(Configuration configuration) {
this.configuration = configuration; this.configuration = configuration;
this.userSession = userSession;
} }
@Override @Override
@@ -38,19 +37,19 @@ public final class BifrostWebService implements WebService {
} }
private void orgs(Request request, Response response) throws Exception { private void orgs(Request request, Response response) throws Exception {
requirePermission(); requirePermission(request);
GiteaClient client = client(); GiteaClient client = client();
OrganizationPolicy policy = policy(); OrganizationPolicy policy = policy();
List<String> tokenOrganizations = client.organizations(); List<String> tokenOrganizations = client.organizations();
List<String> visible = new java.util.ArrayList<>(policy.visibleOrganizations(tokenOrganizations)); List<String> visible = new java.util.ArrayList<>(policy.visibleOrganizations(tokenOrganizations));
if (configuration.getBoolean(BifrostProperties.INCLUDE_PERSONAL).orElse(false)) visible.add(client.currentUsername()); 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); for (String organization : visible) json.value(organization);
json.endArray().endObject().close(); json.endArray().endObject().close();
} }
private void repos(Request request, Response response) throws Exception { private void repos(Request request, Response response) throws Exception {
requirePermission(); requirePermission(request);
String organization = request.mandatoryParam("org"); String organization = request.mandatoryParam("org");
GiteaClient client = client(); GiteaClient client = client();
String username = configuration.getBoolean(BifrostProperties.INCLUDE_PERSONAL).orElse(false) ? client.currentUsername() : ""; 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."); throw new IllegalArgumentException("The requested organization is not allowed by the plugin configuration.");
} }
List<GiteaRepository> repositories = organization.equals(username) && !username.isEmpty() ? client.personalRepositories() : client.repositories(organization); List<GiteaRepository> 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) { 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(); json.endArray().endObject().close();
} }
private void validateImport(Request request, Response response) throws Exception { private void validateImport(Request request, Response response) throws Exception {
requirePermission(); requirePermission(request);
String payload = request.param("selection"); String payload = request.param("selection");
if (payload == null || payload.length() > 30_000) throw new IllegalArgumentException("The import selection is missing or too large."); if (payload == null || payload.length() > 30_000) throw new IllegalArgumentException("The import selection is missing or too large.");
List<ImportSelection> items = ImportSelection.parse(payload); List<ImportSelection> 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); 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."); 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) { for (ImportSelection item : items) {
GiteaRepository repository = catalog.get(item.organization()).stream().filter(repo -> repo.name().equals(item.repository())).findFirst().orElseThrow(); 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(); 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); return new OrganizationPolicy(allMode, organizations);
} }
private void requirePermission() { private void requirePermission(Request request) throws IOException {
if (!userSession.hasPermission(GlobalPermission.PROVISION_PROJECTS)) { 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."); 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<String, String> 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<String> getMultiParam(String key) { return parameters.containsKey(key) ? List.of(parameters.get(key)) : List.of(); }
public Optional<String> getHeader(String name) { return Optional.empty(); }
public Map<String, String[]> getParameterMap() {
var result = new java.util.HashMap<String, String[]>();
parameters.forEach((key, value) -> result.put(key, new String[] {value}));
return result;
}
}
private record ImportSelection(String organization, String repository) { private record ImportSelection(String organization, String repository) {
static List<ImportSelection> parse(String json) throws IOException { static List<ImportSelection> parse(String json) throws IOException {
var mapper = new com.fasterxml.jackson.databind.ObjectMapper(); var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
-6
View File
@@ -100,12 +100,6 @@
return request("/api/bifrost/repos?org=" + encodeURIComponent(org)).then(function (data) { return data.repositories || []; }); return request("/api/bifrost/repos?org=" + encodeURIComponent(org)).then(function (data) { return data.repositories || []; });
})).then(function (groups) { })).then(function (groups) {
repositories = groups.flat(); 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 () { }).then(function () {
status.textContent = repositories.length + " repositories displayed."; status.textContent = repositories.length + " repositories displayed.";
render(); render();
@@ -27,7 +27,7 @@ class GiteaClientTest {
assertThat(exchange.getRequestHeaders().getFirst("Authorization")).isEqualTo("token test-secret"); assertThat(exchange.getRequestHeaders().getFirst("Authorization")).isEqualTo("token test-secret");
int page = Integer.parseInt(exchange.getRequestURI().getRawQuery().split("[=&]")[1]); int page = Integer.parseInt(exchange.getRequestURI().getRawQuery().split("[=&]")[1]);
requests.incrementAndGet(); 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); byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length); exchange.sendResponseHeaders(200, bytes.length);