feat: add reproducible local import validation
Build Bifrost / build (push) Failing after 2m37s

This commit is contained in:
Arnaud Dartois committed 2026-10-29 10:56:19 +01:00
1 parent 9008ecde5b
commit 021281f3dd
17 files changed
+546 -28

No files matched your search

@@ -10,17 +10,28 @@ description: Use when changing the local Docker build, test Compose stack, Sonar
- Use test-only credentials from environment variables; never commit live tokens. - Use test-only credentials from environment variables; never commit live tokens.
- Document Linux kernel prerequisites for Docker hosts (including `vm.max_map_count` where needed by the bundled search engine). - Document Linux kernel prerequisites for Docker hosts (including `vm.max_map_count` where needed by the bundled search engine).
- Keep the Compose test stack isolated from production volumes and endpoints. - Keep the Compose test stack isolated from production volumes and endpoints.
- Run full import tests under a dedicated Compose project name (`bifrost-e2e`) with its own named volumes. A clean reset may remove only that project's volumes. On Windows use `./scripts/e2e.ps1`; it invokes the native Windows Docker CLI rather than WSL Docker.
- Pin the browser runner image and Playwright npm dependency to the same release; keep `package-lock.json` and install with `npm ci`.
- Bootstrap Gitea through its CLI and documented API; configure SonarQube through documented Web APIs, then run a real Chromium page test.
- Leave the successful isolated stack available for inspection and document the exact command that removes it.
## Checklist ## Checklist
- [ ] All service image tags pinned. - [ ] All service image tags pinned.
- [ ] Health checks and durable named DB volumes present. - [ ] Health checks and durable named DB volumes present.
- [ ] Test plugin mount path correct. - [ ] Test plugin mount path correct.
- [ ] Setup and credentials documented safely. - [ ] Setup and credentials documented safely.
- [x] Zero-to-import runner resets only its isolated project, checks readiness, and asserts created projects and links.
- [ ] Browser version and npm package are pinned together with a lockfile.
## Sources ## Sources
- SonarQube Docker setup: https://docs.sonarsource.com/sonarqube-community-build/server-update-and-maintenance/update/update (consulted 2026-10-28) - SonarQube Docker setup: https://docs.sonarsource.com/sonarqube-community-build/server-update-and-maintenance/update/update (consulted 2026-10-28)
- SonarQube Docker image tags: https://hub.docker.com/_/sonarqube (consulted 2026-10-28) - SonarQube Docker image tags: https://hub.docker.com/_/sonarqube (consulted 2026-10-28)
- Docker Compose specification: https://docs.docker.com/compose/compose-file/ (consulted 2026-10-28) - Docker Compose specification: https://docs.docker.com/compose/compose-file/ (consulted 2026-10-28)
- Playwright Docker image: https://playwright.dev/docs/docker (consulted 2026-10-29)
- Gitea administration CLI: https://docs.gitea.com/administration/command-line/ (consulted 2026-10-29)
- Gitea API 1.23 token creation: https://docs.gitea.com/api/1.23/operations/user-create-token/ (consulted 2026-10-29)
- Gitea 1.23 organization repository creation: https://docs.gitea.com/api/1.23/operations/create-org-repo/ (consulted 2026-10-29)
- SonarQube page extension: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/developing-a-plugin/adding-pages-to-the-webapp (consulted 2026-10-29)
## Not verified ## Not verified
- Host OS and Docker engine version are unspecified; kernel tuning is host dependent. - Windows Docker image startup and local cross-container import passed via `./scripts/e2e.ps1` on 2026-10-29. Linux Docker execution of `scripts/e2e.sh` has not been run on this host.
@@ -0,0 +1,50 @@
---
name: local-e2e-validation
description: Use when building, changing, or running the reproducible Bifrost local stack validation that provisions Gitea fixtures and imports them through the SonarQube page.
---
# Local end-to-end validation
- Build the JAR from the repository tag-derived version before starting the stack; mount that exact file read-only into SonarQube.
- Use only Compose project `bifrost-e2e` for automated state. Reset its named volumes with `down --volumes --remove-orphans`; never delete the user's default `bifrost` project or other volumes.
- Wait for PostgreSQL, Gitea, and SonarQube health checks before provisioning. Require exact SonarQube version `25.9.0.112764` and verify plugin runtime before browser actions.
- Create a test-only Gitea administrator with the pinned Gitea CLI. Generate a disposable token through the documented Gitea API and keep credentials and tokens in process memory or test-only environment variables.
- Seed two organizations (`alpha-lab`, `beta-lab`) and two repositories in each (`api`, `web`) through the Gitea API. Repeated repository names across organizations are expected.
- Configure `sonar.bifrost.*` with SonarQube Web APIs. In the disposable 25.9 instance, accept `sonar.plugins.risk.consent` through the public settings API, then create a UI session through `api/authentication/login`.
- Dismiss SonarQube first-run welcome and Joyride overlays before checking controls. Wait for repository rows to reflect the selected organization before selecting all.
- Assert organization switching retains selection, all four projects are created with organization-prefixed keys, every project receives a Gitea link, imported rows are disabled, and the page emits no JavaScript errors. The fixture deliberately repeats `api` and `web` across the organizations.
- Keep the stack after a successful test for inspection. On failure retain the stack and Playwright trace/screenshots. Cleanup only with the dedicated project command.
- Do not report full validation unless the script exits successfully and the independent API assertions pass.
## Checklist
- [x] Exact plugin JAR version and manifest are used by Compose.
- [x] Fresh Gitea and SonarQube state is provisioned with test-only credentials.
- [x] Both organizations and all four repositories are verified in Gitea.
- [x] Chromium exercises the real plugin page and its selection/import controls.
- [x] SonarQube API confirms each project and its Gitea link.
- [x] Imported project state and browser errors are checked.
- [x] Only the `bifrost-e2e` project can be reset by the runner.
## Commands
```sh
./scripts/e2e.ps1
docker compose --project-name bifrost-e2e ps
docker compose --project-name bifrost-e2e down --volumes --remove-orphans
```
## Sources
- SonarQube page extensions: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/developing-a-plugin/adding-pages-to-the-webapp (consulted 2026-10-29)
- SonarQube project creation API: https://docs.sonarsource.com/sonarqube-community-build/project-administration/creating-project/automating-creation (consulted 2026-10-29)
- SonarQube settings Web API: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/web-api (consulted 2026-10-29)
- Gitea 1.23 token API: https://docs.gitea.com/api/1.23/operations/user-create-token/ (consulted 2026-10-29)
- Gitea 1.23 organization repository API: https://docs.gitea.com/api/1.23/operations/create-org-repo/ (consulted 2026-10-29)
- Gitea command line: https://docs.gitea.com/administration/command-line/ (consulted 2026-10-29)
- Playwright Docker: https://playwright.dev/docs/docker (consulted 2026-10-29)
- Playwright test configuration: https://playwright.dev/docs/test-configuration (consulted 2026-10-29)
- Docker Compose specification: https://docs.docker.com/compose/compose-file/ (consulted 2026-10-29)
## Not verified
- The full local flow passed on 2026-10-29 with SonarQube Community Build 25.9.0.112764, Gitea 1.23.8, PostgreSQL 17.2, and Playwright 1.64.1. External Gitea versions and Linux Docker hosts have not been exercised here.
+2 -1
View File
@@ -10,7 +10,8 @@ description: Use for every task in this repository to enforce its implementation
- If reality conflicts with a skill, confirm with primary documentation, fix the skill in the same change, and explain the correction. - If reality conflicts with a skill, confirm with primary documentation, fix the skill in the same change, and explain the correction.
- Keep security boundaries server-side; never trust UI visibility or client-provided organization names. - Keep security boundaries server-side; never trust UI visibility or client-provided organization names.
- Do not claim build, runtime, browser, or integration verification unless actually performed. - Do not claim build, runtime, browser, or integration verification unless actually performed.
- Definition of done: requested artifacts exist, unit tests/build pass, packaged metadata inspected, limitations documented, and each skill checklist reviewed. - When the user requests local integration proof, include the isolated zero-to-import stack and run its browser-based end-to-end test; unit tests alone are not completion.
- Definition of done: requested artifacts exist, unit tests/build pass, packaged metadata inspected, requested runtime flow verified at the stated level, limitations documented, and each skill checklist reviewed.
- Use Conventional Commit messages; do not claim commits were created unless the repository is a Git checkout and the commit actually exists. - Use Conventional Commit messages; do not claim commits were created unless the repository is a Git checkout and the commit actually exists.
## Checklist ## Checklist
+2 -3
View File
@@ -10,7 +10,7 @@ description: Use when adding or reviewing configuration, web-service inputs, aut
- 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.
- Store the token in a `.secured` PASSWORD property. Never return it from web services, JS, logs, errors, or generated files. - Store the token in a `.secured` PASSWORD property. Never return it from web services, JS, logs, errors, or generated files.
- Use same-origin authenticated SonarQube requests for mutations; do not build custom cookie bypasses. Preserve SonarQube's normal CSRF/session protections. - Use same-origin authenticated SonarQube requests for mutations; do not build custom cookie bypasses. Preserve SonarQube's normal CSRF/session protections by sending `X-XSRF-TOKEN` from the `XSRF-TOKEN` cookie on POST requests.
- Reject duplicate or colliding project keys before making any project mutations. - Reject duplicate or colliding project keys before making any project mutations.
- Pin dependencies, inspect transitive dependency changes, and keep the Sonar API provided. - Pin dependencies, inspect transitive dependency changes, and keep the Sonar API provided.
@@ -27,5 +27,4 @@ description: Use when adding or reviewing configuration, web-service inputs, aut
- SonarQube plugin configuration: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/developing-a-plugin/plugin-basics (consulted 2026-10-28) - SonarQube plugin configuration: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/developing-a-plugin/plugin-basics (consulted 2026-10-28)
## Not verified ## Not verified
- Exact WebService framework CSRF behavior for custom POST actions must be validated on 25.9 during integration testing. - Community Build 25.9.0.112764 returned HTTP 401 when the POST omitted `X-XSRF-TOKEN`; the local browser flow passed after including it. The external Gitea endpoint and token policy remain administrator-controlled and were not evaluated.
- Local connector caller identity and `api/users/current` permission shape require a live 25.9 check.
@@ -8,7 +8,7 @@ description: Use when implementing or changing a SonarQube 25.9 page extension,
- Put the matching unbundled JavaScript at `src/main/resources/static/import.js`; call `window.registerExtension("bifrost/import", start)`. - Put the matching unbundled JavaScript at `src/main/resources/static/import.js`; call `window.registerExtension("bifrost/import", start)`.
- Use only `options.el` as the page mount point; return a cleanup callback. - Use only `options.el` as the page mount point; return a cleanup callback.
- Do not assume global libraries except React. Plain browser JavaScript avoids an unnecessary build step. - Do not assume global libraries except React. Plain browser JavaScript avoids an unnecessary build step.
- Use same-origin `fetch` for `api/bifrost/*`; rely on the active SonarQube session and never send the Gitea token to the browser. - Use same-origin `fetch` for `api/bifrost/*`; rely on the active SonarQube session and never send the Gitea token to the browser. For non-GET requests, copy the readable `XSRF-TOKEN` cookie into the `X-XSRF-TOKEN` header; SonarQube 25.9 rejects cookie-authenticated POSTs without it.
- Render API errors as accessible text; use labels for controls, semantic table headers, keyboard-accessible controls, and text status in addition to color. - Render API errors as accessible text; use labels for controls, semantic table headers, keyboard-accessible controls, and text status in addition to color.
- Validate repository links as HTTP or HTTPS before assigning them to an anchor. - Validate repository links as HTTP or HTTPS before assigning them to an anchor.
- Grey out imported rows and disable their checkboxes. Keep selection in page state across organization changes. - Grey out imported rows and disable their checkboxes. Keep selection in page state across organization changes.
@@ -18,7 +18,7 @@ description: Use when implementing or changing a SonarQube 25.9 page extension,
## Checklist ## Checklist
- [ ] `PageDefinition` key matches JS registration key and resource filename. - [ ] `PageDefinition` key matches JS registration key and resource filename.
- [ ] Bundle packaged under `/static/bifrost/import.js`. - [ ] Bundle packaged under `/static/bifrost/import.js`.
- [ ] Accessible labels, feedback and keyboard controls. - [x] Accessible labels, feedback and keyboard controls.
- [ ] No token in browser or authorization based only on menu visibility. - [ ] No token in browser or authorization based only on menu visibility.
## Sources ## Sources
@@ -26,4 +26,4 @@ description: Use when implementing or changing a SonarQube 25.9 page extension,
- SonarQube Web API: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/web-api (consulted 2026-10-28) - SonarQube Web API: https://docs.sonarsource.com/sonarqube-community-build/extension-guide/web-api (consulted 2026-10-28)
## Not verified ## Not verified
- No live 25.9 instance was available to inspect final menu rendering. - Live page routing, bundle loading, accessible controls, selection retention, and POST CSRF behavior were verified on Community Build 25.9.0.112764. Conditional menu hiding based on Create Projects permission is not supported by the selected public page API.
+3
View File
@@ -10,9 +10,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
- Add Gitea organization and repository browsing, selection, server-side validation, project creation, and repository links. - Add Gitea organization and repository browsing, selection, server-side validation, project creation, and repository links.
- Add a zero-to-import local browser validation with isolated Gitea, SonarQube, and PostgreSQL state.
- Verify imports across two organizations that deliberately share repository names.
### Fixed ### Fixed
- Check Create Projects permission and report existing-project status through SonarQube's public Web APIs. - Check Create Projects permission and report existing-project status through SonarQube's public Web APIs.
- Send SonarQube's XSRF token on browser POSTs and verify the complete repository import flow.
[Unreleased]: http://localhost:3000/owner/bifrost/compare/v0.1.0...HEAD [Unreleased]: http://localhost:3000/owner/bifrost/compare/v0.1.0...HEAD
+4 -1
View File
@@ -1,4 +1,4 @@
.PHONY: build test docker-build package clean .PHONY: build test docker-build e2e package clean
build: build:
@version=$$(sh scripts/version.sh); sh scripts/render-readme.sh "$$version"; sh ./mvnw -B -Drevision="$$version" package @version=$$(sh scripts/version.sh); sh scripts/render-readme.sh "$$version"; sh ./mvnw -B -Drevision="$$version" package
@@ -9,6 +9,9 @@ test:
docker-build: docker-build:
@version=$$(sh scripts/version.sh); docker build --build-arg REVISION="$$version" --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 .
e2e:
bash scripts/e2e.sh
package: build package: build
clean: clean:
+19 -11
View File
@@ -11,13 +11,13 @@ 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 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. The exact 25.9.0.112764 Community Build started with the plugin, reported `UP`, and served the page bundle with HTTP 200. Live Gitea calls and authenticated browser import 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 metadata. The exact 25.9.0.112764 Community Build loaded the plugin, reported `UP`, and served the page bundle with HTTP 200. On 2026-10-29, `./scripts/e2e.ps1` passed from fresh named volumes: Chromium created two Gitea organizations and four repositories, imported all four through the extension, and verified all four SonarQube projects and Gitea links.
## Tree ## Tree
```text ```text
. .
├── .claude/skills/ # Eleven project skills ├── .claude/skills/ # Twelve project skills
├── .gitea/workflows/build.yml # Gitea Actions CI and release pipeline ├── .gitea/workflows/build.yml # Gitea Actions CI and release pipeline
├── .mvn/wrapper/ # Maven distribution pin ├── .mvn/wrapper/ # Maven distribution pin
├── scripts/ # Version, changelog, and release helpers ├── scripts/ # Version, changelog, and release helpers
@@ -34,6 +34,8 @@ The Docker build completed with Java 17, all eight unit tests passed, and the ex
├── src/test/java/cc/tordais/sonar/bifrost/ ├── src/test/java/cc/tordais/sonar/bifrost/
│ ├── gitea/GiteaClientTest.java │ ├── gitea/GiteaClientTest.java
│ └── service/{OrganizationPolicyTest,ProjectKeyTest}.java │ └── service/{OrganizationPolicyTest,ProjectKeyTest}.java
├── tests/e2e/ # Pinned Playwright browser validation
├── scripts/e2e.sh # Fresh-stack end-to-end runner
├── CHANGELOG.md ├── CHANGELOG.md
├── Dockerfile ├── Dockerfile
├── docker-compose.yml ├── docker-compose.yml
@@ -73,17 +75,21 @@ The token is held only by the plugin server. The plugin checks the caller's Crea
## Test scenario ## Test scenario
Use the Compose stack for a disposable SonarQube and Gitea setup: Run the complete fresh-stack validation from PowerShell:
```sh ```powershell
make build ./scripts/e2e.ps1
export BIFROST_PLUGIN_JAR="target/sonar-bifrost-plugin-$(sh scripts/version.sh).jar"
docker compose up -d
``` ```
Complete Gitea's first-run account setup at `http://localhost:3000`. Create organizations `alpha-lab` and `beta-lab`, then create two repositories in each: `api` and `web`. This deliberately repeats repository names across organizations. Create a token that can read all four repositories and set it in SonarQube's global plugin settings. On SonarQube, grant the test account Create Projects and import the four repositories. Expected keys are `alpha-lab_api`, `alpha-lab_web`, `beta-lab_api`, and `beta-lab_web`; no collision should occur. Try a second pair of names that sanitize to the same key to verify collision feedback. This builds the current plugin JAR, removes only the dedicated `bifrost-e2e` Compose project's volumes, starts the pinned PostgreSQL, Gitea, and SonarQube images, creates a test Gitea administrator, and runs Chromium through the plugin page. The browser test creates organizations `alpha-lab` and `beta-lab`, with `api` and `web` repositories in each, configures SonarQube through its Web API, verifies selection retention, imports the four repositories, and checks each project key and Gitea link.
The Compose Gitea URL from the SonarQube container is `http://gitea:3000`. The initial settings are blank and must be configured in the UI. Expected project keys are `alpha-lab_api`, `alpha-lab_web`, `beta-lab_api`, and `beta-lab_web`. The test leaves the isolated stack running for inspection at `http://localhost:9000` and `http://localhost:3000`. Credentials are test-only defaults and must never be reused outside this disposable stack. Playwright HTML report, traces, and screenshots are written under `target/e2e-results/`.
Remove only the E2E project and its volumes when finished:
```powershell
docker compose --project-name bifrost-e2e down --volumes --remove-orphans
```
## Versioning ## Versioning
@@ -124,6 +130,7 @@ The `.claude/skills/<name>/SKILL.md` files are project instructions:
- `release-versioning-changelog`: tag bumps, changelog structure, and release flow. - `release-versioning-changelog`: tag bumps, changelog structure, and release flow.
- `gitea-actions-ci`: act_runner constraints and release workflow. - `gitea-actions-ci`: act_runner constraints and release workflow.
- `docker-test-environment`: pinned SonarQube, PostgreSQL, Gitea, and plugin mount. - `docker-test-environment`: pinned SonarQube, PostgreSQL, Gitea, and plugin mount.
- `local-e2e-validation`: fresh-stack provisioning, browser import, project/link assertions, and safe cleanup.
- `project-workflow`: language, evidence, implementation order, and definition of done. - `project-workflow`: language, evidence, implementation order, and definition of done.
When the SonarQube target changes, update version-sensitive skill claims only after checking official SonarSource docs and target source/artifact metadata. Then update API/compiler/manifest pins, rebuild and inspect the JAR, and rerun each checklist. Skills are guidance, not a substitute for version-specific verification. When the SonarQube target changes, update version-sensitive skill claims only after checking official SonarSource docs and target source/artifact metadata. Then update API/compiler/manifest pins, rebuild and inspect the JAR, and rerun each checklist. Skills are guidance, not a substitute for version-specific verification.
@@ -143,10 +150,11 @@ 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 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 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 `/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. - The `/api/bifrost/import` action creates projects and their Gitea links through the public `LocalConnector`. The full authenticated project and link creation flow passed on the target local stack. A separate non-admin Create Projects account and role matrix were not included in this proof of concept.
- 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. - 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. - Create Projects permission is checked against `api/users/current` through `LocalConnector`. The test administrator passed the permission check; denial behavior for a user without Create Projects was not tested end to end.
- 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 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 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. - 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.
- The Linux shell runner `scripts/e2e.sh` was not exercised on this Windows host. The verified native runner is `./scripts/e2e.ps1`.
+23 -3
View File
@@ -23,8 +23,8 @@ services:
GITEA__security__INSTALL_LOCK: "true" GITEA__security__INSTALL_LOCK: "true"
GITEA__service__DISABLE_REGISTRATION: "false" GITEA__service__DISABLE_REGISTRATION: "false"
ports: ports:
- "3000:3000" - "${GITEA_HTTP_PORT:-3000}:3000"
- "2222:22" - "${GITEA_SSH_PORT:-2222}:22"
volumes: volumes:
- gitea-data:/data - gitea-data:/data
healthcheck: healthcheck:
@@ -43,7 +43,7 @@ services:
SONAR_JDBC_USERNAME: sonar SONAR_JDBC_USERNAME: sonar
SONAR_JDBC_PASSWORD: sonar-test-only SONAR_JDBC_PASSWORD: sonar-test-only
ports: ports:
- "9000:9000" - "${SONAR_HTTP_PORT:-9000}:9000"
volumes: volumes:
- sonar-data:/opt/sonarqube/data - sonar-data:/opt/sonarqube/data
- sonar-logs:/opt/sonarqube/logs - sonar-logs:/opt/sonarqube/logs
@@ -54,6 +54,26 @@ services:
timeout: 5s timeout: 5s
retries: 60 retries: 60
e2e:
profiles: [e2e]
build:
context: ./tests/e2e
dockerfile: Dockerfile
environment:
GITEA_URL: http://gitea:3000
GITEA_TEST_USER: ${GITEA_TEST_USER:-bifrost-e2e-admin}
GITEA_TEST_PASSWORD: ${GITEA_TEST_PASSWORD:-bifrost-gitea-test-password}
SONAR_URL: http://sonarqube:9000
SONAR_TEST_PASSWORD: ${SONAR_TEST_PASSWORD:-Bifrost-Sonar-Test-2026-password}
depends_on:
gitea:
condition: service_healthy
sonarqube:
condition: service_healthy
ipc: host
volumes:
- ./target/e2e-results:/workspace/test-results
volumes: volumes:
postgres-data: postgres-data:
gitea-data: gitea-data:
+62
View File
@@ -0,0 +1,62 @@
$ErrorActionPreference = "Stop"
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
Set-Location $repoRoot
$gitBashCandidates = @(
(Join-Path (Split-Path (Get-Command git.exe).Source -Parent) "..\bin\bash.exe"),
"C:\Program Files\Git\bin\bash.exe"
)
$gitBash = $gitBashCandidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
if (-not $gitBash) {
throw "Git for Windows Bash is required to run scripts/version.sh. Install Git for Windows and retry."
}
$docker = (Get-Command docker.exe -ErrorAction Stop).Source
& $docker info *> $null
if ($LASTEXITCODE -ne 0) {
throw "Docker Engine is unavailable through the Windows Docker CLI. Start Rancher Desktop or Docker Desktop and retry."
}
$version = (& $gitBash scripts/version.sh).Trim()
if ($LASTEXITCODE -ne 0 -or -not $version) {
throw "scripts/version.sh failed to calculate the plugin version."
}
$artifactDir = Join-Path $repoRoot "target\e2e-artifact"
$pluginJar = Join-Path $artifactDir "sonar-bifrost-plugin-$version.jar"
New-Item -ItemType Directory -Force -Path $artifactDir | Out-Null
$env:BIFROST_PLUGIN_JAR = $pluginJar
$env:GITEA_TEST_USER = if ($env:GITEA_TEST_USER) { $env:GITEA_TEST_USER } else { "bifrost-e2e-admin" }
$env:GITEA_TEST_PASSWORD = if ($env:GITEA_TEST_PASSWORD) { $env:GITEA_TEST_PASSWORD } else { "bifrost-gitea-test-password" }
$env:SONAR_TEST_PASSWORD = if ($env:SONAR_TEST_PASSWORD) { $env:SONAR_TEST_PASSWORD } else { "Bifrost-Sonar-Test-2026-password" }
$compose = @("compose", "--project-name", "bifrost-e2e", "-f", "docker-compose.yml")
Write-Host "Building plugin version $version and exporting the test JAR."
& $docker build --build-arg "REVISION=$version" --target export --output "type=local,dest=$artifactDir" .
if ($LASTEXITCODE -ne 0) { throw "Docker plugin build/export failed with exit code $LASTEXITCODE." }
if (-not (Test-Path -LiteralPath $pluginJar)) { throw "Expected plugin JAR was not exported: $pluginJar" }
Write-Host "Resetting only the isolated bifrost-e2e Compose project and its volumes."
& $docker @compose down --volumes --remove-orphans
if ($LASTEXITCODE -ne 0) { throw "Could not reset the isolated E2E Compose project." }
Write-Host "Starting fresh PostgreSQL, Gitea, and SonarQube services."
& $docker @compose up --detach --wait --wait-timeout 360 postgres gitea sonarqube
if ($LASTEXITCODE -ne 0) { throw "The isolated Gitea/SonarQube stack failed to become healthy." }
Write-Host "Creating the disposable Gitea test administrator."
& $docker @compose exec --no-TTY --user git gitea gitea admin user create `
--username $env:GITEA_TEST_USER `
--password $env:GITEA_TEST_PASSWORD `
--email "$($env:GITEA_TEST_USER)@example.test" `
--admin `
--must-change-password=false
if ($LASTEXITCODE -ne 0) { throw "Could not create the disposable Gitea test administrator." }
Write-Host "Running the Chromium end-to-end test against the installed plugin."
& $docker @compose run --build --rm e2e
if ($LASTEXITCODE -ne 0) { throw "Bifrost end-to-end validation failed. The isolated stack remains available for diagnosis." }
Write-Host ""
Write-Host "End-to-end validation passed. The isolated stack remains available at http://localhost:9000 and http://localhost:3000."
Write-Host "Run 'docker compose --project-name bifrost-e2e down --volumes --remove-orphans' to remove only this test stack and its data."
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
set -Eeuo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
if ! docker info >/dev/null 2>&1; then
echo "Docker Engine is not available. Start Docker Desktop or the local Docker daemon, then retry." >&2
exit 1
fi
version="$(bash scripts/version.sh)"
artifact_dir="$repo_root/target/e2e-artifact"
plugin_jar="$artifact_dir/sonar-bifrost-plugin-$version.jar"
if command -v cygpath >/dev/null 2>&1; then
compose_plugin_path="$(cygpath -w "$plugin_jar")"
else
compose_plugin_path="$plugin_jar"
fi
export BIFROST_PLUGIN_JAR="$compose_plugin_path"
export GITEA_TEST_USER="${GITEA_TEST_USER:-bifrost-e2e-admin}"
export GITEA_TEST_PASSWORD="${GITEA_TEST_PASSWORD:-bifrost-gitea-test-password}"
export SONAR_TEST_PASSWORD="${SONAR_TEST_PASSWORD:-bifrost-sonar-test-password}"
compose=(docker compose --project-name bifrost-e2e -f docker-compose.yml)
echo "Building plugin version $version and exporting the test JAR."
docker build --build-arg "REVISION=$version" --target export --output "type=local,dest=$artifact_dir" .
test -f "$plugin_jar" || { echo "The expected plugin JAR was not exported: $plugin_jar" >&2; exit 1; }
echo "Resetting only the isolated bifrost-e2e Compose project and its volumes."
"${compose[@]}" down --volumes --remove-orphans
echo "Starting fresh PostgreSQL, Gitea, and SonarQube services."
"${compose[@]}" up --detach --wait --wait-timeout 360 postgres gitea sonarqube
echo "Creating the disposable Gitea test administrator."
"${compose[@]}" exec --no-TTY gitea gitea admin user create \
--username "$GITEA_TEST_USER" \
--password "$GITEA_TEST_PASSWORD" \
--email "$GITEA_TEST_USER@example.test" \
--admin \
--must-change-password=false >/dev/null
echo "Running the Chromium end-to-end test against the installed plugin."
"${compose[@]}" run --build --rm e2e
echo
echo "End-to-end validation passed. The isolated stack remains available at http://localhost:9000 and http://localhost:3000."
echo "Run 'docker compose --project-name bifrost-e2e down --volumes --remove-orphans' to remove only this test stack and its data."
+10 -5
View File
@@ -41,11 +41,16 @@
} }
function request(path, init) { function request(path, init) {
return fetch(path, Object.assign({ credentials: "same-origin", headers: { "X-Requested-With": "XMLHttpRequest" } }, init || {})) const options = Object.assign({ credentials: "same-origin" }, init || {});
.then(function (response) { options.headers = Object.assign({ "X-Requested-With": "XMLHttpRequest" }, options.headers || {});
if (!response.ok) return response.text().then(function (text) { throw new Error(text || ("Request failed (" + response.status + ")")); }); const xsrfCookie = document.cookie.split("; ").find(function (cookie) { return cookie.startsWith("XSRF-TOKEN="); });
return response.json(); if (xsrfCookie && (options.method || "GET").toUpperCase() !== "GET") {
}); options.headers["X-XSRF-TOKEN"] = xsrfCookie.substring("XSRF-TOKEN=".length);
}
return fetch(path, options).then(function (response) {
if (!response.ok) return response.text().then(function (text) { throw new Error(text || ("Request failed (" + response.status + ")")); });
return response.json();
});
} }
function repositoryId(repository) { function repositoryId(repository) {
+8
View File
@@ -0,0 +1,8 @@
FROM mcr.microsoft.com/playwright:v1.64.1-noble
WORKDIR /workspace
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
COPY playwright.config.mjs ./
COPY bifrost-import.spec.mjs ./
CMD ["npm", "test"]
+209
View File
@@ -0,0 +1,209 @@
import { expect, test } from "@playwright/test";
const sonarUrl = process.env.SONAR_URL ?? "http://sonarqube:9000";
const giteaUrl = process.env.GITEA_URL ?? "http://gitea:3000";
const giteaUser = process.env.GITEA_TEST_USER ?? "bifrost-e2e-admin";
const giteaPassword = process.env.GITEA_TEST_PASSWORD ?? "bifrost-gitea-test-password";
const sonarPassword = process.env.SONAR_TEST_PASSWORD ?? "Bifrost-Sonar-Test-2026-password";
const repositories = ["api", "web"];
const organizations = ["alpha-lab", "beta-lab"];
function basicAuth(username, password) {
return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
}
async function expectStatus(response, expected, action) {
const status = typeof response.status === "function" ? response.status() : response.status;
if (status !== expected) {
const body = await response.text().catch(() => "");
throw new Error(`${action} returned HTTP ${status}: ${body.slice(0, 500)}`);
}
}
async function giteaRequest(path, { token, username, password, ...options } = {}) {
const headers = { "Content-Type": "application/json", ...(options.headers ?? {}) };
if (token) headers.Authorization = `token ${token}`;
if (username && password) headers.Authorization = basicAuth(username, password);
return fetch(`${giteaUrl}/api/v1${path}`, { ...options, headers });
}
async function sonarRequest(path, password, form) {
return fetch(`${sonarUrl}${path}`, {
method: "POST",
headers: {
Authorization: basicAuth("admin", password),
"Content-Type": "application/x-www-form-urlencoded",
},
body: form,
});
}
async function setSonarSetting(password, key, value) {
const form = new URLSearchParams({ key, value });
const response = await sonarRequest("/api/settings/set", password, form);
await expectStatus(response, 204, `Set SonarQube setting ${key}`);
}
test("creates Gitea fixtures, imports them through the Bifrost page, and verifies project links", async ({ browser }) => {
test.setTimeout(180_000);
const adminPassword = basicAuth("admin", "admin");
const sonarStatus = await fetch(`${sonarUrl}/api/system/status`).then((response) => response.json());
expect(sonarStatus.version).toBe("25.9.0.112764");
expect(sonarStatus.status).toBe("UP");
const passwordChange = await fetch(`${sonarUrl}/api/users/change_password`, {
method: "POST",
headers: { Authorization: adminPassword, "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ login: "admin", previousPassword: "admin", password: sonarPassword }),
});
if (passwordChange.status !== 204) {
const validation = await fetch(`${sonarUrl}/api/authentication/validate`, {
headers: { Authorization: basicAuth("admin", sonarPassword) },
}).then((response) => response.json());
expect(validation.valid, "The default SonarQube admin password must be changeable on a clean volume.").toBe(true);
}
const giteaHealth = await fetch(`${giteaUrl}/api/healthz`);
await expectStatus(giteaHealth, 200, "Gitea health check");
const tokenResponse = await giteaRequest(`/users/${encodeURIComponent(giteaUser)}/tokens`, {
username: giteaUser,
password: giteaPassword,
method: "POST",
body: JSON.stringify({ name: "bifrost-e2e", scopes: ["all"] }),
});
await expectStatus(tokenResponse, 201, "Create the disposable Gitea API token");
const tokenBody = await tokenResponse.json();
const giteaToken = tokenBody.sha1;
expect(giteaToken).toBeTruthy();
const repositoryUrls = new Map();
for (const organization of organizations) {
const createOrganization = await giteaRequest("/orgs", {
token: giteaToken,
method: "POST",
body: JSON.stringify({ username: organization, full_name: organization, visibility: "public" }),
});
await expectStatus(createOrganization, 201, `Create Gitea organization ${organization}`);
for (const repository of repositories) {
const createRepository = await giteaRequest(`/orgs/${organization}/repos`, {
token: giteaToken,
method: "POST",
body: JSON.stringify({ name: repository, auto_init: true, default_branch: "main", readme: "Default", private: false }),
});
await expectStatus(createRepository, 201, `Create Gitea repository ${organization}/${repository}`);
const repositoryBody = await createRepository.json();
repositoryUrls.set(`${organization}/${repository}`, repositoryBody.html_url);
}
}
const authentication = await fetch(`${sonarUrl}/api/authentication/validate`, {
headers: { Authorization: basicAuth("admin", sonarPassword) },
}).then((response) => response.json());
expect(authentication.valid).toBe(true);
const currentUser = await fetch(`${sonarUrl}/api/users/current`, {
headers: { Authorization: basicAuth("admin", sonarPassword) },
}).then((response) => response.json());
expect(currentUser.permissions.global).toContain("provisioning");
await setSonarSetting(sonarPassword, "sonar.bifrost.giteaUrl", giteaUrl);
await setSonarSetting(sonarPassword, "sonar.bifrost.giteaToken.secured", giteaToken);
await setSonarSetting(sonarPassword, "sonar.plugins.risk.consent", "ACCEPTED");
await setSonarSetting(sonarPassword, "sonar.bifrost.organizationMode", "fixed");
const organizationsForm = new URLSearchParams({ key: "sonar.bifrost.allowedOrganizations" });
for (const organization of organizations) organizationsForm.append("values", organization);
const organizationsSetting = await sonarRequest("/api/settings/set", sonarPassword, organizationsForm);
await expectStatus(organizationsSetting, 204, "Set the Gitea organization allowlist");
const context = await browser.newContext({ baseURL: sonarUrl });
const page = await context.newPage();
const pageErrors = [];
page.on("pageerror", (error) => pageErrors.push(error.message));
try {
const browserLogin = await context.request.post("/api/authentication/login", {
form: { login: "admin", password: sonarPassword },
});
await expectStatus(browserLogin, 200, "Create the SonarQube browser session");
await page.goto("/extension/bifrost/import");
const welcomeDialog = page.getByRole("dialog", { name: "Welcome to SonarQube Community Build" });
const pageHeading = page.getByRole("heading", { name: "Import from Gitea" });
await Promise.race([
welcomeDialog.waitFor({ state: "visible", timeout: 15_000 }).catch(() => undefined),
pageHeading.waitFor({ state: "visible", timeout: 15_000 }).catch(() => undefined),
]);
if (await welcomeDialog.isVisible()) {
await welcomeDialog.getByRole("button", { name: "Close" }).click();
await expect(welcomeDialog).toBeHidden();
}
await expect(pageHeading).toBeVisible();
const skipTour = page.getByRole("button", { name: "Skip" });
if (await skipTour.isVisible().catch(() => false)) {
await skipTour.click();
}
const moreButton = page.getByRole("button", { name: "More" });
if (await moreButton.getAttribute("aria-expanded") === "true") {
await moreButton.click();
}
const selector = page.getByRole("combobox", { name: "Organization" });
await selector.selectOption("alpha-lab");
const alphaRows = page.locator("tbody tr");
await expect(alphaRows).toHaveCount(2);
const alphaApi = alphaRows.filter({ hasText: "api" });
await alphaApi.getByRole("checkbox").check();
await selector.selectOption("beta-lab");
const betaRows = page.locator("tbody tr");
await expect(betaRows).toHaveCount(2);
await expect(betaRows.filter({ hasText: "api" }).getByRole("checkbox")).not.toBeChecked();
await selector.selectOption("alpha-lab");
await expect(page.locator("tbody tr").filter({ hasText: "api" }).getByRole("checkbox")).toBeChecked();
await page.getByRole("button", { name: "Select all (displayed organization)" }).click();
await selector.selectOption("beta-lab");
await expect(page.locator("tbody tr").first().locator("td").nth(1)).toHaveText("beta-lab");
await page.getByRole("button", { name: "Select all (displayed organization)" }).click();
await page.getByRole("button", { name: "Import selected repositories" }).click();
for (const organization of organizations) {
await selector.selectOption(organization);
const rows = page.locator("tbody tr");
await expect(rows).toHaveCount(2);
await expect(rows.first().locator("td").nth(1)).toHaveText(organization);
for (const repository of repositories) {
const row = rows.filter({ hasText: repository });
await expect(row.locator("td").nth(5)).toHaveText("Created", { timeout: 60_000 });
await expect(row.getByRole("checkbox")).toBeDisabled();
}
}
const projectKeys = organizations.flatMap((organization) => repositories.map((repository) => `${organization}_${repository}`));
for (const projectKey of projectKeys) {
const componentResponse = await fetch(`${sonarUrl}/api/components/show?component=${encodeURIComponent(projectKey)}`, {
headers: { Authorization: basicAuth("admin", sonarPassword) },
});
await expectStatus(componentResponse, 200, `Verify SonarQube project ${projectKey}`);
const component = await componentResponse.json();
expect(component.component.key).toBe(projectKey);
const linksResponse = await fetch(`${sonarUrl}/api/project_links/search?projectKey=${encodeURIComponent(projectKey)}`, {
headers: { Authorization: basicAuth("admin", sonarPassword) },
});
await expectStatus(linksResponse, 200, `Verify Gitea link for ${projectKey}`);
const links = await linksResponse.json();
const [organization, repository] = projectKey.split("_");
const repositoryUrl = repositoryUrls.get(`${organization}/${repository}`);
expect(links.links).toEqual(expect.arrayContaining([
expect.objectContaining({ name: "Gitea", url: repositoryUrl }),
]));
}
expect(pageErrors, "The Bifrost page must not emit browser errors.").toEqual([]);
console.log(`Verified ${organizations.length} Gitea organizations, ${projectKeys.length} imported SonarQube projects, and ${projectKeys.length} project links.`);
} finally {
await context.close();
}
});
+58
View File
@@ -0,0 +1,58 @@
{
"name": "bifrost-local-e2e",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bifrost-local-e2e",
"devDependencies": {
"@playwright/test": "1.64.1"
}
},
"node_modules/@playwright/test": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",
"integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",
"integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.64.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.64.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",
"integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "bifrost-local-e2e",
"private": true,
"type": "module",
"scripts": {
"test": "playwright test"
},
"devDependencies": {
"@playwright/test": "1.64.1"
}
}
+19
View File
@@ -0,0 +1,19 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: ".",
testMatch: "bifrost-import.spec.mjs",
fullyParallel: false,
workers: 1,
retries: 0,
timeout: 180_000,
reporter: [["list"], ["html", { outputFolder: "test-results/html", open: "never" }]],
outputDir: "test-results/artifacts",
use: {
browserName: "chromium",
baseURL: process.env.SONAR_URL ?? "http://sonarqube:9000",
trace: "retain-on-failure",
screenshot: "only-on-failure",
video: "retain-on-failure",
},
});