diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml deleted file mode 100644 index 51de659901b..00000000000 --- a/.github/workflows/fullsend.yaml +++ /dev/null @@ -1,79 +0,0 @@ -# lint-workflow-size: max-lines=280 -# fullsend shim workflow (workflow_call mode) -# Routes events to agent workflows in .fullsend via workflow_call. -# No secrets are needed in the enrolled repo — agents fetch scoped tokens -# from the centralized token mint using GitHub OIDC. -# -# Security: pull_request_target runs the BASE branch version of this workflow, -# preventing PRs from modifying it to exfiltrate credentials. -# This shim never checks out PR code, so it is not vulnerable to "pwn request" -# attacks. -# -# konflux-ci is replaced by reconcile-repos.sh at deploy time. -# -# Routing: this shim forwards the raw event context to dispatch.yml, which -# determines the stage from event_type + event_action + payload fields. -# Adding a new stage requires only a case branch in dispatch.yml — zero -# changes to enrolled repos. -name: fullsend - -permissions: - actions: write - id-token: write - contents: read - pull-requests: read - -on: - issues: - types: [opened, edited, labeled] - issue_comment: - types: [created] - pull_request_target: - types: [opened, synchronize, ready_for_review, closed] - pull_request_review: - types: [submitted] - -jobs: - dispatch: - concurrency: - group: fullsend-dispatch-${{ github.event.issue.number || github.event.pull_request.number }} - cancel-in-progress: false - if: >- - github.event_name != 'issue_comment' - || github.event.comment.user.type != 'Bot' - uses: konflux-ci/.fullsend/.github/workflows/dispatch.yml@701e62a9c6f104ed68f8d4085d9c3b8bad3a82e4 # main - with: - event_action: ${{ github.event.action }} - - stop-fix: - if: >- - github.event_name == 'issue_comment' - && github.event.issue.pull_request - && github.event.comment.user.type != 'Bot' - && github.event.comment.body == '/fs-fix-stop' - && ( - github.event.comment.author_association == 'OWNER' - || github.event.comment.author_association == 'MEMBER' - || github.event.comment.author_association == 'COLLABORATOR' - || github.event.comment.author_association == 'CONTRIBUTOR' - || github.event.comment.user.login == github.event.issue.user.login - ) - runs-on: ubuntu-latest - permissions: - contents: read - issues: write - pull-requests: write - steps: - - name: Add fullsend-no-fix label and notify - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ github.event.issue.number }} - REPO: ${{ github.repository }} - run: | - gh label create "fullsend-no-fix" --repo "$REPO" \ - --description "Skip bot-triggered fix agent runs" --color "FBCA04" \ - --force 2>/dev/null || true - gh pr edit "$PR_NUMBER" --repo "$REPO" \ - --add-label "fullsend-no-fix" - gh pr comment "$PR_NUMBER" --repo "$REPO" \ - --body "Fix agent disabled for this PR. Remove the \`fullsend-no-fix\` label or use \`/fs-fix\` to re-engage." diff --git a/.github/workflows/test-e2e-coverage.yml b/.github/workflows/test-e2e-coverage.yml index 02378e2716c..41f6ccb4fa2 100644 --- a/.github/workflows/test-e2e-coverage.yml +++ b/.github/workflows/test-e2e-coverage.yml @@ -96,11 +96,33 @@ jobs: npm ci npx playwright install chromium --with-deps - - name: Run Playwright e2e tests + - name: Run basic-flow Playwright e2e tests run: | cd e2e npx playwright test basic-flow.spec.ts + - name: Verify Codecov e2e prerequisites + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + run: | + if [ -z "$CODECOV_TOKEN" ]; then + echo "::error::CODECOV_TOKEN GitHub Actions secret is required for codecov e2e tests" + exit 1 + fi + + - name: Run codecov-flow Playwright e2e tests + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + CODECOV_ORG: konflux-ci + CODECOV_SERVICE: github + CODECOV_ENDPOINT: https://api.codecov.io + CODECOV_REPO: konflux-ci/coverport + run: | + cd e2e + npx playwright test codecov-flow.spec.ts + - name: Collect Go e2e coverage via coverport if: always() run: | @@ -120,10 +142,6 @@ jobs: echo "Go e2e coverage generated:" go tool cover -func=./e2e-coverage/go-coverage.out | tail -1 - - name: Install gpg for Codecov - if: always() - run: sudo apt-get update -qq && sudo apt-get install -y -qq gpg > /dev/null 2>&1 - - name: Upload Go e2e coverage to Codecov if: always() uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a4b293835ec..080cd65397b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -43,7 +43,7 @@ jobs: runs-on: ${{ matrix.os }} container: mericodev/lake-builder:latest permissions: - id-token: write + contents: read steps: - name: Checkout code uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 @@ -83,16 +83,40 @@ jobs: run: | cd backend COVERAGE_OUTPUT_DIR=python/coverage make unit-test-python || echo "::warning::Python unit tests had failures (coverage still uploaded)" - - name: Install gpg for Codecov - if: always() - run: apt-get update -qq && apt-get install -y -qq gpg > /dev/null 2>&1 - name: Custom plugins coverage if: always() run: | cd backend bash scripts/coverage-custom-plugins.sh - - name: Upload Go coverage to Codecov + - name: Upload coverage artifacts if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: unit-coverage + if-no-files-found: warn + retention-days: 1 + path: | + backend/coverage-custom-plugins.out + backend/python/coverage/ + + # Fork-only: upload from the Ubuntu runner so codecov-action has gpg + upload-coverage: + needs: test + if: always() && needs.test.result != 'cancelled' + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - name: Checkout code + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - name: Download coverage artifacts + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: unit-coverage + path: backend + if-no-artifact-found: warn + - name: Upload Go coverage to Codecov uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5 with: use_oidc: true diff --git a/.tekton/devlake-backend-d41aa-pull-request.yaml b/.tekton/devlake-backend-pull-request.yaml similarity index 69% rename from .tekton/devlake-backend-d41aa-pull-request.yaml rename to .tekton/devlake-backend-pull-request.yaml index 53a349d3c6c..723edf05af2 100644 --- a/.tekton/devlake-backend-d41aa-pull-request.yaml +++ b/.tekton/devlake-backend-pull-request.yaml @@ -2,20 +2,20 @@ apiVersion: tekton.dev/v1 kind: PipelineRun metadata: annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} + build.appstudio.openshift.io/repo: https://github.com/RH-DevProd/devlake?rev={{revision}} build.appstudio.redhat.com/commit_sha: '{{revision}}' build.appstudio.redhat.com/pull_request_number: '{{pull_request_number}}' build.appstudio.redhat.com/target_branch: '{{target_branch}}' pipelinesascode.tekton.dev/cancel-in-progress: "true" pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "pull_request" && target_branch == "main" - creationTimestamp: + pipelinesascode.tekton.dev/on-cel-expression: event == "pull_request" && target_branch + == "main" labels: appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-backend-d41aa + appstudio.openshift.io/component: devlake-backend pipelines.appstudio.openshift.io/type: build - name: devlake-backend-d41aa-on-pull-request - namespace: rh-konflux-devprod-tenant + name: devlake-backend-on-pull-request + namespace: dprod-tenant spec: params: - name: git-url @@ -23,19 +23,22 @@ spec: - name: revision value: '{{revision}}' - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-backend:on-pr-{{revision}} + value: quay.io/redhat-user-workloads/dprod-tenant/devlake-backend:on-pr-{{revision}} - name: image-expires-after value: 5d + - name: build-platforms + value: + - linux/x86_64 - name: dockerfile - value: backend/Containerfile + value: Containerfile - name: path-context value: backend pipelineSpec: description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. + This pipeline is ideal for building multi-arch container images from a Containerfile while maintaining trust after pipeline customization. - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ + _Uses `buildah` to create a multi-platform container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. This pipeline requires that the [multi platform controller](https://github.com/konflux-ci/multi-platform-controller) is deployed and configured on your Konflux instance. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. + This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-multi-platform-oci-ta?tab=tags)_ params: - description: Source Repository URL name: git-url @@ -48,17 +51,15 @@ spec: name: output-image type: string - default: . - description: Path to the source code of an application's component from where to build image. + description: Path to the source code of an application's component from where + to build image. name: path-context type: string - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context + description: Path to the Dockerfile inside the context specified by parameter + path-context name: dockerfile type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - default: "false" description: Skip checks against built image name: skip-checks @@ -72,23 +73,35 @@ spec: name: prefetch-input type: string - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. + description: Image tag expiration time, time values could be something like + 1h, 2d, 3w for hours, days, and weeks, respectively. name: image-expires-after type: string - default: "false" description: Build a source image. name: build-source-image type: string - - default: "false" + - default: "true" description: Add built image into an OCI image index name: build-image-index type: string - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. + description: The format for the resulting image's mediaType. Valid values are + oci or docker. name: buildah-format type: string - - default: - - "BUILDPLATFORM=linux/amd64" + - default: "false" + description: Enable cache proxy configuration + name: enable-cache-proxy + - default: "true" + description: Use the package registry proxy when prefetching dependencies + name: enable-package-registry-proxy + - default: . + description: Target directories in component's source code to scan with SAST + tools. Multiple values should be separated with commas. + name: sast-target-dirs + type: string + - default: [] description: Array of --build-arg values ("arg=value" strings) for buildah name: build-args type: array @@ -97,13 +110,32 @@ spec: name: build-args-file type: string - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs + description: Whether to enable privileged mode, should be used only with remote + VMs name: privileged-nested type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration + - default: "" + description: Sets the image created time and the SOURCE_DATE_EPOCH build argument. + On its own, it does not change file timestamps inside the layers (set rewrite-timestamp + to "true" for that). Leave empty to keep the actual build time. + name: source-date-epoch + type: string + - default: "false" + description: When "true", clamp file modification times in the image layers + to at most source-date-epoch. Does nothing unless source-date-epoch is set. + name: rewrite-timestamp + type: string + - default: "false" + description: When "true", omit the build history (history timestamps, layer + metadata, etc.) from the resulting image. + name: omit-history type: string + - default: + - linux/x86_64 + description: List of platforms to build the container images on. The available + set of values is determined by the configuration of the multi-platform-controller. + name: build-platforms + type: array results: - description: "" name: IMAGE_URL @@ -120,12 +152,6 @@ spec: tasks: - name: init params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - name: enable-cache-proxy value: $(params.enable-cache-proxy) taskRef: @@ -133,7 +159,7 @@ spec: - name: name value: init - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 + value: quay.io/konflux-ci/tekton-catalog/task-init:0.4.2@sha256:421003a5c077ecb820460e71637125ec9093d2101c749a32ede28e190283e9db - name: kind value: task resolver: bundles @@ -154,15 +180,10 @@ spec: - name: name value: git-clone-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 + value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.2.4@sha256:df3c42d78223f07b40a84dd29e5c8860d14777ffdf150ea08c738770f51216dc - name: kind value: task resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" workspaces: - name: basic-auth workspace: git-auth @@ -170,6 +191,8 @@ spec: params: - name: input value: $(params.prefetch-input) + - name: enable-package-registry-proxy + value: $(params.enable-package-registry-proxy) - name: SOURCE_ARTIFACT value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - name: ociStorage @@ -183,7 +206,7 @@ spec: - name: name value: prefetch-dependencies-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 + value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.10.1@sha256:c09c1c3ced67fb8740b2925a7de09c0810d4e8c8f148d41c21ffe37810d85c62 - name: kind value: task resolver: bundles @@ -192,12 +215,12 @@ spec: workspace: git-auth - name: netrc workspace: netrc - - name: build-container - computeResources: - limits: - memory: 12Gi - requests: - memory: 4Gi + - matrix: + params: + - name: PLATFORM + value: + - $(params.build-platforms) + name: build-images params: - name: IMAGE value: $(params.output-image) @@ -224,61 +247,55 @@ spec: value: $(tasks.clone-repository.results.url) - name: BUILDAH_FORMAT value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - name: HTTP_PROXY value: $(tasks.init.results.http-proxy) - name: NO_PROXY value: $(tasks.init.results.no-proxy) + - name: SOURCE_DATE_EPOCH + value: $(params.source-date-epoch) + - name: REWRITE_TIMESTAMP + value: $(params.rewrite-timestamp) + - name: OMIT_HISTORY + value: $(params.omit-history) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + - name: IMAGE_APPEND_PLATFORM + value: "true" runAfter: - prefetch-dependencies taskRef: params: - name: name - value: buildah-oci-ta + value: buildah-remote-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b + value: quay.io/konflux-ci/tekton-catalog/task-buildah-remote-oci-ta:0.10.5@sha256:eb277ec7b44443f0506a60ac940a2e52178d60f17cb0f51a6966daed5b3755de - name: kind value: task resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - name: build-image-index params: - name: IMAGE value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - name: ALWAYS_BUILD_INDEX value: $(params.build-image-index) - name: IMAGES value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) + - $(tasks.build-images.results.IMAGE_REF[*]) - name: BUILDAH_FORMAT value: $(params.buildah-format) runAfter: - - build-container + - build-images taskRef: params: - name: name value: build-image-index - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 + value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.3.1@sha256:cc75f64deecccb1b59e96ac1182665a5342d79c9e22eebff63d26b0f00a4319c - name: kind value: task resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - name: build-source-image params: - name: BINARY_IMAGE @@ -296,15 +313,11 @@ spec: - name: name value: source-build-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c + value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:7c5575ac8e292f27f57716c021ab0324460dc958e73946724c588c5228e5f372 - name: kind value: task resolver: bundles when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - input: $(params.build-source-image) operator: in values: @@ -322,7 +335,7 @@ spec: - name: name value: deprecated-image-check - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f + value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:0ccc688a77e9b7b0b8973c132a1e840844137e77f887be4a0bec8893b0776872 - name: kind value: task resolver: bundles @@ -331,7 +344,12 @@ spec: operator: in values: - "false" - - name: clair-scan + - matrix: + params: + - name: image-platform + value: + - $(params.build-platforms) + name: clair-scan params: - name: image-digest value: $(tasks.build-image-index.results.IMAGE_DIGEST) @@ -344,7 +362,7 @@ spec: - name: name value: clair-scan - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb + value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:f5b4415db9ac1fba3e11d993a617e0b275d1f0ed2fc669b12c400ed848c39174 - name: kind value: task resolver: bundles @@ -353,7 +371,12 @@ spec: operator: in values: - "false" - - name: ecosystem-cert-preflight-checks + - matrix: + params: + - name: platform + value: + - $(params.build-platforms) + name: ecosystem-cert-preflight-checks params: - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) @@ -364,7 +387,7 @@ spec: - name: name value: ecosystem-cert-preflight-checks - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 + value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:c07d2befa8abf48d4a223a5bdf5ea2335e756d4d0bbc422761087c263060aa94 - name: kind value: task resolver: bundles @@ -379,6 +402,8 @@ spec: value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) - name: SOURCE_ARTIFACT value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - name: CACHI2_ARTIFACT @@ -390,7 +415,7 @@ spec: - name: name value: sast-snyk-check-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 + value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.5@sha256:eba24f5d9f4b18aa71e523b9b3dbcf22982aa4b018824260a090b19dfc9abf6f - name: kind value: task resolver: bundles @@ -399,86 +424,25 @@ spec: operator: in values: - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: + - matrix: params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check + - name: image-arch + value: + - $(params.build-platforms) + name: clamav-scan params: - name: image-digest value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check runAfter: - build-image-index taskRef: params: - name: name - value: coverity-availability-check + value: clamav-scan - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 + value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:53a02326bfb930ca5ef6bfa7a33acca833d57752f34f3cb79255fe2e25e7d217 - name: kind value: task resolver: bundles @@ -493,6 +457,8 @@ spec: value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) - name: SOURCE_ARTIFACT value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - name: CACHI2_ARTIFACT @@ -504,7 +470,7 @@ spec: - name: name value: sast-shell-check-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 + value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:61b27e6ad5daba761d41bb37efb790ed98380603fd4fe2f86d156def5bd72ecc - name: kind value: task resolver: bundles @@ -519,6 +485,8 @@ spec: value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) - name: SOURCE_ARTIFACT value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - name: CACHI2_ARTIFACT @@ -530,7 +498,7 @@ spec: - name: name value: sast-unicode-check-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe + value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:eb9d5392f215cb8b52b16382098cac4885b1e6cd989f88ebd83fdb234d283eb9 - name: kind value: task resolver: bundles @@ -552,7 +520,7 @@ spec: - name: name value: apply-tags - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca + value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:3ab844157eccd68e95e4852adc06c3c4ea674edb7865a474b0a898227f2893d6 - name: kind value: task resolver: bundles @@ -575,7 +543,7 @@ spec: - name: name value: push-dockerfile-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e + value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.3.1@sha256:5a6cbebd89e5bc163b38231859767f7f6a0dd66cf1333699574379f062731183 - name: kind value: task resolver: bundles @@ -592,7 +560,7 @@ spec: - name: name value: rpms-signature-scan - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac + value: quay.io/konflux-ci/tekton-catalog/task-rpms-signature-scan:0.2@sha256:f110c53fd58cab7ac6e47d472bb801d49e2f584eb31837db9d611e11b3862a3d - name: kind value: task resolver: bundles @@ -607,7 +575,7 @@ spec: - name: netrc optional: true taskRunSpecs: - - pipelineTaskName: build-container + - pipelineTaskName: build-images stepSpecs: - name: build computeResources: @@ -618,7 +586,7 @@ spec: memory: 16Gi cpu: "6" taskRunTemplate: - serviceAccountName: build-pipeline-devlake-backend-d41aa + serviceAccountName: build-pipeline-devlake-backend workspaces: - name: git-auth secret: diff --git a/.tekton/devlake-backend-d41aa-push.yaml b/.tekton/devlake-backend-push.yaml similarity index 70% rename from .tekton/devlake-backend-d41aa-push.yaml rename to .tekton/devlake-backend-push.yaml index 792280ecd02..7e32552640a 100644 --- a/.tekton/devlake-backend-d41aa-push.yaml +++ b/.tekton/devlake-backend-push.yaml @@ -2,19 +2,19 @@ apiVersion: tekton.dev/v1 kind: PipelineRun metadata: annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} + build.appstudio.openshift.io/repo: https://github.com/RH-DevProd/devlake?rev={{revision}} build.appstudio.redhat.com/commit_sha: '{{revision}}' build.appstudio.redhat.com/target_branch: '{{target_branch}}' pipelinesascode.tekton.dev/cancel-in-progress: "false" pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "push" && target_branch == "main" - creationTimestamp: + pipelinesascode.tekton.dev/on-cel-expression: event == "push" && target_branch + == "main" labels: appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-backend-d41aa + appstudio.openshift.io/component: devlake-backend pipelines.appstudio.openshift.io/type: build - name: devlake-backend-d41aa-on-push - namespace: rh-konflux-devprod-tenant + name: devlake-backend-on-push + namespace: dprod-tenant spec: params: - name: git-url @@ -22,17 +22,20 @@ spec: - name: revision value: '{{revision}}' - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-backend:{{revision}} + value: quay.io/redhat-user-workloads/dprod-tenant/devlake-backend:{{revision}} + - name: build-platforms + value: + - linux/x86_64 - name: dockerfile - value: backend/Containerfile + value: Containerfile - name: path-context value: backend pipelineSpec: description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. + This pipeline is ideal for building multi-arch container images from a Containerfile while maintaining trust after pipeline customization. - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ + _Uses `buildah` to create a multi-platform container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. This pipeline requires that the [multi platform controller](https://github.com/konflux-ci/multi-platform-controller) is deployed and configured on your Konflux instance. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. + This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-multi-platform-oci-ta?tab=tags)_ params: - description: Source Repository URL name: git-url @@ -45,17 +48,15 @@ spec: name: output-image type: string - default: . - description: Path to the source code of an application's component from where to build image. + description: Path to the source code of an application's component from where + to build image. name: path-context type: string - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context + description: Path to the Dockerfile inside the context specified by parameter + path-context name: dockerfile type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - default: "false" description: Skip checks against built image name: skip-checks @@ -69,23 +70,35 @@ spec: name: prefetch-input type: string - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. + description: Image tag expiration time, time values could be something like + 1h, 2d, 3w for hours, days, and weeks, respectively. name: image-expires-after type: string - default: "false" description: Build a source image. name: build-source-image type: string - - default: "false" + - default: "true" description: Add built image into an OCI image index name: build-image-index type: string - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. + description: The format for the resulting image's mediaType. Valid values are + oci or docker. name: buildah-format type: string - - default: - - "BUILDPLATFORM=linux/amd64" + - default: "false" + description: Enable cache proxy configuration + name: enable-cache-proxy + - default: "true" + description: Use the package registry proxy when prefetching dependencies + name: enable-package-registry-proxy + - default: . + description: Target directories in component's source code to scan with SAST + tools. Multiple values should be separated with commas. + name: sast-target-dirs + type: string + - default: [] description: Array of --build-arg values ("arg=value" strings) for buildah name: build-args type: array @@ -94,13 +107,32 @@ spec: name: build-args-file type: string - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs + description: Whether to enable privileged mode, should be used only with remote + VMs name: privileged-nested type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration + - default: "" + description: Sets the image created time and the SOURCE_DATE_EPOCH build argument. + On its own, it does not change file timestamps inside the layers (set rewrite-timestamp + to "true" for that). Leave empty to keep the actual build time. + name: source-date-epoch + type: string + - default: "false" + description: When "true", clamp file modification times in the image layers + to at most source-date-epoch. Does nothing unless source-date-epoch is set. + name: rewrite-timestamp + type: string + - default: "false" + description: When "true", omit the build history (history timestamps, layer + metadata, etc.) from the resulting image. + name: omit-history type: string + - default: + - linux/x86_64 + description: List of platforms to build the container images on. The available + set of values is determined by the configuration of the multi-platform-controller. + name: build-platforms + type: array results: - description: "" name: IMAGE_URL @@ -117,12 +149,6 @@ spec: tasks: - name: init params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - name: enable-cache-proxy value: $(params.enable-cache-proxy) taskRef: @@ -130,7 +156,7 @@ spec: - name: name value: init - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 + value: quay.io/konflux-ci/tekton-catalog/task-init:0.4.2@sha256:421003a5c077ecb820460e71637125ec9093d2101c749a32ede28e190283e9db - name: kind value: task resolver: bundles @@ -151,15 +177,10 @@ spec: - name: name value: git-clone-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 + value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.2.4@sha256:df3c42d78223f07b40a84dd29e5c8860d14777ffdf150ea08c738770f51216dc - name: kind value: task resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" workspaces: - name: basic-auth workspace: git-auth @@ -167,6 +188,8 @@ spec: params: - name: input value: $(params.prefetch-input) + - name: enable-package-registry-proxy + value: $(params.enable-package-registry-proxy) - name: SOURCE_ARTIFACT value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - name: ociStorage @@ -180,7 +203,7 @@ spec: - name: name value: prefetch-dependencies-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 + value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.10.1@sha256:c09c1c3ced67fb8740b2925a7de09c0810d4e8c8f148d41c21ffe37810d85c62 - name: kind value: task resolver: bundles @@ -189,7 +212,12 @@ spec: workspace: git-auth - name: netrc workspace: netrc - - name: build-container + - matrix: + params: + - name: PLATFORM + value: + - $(params.build-platforms) + name: build-images params: - name: IMAGE value: $(params.output-image) @@ -216,61 +244,55 @@ spec: value: $(tasks.clone-repository.results.url) - name: BUILDAH_FORMAT value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - name: HTTP_PROXY value: $(tasks.init.results.http-proxy) - name: NO_PROXY value: $(tasks.init.results.no-proxy) + - name: SOURCE_DATE_EPOCH + value: $(params.source-date-epoch) + - name: REWRITE_TIMESTAMP + value: $(params.rewrite-timestamp) + - name: OMIT_HISTORY + value: $(params.omit-history) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + - name: IMAGE_APPEND_PLATFORM + value: "true" runAfter: - prefetch-dependencies taskRef: params: - name: name - value: buildah-oci-ta + value: buildah-remote-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b + value: quay.io/konflux-ci/tekton-catalog/task-buildah-remote-oci-ta:0.10.5@sha256:eb277ec7b44443f0506a60ac940a2e52178d60f17cb0f51a6966daed5b3755de - name: kind value: task resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - name: build-image-index params: - name: IMAGE value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - name: ALWAYS_BUILD_INDEX value: $(params.build-image-index) - name: IMAGES value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) + - $(tasks.build-images.results.IMAGE_REF[*]) - name: BUILDAH_FORMAT value: $(params.buildah-format) runAfter: - - build-container + - build-images taskRef: params: - name: name value: build-image-index - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 + value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.3.1@sha256:cc75f64deecccb1b59e96ac1182665a5342d79c9e22eebff63d26b0f00a4319c - name: kind value: task resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - name: build-source-image params: - name: BINARY_IMAGE @@ -288,15 +310,11 @@ spec: - name: name value: source-build-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c + value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:7c5575ac8e292f27f57716c021ab0324460dc958e73946724c588c5228e5f372 - name: kind value: task resolver: bundles when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - input: $(params.build-source-image) operator: in values: @@ -314,7 +332,7 @@ spec: - name: name value: deprecated-image-check - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f + value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:0ccc688a77e9b7b0b8973c132a1e840844137e77f887be4a0bec8893b0776872 - name: kind value: task resolver: bundles @@ -323,7 +341,12 @@ spec: operator: in values: - "false" - - name: clair-scan + - matrix: + params: + - name: image-platform + value: + - $(params.build-platforms) + name: clair-scan params: - name: image-digest value: $(tasks.build-image-index.results.IMAGE_DIGEST) @@ -336,7 +359,7 @@ spec: - name: name value: clair-scan - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb + value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:f5b4415db9ac1fba3e11d993a617e0b275d1f0ed2fc669b12c400ed848c39174 - name: kind value: task resolver: bundles @@ -345,7 +368,12 @@ spec: operator: in values: - "false" - - name: ecosystem-cert-preflight-checks + - matrix: + params: + - name: platform + value: + - $(params.build-platforms) + name: ecosystem-cert-preflight-checks params: - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) @@ -356,7 +384,7 @@ spec: - name: name value: ecosystem-cert-preflight-checks - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 + value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:c07d2befa8abf48d4a223a5bdf5ea2335e756d4d0bbc422761087c263060aa94 - name: kind value: task resolver: bundles @@ -371,6 +399,8 @@ spec: value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) - name: SOURCE_ARTIFACT value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - name: CACHI2_ARTIFACT @@ -382,7 +412,7 @@ spec: - name: name value: sast-snyk-check-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 + value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.5@sha256:eba24f5d9f4b18aa71e523b9b3dbcf22982aa4b018824260a090b19dfc9abf6f - name: kind value: task resolver: bundles @@ -391,86 +421,25 @@ spec: operator: in values: - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: + - matrix: params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check + - name: image-arch + value: + - $(params.build-platforms) + name: clamav-scan params: - name: image-digest value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check runAfter: - build-image-index taskRef: params: - name: name - value: coverity-availability-check + value: clamav-scan - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 + value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:53a02326bfb930ca5ef6bfa7a33acca833d57752f34f3cb79255fe2e25e7d217 - name: kind value: task resolver: bundles @@ -485,6 +454,8 @@ spec: value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) - name: SOURCE_ARTIFACT value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - name: CACHI2_ARTIFACT @@ -496,7 +467,7 @@ spec: - name: name value: sast-shell-check-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 + value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:61b27e6ad5daba761d41bb37efb790ed98380603fd4fe2f86d156def5bd72ecc - name: kind value: task resolver: bundles @@ -511,6 +482,8 @@ spec: value: $(tasks.build-image-index.results.IMAGE_DIGEST) - name: image-url value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) - name: SOURCE_ARTIFACT value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - name: CACHI2_ARTIFACT @@ -522,7 +495,7 @@ spec: - name: name value: sast-unicode-check-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe + value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:eb9d5392f215cb8b52b16382098cac4885b1e6cd989f88ebd83fdb234d283eb9 - name: kind value: task resolver: bundles @@ -544,7 +517,7 @@ spec: - name: name value: apply-tags - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca + value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:3ab844157eccd68e95e4852adc06c3c4ea674edb7865a474b0a898227f2893d6 - name: kind value: task resolver: bundles @@ -567,7 +540,7 @@ spec: - name: name value: push-dockerfile-oci-ta - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e + value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.3.1@sha256:5a6cbebd89e5bc163b38231859767f7f6a0dd66cf1333699574379f062731183 - name: kind value: task resolver: bundles @@ -584,7 +557,7 @@ spec: - name: name value: rpms-signature-scan - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac + value: quay.io/konflux-ci/tekton-catalog/task-rpms-signature-scan:0.2@sha256:f110c53fd58cab7ac6e47d472bb801d49e2f584eb31837db9d611e11b3862a3d - name: kind value: task resolver: bundles @@ -599,7 +572,7 @@ spec: - name: netrc optional: true taskRunSpecs: - - pipelineTaskName: build-container + - pipelineTaskName: build-images stepSpecs: - name: build computeResources: @@ -610,7 +583,7 @@ spec: memory: 16Gi cpu: "6" taskRunTemplate: - serviceAccountName: build-pipeline-devlake-backend-d41aa + serviceAccountName: build-pipeline-devlake-backend workspaces: - name: git-auth secret: diff --git a/.tekton/devlake-frontend-ba03c-pull-request.yaml b/.tekton/devlake-frontend-ba03c-pull-request.yaml deleted file mode 100644 index c3dbb65ca75..00000000000 --- a/.tekton/devlake-frontend-ba03c-pull-request.yaml +++ /dev/null @@ -1,609 +0,0 @@ -apiVersion: tekton.dev/v1 -kind: PipelineRun -metadata: - annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} - build.appstudio.redhat.com/commit_sha: '{{revision}}' - build.appstudio.redhat.com/pull_request_number: '{{pull_request_number}}' - build.appstudio.redhat.com/target_branch: '{{target_branch}}' - pipelinesascode.tekton.dev/cancel-in-progress: "true" - pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "pull_request" && target_branch == "main" && ( "config-ui/***".pathChanged() || ".tekton/devlake-frontend-ba03c-pull-request.yaml".pathChanged() || "config-ui/frontend".pathChanged() ) - creationTimestamp: - labels: - appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-frontend-ba03c - pipelines.appstudio.openshift.io/type: build - name: devlake-frontend-ba03c-on-pull-request - namespace: rh-konflux-devprod-tenant -spec: - params: - - name: git-url - value: '{{source_url}}' - - name: revision - value: '{{revision}}' - - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-frontend:on-pr-{{revision}} - - name: image-expires-after - value: 5d - - name: dockerfile - value: config-ui/Containerfile - - name: path-context - value: config-ui - pipelineSpec: - description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. - - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ - params: - - description: Source Repository URL - name: git-url - type: string - - default: "" - description: Revision of the Source Repository - name: revision - type: string - - description: Fully Qualified Output Image - name: output-image - type: string - - default: . - description: Path to the source code of an application's component from where to build image. - name: path-context - type: string - - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context - name: dockerfile - type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - - default: "false" - description: Skip checks against built image - name: skip-checks - type: string - - default: "false" - description: Execute the build with network isolation - name: hermetic - type: string - - default: "" - description: Build dependencies to be prefetched - name: prefetch-input - type: string - - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. - name: image-expires-after - type: string - - default: "false" - description: Build a source image. - name: build-source-image - type: string - - default: "false" - description: Add built image into an OCI image index - name: build-image-index - type: string - - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. - name: buildah-format - type: string - - default: [] - description: Array of --build-arg values ("arg=value" strings) for buildah - name: build-args - type: array - - default: "" - description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file - name: build-args-file - type: string - - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs - name: privileged-nested - type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration - type: string - results: - - description: "" - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - description: "" - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - description: "" - name: CHAINS-GIT_URL - value: $(tasks.clone-repository.results.url) - - description: "" - name: CHAINS-GIT_COMMIT - value: $(tasks.clone-repository.results.commit) - tasks: - - name: init - params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - - name: enable-cache-proxy - value: $(params.enable-cache-proxy) - taskRef: - params: - - name: name - value: init - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 - - name: kind - value: task - resolver: bundles - - name: clone-repository - params: - - name: url - value: $(params.git-url) - - name: revision - value: $(params.revision) - - name: ociStorage - value: $(params.output-image).git - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - init - taskRef: - params: - - name: name - value: git-clone-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - workspaces: - - name: basic-auth - workspace: git-auth - - name: prefetch-dependencies - params: - - name: input - value: $(params.prefetch-input) - - name: SOURCE_ARTIFACT - value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - - name: ociStorage - value: $(params.output-image).prefetch - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - clone-repository - taskRef: - params: - - name: name - value: prefetch-dependencies-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 - - name: kind - value: task - resolver: bundles - workspaces: - - name: git-basic-auth - workspace: git-auth - - name: netrc - workspace: netrc - - name: build-container - params: - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: PRIVILEGED_NESTED - value: $(params.privileged-nested) - - name: SOURCE_URL - value: $(tasks.clone-repository.results.url) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - - name: HTTP_PROXY - value: $(tasks.init.results.http-proxy) - - name: NO_PROXY - value: $(tasks.init.results.no-proxy) - runAfter: - - prefetch-dependencies - taskRef: - params: - - name: name - value: buildah-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-image-index - params: - - name: IMAGE - value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: ALWAYS_BUILD_INDEX - value: $(params.build-image-index) - - name: IMAGES - value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - runAfter: - - build-container - taskRef: - params: - - name: name - value: build-image-index - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-source-image - params: - - name: BINARY_IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: BINARY_IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: source-build-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - input: $(params.build-source-image) - operator: in - values: - - "true" - - name: deprecated-base-image-check - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: deprecated-image-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clair-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clair-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: ecosystem-cert-preflight-checks - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: ecosystem-cert-preflight-checks - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-snyk-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-snyk-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: coverity-availability-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-shell-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-shell-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-unicode-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-unicode-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: apply-tags - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: apply-tags - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca - - name: kind - value: task - resolver: bundles - - name: push-dockerfile - params: - - name: IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: push-dockerfile-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e - - name: kind - value: task - resolver: bundles - - name: rpms-signature-scan - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: rpms-signature-scan - - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - workspaces: - - name: git-auth - optional: true - - name: netrc - optional: true - taskRunTemplate: - serviceAccountName: build-pipeline-devlake-frontend-ba03c - workspaces: - - name: git-auth - secret: - secretName: '{{ git_auth_secret }}' -status: {} diff --git a/.tekton/devlake-frontend-ba03c-push.yaml b/.tekton/devlake-frontend-ba03c-push.yaml deleted file mode 100644 index c8402983ce3..00000000000 --- a/.tekton/devlake-frontend-ba03c-push.yaml +++ /dev/null @@ -1,606 +0,0 @@ -apiVersion: tekton.dev/v1 -kind: PipelineRun -metadata: - annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} - build.appstudio.redhat.com/commit_sha: '{{revision}}' - build.appstudio.redhat.com/target_branch: '{{target_branch}}' - pipelinesascode.tekton.dev/cancel-in-progress: "false" - pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "push" && target_branch == "main" && ( "config-ui/***".pathChanged() || ".tekton/devlake-frontend-ba03c-push.yaml".pathChanged() || "config-ui/frontend".pathChanged() ) - creationTimestamp: - labels: - appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-frontend-ba03c - pipelines.appstudio.openshift.io/type: build - name: devlake-frontend-ba03c-on-push - namespace: rh-konflux-devprod-tenant -spec: - params: - - name: git-url - value: '{{source_url}}' - - name: revision - value: '{{revision}}' - - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-frontend:{{revision}} - - name: dockerfile - value: config-ui/Containerfile - - name: path-context - value: config-ui - pipelineSpec: - description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. - - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ - params: - - description: Source Repository URL - name: git-url - type: string - - default: "" - description: Revision of the Source Repository - name: revision - type: string - - description: Fully Qualified Output Image - name: output-image - type: string - - default: . - description: Path to the source code of an application's component from where to build image. - name: path-context - type: string - - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context - name: dockerfile - type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - - default: "false" - description: Skip checks against built image - name: skip-checks - type: string - - default: "false" - description: Execute the build with network isolation - name: hermetic - type: string - - default: "" - description: Build dependencies to be prefetched - name: prefetch-input - type: string - - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. - name: image-expires-after - type: string - - default: "false" - description: Build a source image. - name: build-source-image - type: string - - default: "false" - description: Add built image into an OCI image index - name: build-image-index - type: string - - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. - name: buildah-format - type: string - - default: [] - description: Array of --build-arg values ("arg=value" strings) for buildah - name: build-args - type: array - - default: "" - description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file - name: build-args-file - type: string - - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs - name: privileged-nested - type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration - type: string - results: - - description: "" - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - description: "" - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - description: "" - name: CHAINS-GIT_URL - value: $(tasks.clone-repository.results.url) - - description: "" - name: CHAINS-GIT_COMMIT - value: $(tasks.clone-repository.results.commit) - tasks: - - name: init - params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - - name: enable-cache-proxy - value: $(params.enable-cache-proxy) - taskRef: - params: - - name: name - value: init - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 - - name: kind - value: task - resolver: bundles - - name: clone-repository - params: - - name: url - value: $(params.git-url) - - name: revision - value: $(params.revision) - - name: ociStorage - value: $(params.output-image).git - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - init - taskRef: - params: - - name: name - value: git-clone-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - workspaces: - - name: basic-auth - workspace: git-auth - - name: prefetch-dependencies - params: - - name: input - value: $(params.prefetch-input) - - name: SOURCE_ARTIFACT - value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - - name: ociStorage - value: $(params.output-image).prefetch - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - clone-repository - taskRef: - params: - - name: name - value: prefetch-dependencies-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 - - name: kind - value: task - resolver: bundles - workspaces: - - name: git-basic-auth - workspace: git-auth - - name: netrc - workspace: netrc - - name: build-container - params: - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: PRIVILEGED_NESTED - value: $(params.privileged-nested) - - name: SOURCE_URL - value: $(tasks.clone-repository.results.url) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - - name: HTTP_PROXY - value: $(tasks.init.results.http-proxy) - - name: NO_PROXY - value: $(tasks.init.results.no-proxy) - runAfter: - - prefetch-dependencies - taskRef: - params: - - name: name - value: buildah-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-image-index - params: - - name: IMAGE - value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: ALWAYS_BUILD_INDEX - value: $(params.build-image-index) - - name: IMAGES - value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - runAfter: - - build-container - taskRef: - params: - - name: name - value: build-image-index - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-source-image - params: - - name: BINARY_IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: BINARY_IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: source-build-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - input: $(params.build-source-image) - operator: in - values: - - "true" - - name: deprecated-base-image-check - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: deprecated-image-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clair-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clair-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: ecosystem-cert-preflight-checks - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: ecosystem-cert-preflight-checks - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-snyk-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-snyk-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: coverity-availability-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-shell-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-shell-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-unicode-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-unicode-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: apply-tags - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: apply-tags - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca - - name: kind - value: task - resolver: bundles - - name: push-dockerfile - params: - - name: IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: push-dockerfile-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e - - name: kind - value: task - resolver: bundles - - name: rpms-signature-scan - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: rpms-signature-scan - - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - workspaces: - - name: git-auth - optional: true - - name: netrc - optional: true - taskRunTemplate: - serviceAccountName: build-pipeline-devlake-frontend-ba03c - workspaces: - - name: git-auth - secret: - secretName: '{{ git_auth_secret }}' -status: {} diff --git a/backend/helpers/pluginhelper/api/graphql_collector.go b/backend/helpers/pluginhelper/api/graphql_collector.go index 28a5b2b9d86..6dd75f36631 100644 --- a/backend/helpers/pluginhelper/api/graphql_collector.go +++ b/backend/helpers/pluginhelper/api/graphql_collector.go @@ -20,6 +20,7 @@ package api import ( "context" "encoding/json" + "fmt" "net/http" "reflect" "strings" @@ -187,9 +188,11 @@ func (collector *GraphqlCollector) Execute() errors.Error { collector.args.GraphqlClient.Wait() if collector.HasError() { + for i, workerErr := range collector.workerErrors { + logger.Error(nil, "graphql collector worker error [%d/%d]: %s", i+1, len(collector.workerErrors), workerErr) + } err = errors.Default.Combine(collector.workerErrors) logger.Error(err, "ended Graphql collector execution with error") - logger.Error(collector.workerErrors[0], "the first error of them") return err } else { logger.Info("ended api collection without error") @@ -270,7 +273,9 @@ func (collector *GraphqlCollector) fetchAsync(reqData *GraphqlRequestData, handl // direct error message for error combine collector.checkError(err) } else { - collector.checkError(errors.Default.Wrap(err, `graphql query failed`)) + msg := formatGraphqlQueryFailure(err, variables) + logger.Error(nil, "%s", msg) + collector.checkError(errors.Default.New(msg)) } return } @@ -279,11 +284,13 @@ func (collector *GraphqlCollector) fetchAsync(reqData *GraphqlRequestData, handl hasNonIgnorableDataErrors := false for _, dataError := range dataErrors { if isIgnorableGraphqlQueryError(dataError) { - logger.Warn(nil, "Issue may have been transferred or deleted.") + logger.Warn(nil, "ignorable graphql data error (issue transferred or deleted): %s", formatGraphqlDataError(dataError, variables)) continue } hasNonIgnorableDataErrors = true - collector.checkError(errors.Default.Wrap(dataError, `graphql query got error`)) + msg := formatGraphqlDataError(dataError, variables) + logger.Error(nil, "%s", msg) + collector.checkError(errors.Default.New(msg)) } if hasNonIgnorableDataErrors { return @@ -352,4 +359,31 @@ func isIgnorableGraphqlQueryError(err error) bool { return err != nil && strings.Contains(err.Error(), "Could not resolve to an Issue") } +func formatGraphqlQueryFailure(err error, variables map[string]interface{}) string { + return fmt.Sprintf("graphql query failed: %s%s", err.Error(), formatGraphqlVariables(variables)) +} + +func formatGraphqlDataError(err error, variables map[string]interface{}) string { + msg := err.Error() + if de, ok := err.(graphql.DataError); ok && len(de.Locations) > 0 { + locs := make([]string, 0, len(de.Locations)) + for _, loc := range de.Locations { + locs = append(locs, fmt.Sprintf("line %d col %d", loc.Line, loc.Column)) + } + msg = fmt.Sprintf("%s (%s)", msg, strings.Join(locs, ", ")) + } + return fmt.Sprintf("graphql query got error: %s%s", msg, formatGraphqlVariables(variables)) +} + +func formatGraphqlVariables(variables map[string]interface{}) string { + if len(variables) == 0 { + return "" + } + varsJSON, err := json.Marshal(variables) + if err != nil { + return fmt.Sprintf(" variables=%v", variables) + } + return fmt.Sprintf(" variables=%s", varsJSON) +} + var _ plugin.SubTask = (*GraphqlCollector)(nil) diff --git a/backend/helpers/pluginhelper/api/graphql_collector_test.go b/backend/helpers/pluginhelper/api/graphql_collector_test.go index fcab4dce098..ef530c4bef4 100644 --- a/backend/helpers/pluginhelper/api/graphql_collector_test.go +++ b/backend/helpers/pluginhelper/api/graphql_collector_test.go @@ -21,6 +21,7 @@ import ( "errors" "testing" + "github.com/merico-ai/graphql" "github.com/stretchr/testify/assert" ) @@ -29,3 +30,29 @@ func TestIsIgnorableGraphqlQueryError(t *testing.T) { assert.False(t, isIgnorableGraphqlQueryError(errors.New("some other graphql error"))) assert.False(t, isIgnorableGraphqlQueryError(nil)) } + +func TestFormatGraphqlDataError(t *testing.T) { + err := graphql.DataError{ + Message: "Could not resolve to a PullRequest with the number of 42.", + Locations: []struct { + Line int + Column int + }{{Line: 3, Column: 5}}, + } + got := formatGraphqlDataError(err, map[string]interface{}{ + "owner": "acme", + "name": "repo", + }) + assert.Contains(t, got, "Could not resolve to a PullRequest with the number of 42.") + assert.Contains(t, got, "line 3 col 5") + assert.Contains(t, got, `"owner":"acme"`) + assert.Contains(t, got, `"name":"repo"`) +} + +func TestFormatGraphqlQueryFailure(t *testing.T) { + got := formatGraphqlQueryFailure(errors.New("non-200 OK status code: 502"), map[string]interface{}{ + "pageSize": 10, + }) + assert.Contains(t, got, "graphql query failed: non-200 OK status code: 502") + assert.Contains(t, got, `"pageSize":10`) +} diff --git a/backend/plugins/codecov/AGENTS.md b/backend/plugins/codecov/AGENTS.md index 87b4ae1ae43..5722a8e6ac7 100644 --- a/backend/plugins/codecov/AGENTS.md +++ b/backend/plugins/codecov/AGENTS.md @@ -12,7 +12,15 @@ golangci-lint run ./plugins/codecov/... # lint Single-file verification: `go vet ./plugins/codecov/...` -No e2e tests yet — coverage data is validated via unit tests and manual Grafana dashboard checks. +Playwright e2e (requires `CODECOV_TOKEN`): + +```bash +cd e2e +export CODECOV_TOKEN=... # Codecov API token for konflux-ci org +npm run test:codecov +``` + +Exercises the full plugin lifecycle (connection → scope → blueprint → pipeline with all 13 subtasks). Runs in CI via `.github/workflows/test-e2e-coverage.yml` to drive Go coverage under the `e2e-go` flag. ## Layout diff --git a/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md b/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md index 46551a3d258..f1da097b805 100644 --- a/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md +++ b/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md @@ -36,6 +36,6 @@ description: >- ## CI Behavior - **Unit tests**: Run on PRs via `make unit-test-go` (excludes `e2e/` and `models/` packages) -- **E2E tests**: No e2e tests exist yet; adding `codecov/e2e/` would be auto-discovered by CI +- **E2E tests**: Playwright spec at `e2e/codecov-flow.spec.ts` runs in `test-e2e-coverage` workflow (requires `CODECOV_TOKEN` secret) - **Lint**: Runs only on push to main/tags, not on PRs - Upstream CI also runs `plugins/table_info_test.go` — fails if `GetTablesInfo()` is incomplete diff --git a/backend/plugins/jira/api/connection_api.go b/backend/plugins/jira/api/connection_api.go index 9b6071b15fc..198be0a13e8 100644 --- a/backend/plugins/jira/api/connection_api.go +++ b/backend/plugins/jira/api/connection_api.go @@ -19,7 +19,9 @@ package api import ( "context" + "encoding/json" "fmt" + "io" "net/http" "net/url" "strings" @@ -39,11 +41,9 @@ type JiraTestConnResponse struct { } func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestConnResponse, errors.Error) { - // validate - if vld != nil { - e := vld.StructExcept(connection, "BasicAuth", "AccessToken") - if e != nil { - return nil, errors.Convert(e) + if connection.IsOAuth2() || vld != nil { + if err := connection.ValidateConnection(&connection, vld); err != nil { + return nil, err } } // test connection @@ -71,10 +71,12 @@ func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestC return nil, errors.NotFound.New(fmt.Sprintf("Seems like an invalid Endpoint URL, please try %s", restUrl.String())) } if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { - return nil, errors.HttpStatus(res.StatusCode).New("Please check your credential") + // 400 not 401: Config UI treats HTTP 401 as a DevLake session expiry and + // navigates to /login, wiping the connection form and Network tab. + return nil, errors.BadInput.New(withJiraHTTPDetail(res, "Please check your credential")) } if res.StatusCode != http.StatusOK { - return nil, errors.HttpStatus(res.StatusCode).New(fmt.Sprintf("%s unexpected status code: %d", serverInfoFail, res.StatusCode)) + return nil, errors.HttpStatus(res.StatusCode).New(withJiraHTTPDetail(res, fmt.Sprintf("%s unexpected status code: %d", serverInfoFail, res.StatusCode))) } resBody := &models.JiraServerInfo{} @@ -98,13 +100,16 @@ func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestC } getStatusFail += ": [ " + res.Request.URL.String() + " ]" - errMsg := "" - if res.StatusCode == http.StatusUnauthorized { - return nil, errors.HttpStatus(res.StatusCode).New("Please check your credential") + if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { + return nil, errors.BadInput.New(withJiraHTTPDetail(res, fmt.Sprintf( + "Jira accepted the connection (serverInfo OK) but GET %s returned %d", + res.Request.URL.String(), + res.StatusCode, + ))) } if res.StatusCode != http.StatusOK { - return nil, errors.HttpStatus(res.StatusCode).New(fmt.Sprintf("%s Unexpected [%s] status code: %d %s", getStatusFail, res.Request.URL, res.StatusCode, errMsg)) + return nil, errors.HttpStatus(res.StatusCode).New(withJiraHTTPDetail(res, fmt.Sprintf("%s Unexpected [%s] status code: %d", getStatusFail, res.Request.URL, res.StatusCode))) } connection = connection.Sanitize() body := JiraTestConnResponse{} @@ -219,3 +224,62 @@ func ListConnections(input *plugin.ApiResourceInput) (*plugin.ApiResourceOutput, func GetConnection(input *plugin.ApiResourceInput) (*plugin.ApiResourceOutput, errors.Error) { return dsHelper.ConnApi.GetDetail(input) } + +func withJiraHTTPDetail(res *http.Response, msg string) string { + if detail := jiraHTTPErrorDetail(res); detail != "" { + return msg + ": " + detail + } + return msg +} + +// jiraHTTPErrorDetail reads Jira's error payload. Classic REST uses +// errorMessages; the Atlassian OAuth gateway often uses message and/or +// WWW-Authenticate (e.g. insufficient_scope). +func jiraHTTPErrorDetail(res *http.Response) string { + if res == nil || res.Body == nil { + return "" + } + defer res.Body.Close() + raw, err := io.ReadAll(io.LimitReader(res.Body, 4096)) + if err != nil { + return "" + } + if parsed := parseJiraErrorBody(strings.TrimSpace(string(raw))); parsed != "" { + return parsed + } + if auth := strings.TrimSpace(res.Header.Get("WWW-Authenticate")); auth != "" { + return auth + } + text := strings.TrimSpace(string(raw)) + if text == "" || strings.HasPrefix(text, "<") { + return "" + } + const maxLen = 500 + if len(text) > maxLen { + return text[:maxLen] + "..." + } + return text +} + +func parseJiraErrorBody(text string) string { + if text == "" || text[0] != '{' { + return "" + } + var payload struct { + ErrorMessages []string `json:"errorMessages"` + Message string `json:"message"` + } + if json.Unmarshal([]byte(text), &payload) != nil { + return "" + } + parts := make([]string, 0, len(payload.ErrorMessages)+1) + for _, m := range payload.ErrorMessages { + if m = strings.TrimSpace(m); m != "" { + parts = append(parts, m) + } + } + if m := strings.TrimSpace(payload.Message); m != "" { + parts = append(parts, m) + } + return strings.Join(parts, "; ") +} diff --git a/backend/plugins/jira/api/connection_api_test.go b/backend/plugins/jira/api/connection_api_test.go new file mode 100644 index 00000000000..31d3962a36f --- /dev/null +++ b/backend/plugins/jira/api/connection_api_test.go @@ -0,0 +1,70 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package api + +import ( + "io" + "net/http" + "strings" + "testing" +) + +func TestJiraHTTPErrorDetail(t *testing.T) { + tests := []struct { + name string + body string + header string + want string + }{ + { + name: "classic jira errorMessages", + body: `{"errorMessages":["Client must be authenticated to access this resource."],"errors":{}}`, + want: "Client must be authenticated to access this resource.", + }, + { + name: "atlassian gateway message", + body: `{"code":401,"message":"Unauthorized; scope does not match"}`, + want: "Unauthorized; scope does not match", + }, + { + name: "www-authenticate when body empty", + header: `Bearer error="insufficient_scope"`, + want: `Bearer error="insufficient_scope"`, + }, + { + name: "html body ignored", + body: `Unauthorized`, + want: "", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + res := &http.Response{ + StatusCode: http.StatusUnauthorized, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(tt.body)), + } + if tt.header != "" { + res.Header.Set("WWW-Authenticate", tt.header) + } + if got := jiraHTTPErrorDetail(res); got != tt.want { + t.Errorf("jiraHTTPErrorDetail() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/backend/plugins/jira/models/connection.go b/backend/plugins/jira/models/connection.go index 8060c308aaf..578ac3395a0 100644 --- a/backend/plugins/jira/models/connection.go +++ b/backend/plugins/jira/models/connection.go @@ -18,13 +18,30 @@ limitations under the License. package models import ( - "github.com/apache/incubator-devlake/core/utils" + "fmt" "net/http" + "regexp" + "strings" + "time" + + "github.com/go-playground/validator/v10" "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/core/plugin" + "github.com/apache/incubator-devlake/core/utils" helper "github.com/apache/incubator-devlake/helpers/pluginhelper/api" ) +const ( + // AUTH_METHOD_OAUTH2 is Jira Cloud service-account OAuth 2.0 (client credentials / 2LO). + // It is plugin-specific and is not registered in core MultiAuth. + AUTH_METHOD_OAUTH2 = "OAuth2" +) + +// cloudIDPattern allows Atlassian Cloud IDs (UUIDs) and test fixtures such as "cloud-1". +// It rejects path separators and URL metacharacters so CloudId cannot change the gateway path. +var cloudIDPattern = regexp.MustCompile(`^[a-zA-Z0-9-]{1,64}$`) + type EpicResponse struct { Id int Title string @@ -43,20 +60,107 @@ type JiraConn struct { helper.MultiAuth `mapstructure:",squash"` helper.BasicAuth `mapstructure:",squash"` helper.AccessToken `mapstructure:",squash"` + + ClientId string `mapstructure:"clientId" json:"clientId" gorm:"type:varchar(255)"` + ClientSecret string `mapstructure:"clientSecret" json:"clientSecret" gorm:"type:text;serializer:encdec"` + CloudId string `mapstructure:"cloudId" json:"cloudId" gorm:"type:varchar(255)"` + + // OAuthTokenURL overrides the Atlassian token endpoint (tests only). + OAuthTokenURL string `json:"-" mapstructure:"-" gorm:"-"` + + oauthToken string + oauthTokenExpiresAt *time.Time } func (jc *JiraConn) Sanitize() JiraConn { jc.Password = "" jc.AccessToken.Token = utils.SanitizeString(jc.AccessToken.Token) + jc.ClientSecret = utils.SanitizeString(jc.ClientSecret) + jc.oauthToken = "" + jc.oauthTokenExpiresAt = nil return *jc } +func (jc *JiraConn) IsOAuth2() bool { + return jc.AuthMethod == AUTH_METHOD_OAUTH2 +} + +func sanitizedCloudID(cloudId string) string { + cloudId = strings.TrimSpace(cloudId) + if !cloudIDPattern.MatchString(cloudId) { + return "" + } + return cloudId +} + +// GatewayEndpoint returns the Atlassian API gateway base URL for this cloud ID. +func (jc *JiraConn) GatewayEndpoint() string { + cloudId := sanitizedCloudID(jc.CloudId) + if cloudId == "" { + return "" + } + return fmt.Sprintf("https://api.atlassian.com/ex/jira/%s/rest/", cloudId) +} + +// ApplyGatewayEndpoint sets Endpoint to the OAuth 2.0 gateway URL. +func (jc *JiraConn) ApplyGatewayEndpoint() { + if !jc.IsOAuth2() { + return + } + if endpoint := jc.GatewayEndpoint(); endpoint != "" { + jc.Endpoint = endpoint + } +} + +func (jc *JiraConn) OAuthAccessToken() string { + return jc.oauthToken +} + +func (jc *JiraConn) OAuthAccessTokenExpiresAt() *time.Time { + return jc.oauthTokenExpiresAt +} + +func (jc *JiraConn) SetOAuthAccessToken(token string, expiresAt time.Time) { + jc.oauthToken = token + expiry := expiresAt + jc.oauthTokenExpiresAt = &expiry +} + // SetupAuthentication implements the `IAuthentication` interface by delegating // the actual logic to the `MultiAuth` struct to help us write less code func (jc *JiraConn) SetupAuthentication(req *http.Request) errors.Error { + if jc.IsOAuth2() { + token := jc.OAuthAccessToken() + if token == "" { + return errors.Unauthorized.New("oauth2 access token is missing") + } + req.Header.Set("Authorization", "Bearer "+token) + return nil + } return jc.MultiAuth.SetupAuthenticationForConnection(jc, req) } +// ValidateConnection shadows MultiAuth so authMethod=OAuth2 is not rejected by +// the shared oneof=BasicAuth AccessToken AppKey constraint. +func (jc *JiraConn) ValidateConnection(connection interface{}, v *validator.Validate) errors.Error { + if jc.IsOAuth2() { + if strings.TrimSpace(jc.ClientId) == "" || strings.TrimSpace(jc.ClientSecret) == "" || strings.TrimSpace(jc.CloudId) == "" { + return errors.BadInput.New("clientId, clientSecret and cloudId are required for OAuth2") + } + if sanitizedCloudID(jc.CloudId) == "" { + return errors.BadInput.New("cloudId must contain only letters, digits, and hyphens") + } + jc.ApplyGatewayEndpoint() + if conn, ok := connection.(*JiraConnection); ok && strings.TrimSpace(conn.Name) == "" { + return errors.BadInput.New("name is required") + } + return nil + } + return jc.MultiAuth.ValidateConnection(connection, v) +} + +var _ plugin.PrepareApiClient = (*JiraConn)(nil) + // JiraConnection holds JiraConn plus ID/Name for database storage type JiraConnection struct { helper.BaseConnection `mapstructure:",squash"` @@ -67,9 +171,14 @@ func (JiraConnection) TableName() string { return "_tool_jira_connections" } +func (connection *JiraConnection) CustomValidate(entity interface{}, v *validator.Validate) errors.Error { + return connection.JiraConn.ValidateConnection(entity, v) +} + func (connection *JiraConnection) MergeFromRequest(target *JiraConnection, body map[string]interface{}) error { token := target.Token password := target.Password + clientSecret := target.ClientSecret authMethod := target.AuthMethod if err := helper.DecodeMapStruct(body, target, true); err != nil { @@ -78,6 +187,7 @@ func (connection *JiraConnection) MergeFromRequest(target *JiraConnection, body modifiedToken := target.Token modifiedPassword := target.Password + modifiedClientSecret := target.ClientSecret modifiedAuthMethod := target.AuthMethod // maybe auth method has changed @@ -88,6 +198,13 @@ func (connection *JiraConnection) MergeFromRequest(target *JiraConnection, body if modifiedPassword == "" || modifiedPassword == utils.SanitizeString(password) { target.Password = password } + if modifiedClientSecret == "" || modifiedClientSecret == utils.SanitizeString(clientSecret) { + target.ClientSecret = clientSecret + } + } + + if target.IsOAuth2() { + target.ApplyGatewayEndpoint() } return nil diff --git a/backend/plugins/jira/models/connection_test.go b/backend/plugins/jira/models/connection_test.go new file mode 100644 index 00000000000..a1fad3e6dca --- /dev/null +++ b/backend/plugins/jira/models/connection_test.go @@ -0,0 +1,163 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package models + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/go-playground/validator/v10" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/apache/incubator-devlake/core/utils" + helper "github.com/apache/incubator-devlake/helpers/pluginhelper/api" +) + +func TestGatewayEndpoint(t *testing.T) { + jc := &JiraConn{CloudId: "abc-123"} + assert.Equal(t, "https://api.atlassian.com/ex/jira/abc-123/rest/", jc.GatewayEndpoint()) + + jc.CloudId = " abc-123 " + assert.Equal(t, "https://api.atlassian.com/ex/jira/abc-123/rest/", jc.GatewayEndpoint()) + + jc.CloudId = "" + assert.Equal(t, "", jc.GatewayEndpoint()) + + jc.CloudId = "../evil" + assert.Equal(t, "", jc.GatewayEndpoint()) + + jc.CloudId = "foo/bar" + assert.Equal(t, "", jc.GatewayEndpoint()) + + jc.CloudId = "foo?x=1" + assert.Equal(t, "", jc.GatewayEndpoint()) +} + +func TestApplyGatewayEndpoint(t *testing.T) { + jc := &JiraConn{ + CloudId: "cloud-1", + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + jc.ApplyGatewayEndpoint() + assert.Equal(t, "https://api.atlassian.com/ex/jira/cloud-1/rest/", jc.Endpoint) + + basic := &JiraConn{CloudId: "cloud-1"} + basic.AuthMethod = "BasicAuth" + basic.Endpoint = "https://example.atlassian.net/rest/" + basic.ApplyGatewayEndpoint() + assert.Equal(t, "https://example.atlassian.net/rest/", basic.Endpoint) +} + +func TestValidateConnectionOAuth2(t *testing.T) { + v := validator.New() + jc := &JiraConn{ + ClientId: "id", + ClientSecret: "secret", + CloudId: "cloud-1", + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + + err := jc.ValidateConnection(jc, v) + require.NoError(t, err) + assert.Equal(t, "https://api.atlassian.com/ex/jira/cloud-1/rest/", jc.Endpoint) + + missing := &JiraConn{CloudId: "cloud-1"} + missing.AuthMethod = AUTH_METHOD_OAUTH2 + err = missing.ValidateConnection(missing, v) + require.Error(t, err) + assert.Contains(t, err.Error(), "clientId, clientSecret and cloudId are required") + + invalid := &JiraConn{ + ClientId: "id", + ClientSecret: "secret", + CloudId: "../evil", + } + invalid.AuthMethod = AUTH_METHOD_OAUTH2 + err = invalid.ValidateConnection(invalid, v) + require.Error(t, err) + assert.Contains(t, err.Error(), "cloudId must contain only letters, digits, and hyphens") +} + +func TestValidateConnectionOAuth2DoesNotUseMultiAuthOneOf(t *testing.T) { + v := validator.New() + conn := &JiraConnection{} + conn.Name = "jira-oauth" + conn.AuthMethod = AUTH_METHOD_OAUTH2 + conn.ClientId = "id" + conn.ClientSecret = "secret" + conn.CloudId = "cloud-1" + + err := conn.CustomValidate(conn, v) + require.NoError(t, err) +} + +func TestSanitizeAndMergeFromRequestClientSecret(t *testing.T) { + conn := &JiraConnection{} + conn.AuthMethod = AUTH_METHOD_OAUTH2 + conn.ClientId = "id" + conn.ClientSecret = "super-secret" + conn.CloudId = "cloud-1" + conn.ApplyGatewayEndpoint() + + sanitized := conn.Sanitize() + assert.Equal(t, utils.SanitizeString("super-secret"), sanitized.ClientSecret) + assert.Empty(t, sanitized.OAuthAccessToken()) + + err := conn.MergeFromRequest(conn, map[string]interface{}{ + "authMethod": AUTH_METHOD_OAUTH2, + "clientId": "id", + "clientSecret": utils.SanitizeString("super-secret"), + "cloudId": "cloud-1", + }) + require.NoError(t, err) + assert.Equal(t, "super-secret", conn.ClientSecret) + assert.Equal(t, "https://api.atlassian.com/ex/jira/cloud-1/rest/", conn.Endpoint) +} + +func TestSetupAuthenticationOAuth2(t *testing.T) { + jc := &JiraConn{} + jc.AuthMethod = AUTH_METHOD_OAUTH2 + jc.SetOAuthAccessToken("access-token", time.Now().Add(time.Hour)) + + req := httptest.NewRequest(http.MethodGet, "https://api.atlassian.com/ex/jira/c/rest/api/2/serverInfo", nil) + err := jc.SetupAuthentication(req) + require.NoError(t, err) + assert.Equal(t, "Bearer access-token", req.Header.Get("Authorization")) +} + +func TestSetupAuthenticationOAuth2MissingToken(t *testing.T) { + jc := &JiraConn{} + jc.AuthMethod = AUTH_METHOD_OAUTH2 + req := httptest.NewRequest(http.MethodGet, "https://example.com", nil) + err := jc.SetupAuthentication(req) + require.Error(t, err) +} + +func TestValidateConnectionBasicAuthStillWorks(t *testing.T) { + v := validator.New() + jc := &JiraConn{ + RestConnection: helper.RestConnection{Endpoint: "https://example.atlassian.net/rest/"}, + BasicAuth: helper.BasicAuth{Username: "user@example.com", Password: "token"}, + } + jc.AuthMethod = "BasicAuth" + err := jc.ValidateConnection(jc, v) + require.NoError(t, err) +} diff --git a/backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go b/backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go new file mode 100644 index 00000000000..0336e500655 --- /dev/null +++ b/backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go @@ -0,0 +1,48 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package migrationscripts + +import ( + "github.com/apache/incubator-devlake/core/context" + "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/helpers/migrationhelper" +) + +type jiraOAuth20260907 struct { + ClientId string `gorm:"type:varchar(255)"` + ClientSecret string `gorm:"type:text"` + CloudId string `gorm:"type:varchar(255)"` +} + +func (jiraOAuth20260907) TableName() string { + return "_tool_jira_connections" +} + +type addJiraOAuth20260907 struct{} + +func (script *addJiraOAuth20260907) Up(basicRes context.BasicRes) errors.Error { + return migrationhelper.AutoMigrateTables(basicRes, &jiraOAuth20260907{}) +} + +func (*addJiraOAuth20260907) Version() uint64 { + return 20260907120000 +} + +func (*addJiraOAuth20260907) Name() string { + return "add oauth2 client credentials to _tool_jira_connections" +} diff --git a/backend/plugins/jira/models/migrationscripts/register.go b/backend/plugins/jira/models/migrationscripts/register.go index 9c334a9ef88..1e6b3cfd888 100644 --- a/backend/plugins/jira/models/migrationscripts/register.go +++ b/backend/plugins/jira/models/migrationscripts/register.go @@ -55,5 +55,6 @@ func All() []plugin.MigrationScript { new(flushJiraIssues), new(updateScopeConfig), new(addFixVersions20250619), + new(addJiraOAuth20260907), } } diff --git a/backend/plugins/jira/models/oauth.go b/backend/plugins/jira/models/oauth.go new file mode 100644 index 00000000000..c1f86107543 --- /dev/null +++ b/backend/plugins/jira/models/oauth.go @@ -0,0 +1,165 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package models + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/core/plugin" +) + +const ( + // atlassianOAuthEndpoint is the public Atlassian OAuth 2.0 client-credentials endpoint. + atlassianOAuthEndpoint = "https://auth.atlassian.com/oauth/token" + defaultTokenTimeout = 10 * time.Second + defaultTokenTTL = 3600 * time.Second + // Atlassian access tokens are JWTs; with many scopes the JSON easily + // exceeds 4KiB. Keep a cap as a DoS guard, not a typical-token size. + maxOAuthResponseBytes = 64 * 1024 +) + +// NewOAuthHTTPClient returns an HTTP client for Atlassian token requests. +// It must not share a transport with the Jira API client (which may wrap a refresh round tripper). +func NewOAuthHTTPClient(proxy string) (*http.Client, errors.Error) { + transport := &http.Transport{} + if proxy != "" { + pu, err := url.Parse(proxy) + if err != nil { + return nil, errors.Convert(err) + } + transport.Proxy = http.ProxyURL(pu) + } + return &http.Client{ + Timeout: defaultTokenTimeout, + Transport: transport, + }, nil +} + +func (jc *JiraConn) tokenURL() string { + if jc.OAuthTokenURL != "" { + return jc.OAuthTokenURL + } + return atlassianOAuthEndpoint +} + +// MintOAuthAccessToken exchanges client_id/client_secret for a Bearer access token. +func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) (string, time.Time, errors.Error) { + if httpClient == nil { + return "", time.Time{}, errors.Default.New("oauth http client is required") + } + + form := url.Values{} + form.Set("grant_type", "client_credentials") + form.Set("client_id", jc.ClientId) + form.Set("client_secret", jc.ClientSecret) + + ctx, cancel := context.WithTimeout(context.Background(), defaultTokenTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, jc.tokenURL(), strings.NewReader(form.Encode())) + if err != nil { + return "", time.Time{}, errors.Convert(err) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := httpClient.Do(req) + if err != nil { + return "", time.Time{}, errors.Default.Wrap(err, "failed to request oauth2 access token") + } + defer resp.Body.Close() + + body, err := io.ReadAll(io.LimitReader(resp.Body, maxOAuthResponseBytes+1)) + if err != nil { + return "", time.Time{}, errors.Convert(err) + } + if len(body) > maxOAuthResponseBytes { + return "", time.Time{}, errors.Default.New("oauth2 token response exceeded size limit") + } + if resp.StatusCode != http.StatusOK { + return "", time.Time{}, errors.Default.New(fmt.Sprintf("failed to mint oauth2 access token: %d: %s", resp.StatusCode, oauthErrorDetail(body))) + } + if len(strings.TrimSpace(string(body))) == 0 { + return "", time.Time{}, errors.Default.New("oauth2 token endpoint returned an empty body") + } + + var result struct { + AccessToken string `json:"access_token"` + ExpiresIn int `json:"expires_in"` + TokenType string `json:"token_type"` + } + if err := json.Unmarshal(body, &result); err != nil { + return "", time.Time{}, errors.Default.Wrap(err, fmt.Sprintf("decoding oauth2 token response (%d bytes)", len(body))) + } + if result.AccessToken == "" { + return "", time.Time{}, errors.Default.New("empty oauth2 access token returned") + } + + ttl := time.Duration(result.ExpiresIn) * time.Second + if ttl <= 0 { + ttl = defaultTokenTTL + } + return result.AccessToken, time.Now().Add(ttl), nil +} + +// PrepareApiClient mints an OAuth 2.0 access token so subsequent requests can use Bearer auth. +func (jc *JiraConn) PrepareApiClient(_ plugin.ApiClient) errors.Error { + if !jc.IsOAuth2() { + return nil + } + jc.ApplyGatewayEndpoint() + if jc.OAuthAccessToken() != "" { + return nil + } + httpClient, err := NewOAuthHTTPClient(jc.GetProxy()) + if err != nil { + return err + } + token, expiresAt, err := jc.MintOAuthAccessToken(httpClient) + if err != nil { + return err + } + jc.SetOAuthAccessToken(token, expiresAt) + return nil +} + +func oauthErrorDetail(body []byte) string { + var payload struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` + } + if json.Unmarshal(body, &payload) == nil { + switch { + case payload.Error != "" && payload.ErrorDescription != "": + return payload.Error + ": " + payload.ErrorDescription + case payload.Error != "": + return payload.Error + case payload.ErrorDescription != "": + return payload.ErrorDescription + } + } + return "unexpected token endpoint response" +} diff --git a/backend/plugins/jira/models/oauth_test.go b/backend/plugins/jira/models/oauth_test.go new file mode 100644 index 00000000000..325c5d6f42a --- /dev/null +++ b/backend/plugins/jira/models/oauth_test.go @@ -0,0 +1,146 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package models + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMintOAuthAccessToken(t *testing.T) { + var gotGrant, gotID, gotSecret, gotContentType string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotContentType = r.Header.Get("Content-Type") + require.NoError(t, r.ParseForm()) + gotGrant = r.Form.Get("grant_type") + gotID = r.Form.Get("client_id") + gotSecret = r.Form.Get("client_secret") + w.Header().Set("Content-Type", "application/json") + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "minted-token", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "read:jira-work", + })) + })) + defer server.Close() + + jc := &JiraConn{ + ClientId: "cid", + ClientSecret: "csecret", + CloudId: "cloud-1", + OAuthTokenURL: server.URL, + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + + token, expiresAt, err := jc.MintOAuthAccessToken(server.Client()) + require.NoError(t, err) + assert.Equal(t, "application/x-www-form-urlencoded", gotContentType) + assert.Equal(t, "client_credentials", gotGrant) + assert.Equal(t, "cid", gotID) + assert.Equal(t, "csecret", gotSecret) + assert.Equal(t, "minted-token", token) + assert.True(t, expiresAt.After(time.Now().Add(50*time.Minute))) +} + +func TestMintOAuthAccessTokenRejectsEmptyToken(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, `{"access_token":"","expires_in":3600}`) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + _, _, err := jc.MintOAuthAccessToken(server.Client()) + require.Error(t, err) + assert.Contains(t, err.Error(), "empty oauth2 access token") +} + +func TestMintOAuthAccessTokenHTTPError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"invalid_client"}`) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + _, _, err := jc.MintOAuthAccessToken(server.Client()) + require.Error(t, err) + assert.Contains(t, err.Error(), "401") + assert.Contains(t, err.Error(), "invalid_client") + assert.NotContains(t, err.Error(), `"error"`) +} + +func TestMintOAuthAccessTokenAcceptsLargeJWT(t *testing.T) { + token := strings.Repeat("a", 8000) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": token, + "expires_in": 3600, + "token_type": "Bearer", + "scope": strings.Repeat("read:jira-work ", 50), + })) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + got, _, err := jc.MintOAuthAccessToken(server.Client()) + require.NoError(t, err) + assert.Equal(t, token, got) +} + +func TestMintOAuthAccessTokenEmptyBody(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + _, _, err := jc.MintOAuthAccessToken(server.Client()) + require.Error(t, err) + assert.Contains(t, err.Error(), "empty body") +} + +func TestPrepareApiClientStoresTokenOnConn(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "test-conn-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + jc := &JiraConn{ + ClientId: "cid", + ClientSecret: "csecret", + CloudId: "cloud-1", + OAuthTokenURL: server.URL, + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + + require.NoError(t, jc.PrepareApiClient(nil)) + assert.Equal(t, "test-conn-token", jc.OAuthAccessToken()) + require.NotNil(t, jc.OAuthAccessTokenExpiresAt()) +} diff --git a/backend/plugins/jira/tasks/api_client.go b/backend/plugins/jira/tasks/api_client.go index 2062645b6b5..f088117156d 100644 --- a/backend/plugins/jira/tasks/api_client.go +++ b/backend/plugins/jira/tasks/api_client.go @@ -25,13 +25,42 @@ import ( "github.com/apache/incubator-devlake/core/plugin" "github.com/apache/incubator-devlake/helpers/pluginhelper/api" "github.com/apache/incubator-devlake/plugins/jira/models" + "github.com/apache/incubator-devlake/plugins/jira/token" ) func NewJiraApiClient(taskCtx plugin.TaskContext, connection *models.JiraConnection) (*api.ApiAsyncClient, errors.Error) { - // create synchronize api client so we can calculate api rate limit dynamically - apiClient, err := api.NewApiClientFromConnection(taskCtx.GetContext(), taskCtx, connection) - if err != nil { - return nil, err + var apiClient *api.ApiClient + var err errors.Error + if connection.IsOAuth2() { + connection.ApplyGatewayEndpoint() + apiClient, err = api.NewApiClient( + taskCtx.GetContext(), + connection.GetEndpoint(), + nil, + 0, + connection.GetProxy(), + taskCtx, + ) + if err != nil { + return nil, err + } + logger := taskCtx.GetLogger() + var tp *token.TokenProvider + tp, err = token.NewTokenProvider(&connection.JiraConn, logger) + if err != nil { + return nil, err + } + baseTransport := apiClient.GetClient().Transport + if baseTransport == nil { + baseTransport = http.DefaultTransport + } + apiClient.GetClient().Transport = token.NewRefreshRoundTripper(baseTransport, tp) + logger.Info("Installed oauth2 token refresh round tripper for Jira connection %d", connection.ID) + } else { + apiClient, err = api.NewApiClientFromConnection(taskCtx.GetContext(), taskCtx, connection) + if err != nil { + return nil, err + } } // create rate limit calculator diff --git a/backend/plugins/jira/token/round_tripper.go b/backend/plugins/jira/token/round_tripper.go new file mode 100644 index 00000000000..212fd2b4eac --- /dev/null +++ b/backend/plugins/jira/token/round_tripper.go @@ -0,0 +1,136 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package token + +import ( + "bytes" + "fmt" + "io" + "net/http" +) + +// maxRetryBodyBytes caps how much of a request body is buffered so a 401 +// retry can re-send it. Collection is almost entirely GET; this is a DoS guard. +const maxRetryBodyBytes = int64(1 << 20) + +// RefreshRoundTripper automatically remints OAuth 2.0 client-credentials tokens. +// On 401 the round tripper will: +// - Force a refresh of the access token via the TokenProvider +// - Retry the original request with the new token +// +// When active, the RefreshRoundTripper overwrites the Authorization header +// on every request, superseding any header previously set by SetupAuthentication. +type RefreshRoundTripper struct { + base http.RoundTripper + tokenProvider *TokenProvider +} + +// NewRefreshRoundTripper wraps base with a round tripper that automatically remints the OAuth 2.0 token on 401 responses. +func NewRefreshRoundTripper(base http.RoundTripper, tp *TokenProvider) *RefreshRoundTripper { + return &RefreshRoundTripper{ + base: base, + tokenProvider: tp, + } +} + +// RoundTrip implements http.RoundTripper and remints the access token once on 401. +// It may consume and close req.Body (per the RoundTripper contract) so a retry can +// re-send the payload; it does not otherwise mutate req. +func (rt *RefreshRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + replay, err := snapshotRequestBody(req) + if err != nil { + return nil, err + } + return rt.roundTripWithRetry(req, replay, false) +} + +func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, replay bodyReplay, refreshAttempted bool) (*http.Response, error) { + token, err := rt.tokenProvider.GetToken() + if err != nil { + return nil, err + } + + reqClone, cloneErr := cloneRequestWithBearer(req, token, replay) + if cloneErr != nil { + return nil, cloneErr + } + + resp, reqErr := rt.base.RoundTrip(reqClone) + if reqErr != nil { + return nil, reqErr + } + + if resp.StatusCode == http.StatusUnauthorized && !refreshAttempted { + resp.Body.Close() + + if err := rt.tokenProvider.ForceRefresh(token); err != nil { + return nil, err + } + + return rt.roundTripWithRetry(req, replay, true) + } + + return resp, nil +} + +type bodyReplay struct { + getBody func() (io.ReadCloser, error) + length int64 +} + +func cloneRequestWithBearer(req *http.Request, token string, replay bodyReplay) (*http.Request, error) { + reqClone := req.Clone(req.Context()) + if replay.getBody != nil { + body, err := replay.getBody() + if err != nil { + return nil, err + } + reqClone.Body = body + reqClone.GetBody = replay.getBody + if replay.length >= 0 { + reqClone.ContentLength = replay.length + } + } + reqClone.Header.Set("Authorization", "Bearer "+token) + return reqClone, nil +} + +// snapshotRequestBody returns a replayable body for clones. When GetBody is +// already set, the original request is left untouched. Otherwise the original +// Body is consumed and closed (allowed by http.RoundTripper) and a GetBody is +// synthesized for clones only. +func snapshotRequestBody(req *http.Request) (bodyReplay, error) { + if req.GetBody != nil { + return bodyReplay{getBody: req.GetBody, length: req.ContentLength}, nil + } + if req.Body == nil || req.Body == http.NoBody { + return bodyReplay{}, nil + } + buf, err := io.ReadAll(io.LimitReader(req.Body, maxRetryBodyBytes+1)) + _ = req.Body.Close() + if err != nil { + return bodyReplay{}, err + } + if int64(len(buf)) > maxRetryBodyBytes { + return bodyReplay{}, fmt.Errorf("request body exceeded %d-byte retry snapshot limit", maxRetryBodyBytes) + } + getBody := func() (io.ReadCloser, error) { + return io.NopCloser(bytes.NewReader(buf)), nil + } + return bodyReplay{getBody: getBody, length: int64(len(buf))}, nil +} diff --git a/backend/plugins/jira/token/token_provider.go b/backend/plugins/jira/token/token_provider.go new file mode 100644 index 00000000000..2ee44751fae --- /dev/null +++ b/backend/plugins/jira/token/token_provider.go @@ -0,0 +1,122 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package token + +import ( + "net/http" + "sync" + "time" + + "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/core/log" + "github.com/apache/incubator-devlake/plugins/jira/models" +) + +const ( + DefaultRefreshBuffer = 5 * time.Minute +) + +// TokenProvider mints Atlassian OAuth 2.0 client-credentials tokens and caches them in memory. +type TokenProvider struct { + conn *models.JiraConn + httpClient *http.Client + logger log.Logger + mu sync.Mutex + token string + expiresAt *time.Time +} + +// NewTokenProvider creates a TokenProvider that uses a dedicated HTTP client for token requests. +// Call this BEFORE wrapping the Jira API client's transport with RefreshRoundTripper so token +// minting never goes through the round tripper. +func NewTokenProvider(conn *models.JiraConn, logger log.Logger) (*TokenProvider, errors.Error) { + httpClient, err := models.NewOAuthHTTPClient(conn.GetProxy()) + if err != nil { + return nil, err + } + return &TokenProvider{ + conn: conn, + httpClient: httpClient, + logger: logger, + }, nil +} + +// GetToken returns a valid OAuth 2.0 access token, minting a new one if the cached token is absent or near expiry. +func (tp *TokenProvider) GetToken() (string, errors.Error) { + tp.mu.Lock() + defer tp.mu.Unlock() + + if tp.needsRefresh() { + if tp.logger != nil { + expiresStr := "unknown" + if tp.expiresAt != nil { + expiresStr = tp.expiresAt.Format(time.RFC3339) + } + tp.logger.Info("Proactive oauth2 token refresh triggered (token expires at %s)", expiresStr) + } + if err := tp.refreshToken(); err != nil { + return "", err + } + } + return tp.token, nil +} + +func (tp *TokenProvider) needsRefresh() bool { + if tp.token == "" { + return true + } + if tp.expiresAt == nil { + return false + } + return time.Now().Add(DefaultRefreshBuffer).After(*tp.expiresAt) +} + +func (tp *TokenProvider) refreshToken() errors.Error { + if tp.logger != nil { + tp.logger.Info("Minting Jira oauth2 access token via client_credentials") + } + token, expiresAt, err := tp.conn.MintOAuthAccessToken(tp.httpClient) + if err != nil { + return err + } + tp.cacheToken(token, expiresAt) + return nil +} + +func (tp *TokenProvider) cacheToken(token string, expiresAt time.Time) { + tp.token = token + expiry := expiresAt + tp.expiresAt = &expiry +} + +// ForceRefresh remints the access token if the current token is still equal to oldToken. +func (tp *TokenProvider) ForceRefresh(oldToken string) errors.Error { + tp.mu.Lock() + defer tp.mu.Unlock() + + if tp.token != oldToken { + if tp.logger != nil { + tp.logger.Info("Skipping reactive oauth2 token refresh — token already changed by another goroutine") + } + return nil + } + if tp.logger != nil { + tp.logger.Info("Reactive oauth2 token refresh triggered (received 401)") + } + return tp.refreshToken() +} diff --git a/backend/plugins/jira/token/token_provider_test.go b/backend/plugins/jira/token/token_provider_test.go new file mode 100644 index 00000000000..95ac4fe6feb --- /dev/null +++ b/backend/plugins/jira/token/token_provider_test.go @@ -0,0 +1,360 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package token + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/apache/incubator-devlake/plugins/jira/models" +) + +func oauthConn(tokenURL string) *models.JiraConn { + jc := &models.JiraConn{ + ClientId: "cid", + ClientSecret: "csecret", + CloudId: "cloud-1", + OAuthTokenURL: tokenURL, + } + jc.AuthMethod = models.AUTH_METHOD_OAUTH2 + return jc +} + +func seedToken(tp *TokenProvider, token string, ttl time.Duration) { + tp.cacheToken(token, time.Now().Add(ttl)) +} + +func TestNeedsRefresh(t *testing.T) { + tp := &TokenProvider{conn: oauthConn("")} + + assert.True(t, tp.needsRefresh(), "empty token should refresh") + + seedToken(tp, "tok", 10*time.Minute) + assert.False(t, tp.needsRefresh()) + + seedToken(tp, "tok", 1*time.Minute) + assert.True(t, tp.needsRefresh()) + + seedToken(tp, "tok", -1*time.Minute) + assert.True(t, tp.needsRefresh()) +} + +func TestGetTokenMintsWhenExpired(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, r.ParseForm()) + assert.Equal(t, "client_credentials", r.Form.Get("grant_type")) + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "fresh-token", + "expires_in": 3600, + "token_type": "Bearer", + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + seedToken(tp, "stale", -time.Minute) + + token, err := tp.GetToken() + require.NoError(t, err) + assert.Equal(t, "fresh-token", token) +} + +func TestForceRefreshSkipsIfTokenChanged(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls++ + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + seedToken(tp, "current", time.Hour) + + require.NoError(t, tp.ForceRefresh("stale-old-token")) + assert.Equal(t, 0, calls) + assert.Equal(t, "current", tp.token) + + require.NoError(t, tp.ForceRefresh("current")) + assert.Equal(t, 1, calls) + assert.Equal(t, "new-token", tp.token) +} + +func TestGetTokenConcurrency(t *testing.T) { + var mu sync.Mutex + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + mu.Lock() + calls++ + mu.Unlock() + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "shared-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + token, gerr := tp.GetToken() + assert.NoError(t, gerr) + assert.Equal(t, "shared-token", token) + }() + } + wg.Wait() + + mu.Lock() + defer mu.Unlock() + assert.Equal(t, 1, calls) +} + +func TestRoundTripper401Refresh(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, r.ParseForm()) + assert.Equal(t, "client_credentials", r.Form.Get("grant_type")) + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) + + apiCalls := 0 + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + apiCalls++ + auth := req.Header.Get("Authorization") + if auth == "Bearer old-token" { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + if auth == "Bearer new-token" { + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + return &http.Response{StatusCode: http.StatusInternalServerError, Body: io.NopCloser(http.NoBody), Request: req}, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodGet, "https://api.atlassian.com/ex/jira/c/rest/api/2/serverInfo", nil) + require.NoError(t, reqErr) + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusOK, resp.StatusCode) + assert.Equal(t, 2, apiCalls) + assert.Equal(t, "new-token", tp.token) +} + +// TestRoundTripper401RetryRestoresBody: fake Jira 401s Bearer old-token, the +// round tripper remints via the token server, and retries with new-token. +// Both attempts must still send the original POST body. +func TestRoundTripper401RetryRestoresBody(t *testing.T) { + // Token endpoint: ForceRefresh POSTs here and gets new-token. + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) + + var bodies []string + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, readErr := io.ReadAll(req.Body) + require.NoError(t, readErr) + bodies = append(bodies, string(body)) + if req.Header.Get("Authorization") == "Bearer old-token" { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodPost, "https://example.com/rest", strings.NewReader(`{"ok":true}`)) + require.NoError(t, reqErr) + req.Header.Set("Content-Type", "application/json") + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusOK, resp.StatusCode) + // bodies[0] = first POST (old-token, 401); bodies[1] = retry (new-token, 200) + require.Len(t, bodies, 2) + assert.Equal(t, `{"ok":true}`, bodies[0]) + assert.Equal(t, `{"ok":true}`, bodies[1]) +} + +// TestRoundTripper401RetryRestoresBodyWithoutGetBody covers collectors that +// attach an io.Reader without http.NewRequest setting GetBody. +func TestRoundTripper401RetryRestoresBodyWithoutGetBody(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) + + var bodies []string + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, readErr := io.ReadAll(req.Body) + require.NoError(t, readErr) + bodies = append(bodies, string(body)) + if req.Header.Get("Authorization") == "Bearer old-token" { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodPost, "https://example.com/rest", nil) + require.NoError(t, reqErr) + payload := `{"ok":true}` + req.Body = io.NopCloser(strings.NewReader(payload)) + req.GetBody = nil + req.ContentLength = int64(len(payload)) + req.Header.Set("Content-Type", "application/json") + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusOK, resp.StatusCode) + require.Len(t, bodies, 2) + assert.Equal(t, payload, bodies[0]) + assert.Equal(t, payload, bodies[1]) + assert.Nil(t, req.GetBody, "RoundTrip must not mutate the original request") +} + +// TestRoundTripperPersistent401: fake Jira 401s even after remint. The round +// tripper must retry once, then return that 401 (no infinite loop). +func TestRoundTripperPersistent401(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) + + apiCalls := 0 + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + apiCalls++ + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodGet, "https://example.com/rest", nil) + require.NoError(t, reqErr) + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) + assert.Equal(t, 2, apiCalls) +} + +func TestRoundTripperRejectsOversizedBody(t *testing.T) { + tp := &TokenProvider{conn: oauthConn("")} + seedToken(tp, "tok", time.Hour) + rt := NewRefreshRoundTripper(roundTripperFunc(func(*http.Request) (*http.Response, error) { + t.Fatal("must not send an oversized body") + return nil, nil + }), tp) + + payload := strings.Repeat("a", int(maxRetryBodyBytes)+1) + req, err := http.NewRequest(http.MethodPost, "https://example.com/rest", nil) + require.NoError(t, err) + req.Body = io.NopCloser(strings.NewReader(payload)) + req.GetBody = nil + req.ContentLength = int64(len(payload)) + + _, tripErr := rt.RoundTrip(req) + require.Error(t, tripErr) + assert.Contains(t, tripErr.Error(), "retry snapshot limit") +} + +type roundTripperFunc func(*http.Request) (*http.Response, error) + +func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} diff --git a/config-ui/src/api/connection/index.ts b/config-ui/src/api/connection/index.ts index 3cf46ee9063..c8b3afa7ffe 100644 --- a/config-ui/src/api/connection/index.ts +++ b/config-ui/src/api/connection/index.ts @@ -49,6 +49,9 @@ export const test = ( | 'token' | 'appId' | 'secretKey' + | 'cloudId' + | 'clientId' + | 'clientSecret' | 'proxy' | 'rateLimitPerHour' | 'dbUrl' @@ -56,6 +59,7 @@ export const test = ( | 'adminApiKey' | 'organization' | 'organizationId' + | 'service' | 'customHeaders' | 'ciTool' | 'quayOrganization' @@ -79,12 +83,16 @@ export const testOld = ( | 'token' | 'appId' | 'secretKey' + | 'cloudId' + | 'clientId' + | 'clientSecret' | 'proxy' | 'rateLimitPerHour' | 'dbUrl' | 'adminApiKey' | 'organization' | 'organizationId' + | 'service' | 'customHeaders' | 'ciTool' | 'quayOrganization' diff --git a/config-ui/src/plugins/components/connection-form/index.tsx b/config-ui/src/plugins/components/connection-form/index.tsx index d728b17b063..76a255bfc64 100644 --- a/config-ui/src/plugins/components/connection-form/index.tsx +++ b/config-ui/src/plugins/components/connection-form/index.tsx @@ -52,6 +52,9 @@ const buildUpdateTestPayload = (connection: any, values: any, customHeaders: ICu token: isEqual(connection?.token, values.token) ? undefined : values.token, appId: isEqual(connection?.appId, values.appId) ? undefined : values.appId, secretKey: isEqual(connection?.secretKey, values.secretKey) ? undefined : values.secretKey, + cloudId: isEqual(connection?.cloudId, values.cloudId) ? undefined : values.cloudId, + clientId: isEqual(connection?.clientId, values.clientId) ? undefined : values.clientId, + clientSecret: isEqual(connection?.clientSecret, values.clientSecret) ? undefined : values.clientSecret, proxy: isEqual(connection?.proxy, values.proxy) ? undefined : values.proxy, rateLimitPerHour: isEqual(connection?.rateLimitPerHour, values.rateLimitPerHour) ? undefined @@ -59,6 +62,7 @@ const buildUpdateTestPayload = (connection: any, values: any, customHeaders: ICu dbUrl: isEqual(connection?.dbUrl, values.dbUrl) ? undefined : values.dbUrl, companyId: isEqual(connection?.companyId, values.companyId) ? undefined : values.companyId, organization: isEqual(connection?.organization, values.organization) ? undefined : values.organization, + service: isEqual(connection?.service, values.service) ? undefined : values.service, customHeaders: isEqual(connection?.customHeaders, customHeaders) ? undefined : customHeaders, ciTool: isEqual(connection?.ciTool, values.ciTool) ? undefined : values.ciTool, quayOrganization: isEqual(connection?.quayOrganization, values.quayOrganization) ? undefined : values.quayOrganization, @@ -79,6 +83,9 @@ const buildCreateTestPayload = (initialValues: any, values: any, customHeaders: 'authMethod', 'appId', 'secretKey', + 'cloudId', + 'clientId', + 'clientSecret', 'accessKeyId', 'secretAccessKey', 'region', @@ -91,6 +98,7 @@ const buildCreateTestPayload = (initialValues: any, values: any, customHeaders: 'dbUrl', 'companyId', 'organization', + 'service', 'customHeaders', 'ciTool', 'quayOrganization', diff --git a/config-ui/src/plugins/register/jira/connection-fields/auth.tsx b/config-ui/src/plugins/register/jira/connection-fields/auth.tsx index a85999ba3b0..3f488b3f82c 100644 --- a/config-ui/src/plugins/register/jira/connection-fields/auth.tsx +++ b/config-ui/src/plugins/register/jira/connection-fields/auth.tsx @@ -24,8 +24,19 @@ import { Block, ExternalLink } from '@/components'; import { DOC_URL } from '@/release'; const JIRA_CLOUD_REGEX = /^https:\/\/\w+.atlassian.net\/rest\/$/; +const JIRA_OAUTH_GATEWAY_REGEX = /^https:\/\/api\.atlassian\.com\/ex\/jira\/[^/]+\/rest\/$/; -type Method = 'BasicAuth' | 'AccessToken'; +type Method = 'BasicAuth' | 'AccessToken' | 'OAuth2'; +type CloudMethod = 'BasicAuth' | 'OAuth2'; + +const gatewayEndpoint = (cloudId?: string) => + cloudId ? `https://api.atlassian.com/ex/jira/${cloudId.trim()}/rest/` : ''; + +const isCloudConnection = (values: { authMethod?: string; endpoint?: string }) => + values.authMethod === 'OAuth2' || + !values.endpoint || + JIRA_CLOUD_REGEX.test(values.endpoint) || + JIRA_OAUTH_GATEWAY_REGEX.test(values.endpoint); interface Props { type: 'create' | 'update'; @@ -40,10 +51,12 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop const [version, setVersion] = useState('cloud'); useEffect(() => { - if (initialValues.endpoint && !JIRA_CLOUD_REGEX.test(initialValues.endpoint)) { + if (isCloudConnection(initialValues)) { + setVersion('cloud'); + } else if (initialValues.endpoint) { setVersion('server'); } - }, [initialValues.endpoint]); + }, [initialValues.endpoint, initialValues.authMethod]); useEffect(() => { setValues({ @@ -52,6 +65,9 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop username: initialValues.username, password: initialValues.password, token: initialValues.token, + cloudId: initialValues.cloudId, + clientId: initialValues.clientId, + clientSecret: initialValues.clientSecret, }); }, [ initialValues.endpoint, @@ -59,21 +75,25 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop initialValues.username, initialValues.password, initialValues.token, + initialValues.cloudId, + initialValues.clientId, + initialValues.clientSecret, ]); useEffect(() => { const required = (values.authMethod === 'BasicAuth' && values.username && values.password) || (values.authMethod === 'AccessToken' && values.token) || + (values.authMethod === 'OAuth2' && values.cloudId && values.clientId && values.clientSecret) || type === 'update'; setErrors({ - endpoint: !values.endpoint ? 'endpoint is required' : '', + endpoint: values.authMethod === 'OAuth2' || values.endpoint ? '' : 'endpoint is required', auth: required ? '' : 'auth is required', }); }, [values]); const handleChangeVersion = (e: RadioChangeEvent) => { - const version = e.target.value; + const nextVersion = e.target.value; setValues({ endpoint: '', @@ -81,9 +101,12 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop username: undefined, password: undefined, token: undefined, + cloudId: undefined, + clientId: undefined, + clientSecret: undefined, }); - setVersion(version); + setVersion(nextVersion); }; const handleChangeEndpoint = (e: React.ChangeEvent) => { @@ -92,6 +115,20 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop }); }; + const handleChangeCloudMethod = (e: RadioChangeEvent) => { + const authMethod = (e.target as HTMLInputElement).value as CloudMethod; + setValues({ + authMethod, + username: undefined, + password: undefined, + token: undefined, + cloudId: undefined, + clientId: undefined, + clientSecret: undefined, + endpoint: '', + }); + }; + const handleChangeMethod = (e: RadioChangeEvent) => { setValues({ authMethod: (e.target as HTMLInputElement).value as Method, @@ -119,6 +156,28 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop }); }; + const handleChangeCloudId = (e: React.ChangeEvent) => { + const cloudId = e.target.value; + setValues({ + cloudId, + endpoint: gatewayEndpoint(cloudId), + }); + }; + + const handleChangeClientId = (e: React.ChangeEvent) => { + setValues({ + clientId: e.target.value, + }); + }; + + const handleChangeClientSecret = (e: React.ChangeEvent) => { + setValues({ + clientSecret: e.target.value, + }); + }; + + const cloudAuthMethod: CloudMethod = values.authMethod === 'OAuth2' ? 'OAuth2' : 'BasicAuth'; + return ( <> @@ -127,54 +186,107 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop Jira Server - - {version === 'cloud' - ? 'Provide the Jira instance API endpoint. For Jira Cloud, e.g. https://your-company.atlassian.net/rest/. Please note that the endpoint URL should end with /.' - : ''} - {version === 'server' - ? 'Provide the Jira instance API endpoint. For Jira Server, e.g. https://jira.your-company.com/rest/. Please note that the endpoint URL should end with /.' - : ''} - - } - required - > - - - - - {version === 'cloud' && ( - <> - - - + {!(version === 'cloud' && cloudAuthMethod === 'OAuth2') && ( Learn about how to create an API Token + <> + {version === 'cloud' + ? 'Provide the Jira instance API endpoint. For Jira Cloud, e.g. https://your-company.atlassian.net/rest/. Please note that the endpoint URL should end with /.' + : ''} + {version === 'server' + ? 'Provide the Jira instance API endpoint. For Jira Server, e.g. https://jira.your-company.com/rest/. Please note that the endpoint URL should end with /.' + : ''} + } required > + )} + + + {version === 'cloud' && ( + <> + + + API Token + OAuth 2.0 (Service Account) + + + + {cloudAuthMethod === 'BasicAuth' && ( + <> + + + + + Learn about how to create an API Token + + } + required + > + + + + )} + + {cloudAuthMethod === 'OAuth2' && ( + <> + + + + + + + + + + {values.endpoint && ( + + + + )} + + )} )} diff --git a/config-ui/src/types/connection.ts b/config-ui/src/types/connection.ts index bb39fa2e59b..a9072049f84 100644 --- a/config-ui/src/types/connection.ts +++ b/config-ui/src/types/connection.ts @@ -32,12 +32,16 @@ export interface IConnectionAPI { password?: string; appId?: string; secretKey?: string; + cloudId?: string; + clientId?: string; + clientSecret?: string; dbUrl?: string; companyId?: number; proxy: string; rateLimitPerHour?: number; organization?: string; organizationId?: string; + service?: string; customHeaders?: ICustomHeader[]; ciTool?: string; quayOrganization?: string; @@ -95,6 +99,9 @@ export interface IConnection { password?: string; appId?: string; secretKey?: string; + cloudId?: string; + clientId?: string; + clientSecret?: string; dbUrl?: string; companyId?: number; proxy: string; diff --git a/config-ui/src/utils/request.ts b/config-ui/src/utils/request.ts index e91739f7242..3badcc0d4b7 100644 --- a/config-ui/src/utils/request.ts +++ b/config-ui/src/utils/request.ts @@ -41,18 +41,29 @@ export type RequestConfig = { const isLoginRoute = () => window.location.pathname.replace(/\/+$/, '').endsWith('/login'); +// Plugin connection tests often return 401 when the *remote* credential is +// wrong. That is not a DevLake session expiry — do not wipe the form. +const isPluginConnectionTest = (url?: string) => + !!url && /\/plugins\/[^/]+(?:\/connections\/[^/]+)?\/test\/?$/.test(url); + let redirectingToLogin = false; instance.interceptors.response.use( (response) => response, (error) => { const status = error.response?.status; + const requestUrl = error.config?.url as string | undefined; if (status === 428) { window.location.replace('/db-migrate'); } - if (status === 401 && !isLoginRoute() && !redirectingToLogin) { + if ( + status === 401 && + !isLoginRoute() && + !redirectingToLogin && + !isPluginConnectionTest(requestUrl) + ) { redirectingToLogin = true; const returnUrl = encodeURIComponent(window.location.pathname + window.location.search); window.location.replace(`/login?return_url=${returnUrl}`); diff --git a/docs/upstream-diffs.md b/docs/upstream-diffs.md index 090e0a64537..5c7f3ece521 100644 --- a/docs/upstream-diffs.md +++ b/docs/upstream-diffs.md @@ -59,6 +59,7 @@ No conflicts expected unless upstream touches the same field mapping block. - `backend/server/api/auth/revocation_cache.go` - `backend/server/api/auth/revocation_cache_test.go` - `backend/server/api/auth/auth_test.go` +- `config-ui/src/utils/request.ts` (401 interceptor; skip plugin `/test` so remote credential failures do not redirect to `/login`) - `env.example` (OIDC/auth env var documentation) **Reason:** Upstream DevLake has no user authentication. This fork adds full OIDC login @@ -288,3 +289,103 @@ has no equivalent table. **Rebase notes:** New files plus an append in `domaininfo.go` and `register.go:All()`. Low conflict risk unless upstream adds adjacent domain tables in the same slice. + +## jira: OAuth 2.0 client-credentials (service account / 2LO) + +**Files:** +- `backend/plugins/jira/models/connection.go` +- `backend/plugins/jira/models/oauth.go` +- `backend/plugins/jira/models/connection_test.go` +- `backend/plugins/jira/models/oauth_test.go` +- `backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go` +- `backend/plugins/jira/models/migrationscripts/register.go` +- `backend/plugins/jira/api/connection_api.go` +- `backend/plugins/jira/api/connection_api_test.go` +- `backend/plugins/jira/tasks/api_client.go` +- `backend/plugins/jira/token/token_provider.go` +- `backend/plugins/jira/token/round_tripper.go` +- `backend/plugins/jira/token/token_provider_test.go` +- `config-ui/src/plugins/register/jira/connection-fields/auth.tsx` +- `config-ui/src/plugins/components/connection-form/index.tsx` +- `config-ui/src/types/connection.ts` +- `config-ui/src/api/connection/index.ts` + +**Reason:** Jira Cloud service accounts authenticate with OAuth 2.0 client +credentials (`grant_type=client_credentials`), not Basic Auth / PAT. Access +tokens last 60 minutes and API calls must go through +`https://api.atlassian.com/ex/jira/{cloudId}/rest/`. Adds `authMethod=OAuth2` +handling inside the Jira plugin (no core MultiAuth change), in-memory token +minting, and a refresh round tripper for long collections. + +**Upstream status:** Pending — could be contributed upstream as a Jira plugin +enhancement. +**Upstream PR:** none yet +**Owner:** @fmuntean + +**Rebase notes:** Watch upstream changes to `JiraConn` / `_tool_jira_connections`, +`NewJiraApiClient`, `testConnection` validation, and Config UI Cloud auth fields. +`register.go` append is low risk. Shared Config UI connection form/types/API pick +lists gained `cloudId` / `clientId` / `clientSecret`. +## graphql collector: include data-error message and variables in logs + +**Files:** +- `backend/helpers/pluginhelper/api/graphql_collector.go` +- `backend/helpers/pluginhelper/api/graphql_collector_test.go` + +**Reason:** `errors.Default.Wrap(dataError, "graphql query got error")` uses +cockroachdb `WithDetail`. `Error()` then `%+v`s that wrapper, so pipeline +messages look like `Wraps: (2) graphql query got error Error types: (1) +*hintdetail.withDetail (2) *errors.errorString` and drop the GraphQL +`Message`, locations, and request variables. Store/log a flattened string +instead (`errors.Default.New`) so subtask `message` and worker logs include +the real GitHub error and variables. + +**Upstream status:** Pending — should be contributed upstream as a diagnostics +fix. +**Upstream PR:** none yet +**Owner:** @rsoaresd + +**Rebase notes:** Touches `fetchAsync` data-error / transport-error handling +and `Execute` worker-error logging. Watch for upstream changes around +`IgnoreQueryErrors` / `isIgnorableGraphqlQueryError`. + +## ci: unit-test Codecov upload on a separate Ubuntu job + +**Files:** +- `.github/workflows/test.yml` + +**Reason:** Fork-only Codecov upload for owned plugins. `codecov-action` needs +`gpg`, which is not in `mericodev/lake-builder` (Debian 11 / Bullseye). Installing +it via `apt-get` in that container fails because `bullseye-security` InRelease +expired after Debian 11 LTS EOL (2026-08-31). Tests stay in `lake-builder`; +coverage artifacts are uploaded from a follow-on `ubuntu-latest` job with OIDC. + +**Upstream status:** N/A — upstream `test.yml` has no Codecov steps. +**Upstream PR:** none — not applicable +**Owner:** @fmuntean + +**Rebase notes:** Keep the `test` job aligned with upstream (container, unit +tests). Re-apply the `Custom plugins coverage` / artifact upload steps and the +`upload-coverage` job after upstream workflow changes. + +## config-ui: connection fields for owned plugins + +**Files:** +- `config-ui/src/plugins/components/connection-form/index.tsx` +- `config-ui/src/api/connection/index.ts` +- `config-ui/src/types/connection.ts` + +**Reason:** The shared connection form whitelists which values reach the backend, +so each owned-plugin field must be listed in `IConnectionAPI`, the `test` / +`testOld` payload `Pick<>`s, and both test-payload builders. Fields added so far: +`service` (codecov); `ciTool`, `quayOrganization`, `githubOrganization`, +`githubToken`, `project`, `junitRegex` (testregistry). Missing a builder is +silent — Save Connection still works while Test Connection drops the field and +the backend falls back to its default (COVERPORT-351). + +**Upstream status:** N/A — these fields belong to fork-only plugins. +**Upstream PR:** none — not applicable +**Owner:** @lipka28 + +**Rebase notes:** The lists are additive; on conflict keep both upstream's fields +and the fork's. diff --git a/e2e/codecov-flow.spec.ts b/e2e/codecov-flow.spec.ts new file mode 100644 index 00000000000..8c0a290893b --- /dev/null +++ b/e2e/codecov-flow.spec.ts @@ -0,0 +1,229 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import { test, expect, request } from '@playwright/test'; + +const API = 'http://localhost:8080'; +const TOKEN = process.env.CODECOV_TOKEN; +const ORG = process.env.CODECOV_ORG ?? 'konflux-ci'; +const SERVICE = process.env.CODECOV_SERVICE ?? 'github'; +const ENDPOINT = process.env.CODECOV_ENDPOINT ?? 'https://api.codecov.io'; +const REPO = process.env.CODECOV_REPO ?? 'konflux-ci/coverport'; + +const EXPECTED_SUBTASKS = [ + 'CollectFlags', + 'ConvertFlags', + 'CollectCommits', + 'ExtractCommits', + 'CollectCommitTotals', + 'CollectCommitCoverage', + 'CollectComparison', + 'CollectFlagCoverageTrend', + 'CollectRepoConfig', + 'ConvertComparison', + 'ConvertCoverage', + 'ConvertCommitCoverage', + 'ConvertCoverageTrend', +]; + +const state = { + connectionId: 0, + scopeConfigId: 0, + scopeId: '', + blueprintId: 0, + pipelineId: 0, + remoteRepo: null as Record | null, +}; + +async function cleanupResources() { + const api = await request.newContext({ baseURL: API }); + + if (state.blueprintId) { + await api.delete(`/blueprints/${state.blueprintId}`); + console.log(`Deleted blueprint ${state.blueprintId}`); + } + if (state.scopeId) { + await api.delete( + `/plugins/codecov/connections/${state.connectionId}/scopes/${encodeURIComponent(state.scopeId)}`, + ); + console.log(`Deleted scope ${state.scopeId}`); + } + if (state.scopeConfigId) { + await api.delete( + `/plugins/codecov/connections/${state.connectionId}/scope-configs/${state.scopeConfigId}`, + ); + console.log(`Deleted scope config ${state.scopeConfigId}`); + } + if (state.connectionId) { + await api.delete(`/plugins/codecov/connections/${state.connectionId}`); + console.log(`Deleted connection ${state.connectionId}`); + } +} + +test.describe.serial('Codecov Plugin Full Flow', () => { + test.skip(!process.env.CODECOV_TOKEN, 'CODECOV_TOKEN not set'); + test.setTimeout(900_000); + + test.afterAll(async () => { + if (state.connectionId) { + await cleanupResources(); + console.log('Cleanup complete'); + } + }); + + test('Step 1: Create Connection', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post('/plugins/codecov/connections', { + data: { + name: `e2e-codecov-${Date.now()}`, + token: TOKEN, + organization: ORG, + service: SERVICE, + endpoint: ENDPOINT, + }, + }); + expect(resp.ok()).toBeTruthy(); + const conn = await resp.json(); + state.connectionId = conn.id; + console.log(`Connection created: id=${state.connectionId}`); + }); + + test('Step 2: Test Connection', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post(`/plugins/codecov/connections/${state.connectionId}/test`); + const body = await resp.json(); + expect(resp.ok()).toBeTruthy(); + expect(body.success).toBe(true); + console.log('Test connection: OK'); + }); + + test('Step 3: Discover Remote Scopes', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.get(`/plugins/codecov/connections/${state.connectionId}/remote-scopes`); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + + const repo = body.children?.find((c: { fullName: string }) => c.fullName === REPO); + expect(repo, `Repository ${REPO} not found in remote-scopes`).toBeTruthy(); + state.remoteRepo = repo.data; + console.log(`Found remote repo: ${REPO}`); + }); + + test('Step 4: Create Scope Config', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post( + `/plugins/codecov/connections/${state.connectionId}/scope-configs`, + { data: { name: `e2e-scope-config-${Date.now()}`, entities: ['CODE'] } }, + ); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + state.scopeConfigId = body.id; + console.log(`Scope config created: id=${state.scopeConfigId}`); + }); + + test('Step 5: Add Scope', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.put(`/plugins/codecov/connections/${state.connectionId}/scopes`, { + data: { + data: [{ + ...state.remoteRepo, + scopeConfigId: state.scopeConfigId, + }], + }, + }); + expect(resp.ok()).toBeTruthy(); + const scopes = await resp.json(); + state.scopeId = scopes[0].codecovId; + expect(state.scopeId).toBe(REPO); + console.log(`Scope added: id=${state.scopeId}`); + }); + + test('Step 6: Create Blueprint via API', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post('/blueprints', { + data: { + name: `e2e-blueprint-${Date.now()}`, + mode: 'NORMAL', + enable: true, + cronConfig: '0 0 * * *', + isManual: true, + connections: [{ + pluginName: 'codecov', + connectionId: state.connectionId, + scopes: [{ scopeId: state.scopeId }], + }], + }, + }); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + state.blueprintId = body.id; + console.log(`Blueprint created: id=${state.blueprintId}`); + }); + + test('Step 7: Trigger Pipeline via API', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post(`/blueprints/${state.blueprintId}/trigger`, { data: {} }); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + state.pipelineId = body.id; + console.log(`Pipeline triggered: id=${state.pipelineId}`); + }); + + test('Step 8: Wait for Pipeline to Complete', async () => { + const api = await request.newContext({ baseURL: API }); + const maxWait = 900_000; // 15 min — first Codecov collection can be slow + const start = Date.now(); + let status = ''; + + while (Date.now() - start < maxWait) { + const resp = await api.get(`/pipelines/${state.pipelineId}`); + const pipeline = await resp.json(); + status = pipeline.status; + console.log(`Pipeline status: ${status} (${Math.round((Date.now() - start) / 1000)}s)`); + if (['TASK_COMPLETED', 'TASK_FAILED', 'TASK_PARTIAL'].includes(status)) break; + await new Promise((r) => setTimeout(r, 5000)); + } + + const tasksResp = await api.get(`/pipelines/${state.pipelineId}/tasks`); + if (tasksResp.ok()) { + const { tasks } = await tasksResp.json(); + for (const t of tasks || []) { + console.log(` Task ${t.id}: ${t.status}${t.failedSubTask ? ` (failed: ${t.failedSubTask})` : ''}`); + if (t.message) console.log(` Error: ${t.message.substring(0, 300)}`); + } + } + + expect(status).toBe('TASK_COMPLETED'); + }); + + test('Step 9: Verify Pipeline Subtasks', async () => { + const api = await request.newContext({ baseURL: API }); + + const tasksResp = await api.get(`/pipelines/${state.pipelineId}/tasks`); + expect(tasksResp.ok()).toBeTruthy(); + const { tasks } = await tasksResp.json(); + expect(tasks[0].status).toBe('TASK_COMPLETED'); + expect(tasks[0].subtasks).toEqual(EXPECTED_SUBTASKS); + console.log(`Pipeline completed in ${tasks[0].spentSeconds}s with ${tasks[0].subtasks.length} subtasks`); + }); + + test('Step 10: Cleanup', async () => { + await cleanupResources(); + state.connectionId = 0; + console.log('Cleanup complete'); + }); +}); diff --git a/e2e/package.json b/e2e/package.json index 5abf0494f36..a267ec33641 100644 --- a/e2e/package.json +++ b/e2e/package.json @@ -6,7 +6,8 @@ "scripts": { "test": "npx playwright test basic-flow.spec.ts", "test:all": "npx playwright test", - "test:coverage": "npx playwright test basic-flow.spec.ts" + "test:coverage": "npx playwright test basic-flow.spec.ts", + "test:codecov": "npx playwright test codecov-flow.spec.ts --timeout=900000" }, "keywords": [], "author": "", diff --git a/env.example b/env.example index 7eb785d4fb3..9d688f67219 100755 --- a/env.example +++ b/env.example @@ -172,3 +172,11 @@ SESSION_TTL=8h COOKIE_DOMAIN= # Set to false ONLY for local HTTP development. COOKIE_SECURE=true + +# Codecov plugin e2e tests (e2e/codecov-flow.spec.ts) — not used by Docker Compose. +# Export before running: cd e2e && npm run test:codecov +# CODECOV_TOKEN= +# CODECOV_ORG=konflux-ci +# CODECOV_SERVICE=github +# CODECOV_ENDPOINT=https://api.codecov.io +# CODECOV_REPO=konflux-ci/coverport