feat: create imported projects through public web APIs

This commit is contained in:
Arnaud Dartois committed 2026-10-29 09:23:05 +01:00
1 parent 9600d35501
commit 9008ecde5b
5 files changed
+61 -33

No files matched your search

@@ -13,7 +13,7 @@ description: Use when adding or changing Java plugin entry points, extension reg
- 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.
- For project creation, prefer the browser's same-origin public SonarQube REST call when the logged-in user's session must be preserved; do not invoke internal project creation services from a plugin endpoint.
- For project creation within a web service, use `Request.localConnector()` to call public SonarQube Web APIs in the current request context; never invoke internal project creation services.
## Checklist
- [ ] Entry point and only public API types.
+5 -1
View File
@@ -7,8 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- Add Gitea organization and repository browsing, selection, server-side validation, project creation, and repository links.
### Fixed
- Replace unavailable plugin API permission classes with a public local connector check and return existing-project status from the repository service.
- Check Create Projects permission and report existing-project status through SonarQube's public Web APIs.
[Unreleased]: http://localhost:3000/owner/bifrost/compare/v0.1.0...HEAD
+3 -3
View File
@@ -69,7 +69,7 @@ Pass a version with `--build-arg REVISION=1.2.3`. The Docker context excludes Gi
3. Grant the user the global Create Projects permission.
4. Open Import from Gitea, select organizations or All, select repositories, then choose Import.
The token is held only by the plugin server. Project creation and repository-link creation use same-origin SonarQube REST requests from the logged-in browser session. The plugin API checks the caller's Create Projects permission and revalidates each selected organization before returning approval.
The token is held only by the plugin server. The plugin checks the caller's Create Projects permission, revalidates each selected organization and repository, then calls SonarQube's public project and project-link Web APIs through `Request.localConnector()`.
## Test scenario
@@ -143,10 +143,10 @@ When the SonarQube target changes, update version-sensitive skill claims only af
- The official plugin API compatibility table omits Community Build 25.9. `13.0.0.3026` was inferred from target server dependency metadata and adjacent releases; the plugin has now built and loaded successfully on the exact 25.9.0.112764 image.
- 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 same-origin REST endpoints `api/projects/create` and `api/project_links/create`. Their authenticated parameter and permission behavior still needs a browser import test.
- The `/api/bifrost/import` action creates projects and their Gitea links through the public `LocalConnector`. The project creation endpoint is documented for Create Projects users; creating links requires project administration. A full authenticated import still needs a browser check.
- 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`. The unauthenticated route correctly returns HTTP 401, but permission parsing and caller context still need an authenticated check.
- 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; the project and link Web APIs apply their own permissions. 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; 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.
@@ -32,7 +32,7 @@ public final class BifrostWebService implements WebService {
WebService.NewController controller = context.createController("api/bifrost");
controller.createAction("orgs").setDescription("List configured Gitea organizations.").setSince("1.0").setHandler(this::orgs);
controller.createAction("repos").setDescription("List repositories for one allowed organization.").setSince("1.0").setHandler(this::repos).createParam("org").setRequired(true).setExampleValue("engineering");
controller.createAction("import").setDescription("Validate a bounded repository import selection.").setSince("1.0").setPost(true).setHandler(this::validateImport).createParam("selection").setRequired(true).setDescription("JSON array of organization and repository names.");
controller.createAction("import").setDescription("Create projects for a bounded repository selection.").setSince("1.0").setPost(true).setHandler(this::importRepositories).createParam("selection").setRequired(true).setDescription("JSON array of organization and repository names.");
controller.done();
}
@@ -64,7 +64,7 @@ public final class BifrostWebService implements WebService {
json.endArray().endObject().close();
}
private void validateImport(Request request, Response response) throws Exception {
private void importRepositories(Request request, Response response) throws Exception {
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.");
@@ -94,10 +94,37 @@ 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()).name("repositories").beginArray();
var json = response.newJsonWriter().beginObject().prop("processed", items.size()).name("results").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();
String key = ProjectKey.of(repository.organization(), repository.name());
String status;
String message;
try {
if (projectExists(request, key)) {
status = "already_exists";
message = "Project already exists.";
} else {
LocalConnector.LocalResponse create = callSonar(request, "api/projects/create", "POST", Map.of("project", key, "name", repository.name()));
if (create.getStatus() < 200 || create.getStatus() >= 300) {
status = "error";
message = "Project creation failed (HTTP " + create.getStatus() + ").";
} else {
LocalConnector.LocalResponse link = callSonar(request, "api/project_links/create", "POST", Map.of("projectKey", key, "name", "Gitea", "url", repository.htmlUrl()));
if (link.getStatus() < 200 || link.getStatus() >= 300) {
status = "created";
message = "Project created, but the Gitea link could not be added (HTTP " + link.getStatus() + ").";
} else {
status = "created";
message = "Project and Gitea link created.";
}
}
}
} catch (RuntimeException exception) {
status = "error";
message = "Import failed: " + safeMessage(exception);
}
json.beginObject().prop("org", repository.organization()).prop("repo", repository.name()).prop("key", key).prop("status", status).prop("message", message).endObject();
}
json.endArray().endObject().close();
}
@@ -116,7 +143,7 @@ public final class BifrostWebService implements WebService {
}
private void requirePermission(Request request) throws IOException {
LocalConnector.LocalResponse current = request.localConnector().call(new LocalApiRequest("api/users/current", Map.of()));
LocalConnector.LocalResponse current = callSonar(request, "api/users/current", "GET", 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");
@@ -130,16 +157,25 @@ public final class BifrostWebService implements WebService {
}
private boolean projectExists(Request request, String key) {
LocalConnector.LocalResponse result = request.localConnector().call(new LocalApiRequest("api/components/show", Map.of("component", key)));
LocalConnector.LocalResponse result = callSonar(request, "api/components/show", "GET", 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 {
private LocalConnector.LocalResponse callSonar(Request request, String path, String method, Map<String, String> parameters) {
return request.localConnector().call(new LocalApiRequest(path, method, parameters));
}
private static String safeMessage(RuntimeException exception) {
String message = exception.getMessage();
return message == null || message.isBlank() ? "Unexpected SonarQube error." : message;
}
private record LocalApiRequest(String path, String method, Map<String, String> parameters) implements LocalConnector.LocalRequest {
public String getPath() { return path; }
public String getMediaType() { return "application/json"; }
public String getMethod() { return "GET"; }
public String getMediaType() { return "application/x-www-form-urlencoded"; }
public String getMethod() { return method; }
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(); }
+7 -19
View File
@@ -144,28 +144,16 @@
const collisions = items.filter(function (item) { return (resultById.get(repositoryId(item)) || "").startsWith("Error:"); });
const permittedItems = items.filter(function (item) { return !collisions.includes(item); });
if (!permittedItems.length) { render(); return; }
status.textContent = "Validating selection…";
status.textContent = "Importing selected repositories…";
const payload = permittedItems.map(function (item) { return { org: item.org, repo: item.name }; });
request("/api/bifrost/import", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ selection: JSON.stringify(payload) }) })
.then(function (validation) {
const approvedItems = (validation.repositories || []).map(function (repository) {
return { org: repository.org, name: repository.repo, url: repository.url, defaultBranch: repository.defaultBranch };
.then(function (data) {
(data.results || []).forEach(function (result) {
const id = result.org + "/" + result.repo;
const label = result.status === "created" ? (result.message.indexOf("link could not") >= 0 ? "Created; link failed" : "Created") :
result.status === "already_exists" ? "Already exists" : "Error: " + result.message;
resultById.set(id, label);
});
return Promise.all(approvedItems.map(function (item) {
const id = repositoryId(item);
const key = keyOf(item.org, item.name);
return request("/api/projects/create", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ project: key, name: item.name }) })
.then(function () {
return request("/api/project_links/create", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ projectKey: key, name: "Gitea", url: item.url }) })
.then(function () { resultById.set(id, "Created"); })
.catch(function () { resultById.set(id, "Created; repository link could not be added"); });
})
.catch(function (error) {
const text = error.message || "";
resultById.set(id, /already exists|already been taken|already used/i.test(text) ? "Already exists" : "Error: " + text);
});
}));
}).then(function () {
status.textContent = "Import finished.";
permittedItems.forEach(function (item) { selected.delete(repositoryId(item)); });
loadRepositories();