├── .ci-operator.yaml ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── feature_request.md │ └── task.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── go.yml │ └── golangci-lint.yml ├── .gitignore ├── .golangci.yaml ├── .konflux └── Containerfile.plugin ├── .tekton ├── gitops-backend-pull-request.yaml └── gitops-backend-push.yaml ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── Makefile ├── OWNERS ├── README.md ├── cmd └── backend-http │ └── main.go ├── deploy ├── deployment.yaml ├── kustomization.yaml ├── namespace.yaml ├── role.yaml ├── rolebinding.yaml ├── service.yaml └── serviceaccount.yaml ├── go.mod ├── go.sum ├── internal └── sets │ ├── strings.go │ └── strings_test.go ├── openshift-ci └── build-root │ ├── Dockerfile │ ├── OWNERS │ ├── README.md │ └── source-image │ └── Dockerfile ├── pkg ├── cmd │ └── root.go ├── git │ ├── client.go │ ├── client_test.go │ ├── errors.go │ ├── interfaces.go │ ├── scm_factory.go │ ├── scm_factory_test.go │ └── testdata │ │ ├── commit_status.json │ │ ├── content.json │ │ ├── drivers.yaml │ │ └── push_hook.json ├── gitfs │ ├── doc.go │ ├── gitfs.go │ └── gitfs_test.go ├── health │ ├── health.go │ └── health_test.go ├── httpapi │ ├── api.go │ ├── api_test.go │ ├── application.go │ ├── application_test.go │ ├── authorization.go │ ├── authorization_test.go │ ├── conversion.go │ ├── conversion_test.go │ ├── manifest.go │ ├── manifest_test.go │ ├── secrets │ │ ├── config_factory.go │ │ ├── config_factory_test.go │ │ ├── interface.go │ │ ├── mock.go │ │ ├── secrets.go │ │ └── secrets_test.go │ └── testdata │ │ ├── application.yaml │ │ ├── application2.yaml │ │ ├── application3.yaml │ │ └── pipelines.yaml ├── logger │ ├── interface.go │ └── sugar.go ├── metrics │ ├── interface.go │ ├── metrics.go │ ├── metrics_test.go │ └── mock.go └── parser │ ├── converter.go │ ├── extracts.go │ ├── extracts_test.go │ ├── interfaces.go │ ├── parser.go │ ├── parser_test.go │ ├── resource.go │ └── testdata │ ├── app1 │ └── kustomization.yaml │ ├── app2 │ ├── kustomization.yaml │ └── staging_patch.yaml │ └── go-demo │ ├── configMap.yaml │ ├── cron_job.yaml │ ├── deployment.yaml │ ├── deployment_config.yaml │ ├── job.yaml │ ├── kustomization.yaml │ ├── redis_deployment.yaml │ ├── redis_service.yaml │ ├── service.yaml │ └── stateful_set.yaml ├── scripts ├── openshiftci-presubmit-all-tests.sh └── openshiftci-presubmit-unittests.sh └── test ├── clone_options.go ├── errors.go └── logger.go /.ci-operator.yaml: -------------------------------------------------------------------------------- 1 | build_root_image: 2 | name: release 3 | namespace: openshift 4 | tag: golang-1.23 -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Additional context** 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/task.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Task 🔧 3 | about: Internal things, technical debt, and to-do tasks to be performed. 4 | title: '' 5 | labels: 'kind/task' 6 | assignees: '' 7 | 8 | --- 9 | ### Is your task related to a problem? Please describe. 10 | 11 | 12 | ### Describe the solution you'd like 13 | 14 | 15 | ### Describe alternatives you've considered 16 | 17 | 18 | ### Additional context 19 | 20 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **What type of PR is this?** 2 | > Uncomment only one ` /kind` line, and delete the rest. 3 | > For example, `> /kind bug` would simply become: `/kind bug` 4 | 5 | > /kind bug 6 | > /kind cleanup 7 | > /kind failing-test 8 | > /kind enhancement 9 | > /kind documentation 10 | > /kind code-refactoring 11 | 12 | 13 | **What does this PR do / why we need it**: 14 | 15 | **Have you updated the necessary documentation?** 16 | 17 | * [ ] Documentation update is required by this PR. 18 | * [ ] Documentation has been updated. 19 | 20 | **Which issue(s) this PR fixes**: 21 | 22 | Fixes #? 23 | 24 | **How to test changes / Special notes to the reviewer**: 25 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Set up Go 17 | uses: actions/setup-go@v5 18 | with: 19 | go-version-file: go.mod 20 | 21 | - name: Build 22 | run: go build -v ./... 23 | 24 | - name: Test 25 | run: go test -v ./... 26 | -------------------------------------------------------------------------------- /.github/workflows/golangci-lint.yml: -------------------------------------------------------------------------------- 1 | name: golangci-lint 2 | on: 3 | push: 4 | tags: 5 | - v* 6 | branches: 7 | - master 8 | - main 9 | pull_request: 10 | jobs: 11 | golangci: 12 | name: lint 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - name: golangci-lint 17 | uses: golangci/golangci-lint-action@v3 18 | with: 19 | version: v1.52.2 20 | only-new-issues: true 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | vendor/ 16 | 17 | # IDE related files 18 | .idea/* -------------------------------------------------------------------------------- /.golangci.yaml: -------------------------------------------------------------------------------- 1 | run: 2 | timeout: 10m -------------------------------------------------------------------------------- /.konflux/Containerfile.plugin: -------------------------------------------------------------------------------- 1 | # Build Stage 2 | FROM brew.registry.redhat.io/rh-osbs/openshift-golang-builder:rhel_8_golang_1.23 AS builder 3 | WORKDIR /go/src 4 | COPY . /go/src 5 | RUN GIT_COMMIT=$(git rev-parse HEAD) && \ 6 | CGO_ENABLED=0 GOOS=linux go build -a -mod=readonly \ 7 | -ldflags "-X github.com/redhat-developer/gitops-backend/pkg/health.GitRevision=${GIT_COMMIT}" ./cmd/backend-http 8 | 9 | # Final Stage 10 | FROM registry.access.redhat.com/ubi8/ubi-minimal 11 | WORKDIR / 12 | COPY --from=builder /go/src/backend-http . 13 | EXPOSE 8080 14 | ENTRYPOINT ["./backend-http"] 15 | 16 | LABEL \ 17 | name="openshift-gitops-1/gitops-rhel8" \ 18 | License="Apache 2.0" \ 19 | com.redhat.component="openshift-gitops-container" \ 20 | com.redhat.delivery.appregistry="false" \ 21 | upstream-vcs-type="git" \ 22 | summary="Red Hat OpenShift GitOps Backend Service" \ 23 | io.openshift.expose-services="" \ 24 | io.openshift.tags="openshift,gitops" \ 25 | io.k8s.display-name="Red Hat OpenShift GitOps Backend Service" \ 26 | maintainer="William Tam " \ 27 | description="Red Hat OpenShift GitOps Backend Service" -------------------------------------------------------------------------------- /.tekton/gitops-backend-pull-request.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: tekton.dev/v1 2 | kind: PipelineRun 3 | metadata: 4 | annotations: 5 | build.appstudio.openshift.io/repo: https://github.com/redhat-developer/gitops-backend?rev={{revision}} 6 | build.appstudio.redhat.com/commit_sha: '{{revision}}' 7 | build.appstudio.redhat.com/pull_request_number: '{{pull_request_number}}' 8 | build.appstudio.redhat.com/target_branch: '{{target_branch}}' 9 | pipelinesascode.tekton.dev/max-keep-runs: "3" 10 | pipelinesascode.tekton.dev/on-cel-expression: event == "pull_request" && target_branch 11 | == "master" 12 | creationTimestamp: null 13 | labels: 14 | appstudio.openshift.io/application: openshift-gitops-operator 15 | appstudio.openshift.io/component: gitops-backend 16 | pipelines.appstudio.openshift.io/type: build 17 | name: gitops-backend-on-pull-request 18 | namespace: rh-openshift-gitops-tenant 19 | spec: 20 | params: 21 | - name: git-url 22 | value: '{{source_url}}' 23 | - name: revision 24 | value: '{{revision}}' 25 | - name: output-image 26 | value: quay.io/redhat-user-workloads/rh-openshift-gitops-tenant/openshift-gitops-operator/gitops-backend:on-pr-{{revision}} 27 | - name: image-expires-after 28 | value: 5d 29 | - name: build-platforms 30 | value: 31 | - linux/x86_64 32 | - name: dockerfile 33 | value: .konflux/Containerfile.plugin 34 | - name: hermetic 35 | value: "true" 36 | - name: prefetch-input 37 | value: '{"type": "gomod", "path": "."}' 38 | pipelineSpec: 39 | description: | 40 | This pipeline is ideal for building multi-arch container images from a Containerfile while maintaining trust after pipeline customization. 41 | 42 | _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://enterprisecontract.dev/docs/ec-policies/release_policy.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. 43 | 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)_ 44 | finally: 45 | - name: show-sbom 46 | params: 47 | - name: IMAGE_URL 48 | value: $(tasks.build-image-index.results.IMAGE_URL) 49 | taskRef: 50 | params: 51 | - name: name 52 | value: show-sbom 53 | - name: bundle 54 | value: quay.io/konflux-ci/tekton-catalog/task-show-sbom:0.1@sha256:9bfc6b99ef038800fe131d7b45ff3cd4da3a415dd536f7c657b3527b01c4a13b 55 | - name: kind 56 | value: task 57 | resolver: bundles 58 | params: 59 | - description: Source Repository URL 60 | name: git-url 61 | type: string 62 | - default: "" 63 | description: Revision of the Source Repository 64 | name: revision 65 | type: string 66 | - description: Fully Qualified Output Image 67 | name: output-image 68 | type: string 69 | - default: . 70 | description: Path to the source code of an application's component from where 71 | to build image. 72 | name: path-context 73 | type: string 74 | - default: Dockerfile 75 | description: Path to the Dockerfile inside the context specified by parameter 76 | path-context 77 | name: dockerfile 78 | type: string 79 | - default: "false" 80 | description: Force rebuild image 81 | name: rebuild 82 | type: string 83 | - default: "false" 84 | description: Skip checks against built image 85 | name: skip-checks 86 | type: string 87 | - default: "false" 88 | description: Execute the build with network isolation 89 | name: hermetic 90 | type: string 91 | - default: "" 92 | description: Build dependencies to be prefetched by Cachi2 93 | name: prefetch-input 94 | type: string 95 | - default: "" 96 | description: Image tag expiration time, time values could be something like 97 | 1h, 2d, 3w for hours, days, and weeks, respectively. 98 | name: image-expires-after 99 | - default: "false" 100 | description: Build a source image. 101 | name: build-source-image 102 | type: string 103 | - default: "true" 104 | description: Add built image into an OCI image index 105 | name: build-image-index 106 | type: string 107 | - default: [] 108 | description: Array of --build-arg values ("arg=value" strings) for buildah 109 | name: build-args 110 | type: array 111 | - default: "" 112 | description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file 113 | name: build-args-file 114 | type: string 115 | - default: 116 | - linux/x86_64 117 | - linux/arm64 118 | description: List of platforms to build the container images on. The available 119 | set of values is determined by the configuration of the multi-platform-controller. 120 | name: build-platforms 121 | type: array 122 | results: 123 | - description: "" 124 | name: IMAGE_URL 125 | value: $(tasks.build-image-index.results.IMAGE_URL) 126 | - description: "" 127 | name: IMAGE_DIGEST 128 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 129 | - description: "" 130 | name: CHAINS-GIT_URL 131 | value: $(tasks.clone-repository.results.url) 132 | - description: "" 133 | name: CHAINS-GIT_COMMIT 134 | value: $(tasks.clone-repository.results.commit) 135 | tasks: 136 | - name: init 137 | params: 138 | - name: image-url 139 | value: $(params.output-image) 140 | - name: rebuild 141 | value: $(params.rebuild) 142 | - name: skip-checks 143 | value: $(params.skip-checks) 144 | taskRef: 145 | params: 146 | - name: name 147 | value: init 148 | - name: bundle 149 | value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:092c113b614f6551113f17605ae9cb7e822aa704d07f0e37ed209da23ce392cc 150 | - name: kind 151 | value: task 152 | resolver: bundles 153 | - name: clone-repository 154 | params: 155 | - name: url 156 | value: $(params.git-url) 157 | - name: revision 158 | value: $(params.revision) 159 | - name: ociStorage 160 | value: $(params.output-image).git 161 | - name: ociArtifactExpiresAfter 162 | value: $(params.image-expires-after) 163 | runAfter: 164 | - init 165 | taskRef: 166 | params: 167 | - name: name 168 | value: git-clone-oci-ta 169 | - name: bundle 170 | value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:8e1e861d9564caea3f9ce8d1c62789f5622b5a7051209decc9ecf10b6f54aa71 171 | - name: kind 172 | value: task 173 | resolver: bundles 174 | when: 175 | - input: $(tasks.init.results.build) 176 | operator: in 177 | values: 178 | - "true" 179 | workspaces: 180 | - name: basic-auth 181 | workspace: git-auth 182 | - name: prefetch-dependencies 183 | params: 184 | - name: input 185 | value: $(params.prefetch-input) 186 | - name: SOURCE_ARTIFACT 187 | value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) 188 | - name: ociStorage 189 | value: $(params.output-image).prefetch 190 | - name: ociArtifactExpiresAfter 191 | value: $(params.image-expires-after) 192 | runAfter: 193 | - clone-repository 194 | taskRef: 195 | params: 196 | - name: name 197 | value: prefetch-dependencies-oci-ta 198 | - name: bundle 199 | value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.1@sha256:8e2a8de8e8a55a8e657922d5f8303fefa065f7ec2f8a49a666bf749540d63679 200 | - name: kind 201 | value: task 202 | resolver: bundles 203 | workspaces: 204 | - name: git-basic-auth 205 | workspace: git-auth 206 | - name: netrc 207 | workspace: netrc 208 | - matrix: 209 | params: 210 | - name: PLATFORM 211 | value: 212 | - $(params.build-platforms) 213 | name: build-images 214 | params: 215 | - name: IMAGE 216 | value: $(params.output-image) 217 | - name: DOCKERFILE 218 | value: $(params.dockerfile) 219 | - name: CONTEXT 220 | value: $(params.path-context) 221 | - name: HERMETIC 222 | value: $(params.hermetic) 223 | - name: PREFETCH_INPUT 224 | value: $(params.prefetch-input) 225 | - name: IMAGE_EXPIRES_AFTER 226 | value: $(params.image-expires-after) 227 | - name: COMMIT_SHA 228 | value: $(tasks.clone-repository.results.commit) 229 | - name: BUILD_ARGS 230 | value: 231 | - $(params.build-args[*]) 232 | - name: BUILD_ARGS_FILE 233 | value: $(params.build-args-file) 234 | - name: SOURCE_ARTIFACT 235 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 236 | - name: CACHI2_ARTIFACT 237 | value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) 238 | - name: IMAGE_APPEND_PLATFORM 239 | value: "true" 240 | runAfter: 241 | - prefetch-dependencies 242 | taskRef: 243 | params: 244 | - name: name 245 | value: buildah-remote-oci-ta 246 | - name: bundle 247 | value: quay.io/konflux-ci/tekton-catalog/task-buildah-remote-oci-ta:0.2@sha256:dbc5f6c58d4642743719ae9b02cb0445836a210f7438e6d874a68ff38de81534 248 | - name: kind 249 | value: task 250 | resolver: bundles 251 | when: 252 | - input: $(tasks.init.results.build) 253 | operator: in 254 | values: 255 | - "true" 256 | - name: build-image-index 257 | params: 258 | - name: IMAGE 259 | value: $(params.output-image) 260 | - name: COMMIT_SHA 261 | value: $(tasks.clone-repository.results.commit) 262 | - name: IMAGE_EXPIRES_AFTER 263 | value: $(params.image-expires-after) 264 | - name: ALWAYS_BUILD_INDEX 265 | value: $(params.build-image-index) 266 | - name: IMAGES 267 | value: 268 | - $(tasks.build-images.results.IMAGE_REF[*]) 269 | runAfter: 270 | - build-images 271 | taskRef: 272 | params: 273 | - name: name 274 | value: build-image-index 275 | - name: bundle 276 | value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.1@sha256:e4871851566d8b496966b37bcb8c5ce9748a52487f116373d96c6cd28ef684c6 277 | - name: kind 278 | value: task 279 | resolver: bundles 280 | when: 281 | - input: $(tasks.init.results.build) 282 | operator: in 283 | values: 284 | - "true" 285 | - name: build-source-image 286 | params: 287 | - name: BINARY_IMAGE 288 | value: $(params.output-image) 289 | - name: SOURCE_ARTIFACT 290 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 291 | - name: CACHI2_ARTIFACT 292 | value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) 293 | runAfter: 294 | - build-image-index 295 | taskRef: 296 | params: 297 | - name: name 298 | value: source-build-oci-ta 299 | - name: bundle 300 | value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.1@sha256:d1fd616413d45bb6af0532352bfa8692c5ca409127e5a2dd4f1bc52aef27d1dc 301 | - name: kind 302 | value: task 303 | resolver: bundles 304 | when: 305 | - input: $(tasks.init.results.build) 306 | operator: in 307 | values: 308 | - "true" 309 | - input: $(params.build-source-image) 310 | operator: in 311 | values: 312 | - "true" 313 | - name: deprecated-base-image-check 314 | params: 315 | - name: IMAGE_URL 316 | value: $(tasks.build-image-index.results.IMAGE_URL) 317 | - name: IMAGE_DIGEST 318 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 319 | runAfter: 320 | - build-image-index 321 | taskRef: 322 | params: 323 | - name: name 324 | value: deprecated-image-check 325 | - name: bundle 326 | value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.4@sha256:b4f9599f5770ea2e6e4d031224ccc932164c1ecde7f85f68e16e99c98d754003 327 | - name: kind 328 | value: task 329 | resolver: bundles 330 | when: 331 | - input: $(params.skip-checks) 332 | operator: in 333 | values: 334 | - "false" 335 | - name: clair-scan 336 | params: 337 | - name: image-digest 338 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 339 | - name: image-url 340 | value: $(tasks.build-image-index.results.IMAGE_URL) 341 | runAfter: 342 | - build-image-index 343 | taskRef: 344 | params: 345 | - name: name 346 | value: clair-scan 347 | - name: bundle 348 | value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.2@sha256:9f4ddafd599e06b319cece5a4b8ac36b9e7ec46bea378bc6c6af735d3f7f8060 349 | - name: kind 350 | value: task 351 | resolver: bundles 352 | when: 353 | - input: $(params.skip-checks) 354 | operator: in 355 | values: 356 | - "false" 357 | - name: ecosystem-cert-preflight-checks 358 | params: 359 | - name: image-url 360 | value: $(tasks.build-image-index.results.IMAGE_URL) 361 | runAfter: 362 | - build-image-index 363 | taskRef: 364 | params: 365 | - name: name 366 | value: ecosystem-cert-preflight-checks 367 | - name: bundle 368 | value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.1@sha256:5131cce0f93d0b728c7bcc0d6cee4c61d4c9f67c6d619c627e41e3c9775b497d 369 | - name: kind 370 | value: task 371 | resolver: bundles 372 | when: 373 | - input: $(params.skip-checks) 374 | operator: in 375 | values: 376 | - "false" 377 | - name: sast-snyk-check 378 | params: 379 | - name: image-digest 380 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 381 | - name: image-url 382 | value: $(tasks.build-image-index.results.IMAGE_URL) 383 | - name: SOURCE_ARTIFACT 384 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 385 | - name: CACHI2_ARTIFACT 386 | value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) 387 | runAfter: 388 | - build-image-index 389 | taskRef: 390 | params: 391 | - name: name 392 | value: sast-snyk-check-oci-ta 393 | - name: bundle 394 | value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.2@sha256:ad02dd316d68725490f45f23d2b8acf042bf0a80f7a22c28e0cadc6181fc10f1 395 | - name: kind 396 | value: task 397 | resolver: bundles 398 | when: 399 | - input: $(params.skip-checks) 400 | operator: in 401 | values: 402 | - "false" 403 | - name: clamav-scan 404 | params: 405 | - name: image-digest 406 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 407 | - name: image-url 408 | value: $(tasks.build-image-index.results.IMAGE_URL) 409 | runAfter: 410 | - build-image-index 411 | taskRef: 412 | params: 413 | - name: name 414 | value: clamav-scan 415 | - name: bundle 416 | value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.1@sha256:5ac9b24cff7cfb391bc54cd5135536892090354862327d1028fa08872d759c03 417 | - name: kind 418 | value: task 419 | resolver: bundles 420 | when: 421 | - input: $(params.skip-checks) 422 | operator: in 423 | values: 424 | - "false" 425 | - name: apply-tags 426 | params: 427 | - name: IMAGE 428 | value: $(tasks.build-image-index.results.IMAGE_URL) 429 | runAfter: 430 | - build-image-index 431 | taskRef: 432 | params: 433 | - name: name 434 | value: apply-tags 435 | - name: bundle 436 | value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.1@sha256:f485e250fb060060892b633c495a3d7e38de1ec105ae1be48608b0401530ab2c 437 | - name: kind 438 | value: task 439 | resolver: bundles 440 | - name: push-dockerfile 441 | params: 442 | - name: IMAGE 443 | value: $(tasks.build-image-index.results.IMAGE_URL) 444 | - name: IMAGE_DIGEST 445 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 446 | - name: DOCKERFILE 447 | value: $(params.dockerfile) 448 | - name: CONTEXT 449 | value: $(params.path-context) 450 | - name: SOURCE_ARTIFACT 451 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 452 | runAfter: 453 | - build-image-index 454 | taskRef: 455 | params: 456 | - name: name 457 | value: push-dockerfile-oci-ta 458 | - name: bundle 459 | value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:fc109c347c5355a2a563ea782ff12aa82afc967c456082bf978d99bd378349b4 460 | - name: kind 461 | value: task 462 | resolver: bundles 463 | workspaces: 464 | - name: git-auth 465 | optional: true 466 | - name: netrc 467 | optional: true 468 | taskRunTemplate: {} 469 | workspaces: 470 | - name: git-auth 471 | secret: 472 | secretName: '{{ git_auth_secret }}' 473 | status: {} 474 | -------------------------------------------------------------------------------- /.tekton/gitops-backend-push.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: tekton.dev/v1 2 | kind: PipelineRun 3 | metadata: 4 | annotations: 5 | build.appstudio.openshift.io/repo: https://github.com/redhat-developer/gitops-backend?rev={{revision}} 6 | build.appstudio.redhat.com/commit_sha: '{{revision}}' 7 | build.appstudio.redhat.com/target_branch: '{{target_branch}}' 8 | pipelinesascode.tekton.dev/max-keep-runs: "3" 9 | pipelinesascode.tekton.dev/on-cel-expression: event == "push" && target_branch 10 | == "master" 11 | creationTimestamp: null 12 | labels: 13 | appstudio.openshift.io/application: openshift-gitops-operator 14 | appstudio.openshift.io/component: gitops-backend 15 | pipelines.appstudio.openshift.io/type: build 16 | name: gitops-backend-on-push 17 | namespace: rh-openshift-gitops-tenant 18 | spec: 19 | params: 20 | - name: git-url 21 | value: '{{source_url}}' 22 | - name: revision 23 | value: '{{revision}}' 24 | - name: output-image 25 | value: quay.io/redhat-user-workloads/rh-openshift-gitops-tenant/openshift-gitops-operator/gitops-backend:{{revision}} 26 | - name: build-platforms 27 | value: 28 | - linux/x86_64 29 | - linux/arm64 30 | - linux/ppc64le 31 | - linux/s390x 32 | - name: dockerfile 33 | value: .konflux/Containerfile.plugin 34 | - name: hermetic 35 | value: "true" 36 | - name: prefetch-input 37 | value: '{"type": "gomod", "path": "."}' 38 | pipelineSpec: 39 | description: | 40 | This pipeline is ideal for building multi-arch container images from a Containerfile while maintaining trust after pipeline customization. 41 | 42 | _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://enterprisecontract.dev/docs/ec-policies/release_policy.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. 43 | 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)_ 44 | finally: 45 | - name: show-sbom 46 | params: 47 | - name: IMAGE_URL 48 | value: $(tasks.build-image-index.results.IMAGE_URL) 49 | taskRef: 50 | params: 51 | - name: name 52 | value: show-sbom 53 | - name: bundle 54 | value: quay.io/konflux-ci/tekton-catalog/task-show-sbom:0.1@sha256:9bfc6b99ef038800fe131d7b45ff3cd4da3a415dd536f7c657b3527b01c4a13b 55 | - name: kind 56 | value: task 57 | resolver: bundles 58 | params: 59 | - description: Source Repository URL 60 | name: git-url 61 | type: string 62 | - default: "" 63 | description: Revision of the Source Repository 64 | name: revision 65 | type: string 66 | - description: Fully Qualified Output Image 67 | name: output-image 68 | type: string 69 | - default: . 70 | description: Path to the source code of an application's component from where 71 | to build image. 72 | name: path-context 73 | type: string 74 | - default: Dockerfile 75 | description: Path to the Dockerfile inside the context specified by parameter 76 | path-context 77 | name: dockerfile 78 | type: string 79 | - default: "false" 80 | description: Force rebuild image 81 | name: rebuild 82 | type: string 83 | - default: "false" 84 | description: Skip checks against built image 85 | name: skip-checks 86 | type: string 87 | - default: "false" 88 | description: Execute the build with network isolation 89 | name: hermetic 90 | type: string 91 | - default: "" 92 | description: Build dependencies to be prefetched by Cachi2 93 | name: prefetch-input 94 | type: string 95 | - default: "" 96 | description: Image tag expiration time, time values could be something like 97 | 1h, 2d, 3w for hours, days, and weeks, respectively. 98 | name: image-expires-after 99 | - default: "false" 100 | description: Build a source image. 101 | name: build-source-image 102 | type: string 103 | - default: "true" 104 | description: Add built image into an OCI image index 105 | name: build-image-index 106 | type: string 107 | - default: [] 108 | description: Array of --build-arg values ("arg=value" strings) for buildah 109 | name: build-args 110 | type: array 111 | - default: "" 112 | description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file 113 | name: build-args-file 114 | type: string 115 | - default: 116 | - linux/x86_64 117 | - linux/arm64 118 | description: List of platforms to build the container images on. The available 119 | set of values is determined by the configuration of the multi-platform-controller. 120 | name: build-platforms 121 | type: array 122 | results: 123 | - description: "" 124 | name: IMAGE_URL 125 | value: $(tasks.build-image-index.results.IMAGE_URL) 126 | - description: "" 127 | name: IMAGE_DIGEST 128 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 129 | - description: "" 130 | name: CHAINS-GIT_URL 131 | value: $(tasks.clone-repository.results.url) 132 | - description: "" 133 | name: CHAINS-GIT_COMMIT 134 | value: $(tasks.clone-repository.results.commit) 135 | tasks: 136 | - name: init 137 | params: 138 | - name: image-url 139 | value: $(params.output-image) 140 | - name: rebuild 141 | value: $(params.rebuild) 142 | - name: skip-checks 143 | value: $(params.skip-checks) 144 | taskRef: 145 | params: 146 | - name: name 147 | value: init 148 | - name: bundle 149 | value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:092c113b614f6551113f17605ae9cb7e822aa704d07f0e37ed209da23ce392cc 150 | - name: kind 151 | value: task 152 | resolver: bundles 153 | - name: clone-repository 154 | params: 155 | - name: url 156 | value: $(params.git-url) 157 | - name: revision 158 | value: $(params.revision) 159 | - name: ociStorage 160 | value: $(params.output-image).git 161 | - name: ociArtifactExpiresAfter 162 | value: $(params.image-expires-after) 163 | runAfter: 164 | - init 165 | taskRef: 166 | params: 167 | - name: name 168 | value: git-clone-oci-ta 169 | - name: bundle 170 | value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:8e1e861d9564caea3f9ce8d1c62789f5622b5a7051209decc9ecf10b6f54aa71 171 | - name: kind 172 | value: task 173 | resolver: bundles 174 | when: 175 | - input: $(tasks.init.results.build) 176 | operator: in 177 | values: 178 | - "true" 179 | workspaces: 180 | - name: basic-auth 181 | workspace: git-auth 182 | - name: prefetch-dependencies 183 | params: 184 | - name: input 185 | value: $(params.prefetch-input) 186 | - name: SOURCE_ARTIFACT 187 | value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) 188 | - name: ociStorage 189 | value: $(params.output-image).prefetch 190 | - name: ociArtifactExpiresAfter 191 | value: $(params.image-expires-after) 192 | runAfter: 193 | - clone-repository 194 | taskRef: 195 | params: 196 | - name: name 197 | value: prefetch-dependencies-oci-ta 198 | - name: bundle 199 | value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.1@sha256:8e2a8de8e8a55a8e657922d5f8303fefa065f7ec2f8a49a666bf749540d63679 200 | - name: kind 201 | value: task 202 | resolver: bundles 203 | workspaces: 204 | - name: git-basic-auth 205 | workspace: git-auth 206 | - name: netrc 207 | workspace: netrc 208 | - matrix: 209 | params: 210 | - name: PLATFORM 211 | value: 212 | - $(params.build-platforms) 213 | name: build-images 214 | params: 215 | - name: IMAGE 216 | value: $(params.output-image) 217 | - name: DOCKERFILE 218 | value: $(params.dockerfile) 219 | - name: CONTEXT 220 | value: $(params.path-context) 221 | - name: HERMETIC 222 | value: $(params.hermetic) 223 | - name: PREFETCH_INPUT 224 | value: $(params.prefetch-input) 225 | - name: IMAGE_EXPIRES_AFTER 226 | value: $(params.image-expires-after) 227 | - name: COMMIT_SHA 228 | value: $(tasks.clone-repository.results.commit) 229 | - name: BUILD_ARGS 230 | value: 231 | - $(params.build-args[*]) 232 | - name: BUILD_ARGS_FILE 233 | value: $(params.build-args-file) 234 | - name: SOURCE_ARTIFACT 235 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 236 | - name: CACHI2_ARTIFACT 237 | value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) 238 | - name: IMAGE_APPEND_PLATFORM 239 | value: "true" 240 | runAfter: 241 | - prefetch-dependencies 242 | taskRef: 243 | params: 244 | - name: name 245 | value: buildah-remote-oci-ta 246 | - name: bundle 247 | value: quay.io/konflux-ci/tekton-catalog/task-buildah-remote-oci-ta:0.2@sha256:dbc5f6c58d4642743719ae9b02cb0445836a210f7438e6d874a68ff38de81534 248 | - name: kind 249 | value: task 250 | resolver: bundles 251 | when: 252 | - input: $(tasks.init.results.build) 253 | operator: in 254 | values: 255 | - "true" 256 | - name: build-image-index 257 | params: 258 | - name: IMAGE 259 | value: $(params.output-image) 260 | - name: COMMIT_SHA 261 | value: $(tasks.clone-repository.results.commit) 262 | - name: IMAGE_EXPIRES_AFTER 263 | value: $(params.image-expires-after) 264 | - name: ALWAYS_BUILD_INDEX 265 | value: $(params.build-image-index) 266 | - name: IMAGES 267 | value: 268 | - $(tasks.build-images.results.IMAGE_REF[*]) 269 | runAfter: 270 | - build-images 271 | taskRef: 272 | params: 273 | - name: name 274 | value: build-image-index 275 | - name: bundle 276 | value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.1@sha256:e4871851566d8b496966b37bcb8c5ce9748a52487f116373d96c6cd28ef684c6 277 | - name: kind 278 | value: task 279 | resolver: bundles 280 | when: 281 | - input: $(tasks.init.results.build) 282 | operator: in 283 | values: 284 | - "true" 285 | - name: build-source-image 286 | params: 287 | - name: BINARY_IMAGE 288 | value: $(params.output-image) 289 | - name: SOURCE_ARTIFACT 290 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 291 | - name: CACHI2_ARTIFACT 292 | value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) 293 | runAfter: 294 | - build-image-index 295 | taskRef: 296 | params: 297 | - name: name 298 | value: source-build-oci-ta 299 | - name: bundle 300 | value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.1@sha256:d1fd616413d45bb6af0532352bfa8692c5ca409127e5a2dd4f1bc52aef27d1dc 301 | - name: kind 302 | value: task 303 | resolver: bundles 304 | when: 305 | - input: $(tasks.init.results.build) 306 | operator: in 307 | values: 308 | - "true" 309 | - input: $(params.build-source-image) 310 | operator: in 311 | values: 312 | - "true" 313 | - name: deprecated-base-image-check 314 | params: 315 | - name: IMAGE_URL 316 | value: $(tasks.build-image-index.results.IMAGE_URL) 317 | - name: IMAGE_DIGEST 318 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 319 | runAfter: 320 | - build-image-index 321 | taskRef: 322 | params: 323 | - name: name 324 | value: deprecated-image-check 325 | - name: bundle 326 | value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.4@sha256:b4f9599f5770ea2e6e4d031224ccc932164c1ecde7f85f68e16e99c98d754003 327 | - name: kind 328 | value: task 329 | resolver: bundles 330 | when: 331 | - input: $(params.skip-checks) 332 | operator: in 333 | values: 334 | - "false" 335 | - name: clair-scan 336 | params: 337 | - name: image-digest 338 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 339 | - name: image-url 340 | value: $(tasks.build-image-index.results.IMAGE_URL) 341 | runAfter: 342 | - build-image-index 343 | taskRef: 344 | params: 345 | - name: name 346 | value: clair-scan 347 | - name: bundle 348 | value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.2@sha256:9f4ddafd599e06b319cece5a4b8ac36b9e7ec46bea378bc6c6af735d3f7f8060 349 | - name: kind 350 | value: task 351 | resolver: bundles 352 | when: 353 | - input: $(params.skip-checks) 354 | operator: in 355 | values: 356 | - "false" 357 | - name: ecosystem-cert-preflight-checks 358 | params: 359 | - name: image-url 360 | value: $(tasks.build-image-index.results.IMAGE_URL) 361 | runAfter: 362 | - build-image-index 363 | taskRef: 364 | params: 365 | - name: name 366 | value: ecosystem-cert-preflight-checks 367 | - name: bundle 368 | value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.1@sha256:5131cce0f93d0b728c7bcc0d6cee4c61d4c9f67c6d619c627e41e3c9775b497d 369 | - name: kind 370 | value: task 371 | resolver: bundles 372 | when: 373 | - input: $(params.skip-checks) 374 | operator: in 375 | values: 376 | - "false" 377 | - name: sast-snyk-check 378 | params: 379 | - name: image-digest 380 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 381 | - name: image-url 382 | value: $(tasks.build-image-index.results.IMAGE_URL) 383 | - name: SOURCE_ARTIFACT 384 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 385 | - name: CACHI2_ARTIFACT 386 | value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) 387 | runAfter: 388 | - build-image-index 389 | taskRef: 390 | params: 391 | - name: name 392 | value: sast-snyk-check-oci-ta 393 | - name: bundle 394 | value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.2@sha256:ad02dd316d68725490f45f23d2b8acf042bf0a80f7a22c28e0cadc6181fc10f1 395 | - name: kind 396 | value: task 397 | resolver: bundles 398 | when: 399 | - input: $(params.skip-checks) 400 | operator: in 401 | values: 402 | - "false" 403 | - name: clamav-scan 404 | params: 405 | - name: image-digest 406 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 407 | - name: image-url 408 | value: $(tasks.build-image-index.results.IMAGE_URL) 409 | runAfter: 410 | - build-image-index 411 | taskRef: 412 | params: 413 | - name: name 414 | value: clamav-scan 415 | - name: bundle 416 | value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.1@sha256:5ac9b24cff7cfb391bc54cd5135536892090354862327d1028fa08872d759c03 417 | - name: kind 418 | value: task 419 | resolver: bundles 420 | when: 421 | - input: $(params.skip-checks) 422 | operator: in 423 | values: 424 | - "false" 425 | - name: apply-tags 426 | params: 427 | - name: IMAGE 428 | value: $(tasks.build-image-index.results.IMAGE_URL) 429 | runAfter: 430 | - build-image-index 431 | taskRef: 432 | params: 433 | - name: name 434 | value: apply-tags 435 | - name: bundle 436 | value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.1@sha256:f485e250fb060060892b633c495a3d7e38de1ec105ae1be48608b0401530ab2c 437 | - name: kind 438 | value: task 439 | resolver: bundles 440 | - name: push-dockerfile 441 | params: 442 | - name: IMAGE 443 | value: $(tasks.build-image-index.results.IMAGE_URL) 444 | - name: IMAGE_DIGEST 445 | value: $(tasks.build-image-index.results.IMAGE_DIGEST) 446 | - name: DOCKERFILE 447 | value: $(params.dockerfile) 448 | - name: CONTEXT 449 | value: $(params.path-context) 450 | - name: SOURCE_ARTIFACT 451 | value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) 452 | runAfter: 453 | - build-image-index 454 | taskRef: 455 | params: 456 | - name: name 457 | value: push-dockerfile-oci-ta 458 | - name: bundle 459 | value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:fc109c347c5355a2a563ea782ff12aa82afc967c456082bf978d99bd378349b4 460 | - name: kind 461 | value: task 462 | resolver: bundles 463 | workspaces: 464 | - name: git-auth 465 | optional: true 466 | - name: netrc 467 | optional: true 468 | taskRunTemplate: {} 469 | workspaces: 470 | - name: git-auth 471 | secret: 472 | secretName: '{{ git_auth_secret }}' 473 | status: {} 474 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Certificate of Origin 2 | 3 | By contributing to this project you agree to the Developer Certificate of 4 | Origin (DCO). This document was created by the Linux Kernel community and is a 5 | simple statement that you, as a contributor, have the legal right to make the 6 | contribution. Please read the [DCO text here](https://developercertificate.org/) for details. 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.23 AS build 2 | WORKDIR /go/src 3 | COPY . /go/src 4 | RUN GIT_COMMIT=$(git rev-parse HEAD) && \ 5 | CGO_ENABLED=0 GOOS=linux go build -a -mod=readonly \ 6 | -ldflags "-X github.com/redhat-developer/gitops-backend/pkg/health.GitRevision=${GIT_COMMIT}" ./cmd/backend-http 7 | 8 | FROM scratch 9 | WORKDIR / 10 | COPY --from=build /go/src/backend-http . 11 | EXPOSE 8080 12 | ENTRYPOINT ["./backend-http"] 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | default: test 2 | 3 | .PHONY: test 4 | test: 5 | go test `go list ./... | grep -v test` 6 | 7 | .PHONY: gomod_tidy 8 | gomod_tidy: 9 | go mod tidy 10 | 11 | .PHONY: gofmt 12 | gofmt: 13 | go fmt -x ./... 14 | -------------------------------------------------------------------------------- /OWNERS: -------------------------------------------------------------------------------- 1 | # See the OWNERS docs: https://git.k8s.io/community/contributors/guide/owners.md 2 | 3 | approvers: 4 | - sbose78 5 | - wtam2018 6 | - chetan-rns 7 | - jannfis 8 | - iam-veeramalla 9 | 10 | reviewers: 11 | - sbose78 12 | - wtam2018 13 | - chetan-rns 14 | - keithchong 15 | - ishitasequeira 16 | - jannfis 17 | - jopit 18 | - jgwest 19 | - iam-veeramalla 20 | - ranakan19 21 | 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gitops-backend 2 | 3 | This is a service for getting files from a remote Git API. 4 | 5 | ## Installation 6 | 7 | First of all, generate a GitHub access token. 8 | 9 | You will need to create a secret in the correct namespace: 10 | 11 | ```shell 12 | $ kubectl create -f deploy/namespace.yaml 13 | ``` 14 | 15 | ```shell 16 | $ kubectl create secret generic -n pipelines-app-delivery \ 17 | pipelines-app-gitops --from-literal=token=GENERATE_ME 18 | ``` 19 | 20 | Then you can deploy the resources with: 21 | 22 | ```shell 23 | $ kubectl apply -k deploy 24 | ``` 25 | 26 | ## Usage 27 | 28 | Deploy the `Deployment` and `Service` into your cluster. 29 | 30 | You can fetch with `https://...?url=https://github.com/org/repo.git?secretNS=my-ns&secretName=my-secret` 31 | 32 | You'll need to provide your OpenShift authentication token (`oc whoami --show-token`) as a Bearer token. 33 | 34 | ``` 35 | $ curl -H "Authorization: $(oc whoami --show-token)" https://...?url=https://github.com/org/repo.git?secretNS=my-ns&secretName=my-secret 36 | ``` 37 | 38 | This token is used to authenticate the Kube client request to load the secret by name/namespace to authenticate the call to the upstream Git provider. 39 | 40 | The `token` field in the named secret will be extracted and used to authenticate 41 | the request to the upstream Git hosting service. 42 | -------------------------------------------------------------------------------- /cmd/backend-http/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/redhat-developer/gitops-backend/pkg/cmd" 5 | ) 6 | 7 | func main() { 8 | cmd.Execute() 9 | } 10 | -------------------------------------------------------------------------------- /deploy/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: pipelines-app-delivery-backend 5 | labels: 6 | app.kubernetes.io/name: pipelines-app-delivery-backend 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app.kubernetes.io/name: pipelines-app-delivery-backend 12 | template: 13 | metadata: 14 | labels: 15 | app.kubernetes.io/name: pipelines-app-delivery-backend 16 | spec: 17 | serviceAccountName: pipelines-app-delivery 18 | containers: 19 | - name: pipelines-app-delivery-http 20 | image: quay.io/kmcdermo/gitops-backend:v0.0.4 21 | imagePullPolicy: Always 22 | env: 23 | - name: INSECURE 24 | value: "true" 25 | volumeMounts: 26 | - mountPath: "/etc/gitops/ssl" 27 | name: backend-ssl 28 | readOnly: true 29 | ports: 30 | - containerPort: 8080 31 | volumes: 32 | - name: backend-ssl 33 | secret: 34 | secretName: pipelines-app-delivery-backend 35 | -------------------------------------------------------------------------------- /deploy/kustomization.yaml: -------------------------------------------------------------------------------- 1 | namespace: pipelines-app-delivery 2 | resources: 3 | - serviceaccount.yaml 4 | - rolebinding.yaml 5 | - role.yaml 6 | - deployment.yaml 7 | - service.yaml 8 | -------------------------------------------------------------------------------- /deploy/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: pipelines-app-delivery 5 | -------------------------------------------------------------------------------- /deploy/role.yaml: -------------------------------------------------------------------------------- 1 | kind: Role 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | metadata: 4 | name: pipelines-app-delivery 5 | rules: 6 | - apiGroups: 7 | - "" 8 | resources: 9 | - secrets 10 | verbs: 11 | - get 12 | -------------------------------------------------------------------------------- /deploy/rolebinding.yaml: -------------------------------------------------------------------------------- 1 | kind: RoleBinding 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | metadata: 4 | name: pipelines-app-delivery 5 | subjects: 6 | - kind: ServiceAccount 7 | name: pipelines-app-delivery 8 | roleRef: 9 | kind: Role 10 | name: pipelines-app-delivery 11 | apiGroup: rbac.authorization.k8s.io 12 | -------------------------------------------------------------------------------- /deploy/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: pipelines-app-delivery-backend 5 | annotations: 6 | service.beta.openshift.io/serving-cert-secret-name: pipelines-app-delivery-backend 7 | labels: 8 | app.kubernetes.io/name: pipelines-app-delivery-backend 9 | spec: 10 | type: ClusterIP 11 | selector: 12 | app.kubernetes.io/name: pipelines-app-delivery-backend 13 | ports: 14 | - protocol: TCP 15 | port: 8080 16 | -------------------------------------------------------------------------------- /deploy/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: pipelines-app-delivery 5 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/redhat-developer/gitops-backend 2 | 3 | go 1.23.0 4 | 5 | toolchain go1.23.8 6 | 7 | require ( 8 | github.com/argoproj/argo-cd v0.8.1-0.20210326223336-719d6a9c252e 9 | github.com/go-git/go-git/v5 v5.13.1 10 | github.com/google/go-cmp v0.6.0 11 | github.com/jenkins-x/go-scm v1.5.151 12 | github.com/julienschmidt/httprouter v1.3.0 13 | github.com/openshift/api v3.9.0+incompatible 14 | github.com/prometheus/client_golang v1.17.0 15 | github.com/sirupsen/logrus v1.9.0 16 | github.com/spf13/cobra v1.1.1 17 | github.com/spf13/viper v1.7.0 18 | go.uber.org/zap v1.15.0 19 | k8s.io/api v0.21.0 20 | k8s.io/apimachinery v0.21.0 21 | k8s.io/client-go v11.0.1-0.20190816222228-6d55c1b1f1ca+incompatible 22 | sigs.k8s.io/controller-runtime v0.8.3 23 | sigs.k8s.io/kustomize v2.0.3+incompatible 24 | sigs.k8s.io/yaml v1.2.0 25 | ) 26 | 27 | require ( 28 | dario.cat/mergo v1.0.0 // indirect 29 | github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect 30 | github.com/MakeNowJust/heredoc v0.0.0-20170808103936-bb23615498cd // indirect 31 | github.com/Masterminds/semver v1.5.0 // indirect 32 | github.com/Microsoft/go-winio v0.6.1 // indirect 33 | github.com/ProtonMail/go-crypto v1.1.3 // indirect 34 | github.com/PuerkitoBio/purell v1.1.1 // indirect 35 | github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect 36 | github.com/argoproj/gitops-engine v0.3.1-0.20210325215106-1ce2acc845d2 // indirect 37 | github.com/argoproj/pkg v0.9.0 // indirect 38 | github.com/beorn7/perks v1.0.1 // indirect 39 | github.com/bombsimon/logrusr v1.0.0 // indirect 40 | github.com/bradleyfalzon/ghinstallation v1.1.1 // indirect 41 | github.com/cespare/xxhash/v2 v2.2.0 // indirect 42 | github.com/chai2010/gettext-go v0.0.0-20170215093142-bf70f2a70fb1 // indirect 43 | github.com/cloudflare/circl v1.3.7 // indirect 44 | github.com/cyphar/filepath-securejoin v0.3.6 // indirect 45 | github.com/davecgh/go-spew v1.1.1 // indirect 46 | github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect 47 | github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect 48 | github.com/docker/distribution v2.7.1+incompatible // indirect 49 | github.com/emicklei/go-restful v2.12.0+incompatible // indirect 50 | github.com/emirpasic/gods v1.18.1 // indirect 51 | github.com/evanphx/json-patch v4.9.0+incompatible // indirect 52 | github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d // indirect 53 | github.com/fatih/camelcase v1.0.0 // indirect 54 | github.com/fsnotify/fsnotify v1.4.9 // indirect 55 | github.com/ghodss/yaml v1.0.0 // indirect 56 | github.com/go-errors/errors v1.0.1 // indirect 57 | github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect 58 | github.com/go-git/go-billy/v5 v5.6.1 // indirect 59 | github.com/go-logr/logr v0.4.0 // indirect 60 | github.com/go-openapi/jsonpointer v0.19.3 // indirect 61 | github.com/go-openapi/jsonreference v0.19.3 // indirect 62 | github.com/go-openapi/spec v0.19.8 // indirect 63 | github.com/go-openapi/swag v0.19.9 // indirect 64 | github.com/go-redis/cache/v8 v8.2.1 // indirect 65 | github.com/go-redis/redis/v8 v8.3.2 // indirect 66 | github.com/gobwas/glob v0.2.3 // indirect 67 | github.com/gogo/protobuf v1.3.2 // indirect 68 | github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect 69 | github.com/golang/protobuf v1.5.3 // indirect 70 | github.com/google/btree v1.0.0 // indirect 71 | github.com/google/go-github/v29 v29.0.2 // indirect 72 | github.com/google/go-querystring v1.0.0 // indirect 73 | github.com/google/gofuzz v1.1.0 // indirect 74 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect 75 | github.com/google/uuid v1.3.0 // indirect 76 | github.com/googleapis/gnostic v0.5.1 // indirect 77 | github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect 78 | github.com/hashicorp/golang-lru v0.5.4 // indirect 79 | github.com/hashicorp/hcl v1.0.0 // indirect 80 | github.com/imdario/mergo v0.3.10 // indirect 81 | github.com/inconshreveable/mousetrap v1.0.0 // indirect 82 | github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect 83 | github.com/jonboulle/clockwork v0.1.0 // indirect 84 | github.com/json-iterator/go v1.1.12 // indirect 85 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect 86 | github.com/kevinburke/ssh_config v1.2.0 // indirect 87 | github.com/klauspost/compress v1.15.9 // indirect 88 | github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect 89 | github.com/magiconair/properties v1.8.1 // indirect 90 | github.com/mailru/easyjson v0.7.1 // indirect 91 | github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect 92 | github.com/mitchellh/go-homedir v1.1.0 // indirect 93 | github.com/mitchellh/go-wordwrap v1.0.0 // indirect 94 | github.com/mitchellh/mapstructure v1.3.2 // indirect 95 | github.com/moby/spdystream v0.2.0 // indirect 96 | github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect 97 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 98 | github.com/modern-go/reflect2 v1.0.2 // indirect 99 | github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect 100 | github.com/opencontainers/go-digest v1.0.0 // indirect 101 | github.com/patrickmn/go-cache v2.1.0+incompatible // indirect 102 | github.com/pelletier/go-toml v1.6.0 // indirect 103 | github.com/peterbourgon/diskv v2.0.1+incompatible // indirect 104 | github.com/pjbgf/sha1cd v0.3.0 // indirect 105 | github.com/pkg/errors v0.9.1 // indirect 106 | github.com/pmezard/go-difflib v1.0.0 // indirect 107 | github.com/prometheus/client_model v0.5.0 // indirect 108 | github.com/prometheus/common v0.45.0 // indirect 109 | github.com/prometheus/procfs v0.12.0 // indirect 110 | github.com/robfig/cron v1.2.0 // indirect 111 | github.com/russross/blackfriday v1.5.2 // indirect 112 | github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 // indirect 113 | github.com/shurcooL/githubv4 v0.0.0-20191102174205-af46314aec7b // indirect 114 | github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f // indirect 115 | github.com/skeema/knownhosts v1.3.0 // indirect 116 | github.com/spf13/afero v1.9.2 // indirect 117 | github.com/spf13/cast v1.3.1 // indirect 118 | github.com/spf13/jwalterweatherman v1.1.0 // indirect 119 | github.com/spf13/pflag v1.0.5 // indirect 120 | github.com/src-d/gcfg v1.4.0 // indirect 121 | github.com/stretchr/testify v1.10.0 // indirect 122 | github.com/subosito/gotenv v1.2.0 // indirect 123 | github.com/vmihailenco/bufpool v0.1.11 // indirect 124 | github.com/vmihailenco/go-tinylfu v0.1.0 // indirect 125 | github.com/vmihailenco/msgpack/v5 v5.1.0 // indirect 126 | github.com/vmihailenco/tagparser v0.1.2 // indirect 127 | github.com/xanzy/ssh-agent v0.3.3 // indirect 128 | github.com/xlab/treeprint v0.0.0-20181112141820-a009c3971eca // indirect 129 | go.opentelemetry.io/otel v0.13.0 // indirect 130 | go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 // indirect 131 | go.uber.org/atomic v1.6.0 // indirect 132 | go.uber.org/multierr v1.5.0 // indirect 133 | golang.org/x/crypto v0.35.0 // indirect 134 | golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect 135 | golang.org/x/mod v0.19.0 // indirect 136 | golang.org/x/net v0.33.0 // indirect 137 | golang.org/x/oauth2 v0.12.0 // indirect 138 | golang.org/x/sync v0.11.0 // indirect 139 | golang.org/x/sys v0.30.0 // indirect 140 | golang.org/x/term v0.29.0 // indirect 141 | golang.org/x/text v0.22.0 // indirect 142 | golang.org/x/time v0.3.0 // indirect 143 | golang.org/x/tools v0.23.0 // indirect 144 | google.golang.org/appengine v1.6.7 // indirect 145 | google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc // indirect 146 | google.golang.org/grpc v1.55.0 // indirect 147 | google.golang.org/protobuf v1.31.0 // indirect 148 | gopkg.in/inf.v0 v0.9.1 // indirect 149 | gopkg.in/ini.v1 v1.57.0 // indirect 150 | gopkg.in/src-d/go-billy.v4 v4.3.2 // indirect 151 | gopkg.in/src-d/go-git.v4 v4.13.1 // indirect 152 | gopkg.in/warnings.v0 v0.1.2 // indirect 153 | gopkg.in/yaml.v2 v2.4.0 // indirect 154 | gopkg.in/yaml.v3 v3.0.1 // indirect 155 | k8s.io/apiserver v0.21.0 // indirect 156 | k8s.io/cli-runtime v0.21.0 // indirect 157 | k8s.io/component-base v0.21.0 // indirect 158 | k8s.io/component-helpers v0.21.0 // indirect 159 | k8s.io/klog/v2 v2.8.0 // indirect 160 | k8s.io/kube-aggregator v0.20.4 // indirect 161 | k8s.io/kube-openapi v0.0.0-20210305001622-591a79e4bda7 // indirect 162 | k8s.io/kubectl v0.20.4 // indirect 163 | k8s.io/kubernetes v1.21.0 // indirect 164 | k8s.io/utils v0.0.0-20210111153108-fddb29f9d009 // indirect 165 | sigs.k8s.io/kustomize/api v0.8.5 // indirect 166 | sigs.k8s.io/kustomize/kyaml v0.10.15 // indirect 167 | sigs.k8s.io/structured-merge-diff/v4 v4.1.0 // indirect 168 | ) 169 | 170 | replace ( 171 | k8s.io/api => k8s.io/api v0.21.0 172 | k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.21.0 173 | k8s.io/apimachinery => k8s.io/apimachinery v0.21.1-rc.0 174 | k8s.io/apiserver => k8s.io/apiserver v0.21.0 175 | k8s.io/cli-runtime => k8s.io/cli-runtime v0.21.0 176 | k8s.io/client-go => k8s.io/client-go v0.21.0 177 | k8s.io/cloud-provider => k8s.io/cloud-provider v0.21.0 178 | k8s.io/cluster-bootstrap => k8s.io/cluster-bootstrap v0.21.0 179 | k8s.io/code-generator => k8s.io/code-generator v0.21.1-rc.0 180 | k8s.io/component-base => k8s.io/component-base v0.21.0 181 | k8s.io/component-helpers => k8s.io/component-helpers v0.21.0 182 | k8s.io/controller-manager => k8s.io/controller-manager v0.21.0 183 | k8s.io/cri-api => k8s.io/cri-api v0.21.1-rc.0 184 | k8s.io/csi-translation-lib => k8s.io/csi-translation-lib v0.21.0 185 | k8s.io/kube-aggregator => k8s.io/kube-aggregator v0.21.0 186 | k8s.io/kube-controller-manager => k8s.io/kube-controller-manager v0.21.0 187 | k8s.io/kube-proxy => k8s.io/kube-proxy v0.21.0 188 | k8s.io/kube-scheduler => k8s.io/kube-scheduler v0.21.0 189 | k8s.io/kubectl => k8s.io/kubectl v0.21.0 190 | k8s.io/kubelet => k8s.io/kubelet v0.21.0 191 | k8s.io/legacy-cloud-providers => k8s.io/legacy-cloud-providers v0.21.0 192 | k8s.io/metrics => k8s.io/metrics v0.21.0 193 | k8s.io/mount-utils => k8s.io/mount-utils v0.21.1-rc.0 194 | k8s.io/sample-apiserver => k8s.io/sample-apiserver v0.21.0 195 | k8s.io/sample-cli-plugin => k8s.io/sample-cli-plugin v0.21.0 196 | k8s.io/sample-controller => k8s.io/sample-controller v0.21.0 197 | ) 198 | 199 | replace github.com/prometheus/client_golang => github.com/prometheus/client_golang v1.17.0 200 | -------------------------------------------------------------------------------- /internal/sets/strings.go: -------------------------------------------------------------------------------- 1 | package sets 2 | 3 | import "sort" 4 | 5 | // StringSet is a set of strings with simple functionality for getting a sorted 6 | // set of elements. 7 | type StringSet map[string]bool 8 | 9 | // NewStringSet creates a new empty StringSet. 10 | func NewStringSet() StringSet { 11 | return StringSet{} 12 | } 13 | 14 | // Add adds a string to the set. 15 | func (s StringSet) Add(n string) { 16 | s[n] = true 17 | } 18 | 19 | // Elements returns a sorted list of elements in the set. 20 | func (s StringSet) Elements() []string { 21 | e := []string{} 22 | for k := range s { 23 | e = append(e, k) 24 | } 25 | sort.Strings(e) 26 | return e 27 | } 28 | -------------------------------------------------------------------------------- /internal/sets/strings_test.go: -------------------------------------------------------------------------------- 1 | package sets 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/google/go-cmp/cmp" 7 | ) 8 | 9 | func TestStringSet(t *testing.T) { 10 | s := NewStringSet() 11 | 12 | s.Add("test2") 13 | s.Add("test3") 14 | s.Add("test1") 15 | s.Add("test1") 16 | 17 | want := []string{"test1", "test2", "test3"} 18 | 19 | if diff := cmp.Diff(want, s.Elements()); diff != "" { 20 | t.Fatalf("StringSet failed:\n%s", diff) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /openshift-ci/build-root/Dockerfile: -------------------------------------------------------------------------------- 1 | # Dockerfile to bootstrap build and test in openshift-ci 2 | 3 | FROM registry.ci.openshift.org/openshift/release:golang-1.23 4 | -------------------------------------------------------------------------------- /openshift-ci/build-root/OWNERS: -------------------------------------------------------------------------------- 1 | # See the OWNERS docs: https://git.k8s.io/community/contributors/guide/owners.md 2 | 3 | approvers: 4 | - sbose78 5 | - wtam2018 6 | - amitkrout 7 | - chetan-rns 8 | - jannfis 9 | 10 | reviewers: 11 | - sbose78 12 | - wtam2018 13 | - bigkevmcd 14 | - chetan-rns 15 | - shubhamagarwal19 16 | - keithchong 17 | - ishitasequeira 18 | - amitkrout 19 | - jannfis 20 | - jopit 21 | - jgwest 22 | - reginapizza 23 | - iam-veeramalla 24 | - dewan-ahmed 25 | -------------------------------------------------------------------------------- /openshift-ci/build-root/README.md: -------------------------------------------------------------------------------- 1 | # Base Image for running tests on OpenShift CI 2 | 3 | This image is meant to be used as build root for tests on [OpenShift CI](https://github.com/openshift/release/blob/master/ci-operator/config/openshift/odo/redhat-developer-odo-master.yaml) 4 | You can find out more in the [ 5 | ](https://github.com/openshift/ci-operator/blob/master/CONFIGURATION.md) 6 | -------------------------------------------------------------------------------- /openshift-ci/build-root/source-image/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM src 2 | 3 | COPY oc /usr/bin/oc 4 | -------------------------------------------------------------------------------- /pkg/cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | 9 | argoV1aplha1 "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1" 10 | "github.com/prometheus/client_golang/prometheus/promhttp" 11 | "github.com/spf13/cobra" 12 | "github.com/spf13/viper" 13 | "k8s.io/client-go/kubernetes/scheme" 14 | "k8s.io/client-go/rest" 15 | ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" 16 | 17 | "github.com/redhat-developer/gitops-backend/pkg/git" 18 | "github.com/redhat-developer/gitops-backend/pkg/health" 19 | "github.com/redhat-developer/gitops-backend/pkg/httpapi" 20 | "github.com/redhat-developer/gitops-backend/pkg/httpapi/secrets" 21 | "github.com/redhat-developer/gitops-backend/pkg/metrics" 22 | ) 23 | 24 | const ( 25 | portFlag = "port" 26 | insecureFlag = "insecure" 27 | tlsCertFlag = "tls-cert" 28 | tlsKeyFlag = "tls-key" 29 | noTLSFlag = "no-tls" 30 | enableHTTP2 = "enable-http2" 31 | ) 32 | 33 | func init() { 34 | cobra.OnInitialize(initConfig) 35 | if err := argoV1aplha1.AddToScheme(scheme.Scheme); err != nil { 36 | log.Fatalf("failed to initialize ArgoCD scheme, err: %v", err) 37 | } 38 | } 39 | 40 | func logIfError(e error) { 41 | if e != nil { 42 | log.Fatal(e) 43 | } 44 | } 45 | 46 | func initConfig() { 47 | viper.AutomaticEnv() 48 | } 49 | 50 | func makeHTTPCmd() *cobra.Command { 51 | cmd := &cobra.Command{ 52 | Use: "gitops-backend", 53 | Short: "provide a simple API for fetching information", 54 | RunE: func(cmd *cobra.Command, args []string) error { 55 | m := metrics.New("backend", nil) 56 | 57 | http.Handle("/metrics", promhttp.Handler()) 58 | http.HandleFunc("/health", health.Handler) 59 | 60 | router, err := makeAPIRouter(m) 61 | if err != nil { 62 | return err 63 | } 64 | http.Handle("/", httpapi.AuthenticationMiddleware(router)) 65 | 66 | listen := fmt.Sprintf(":%d", viper.GetInt(portFlag)) 67 | log.Printf("listening on %s", listen) 68 | 69 | server := &http.Server{ 70 | Addr: listen, 71 | } 72 | // Disable HTTP/2 to mitigate CVE-2023-39325 & CVE-2023-44487 73 | if !viper.GetBool(enableHTTP2) { 74 | log.Printf("Disabled HTTP/2 protocol") 75 | server.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){} 76 | } 77 | 78 | if viper.GetBool(noTLSFlag) { 79 | log.Println("TLS connections disabled") 80 | return server.ListenAndServe() 81 | } 82 | log.Printf("Using TLS from %q and %q", viper.GetString(tlsCertFlag), viper.GetString(tlsKeyFlag)) 83 | return server.ListenAndServeTLS(viper.GetString(tlsCertFlag), viper.GetString(tlsKeyFlag)) 84 | }, 85 | } 86 | 87 | cmd.Flags().Int( 88 | portFlag, 89 | 8080, 90 | "port to serve requests on", 91 | ) 92 | logIfError(viper.BindPFlag(portFlag, cmd.Flags().Lookup(portFlag))) 93 | 94 | cmd.Flags().Bool( 95 | insecureFlag, 96 | false, 97 | "allow insecure TLS requests", 98 | ) 99 | logIfError(viper.BindPFlag(insecureFlag, cmd.Flags().Lookup(insecureFlag))) 100 | 101 | cmd.Flags().String( 102 | tlsKeyFlag, 103 | "/etc/gitops/ssl/tls.key", 104 | "filename for the TLS key", 105 | ) 106 | logIfError(viper.BindPFlag(tlsKeyFlag, cmd.Flags().Lookup(tlsKeyFlag))) 107 | 108 | cmd.Flags().String( 109 | tlsCertFlag, 110 | "/etc/gitops/ssl/tls.crt", 111 | "filename for the TLS certficate", 112 | ) 113 | logIfError(viper.BindPFlag(tlsCertFlag, cmd.Flags().Lookup(tlsCertFlag))) 114 | 115 | cmd.Flags().Bool( 116 | noTLSFlag, 117 | false, 118 | "do not attempt to read TLS certificates", 119 | ) 120 | logIfError(viper.BindPFlag(noTLSFlag, cmd.Flags().Lookup(noTLSFlag))) 121 | 122 | cmd.Flags().Bool( 123 | enableHTTP2, 124 | false, 125 | "enable HTTP/2 for the server", 126 | ) 127 | logIfError(viper.BindPFlag(enableHTTP2, cmd.Flags().Lookup(enableHTTP2))) 128 | return cmd 129 | } 130 | 131 | // Execute is the main entry point into this component. 132 | func Execute() { 133 | if err := makeHTTPCmd().Execute(); err != nil { 134 | log.Fatal(err) 135 | } 136 | } 137 | 138 | func makeClusterConfig() (*rest.Config, error) { 139 | clusterConfig, err := rest.InClusterConfig() 140 | if err != nil { 141 | return nil, fmt.Errorf("failed to create a cluster config: %s", err) 142 | } 143 | return clusterConfig, nil 144 | } 145 | 146 | func makeAPIRouter(m metrics.Interface) (*httpapi.APIRouter, error) { 147 | config, err := makeClusterConfig() 148 | if err != nil { 149 | return nil, err 150 | } 151 | cf := git.NewClientFactory(m) 152 | secretGetter := secrets.NewFromConfig( 153 | &rest.Config{Host: config.Host}, 154 | viper.GetBool(insecureFlag)) 155 | k8sClient, err := ctrlclient.New(config, ctrlclient.Options{}) 156 | if err != nil { 157 | return nil, err 158 | } 159 | router := httpapi.NewRouter(cf, secretGetter, k8sClient) 160 | return router, nil 161 | } 162 | -------------------------------------------------------------------------------- /pkg/git/client.go: -------------------------------------------------------------------------------- 1 | package git 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | "github.com/jenkins-x/go-scm/scm" 8 | "github.com/redhat-developer/gitops-backend/pkg/metrics" 9 | ) 10 | 11 | // New creates and returns a new SCMClient. 12 | func New(c *scm.Client, m metrics.Interface) *SCMClient { 13 | return &SCMClient{Client: c, m: m} 14 | } 15 | 16 | // SCMClient is a wrapper for the go-scm scm.Client with a simplified API. 17 | type SCMClient struct { 18 | Client *scm.Client 19 | m metrics.Interface 20 | } 21 | 22 | // FileContents reads the specific revision of a file from a repository. 23 | // 24 | // If an HTTP error is returned by the upstream service, an error with the 25 | // response status code is returned. 26 | func (c *SCMClient) FileContents(ctx context.Context, repo, path, ref string) ([]byte, error) { 27 | c.m.CountAPICall("file_contents") 28 | content, r, err := c.Client.Contents.Find(ctx, repo, path, ref) 29 | if r != nil && isErrorStatus(r.Status) { 30 | c.m.CountFailedAPICall("file_contents") 31 | return nil, SCMError{msg: fmt.Sprintf("failed to get file %s from repo %s ref %s", path, repo, ref), Status: r.Status} 32 | } 33 | if err != nil { 34 | c.m.CountFailedAPICall("file_contents") 35 | return nil, err 36 | } 37 | 38 | return content.Data, nil 39 | } 40 | 41 | func isErrorStatus(i int) bool { 42 | return i >= 400 43 | } 44 | -------------------------------------------------------------------------------- /pkg/git/client_test.go: -------------------------------------------------------------------------------- 1 | package git 2 | 3 | import ( 4 | "context" 5 | "io/ioutil" 6 | "net/http" 7 | "net/http/httptest" 8 | "testing" 9 | 10 | "github.com/google/go-cmp/cmp" 11 | "github.com/jenkins-x/go-scm/scm/factory" 12 | 13 | "github.com/redhat-developer/gitops-backend/pkg/metrics" 14 | "github.com/redhat-developer/gitops-backend/test" 15 | ) 16 | 17 | func TestFileContents(t *testing.T) { 18 | m := metrics.NewMock() 19 | as := makeAPIServer(t, "/api/v3/repos/Codertocat/Hello-World/contents/pipelines.yaml", "main", "testdata/content.json") 20 | defer as.Close() 21 | scmClient, err := factory.NewClient("github", as.URL, "", factory.Client(as.Client())) 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | client := New(scmClient, m) 26 | 27 | body, err := client.FileContents(context.TODO(), "Codertocat/Hello-World", "pipelines.yaml", "main") 28 | if err != nil { 29 | t.Fatal(err) 30 | } 31 | want := []byte("testing service\n") 32 | if diff := cmp.Diff(want, body); diff != "" { 33 | t.Fatalf("got a different body back: %s\n", diff) 34 | } 35 | if m.APICalls != 1 { 36 | t.Fatalf("metrics count of API calls, got %d, want 1", m.APICalls) 37 | } 38 | } 39 | 40 | func TestFileContentsWithNotFoundResponse(t *testing.T) { 41 | m := metrics.NewMock() 42 | as := makeAPIServer(t, "/api/v3/repos/Codertocat/Hello-World/contents/pipelines.yaml", "main", "") 43 | defer as.Close() 44 | scmClient, err := factory.NewClient("github", as.URL, "", factory.Client(as.Client())) 45 | if err != nil { 46 | t.Fatal(err) 47 | } 48 | client := New(scmClient, m) 49 | 50 | _, err = client.FileContents(context.TODO(), "Codertocat/Hello-World", "pipelines.yaml", "main") 51 | if !IsNotFound(err) { 52 | t.Fatalf("failed with %#v", err) 53 | } 54 | if m.FailedAPICalls != 1 { 55 | t.Fatalf("metrics count of failed API calls, got %d, want 1", m.FailedAPICalls) 56 | } 57 | } 58 | 59 | func TestFileContentsUnableToConnect(t *testing.T) { 60 | m := metrics.NewMock() 61 | scmClient, err := factory.NewClient("github", "https://localhost:2000", "") 62 | if err != nil { 63 | t.Fatal(err) 64 | } 65 | client := New(scmClient, m) 66 | 67 | _, err = client.FileContents(context.TODO(), "Codertocat/Hello-World", "pipelines.yaml", "main") 68 | if !test.MatchError(t, "connection refused", err) { 69 | t.Fatal(err) 70 | } 71 | if m.FailedAPICalls != 1 { 72 | t.Fatalf("metrics count of failed API calls, got %d, want 1", m.FailedAPICalls) 73 | } 74 | } 75 | 76 | func makeAPIServer(t *testing.T, urlPath, ref, fixture string) *httptest.Server { 77 | return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 78 | t.Helper() 79 | if r.URL.Path != urlPath { 80 | http.NotFound(w, r) 81 | t.Fatalf("request path got %s, want %s", r.URL.Path, urlPath) 82 | } 83 | if ref != "" { 84 | if queryRef := r.URL.Query().Get("ref"); queryRef != ref { 85 | t.Fatalf("failed to match ref, got %s, want %s", queryRef, ref) 86 | } 87 | } 88 | if fixture == "" { 89 | http.NotFound(w, r) 90 | return 91 | } 92 | b, err := ioutil.ReadFile(fixture) 93 | if err != nil { 94 | t.Fatalf("failed to read %s: %s", fixture, err) 95 | } 96 | _, err = w.Write(b) 97 | if err != nil { 98 | t.Fatalf("failed to write: %s", err) 99 | } 100 | })) 101 | } 102 | -------------------------------------------------------------------------------- /pkg/git/errors.go: -------------------------------------------------------------------------------- 1 | package git 2 | 3 | import "net/http" 4 | 5 | // IsNotFound returns true if the error represents a NotFound response from an 6 | // upstream service. 7 | func IsNotFound(err error) bool { 8 | e, ok := err.(SCMError) 9 | return ok && e.Status == http.StatusNotFound 10 | } 11 | 12 | type SCMError struct { 13 | msg string 14 | Status int 15 | } 16 | 17 | func (s SCMError) Error() string { 18 | return s.msg 19 | } 20 | -------------------------------------------------------------------------------- /pkg/git/interfaces.go: -------------------------------------------------------------------------------- 1 | package git 2 | 3 | import ( 4 | "context" 5 | ) 6 | 7 | // ClientFactory is an interface for creating SCM clients based on the URL 8 | // to be fetched. 9 | type ClientFactory interface { 10 | // Create creates a new client, using the provided token for authentication. 11 | Create(url, token string) (SCM, error) 12 | } 13 | 14 | // SCM is a wrapper around go-scm's Client implementation. 15 | type SCM interface { 16 | // FileContents returns the contents of a file within a repo. 17 | FileContents(ctx context.Context, repo, path, ref string) ([]byte, error) 18 | } 19 | -------------------------------------------------------------------------------- /pkg/git/scm_factory.go: -------------------------------------------------------------------------------- 1 | package git 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | 7 | scmfactory "github.com/jenkins-x/go-scm/scm/factory" 8 | "github.com/redhat-developer/gitops-backend/pkg/metrics" 9 | ) 10 | 11 | // SCMClientFactory is an implementation of the GitClientFactory interface that can 12 | // create clients based on go-scm. 13 | type SCMClientFactory struct { 14 | metrics metrics.Interface 15 | } 16 | 17 | // NewClientFactory creates and returns an SCMClientFactory. 18 | func NewClientFactory(m metrics.Interface) *SCMClientFactory { 19 | return &SCMClientFactory{metrics: m} 20 | } 21 | 22 | func (s *SCMClientFactory) Create(url, token string) (SCM, error) { 23 | host, err := hostFromURL(url) 24 | if err != nil { 25 | return nil, err 26 | } 27 | driver, err := scmfactory.DefaultIdentifier.Identify(host) 28 | if err != nil { 29 | return nil, err 30 | } 31 | scmClient, err := scmfactory.NewClient(driver, "", token) 32 | if err != nil { 33 | return nil, fmt.Errorf("failed to create a git driver: %w", err) 34 | } 35 | return New(scmClient, s.metrics), nil 36 | } 37 | 38 | func hostFromURL(s string) (string, error) { 39 | parsed, err := url.Parse(s) 40 | if err != nil { 41 | return "", fmt.Errorf("failed to parse URL %q: %w", s, err) 42 | } 43 | return parsed.Host, nil 44 | } 45 | -------------------------------------------------------------------------------- /pkg/git/scm_factory_test.go: -------------------------------------------------------------------------------- 1 | package git 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/jenkins-x/go-scm/scm" 7 | "github.com/redhat-developer/gitops-backend/pkg/metrics" 8 | "github.com/redhat-developer/gitops-backend/test" 9 | ) 10 | 11 | var _ ClientFactory = (*SCMClientFactory)(nil) 12 | 13 | func TestSCMFactory(t *testing.T) { 14 | // TODO non-standard GitHub and GitLab hosts! 15 | // Probably need to return the serverURL part for the scm factory too. 16 | urlTests := []struct { 17 | gitURL string 18 | want scm.Driver 19 | wantErr string 20 | }{ 21 | {"https://github.com/myorg/myrepo.git", scm.DriverGithub, ""}, 22 | {"https://gitlab.com/myorg/myrepo/myother.git", scm.DriverGitlab, ""}, 23 | {"https://scm.example.com/myorg/myother.git", scm.DriverUnknown, "unable to identify driver"}, 24 | } 25 | factory := NewClientFactory(metrics.NewMock()) 26 | for _, tt := range urlTests { 27 | t.Run(tt.gitURL, func(rt *testing.T) { 28 | client, err := factory.Create(tt.gitURL, "test-token") 29 | if !test.MatchError(rt, tt.wantErr, err) { 30 | rt.Errorf("error failed to match, got %#v, want %s", err, tt.wantErr) 31 | } 32 | if tt.want == scm.DriverUnknown { 33 | return 34 | } 35 | gc, ok := client.(*SCMClient) 36 | if !ok { 37 | rt.Errorf("returned client is not an SCMClient: %T", gc) 38 | } 39 | if gc.Client.Driver != tt.want { 40 | rt.Errorf("got %s, want %s", gc.Client.Driver, tt.want) 41 | } 42 | }) 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /pkg/git/testdata/commit_status.json: -------------------------------------------------------------------------------- 1 | { 2 | "url": "https://api.github.com/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", 3 | "avatar_url": "https://github.com/images/error/hubot_happy.gif", 4 | "id": 1, 5 | "node_id": "MDY6U3RhdHVzMQ==", 6 | "state": "success", 7 | "description": "Build has completed successfully", 8 | "target_url": "https://ci.example.com/1000/output", 9 | "context": "continuous-integration/jenkins", 10 | "created_at": "2012-07-20T01:19:13Z", 11 | "updated_at": "2012-07-20T01:19:13Z", 12 | "creator": { 13 | "login": "octocat", 14 | "id": 1, 15 | "node_id": "MDQ6VXNlcjE=", 16 | "avatar_url": "https://github.com/images/error/octocat_happy.gif", 17 | "gravatar_id": "", 18 | "url": "https://api.github.com/users/octocat", 19 | "html_url": "https://github.com/octocat", 20 | "followers_url": "https://api.github.com/users/octocat/followers", 21 | "following_url": "https://api.github.com/users/octocat/following{/other_user}", 22 | "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", 23 | "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", 24 | "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", 25 | "organizations_url": "https://api.github.com/users/octocat/orgs", 26 | "repos_url": "https://api.github.com/users/octocat/repos", 27 | "events_url": "https://api.github.com/users/octocat/events{/privacy}", 28 | "received_events_url": "https://api.github.com/users/octocat/received_events", 29 | "type": "User", 30 | "site_admin": false 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /pkg/git/testdata/content.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": ".tekton_ci.yml", 3 | "path": ".tekton_ci.yml", 4 | "sha": "980a0d5f19a64b4b30a87d4206aade58726b60e3", 5 | "size": 13, 6 | "url": "https://api.github.com/repos/octocat/Hello-World/contents/README?ref=7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", 7 | "html_url": "https://github.com/octocat/Hello-World/blob/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d/README", 8 | "git_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/980a0d5f19a64b4b30a87d4206aade58726b60e3", 9 | "download_url": "https://raw.githubusercontent.com/octocat/Hello-World/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d/README", 10 | "type": "file", 11 | "content": "dGVzdGluZyBzZXJ2aWNlCg==", 12 | "encoding": "base64", 13 | "_links": { 14 | "self": "https://api.github.com/repos/octocat/Hello-World/contents/README?ref=7fd1a60b01f91b314f59955a4e4d4e80d8edf11d", 15 | "git": "https://api.github.com/repos/octocat/Hello-World/git/blobs/980a0d5f19a64b4b30a87d4206aade58726b60e3", 16 | "html": "https://github.com/octocat/Hello-World/blob/7fd1a60b01f91b314f59955a4e4d4e80d8edf11d/README" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /pkg/git/testdata/drivers.yaml: -------------------------------------------------------------------------------- 1 | gh.example.com: github 2 | gl.example.com: gitlab 3 | -------------------------------------------------------------------------------- /pkg/git/testdata/push_hook.json: -------------------------------------------------------------------------------- 1 | { 2 | "ref": "refs/tags/simple-tag", 3 | "before": "6113728f27ae82c7b1a177c8d03f9e96e0adf246", 4 | "after": "0000000000000000000000000000000000000000", 5 | "created": false, 6 | "deleted": true, 7 | "forced": false, 8 | "base_ref": null, 9 | "compare": "https://github.com/Codertocat/Hello-World/compare/6113728f27ae...000000000000", 10 | "commits": [ 11 | 12 | ], 13 | "head_commit": null, 14 | "repository": { 15 | "id": 186853002, 16 | "node_id": "MDEwOlJlcG9zaXRvcnkxODY4NTMwMDI=", 17 | "name": "Hello-World", 18 | "full_name": "Codertocat/Hello-World", 19 | "private": false, 20 | "owner": { 21 | "name": "Codertocat", 22 | "email": "21031067+Codertocat@users.noreply.github.com", 23 | "login": "Codertocat", 24 | "id": 21031067, 25 | "node_id": "MDQ6VXNlcjIxMDMxMDY3", 26 | "avatar_url": "https://avatars1.githubusercontent.com/u/21031067?v=4", 27 | "gravatar_id": "", 28 | "url": "https://api.github.com/users/Codertocat", 29 | "html_url": "https://github.com/Codertocat", 30 | "followers_url": "https://api.github.com/users/Codertocat/followers", 31 | "following_url": "https://api.github.com/users/Codertocat/following{/other_user}", 32 | "gists_url": "https://api.github.com/users/Codertocat/gists{/gist_id}", 33 | "starred_url": "https://api.github.com/users/Codertocat/starred{/owner}{/repo}", 34 | "subscriptions_url": "https://api.github.com/users/Codertocat/subscriptions", 35 | "organizations_url": "https://api.github.com/users/Codertocat/orgs", 36 | "repos_url": "https://api.github.com/users/Codertocat/repos", 37 | "events_url": "https://api.github.com/users/Codertocat/events{/privacy}", 38 | "received_events_url": "https://api.github.com/users/Codertocat/received_events", 39 | "type": "User", 40 | "site_admin": false 41 | }, 42 | "html_url": "https://github.com/Codertocat/Hello-World", 43 | "description": null, 44 | "fork": false, 45 | "url": "https://github.com/Codertocat/Hello-World", 46 | "forks_url": "https://api.github.com/repos/Codertocat/Hello-World/forks", 47 | "keys_url": "https://api.github.com/repos/Codertocat/Hello-World/keys{/key_id}", 48 | "collaborators_url": "https://api.github.com/repos/Codertocat/Hello-World/collaborators{/collaborator}", 49 | "teams_url": "https://api.github.com/repos/Codertocat/Hello-World/teams", 50 | "hooks_url": "https://api.github.com/repos/Codertocat/Hello-World/hooks", 51 | "issue_events_url": "https://api.github.com/repos/Codertocat/Hello-World/issues/events{/number}", 52 | "events_url": "https://api.github.com/repos/Codertocat/Hello-World/events", 53 | "assignees_url": "https://api.github.com/repos/Codertocat/Hello-World/assignees{/user}", 54 | "branches_url": "https://api.github.com/repos/Codertocat/Hello-World/branches{/branch}", 55 | "tags_url": "https://api.github.com/repos/Codertocat/Hello-World/tags", 56 | "blobs_url": "https://api.github.com/repos/Codertocat/Hello-World/git/blobs{/sha}", 57 | "git_tags_url": "https://api.github.com/repos/Codertocat/Hello-World/git/tags{/sha}", 58 | "git_refs_url": "https://api.github.com/repos/Codertocat/Hello-World/git/refs{/sha}", 59 | "trees_url": "https://api.github.com/repos/Codertocat/Hello-World/git/trees{/sha}", 60 | "statuses_url": "https://api.github.com/repos/Codertocat/Hello-World/statuses/{sha}", 61 | "languages_url": "https://api.github.com/repos/Codertocat/Hello-World/languages", 62 | "stargazers_url": "https://api.github.com/repos/Codertocat/Hello-World/stargazers", 63 | "contributors_url": "https://api.github.com/repos/Codertocat/Hello-World/contributors", 64 | "subscribers_url": "https://api.github.com/repos/Codertocat/Hello-World/subscribers", 65 | "subscription_url": "https://api.github.com/repos/Codertocat/Hello-World/subscription", 66 | "commits_url": "https://api.github.com/repos/Codertocat/Hello-World/commits{/sha}", 67 | "git_commits_url": "https://api.github.com/repos/Codertocat/Hello-World/git/commits{/sha}", 68 | "comments_url": "https://api.github.com/repos/Codertocat/Hello-World/comments{/number}", 69 | "issue_comment_url": "https://api.github.com/repos/Codertocat/Hello-World/issues/comments{/number}", 70 | "contents_url": "https://api.github.com/repos/Codertocat/Hello-World/contents/{+path}", 71 | "compare_url": "https://api.github.com/repos/Codertocat/Hello-World/compare/{base}...{head}", 72 | "merges_url": "https://api.github.com/repos/Codertocat/Hello-World/merges", 73 | "archive_url": "https://api.github.com/repos/Codertocat/Hello-World/{archive_format}{/ref}", 74 | "downloads_url": "https://api.github.com/repos/Codertocat/Hello-World/downloads", 75 | "issues_url": "https://api.github.com/repos/Codertocat/Hello-World/issues{/number}", 76 | "pulls_url": "https://api.github.com/repos/Codertocat/Hello-World/pulls{/number}", 77 | "milestones_url": "https://api.github.com/repos/Codertocat/Hello-World/milestones{/number}", 78 | "notifications_url": "https://api.github.com/repos/Codertocat/Hello-World/notifications{?since,all,participating}", 79 | "labels_url": "https://api.github.com/repos/Codertocat/Hello-World/labels{/name}", 80 | "releases_url": "https://api.github.com/repos/Codertocat/Hello-World/releases{/id}", 81 | "deployments_url": "https://api.github.com/repos/Codertocat/Hello-World/deployments", 82 | "created_at": 1557933565, 83 | "updated_at": "2019-05-15T15:20:41Z", 84 | "pushed_at": 1557933657, 85 | "git_url": "git://github.com/Codertocat/Hello-World.git", 86 | "ssh_url": "git@github.com:Codertocat/Hello-World.git", 87 | "clone_url": "https://github.com/Codertocat/Hello-World.git", 88 | "svn_url": "https://github.com/Codertocat/Hello-World", 89 | "homepage": null, 90 | "size": 0, 91 | "stargazers_count": 0, 92 | "watchers_count": 0, 93 | "language": "Ruby", 94 | "has_issues": true, 95 | "has_projects": true, 96 | "has_downloads": true, 97 | "has_wiki": true, 98 | "has_pages": true, 99 | "forks_count": 1, 100 | "mirror_url": null, 101 | "archived": false, 102 | "disabled": false, 103 | "open_issues_count": 2, 104 | "license": null, 105 | "forks": 1, 106 | "open_issues": 2, 107 | "watchers": 0, 108 | "default_branch": "main", 109 | "stargazers": 0, 110 | "main_branch": "main" 111 | }, 112 | "pusher": { 113 | "name": "Codertocat", 114 | "email": "21031067+Codertocat@users.noreply.github.com" 115 | }, 116 | "sender": { 117 | "login": "Codertocat", 118 | "id": 21031067, 119 | "node_id": "MDQ6VXNlcjIxMDMxMDY3", 120 | "avatar_url": "https://avatars1.githubusercontent.com/u/21031067?v=4", 121 | "gravatar_id": "", 122 | "url": "https://api.github.com/users/Codertocat", 123 | "html_url": "https://github.com/Codertocat", 124 | "followers_url": "https://api.github.com/users/Codertocat/followers", 125 | "following_url": "https://api.github.com/users/Codertocat/following{/other_user}", 126 | "gists_url": "https://api.github.com/users/Codertocat/gists{/gist_id}", 127 | "starred_url": "https://api.github.com/users/Codertocat/starred{/owner}{/repo}", 128 | "subscriptions_url": "https://api.github.com/users/Codertocat/subscriptions", 129 | "organizations_url": "https://api.github.com/users/Codertocat/orgs", 130 | "repos_url": "https://api.github.com/users/Codertocat/repos", 131 | "events_url": "https://api.github.com/users/Codertocat/events{/privacy}", 132 | "received_events_url": "https://api.github.com/users/Codertocat/received_events", 133 | "type": "User", 134 | "site_admin": false 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /pkg/gitfs/doc.go: -------------------------------------------------------------------------------- 1 | package gitfs 2 | 3 | // This is an implementation of the Kustomize fs.FileSystem implementation, 4 | // which uses go-git to fetch the files. 5 | // 6 | // It is not a complete implementation of fs.FileSystem, only the necessary 7 | // methods to allow Kustomize to build manifests. 8 | // 9 | // This is a lesson in the Interface Seggregation principal... 10 | -------------------------------------------------------------------------------- /pkg/gitfs/gitfs.go: -------------------------------------------------------------------------------- 1 | package gitfs 2 | 3 | import ( 4 | "fmt" 5 | "path" 6 | "strings" 7 | 8 | "github.com/go-git/go-git/v5" 9 | "github.com/go-git/go-git/v5/plumbing/object" 10 | "github.com/go-git/go-git/v5/plumbing/storer" 11 | "github.com/go-git/go-git/v5/storage/memory" 12 | "sigs.k8s.io/kustomize/pkg/fs" 13 | ) 14 | 15 | // gitFS is an internal implementation of the Kustomize 16 | // filesystem abstraction. 17 | type gitFS struct { 18 | tree *object.Tree 19 | } 20 | 21 | // New creates and returns a go-git storage adapter. 22 | func New(t *object.Tree) fs.FileSystem { 23 | return &gitFS{tree: t} 24 | } 25 | 26 | // NewInMemoryFromOptions clones a Git repository into memory. 27 | func NewInMemoryFromOptions(opts *git.CloneOptions) (fs.FileSystem, error) { 28 | clone, err := git.Clone(memory.NewStorage(), nil, opts) 29 | if err != nil { 30 | return nil, err 31 | } 32 | ref, err := clone.Head() 33 | if err != nil { 34 | return nil, err 35 | } 36 | commit, err := clone.CommitObject(ref.Hash()) 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | tree, err := commit.Tree() 42 | if err != nil { 43 | return nil, err 44 | } 45 | return New(tree), nil 46 | } 47 | 48 | // IsDir implements fs.FileSystem. 49 | func (g gitFS) IsDir(name string) bool { 50 | // If it exists as a file, it's not a directory. 51 | _, err := g.tree.File(name) 52 | if err == nil { 53 | return false 54 | } 55 | // Git doesn't store directories. 56 | // 57 | // If we can find a file with a prefix of the name we're looking for, then 58 | // the name is a directory. 59 | // 60 | // TODO: make this a bit more efficent, cache found dirs? 61 | isDir := false 62 | err = g.tree.Files().ForEach(func(f *object.File) error { 63 | if strings.HasPrefix(f.Name, name) { 64 | isDir = true 65 | return storer.ErrStop 66 | } 67 | return nil 68 | }) 69 | // TODO: not a lot of choice here, there's no scope for returning an error. 70 | if err != nil { 71 | panic(err) 72 | } 73 | return isDir 74 | } 75 | 76 | // CleanedAbs implements fs.FileSystem. 77 | func (g gitFS) CleanedAbs(p string) (fs.ConfirmedDir, string, error) { 78 | if g.IsDir(p) { 79 | return fs.ConfirmedDir(p), "", nil 80 | } 81 | d := path.Dir(p) 82 | f := path.Base(p) 83 | return fs.ConfirmedDir(d), f, nil 84 | } 85 | 86 | // ReadFile implements fs.FileSystem. 87 | func (g gitFS) ReadFile(name string) ([]byte, error) { 88 | f, err := g.tree.File(name) 89 | if err != nil { 90 | return nil, err 91 | } 92 | b, err := f.Contents() 93 | if err != nil { 94 | return nil, err 95 | } 96 | return []byte(b), nil 97 | } 98 | 99 | // Create implements fs.FileSystem. 100 | func (g gitFS) Create(name string) (fs.File, error) { 101 | return nil, errNotSupported("Create") 102 | } 103 | 104 | // MkDir implements fs.FileSystem. 105 | func (g gitFS) Mkdir(name string) error { 106 | return errNotSupported("MkDir") 107 | } 108 | 109 | // MkDirAll implements fs.FileSystem. 110 | func (g gitFS) MkdirAll(name string) error { 111 | return errNotSupported("MkdirAll") 112 | } 113 | 114 | // RemoveAll implements fs.FileSystem. 115 | func (g gitFS) RemoveAll(name string) error { 116 | return errNotSupported("RemoveAll") 117 | } 118 | 119 | // Open implements fs.FileSystem. 120 | func (g gitFS) Open(name string) (fs.File, error) { 121 | return nil, errNotSupported("Open") 122 | } 123 | 124 | // Exists implements fs.FileSystem. 125 | func (g gitFS) Exists(name string) bool { 126 | return false 127 | } 128 | 129 | // Glob implements fs.FileSystem. 130 | func (g gitFS) Glob(pattern string) ([]string, error) { 131 | return nil, errNotSupported("Glob") 132 | } 133 | 134 | // WriteFile implements fs.FileSystem. 135 | func (g gitFS) WriteFile(name string, data []byte) error { 136 | return errNotSupported("WriteFile") 137 | } 138 | 139 | func errNotSupported(s string) error { 140 | return notSupported(s) 141 | } 142 | 143 | type notSupported string 144 | 145 | func (f notSupported) Error() string { 146 | return fmt.Sprintf("feature %#v not supported", string(f)) 147 | } 148 | -------------------------------------------------------------------------------- /pkg/gitfs/gitfs_test.go: -------------------------------------------------------------------------------- 1 | package gitfs 2 | 3 | import ( 4 | "io/ioutil" 5 | "testing" 6 | 7 | "github.com/google/go-cmp/cmp" 8 | "sigs.k8s.io/kustomize/pkg/fs" 9 | 10 | "github.com/redhat-developer/gitops-backend/test" 11 | ) 12 | 13 | var _ fs.FileSystem = gitFS{} 14 | 15 | func TestUnsupportedFeatures(t *testing.T) { 16 | gfs := gitFS{} 17 | 18 | _, err := gfs.Create("testing/file") 19 | assertIsUnsupported(t, err) 20 | assertIsUnsupported(t, gfs.Mkdir("testing")) 21 | assertIsUnsupported(t, gfs.MkdirAll("testing/testing")) 22 | assertIsUnsupported(t, gfs.RemoveAll("testing/testing")) 23 | _, err = gfs.Open("testing/file") 24 | assertIsUnsupported(t, err) 25 | _, err = gfs.Glob("test*") 26 | assertIsUnsupported(t, err) 27 | err = gfs.WriteFile("testing", []byte("testing")) 28 | assertIsUnsupported(t, err) 29 | } 30 | 31 | func TestReadFile(t *testing.T) { 32 | gfs := makeClonedGFS(t) 33 | 34 | remote, err := gfs.ReadFile("README.md") 35 | assertNoError(t, err) 36 | 37 | local, err := ioutil.ReadFile("../../README.md") 38 | assertNoError(t, err) 39 | 40 | if diff := cmp.Diff(local, remote); diff != "" { 41 | t.Fatalf("failed to fetch correct file:\n%s", diff) 42 | } 43 | } 44 | 45 | func TestIsDir(t *testing.T) { 46 | gfs := makeClonedGFS(t) 47 | 48 | if gfs.IsDir("README.md") { 49 | t.Fatal("IsDir() returned true for a file") 50 | } 51 | 52 | if !gfs.IsDir("pkg") { 53 | t.Fatal("IsDir() returned false for a directory") 54 | } 55 | } 56 | 57 | func TestCleanedAbs(t *testing.T) { 58 | gfs := makeClonedGFS(t) 59 | 60 | dir, _, err := gfs.CleanedAbs("pkg/gitfs/gitfs_test.go") 61 | assertNoError(t, err) 62 | 63 | if dir != fs.ConfirmedDir("pkg/gitfs") { 64 | t.Fatalf("got %#v", dir) 65 | } 66 | } 67 | 68 | func TestErrNotSupported(t *testing.T) { 69 | err := errNotSupported("Created") 70 | if s := err.Error(); s != "feature \"Created\" not supported" { 71 | t.Fatalf("got %s, want %v", s, "testing") 72 | } 73 | } 74 | 75 | func assertIsUnsupported(t *testing.T, err error) { 76 | t.Helper() 77 | if _, ok := err.(notSupported); !ok { 78 | t.Fatalf("got %#v, want ErrNotSupported", err) 79 | } 80 | } 81 | 82 | func assertNoError(t *testing.T, err error) { 83 | t.Helper() 84 | if err != nil { 85 | t.Fatal(err) 86 | } 87 | } 88 | 89 | func TestNewInMemoryFromOptions(t *testing.T) { 90 | gfs := makeClonedGFS(t) 91 | 92 | got, err := gfs.ReadFile("LICENSE") 93 | if err != nil { 94 | t.Fatal(err) 95 | } 96 | want, err := ioutil.ReadFile("../../LICENSE") 97 | if err != nil { 98 | t.Fatal(err) 99 | } 100 | 101 | if diff := cmp.Diff(want, got); diff != "" { 102 | t.Fatalf("failed to read file:\n%s", diff) 103 | } 104 | } 105 | 106 | func makeClonedGFS(t *testing.T) fs.FileSystem { 107 | t.Helper() 108 | gfs, err := NewInMemoryFromOptions( 109 | test.MakeCloneOptions()) 110 | assertNoError(t, err) 111 | return gfs 112 | } 113 | -------------------------------------------------------------------------------- /pkg/health/health.go: -------------------------------------------------------------------------------- 1 | package health 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | var GitRevision = "unknown" 10 | 11 | // Handler returns the value of GitRevision in simple struct. 12 | func Handler(w http.ResponseWriter, r *http.Request) { 13 | w.Header().Set("Content-Type", "application/json") 14 | if err := json.NewEncoder(w).Encode(struct { 15 | Version string `json:"version"` 16 | }{Version: GitRevision}); err != nil { 17 | log.Printf("failed to encode Health response: %s", err) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /pkg/health/health_test.go: -------------------------------------------------------------------------------- 1 | package health 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | "net/http/httptest" 8 | "testing" 9 | ) 10 | 11 | func TestGetPipelines(t *testing.T) { 12 | ts := makeServer(t) 13 | 14 | client := ts.Client() 15 | res, err := client.Get(ts.URL) 16 | 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | defer res.Body.Close() 21 | body, err := ioutil.ReadAll(res.Body) 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | 26 | want := fmt.Sprintf("{\"version\":\"%s\"}\n", GitRevision) 27 | if string(body) != want { 28 | t.Fatalf("failed to get the expected version, got %#v, want %#v", string(body), want) 29 | } 30 | } 31 | 32 | func makeServer(t *testing.T) *httptest.Server { 33 | ts := httptest.NewTLSServer(http.HandlerFunc(Handler)) 34 | t.Cleanup(ts.Close) 35 | return ts 36 | } 37 | -------------------------------------------------------------------------------- /pkg/httpapi/api.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "crypto/tls" 7 | "encoding/json" 8 | "fmt" 9 | "io/ioutil" 10 | "log" 11 | "net/http" 12 | "net/url" 13 | "strings" 14 | 15 | argoV1aplha1 "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1" 16 | "github.com/julienschmidt/httprouter" 17 | corev1 "k8s.io/api/core/v1" 18 | "k8s.io/apimachinery/pkg/types" 19 | ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" 20 | "sigs.k8s.io/yaml" 21 | 22 | "github.com/redhat-developer/gitops-backend/pkg/git" 23 | "github.com/redhat-developer/gitops-backend/pkg/httpapi/secrets" 24 | "github.com/redhat-developer/gitops-backend/pkg/parser" 25 | ) 26 | 27 | // DefaultSecretRef is the name looked up if none is provided in the URL. 28 | var DefaultSecretRef = types.NamespacedName{ 29 | Name: "pipelines-app-gitops", 30 | Namespace: "pipelines-app-delivery", 31 | } 32 | 33 | const ( 34 | defaultRef = "HEAD" 35 | defaultArgoCDInstance = "openshift-gitops" 36 | defaultArgocdNamespace = "openshift-gitops" 37 | kindService = "Service" 38 | kindDeployment = "Deployment" 39 | kindSecret = "Secret" 40 | kindSealedSecret = "SealedSecret" 41 | kindRoute = "Route" 42 | kindRoleBinding = "RoleBinding" 43 | kindClusterRole = "ClusterRole" 44 | kindClusterRoleBinding = "ClusterRoleBinding" 45 | ) 46 | 47 | var baseURL = fmt.Sprintf("https://%s-server.%s.svc.cluster.local", defaultArgoCDInstance, defaultArgocdNamespace) 48 | 49 | // APIRouter is an HTTP API for accessing app configurations. 50 | type APIRouter struct { 51 | *httprouter.Router 52 | gitClientFactory git.ClientFactory 53 | secretGetter secrets.SecretGetter 54 | secretRef types.NamespacedName 55 | resourceParser parser.ResourceParser 56 | k8sClient ctrlclient.Client 57 | } 58 | 59 | // NewRouter creates and returns a new APIRouter. 60 | func NewRouter(c git.ClientFactory, s secrets.SecretGetter, kc ctrlclient.Client) *APIRouter { 61 | api := &APIRouter{ 62 | Router: httprouter.New(), 63 | gitClientFactory: c, 64 | secretGetter: s, 65 | secretRef: DefaultSecretRef, 66 | resourceParser: parser.ParseFromGit, 67 | k8sClient: kc, 68 | } 69 | api.HandlerFunc(http.MethodGet, "/pipelines", api.GetPipelines) 70 | api.HandlerFunc(http.MethodGet, "/applications", api.ListApplications) 71 | api.HandlerFunc(http.MethodGet, "/environments/:env/application/:app", api.GetApplication) 72 | api.HandlerFunc(http.MethodGet, "/environment/:env/application/:app", api.GetApplicationDetails) 73 | api.HandlerFunc(http.MethodGet, "/history/environment/:env/application/:app", api.GetApplicationHistory) 74 | return api 75 | } 76 | 77 | type RevisionMeta struct { 78 | Author string `json:"author"` 79 | Message string `json:"message"` 80 | Revision string `json:"revision"` 81 | } 82 | 83 | // GetPipelines fetches and returns the pipeline body. 84 | func (a *APIRouter) GetPipelines(w http.ResponseWriter, r *http.Request) { 85 | urlToFetch := r.URL.Query().Get("url") 86 | if urlToFetch == "" { 87 | log.Println("ERROR: could not get url from request") 88 | http.Error(w, "missing parameter 'url'", http.StatusBadRequest) 89 | return 90 | } 91 | 92 | // TODO: replace this with logr or sugar. 93 | log.Printf("urlToFetch = %#v\n", urlToFetch) 94 | repo, parsedRepo, err := parseURL(urlToFetch) 95 | if err != nil { 96 | log.Printf("ERROR: failed to parse the URL: %s", err) 97 | http.Error(w, err.Error(), http.StatusBadRequest) 98 | return 99 | } 100 | 101 | token, err := a.getAuthToken(r.Context(), r) 102 | if err != nil { 103 | log.Printf("ERROR: failed to get an authentication token: %s", err) 104 | http.Error(w, "unable to authenticate request", http.StatusBadRequest) 105 | return 106 | } 107 | client, err := a.getAuthenticatedGitClient(urlToFetch, token) 108 | if err != nil { 109 | log.Printf("ERROR: failed to get an authenticated client: %s", err) 110 | http.Error(w, "unable to authenticate request", http.StatusBadRequest) 111 | return 112 | } 113 | 114 | // TODO: don't send back the error directly. 115 | // 116 | // Add a "not found" error that can be returned, otherwise it's a 117 | // StatusInternalServerError. 118 | log.Println("got an authenticated client") 119 | body, err := client.FileContents(r.Context(), repo, "pipelines.yaml", refFromQuery(parsedRepo.Query())) 120 | if err != nil { 121 | log.Printf("ERROR: failed to get file contents for repo %#v: %s", repo, err) 122 | http.Error(w, err.Error(), http.StatusBadRequest) 123 | return 124 | } 125 | pipelines := &config{} 126 | err = yaml.Unmarshal(body, &pipelines) 127 | if err != nil { 128 | log.Printf("ERROR: failed to unmarshal body: %s", err) 129 | http.Error(w, fmt.Sprintf("failed to unmarshal pipelines.yaml: %s", err.Error()), http.StatusBadRequest) 130 | return 131 | } 132 | marshalResponse(w, pipelinesToAppsResponse(pipelines)) 133 | } 134 | 135 | // GetApplication fetches an application within a specific environment. 136 | // 137 | // Expects the 138 | func (a *APIRouter) GetApplication(w http.ResponseWriter, r *http.Request) { 139 | urlToFetch := r.URL.Query().Get("url") 140 | if urlToFetch == "" { 141 | log.Println("ERROR: could not get url from request") 142 | http.Error(w, "missing parameter 'url'", http.StatusBadRequest) 143 | return 144 | } 145 | 146 | // TODO: replace this with logr or sugar. 147 | log.Printf("urlToFetch = %#v\n", urlToFetch) 148 | repo, parsedRepo, err := parseURL(urlToFetch) 149 | if err != nil { 150 | log.Printf("ERROR: failed to parse the URL: %s", err) 151 | http.Error(w, err.Error(), http.StatusBadRequest) 152 | return 153 | } 154 | 155 | token, err := a.getAuthToken(r.Context(), r) 156 | if err != nil { 157 | log.Printf("ERROR: failed to get an authentication token: %s", err) 158 | http.Error(w, "unable to authenticate request", http.StatusBadRequest) 159 | return 160 | } 161 | client, err := a.getAuthenticatedGitClient(urlToFetch, token) 162 | if err != nil { 163 | log.Printf("ERROR: failed to get an authenticated client: %s", err) 164 | http.Error(w, "unable to authenticate request", http.StatusBadRequest) 165 | return 166 | } 167 | 168 | // TODO: don't send back the error directly. 169 | // 170 | // Add a "not found" error that can be returned, otherwise it's a 171 | // StatusInternalServerError. 172 | body, err := client.FileContents(r.Context(), repo, "pipelines.yaml", refFromQuery(parsedRepo.Query())) 173 | if err != nil { 174 | log.Printf("ERROR: failed to get file contents for repo %#v: %s", repo, err) 175 | http.Error(w, err.Error(), http.StatusBadRequest) 176 | return 177 | } 178 | pipelines := &config{} 179 | err = yaml.Unmarshal(body, &pipelines) 180 | if err != nil { 181 | log.Printf("ERROR: failed to unmarshal body: %s", err) 182 | http.Error(w, fmt.Sprintf("failed to unmarshal pipelines.yaml: %s", err.Error()), http.StatusBadRequest) 183 | return 184 | } 185 | params := httprouter.ParamsFromContext(r.Context()) 186 | appEnvironments, err := a.environmentApplication(token, pipelines, params.ByName("env"), params.ByName("app")) 187 | if err != nil { 188 | log.Printf("ERROR: failed to get application data: %s", err) 189 | http.Error(w, "failed to extract data", http.StatusBadRequest) 190 | return 191 | } 192 | marshalResponse(w, appEnvironments) 193 | } 194 | 195 | func (a *APIRouter) ListApplications(w http.ResponseWriter, r *http.Request) { 196 | repoURL := strings.TrimSpace(r.URL.Query().Get("url")) 197 | if repoURL == "" { 198 | http.Error(w, "please provide a valid GitOps repo URL", http.StatusBadRequest) 199 | return 200 | } 201 | 202 | parsedRepoURL, err := url.Parse(repoURL) 203 | if err != nil { 204 | http.Error(w, fmt.Sprintf("failed to parse URL, error: %v", err), http.StatusBadRequest) 205 | return 206 | } 207 | 208 | parsedRepoURL.RawQuery = "" 209 | 210 | appList := &argoV1aplha1.ApplicationList{} 211 | var listOptions []ctrlclient.ListOption 212 | 213 | listOptions = append(listOptions, ctrlclient.InNamespace("")) 214 | 215 | err = a.k8sClient.List(r.Context(), appList, listOptions...) 216 | if err != nil { 217 | log.Printf("ERROR: failed to get application list: %v", err) 218 | http.Error(w, fmt.Sprintf("failed to get list of application, err: %v", err), http.StatusBadRequest) 219 | return 220 | } 221 | 222 | apps := make([]*argoV1aplha1.Application, 0) 223 | for _, app := range appList.Items { 224 | apps = append(apps, app.DeepCopy()) 225 | } 226 | 227 | marshalResponse(w, applicationsToAppsResponse(apps, parsedRepoURL.String())) 228 | } 229 | 230 | func (a *APIRouter) GetApplicationHistory(w http.ResponseWriter, r *http.Request) { 231 | params := httprouter.ParamsFromContext(r.Context()) 232 | envName, appName := params.ByName("env"), params.ByName("app") 233 | app := &argoV1aplha1.Application{} 234 | 235 | repoURL := strings.TrimSpace(r.URL.Query().Get("url")) 236 | if repoURL == "" { 237 | log.Println("ERROR: please provide a valid GitOps repo URL") 238 | http.Error(w, "please provide a valid GitOps repo URL", http.StatusBadRequest) 239 | return 240 | } 241 | 242 | parsedRepoURL, err := url.Parse(repoURL) 243 | if err != nil { 244 | log.Printf("ERROR: failed to parse URL, error: %v", err) 245 | http.Error(w, fmt.Sprintf("failed to parse URL, error: %v", err), http.StatusBadRequest) 246 | return 247 | } 248 | 249 | parsedRepoURL.RawQuery = "" 250 | 251 | appList := &argoV1aplha1.ApplicationList{} 252 | var listOptions []ctrlclient.ListOption 253 | 254 | listOptions = append(listOptions, ctrlclient.InNamespace(""), ctrlclient.MatchingFields{ 255 | "metadata.name": fmt.Sprintf("%s-%s", envName, appName), 256 | }) 257 | 258 | err = a.k8sClient.List(r.Context(), appList, listOptions...) 259 | if err != nil { 260 | log.Printf("ERROR: failed to get application list: %v", err) 261 | http.Error(w, fmt.Sprintf("failed to get list of application, err: %v", err), http.StatusBadRequest) 262 | return 263 | } 264 | // At this point, if there are no apps as generated by KAM, then check if there are any 265 | // apps in general, where the app name is the environment name. Users aren't expected to use both 266 | // KAM generated apps and custom apps in their GitOps repo. 267 | if len(appList.Items) == 0 { 268 | listOptions = nil 269 | listOptions = append(listOptions, ctrlclient.InNamespace(""), ctrlclient.MatchingFields{ 270 | "metadata.name": fmt.Sprintf("%s", envName), 271 | }) 272 | err = a.k8sClient.List(r.Context(), appList, listOptions...) 273 | if err != nil { 274 | log.Printf("ERROR: failed to get application list: %v", err) 275 | http.Error(w, fmt.Sprintf("failed to get list of application, err: %v", err), http.StatusBadRequest) 276 | return 277 | } 278 | } 279 | 280 | for _, a := range appList.Items { 281 | if a.Spec.Source.RepoURL == parsedRepoURL.String() { 282 | app = &a 283 | } 284 | } 285 | 286 | if app == nil { 287 | log.Printf("ERROR: failed to get application %s: %v", appName, err) 288 | http.Error(w, fmt.Sprintf("failed to get the application %s, err: %v", appName, err), http.StatusBadRequest) 289 | return 290 | } 291 | 292 | var deployedTime, revision string 293 | hist := app.Status.History 294 | var historyList = make([]envHistory, 0) 295 | for _, h := range hist { 296 | revision = h.Revision 297 | t := h.DeployedAt 298 | if !t.IsZero() { 299 | deployedTime = t.String() 300 | } 301 | commitInfo, err := a.getCommitInfo(app.Name, revision) 302 | if err != nil { 303 | log.Printf("WARNING: failed to retrieve revision metadata for app %s: %v. The app might be unsynced.", appName, err) 304 | } 305 | hist := envHistory{ 306 | Author: commitInfo["author"], 307 | Message: commitInfo["message"], 308 | Revision: revision, 309 | RepoUrl: h.Source.RepoURL, 310 | Environment: envName, 311 | DeployedAt: deployedTime, 312 | } 313 | historyList = append([]envHistory{hist}, historyList...) 314 | } 315 | marshalResponse(w, historyList) 316 | } 317 | 318 | func (a *APIRouter) GetApplicationDetails(w http.ResponseWriter, r *http.Request) { 319 | params := httprouter.ParamsFromContext(r.Context()) 320 | envName, appName := params.ByName("env"), params.ByName("app") 321 | app := &argoV1aplha1.Application{} 322 | var lastDeployed, revision string 323 | 324 | repoURL := strings.TrimSpace(r.URL.Query().Get("url")) 325 | if repoURL == "" { 326 | log.Println("ERROR: please provide a valid GitOps repo URL") 327 | http.Error(w, "please provide a valid GitOps repo URL", http.StatusBadRequest) 328 | return 329 | } 330 | 331 | parsedRepoURL, err := url.Parse(repoURL) 332 | if err != nil { 333 | log.Printf("ERROR: failed to parse URL, error: %v", err) 334 | http.Error(w, fmt.Sprintf("failed to parse URL, error: %v", err), http.StatusBadRequest) 335 | return 336 | } 337 | 338 | parsedRepoURL.RawQuery = "" 339 | 340 | appList := &argoV1aplha1.ApplicationList{} 341 | var listOptions []ctrlclient.ListOption 342 | 343 | listOptions = append(listOptions, ctrlclient.InNamespace(""), ctrlclient.MatchingFields{ 344 | "metadata.name": fmt.Sprintf("%s-%s", envName, appName), 345 | }) 346 | 347 | err = a.k8sClient.List(r.Context(), appList, listOptions...) 348 | if err != nil { 349 | log.Printf("ERROR: failed to get application list: %v", err) 350 | http.Error(w, fmt.Sprintf("failed to get list of application, err: %v", err), http.StatusBadRequest) 351 | return 352 | } 353 | 354 | // At this point, if there are no apps as generated by KAM, then check if there are any 355 | // apps in general, where the app name is the environment name. Users aren't expected to use both 356 | // KAM generated apps and custom apps in their GitOps repo. 357 | // We should error out if we don't have the environments as applications 358 | if len(appList.Items) == 0 { 359 | listOptions = nil 360 | listOptions = append(listOptions, ctrlclient.InNamespace(""), ctrlclient.MatchingFields{ 361 | "metadata.name": fmt.Sprintf("%s", envName), 362 | }) 363 | err = a.k8sClient.List(r.Context(), appList, listOptions...) 364 | if err != nil { 365 | log.Printf("ERROR: failed to get application list: %v", err) 366 | http.Error(w, fmt.Sprintf("failed to get list of application, err: %v", err), http.StatusBadRequest) 367 | return 368 | } 369 | } 370 | 371 | for _, a := range appList.Items { 372 | if a.Spec.Source.RepoURL == parsedRepoURL.String() { 373 | app = &a 374 | } 375 | } 376 | 377 | if app == nil { 378 | log.Printf("ERROR: failed to get application %s: %v", appName, err) 379 | http.Error(w, fmt.Sprintf("failed to get the application %s, err: %v", appName, err), http.StatusBadRequest) 380 | return 381 | } 382 | 383 | if len(app.Status.History) > 0 { 384 | revision = app.Status.History[len(app.Status.History)-1].Revision 385 | t := app.Status.History[len(app.Status.History)-1].DeployedAt 386 | if !t.IsZero() { 387 | lastDeployed = t.String() 388 | } 389 | } 390 | 391 | commitInfo, err := a.getCommitInfo(app.Name, revision) 392 | if err != nil { 393 | log.Printf("Warning: failed to retrieve revision metadata for app %s: %v. The app might be unsynced", appName, err) 394 | } 395 | 396 | revisionMeta := RevisionMeta{ 397 | Author: strings.Split(commitInfo["author"], " ")[0], 398 | Message: commitInfo["message"], 399 | Revision: revision, 400 | } 401 | var envResources = make(map[string][]envHealthResource) 402 | envResources[kindService] = make([]envHealthResource, 0) 403 | envResources[kindDeployment] = make([]envHealthResource, 0) 404 | envResources[kindSecret] = make([]envHealthResource, 0) 405 | envResources[kindRoute] = make([]envHealthResource, 0) 406 | envResources[kindRoleBinding] = make([]envHealthResource, 0) 407 | envResources[kindClusterRole] = make([]envHealthResource, 0) 408 | envResources[kindClusterRoleBinding] = make([]envHealthResource, 0) 409 | 410 | for _, aResource := range app.Status.Resources { 411 | switch aResource.Kind { 412 | case kindService: 413 | envResources[kindService] = append(envResources[kindService], envHealthResource{ 414 | Name: aResource.Name, 415 | Health: string(aResource.Health.Status), 416 | Status: string(aResource.Status), 417 | }) 418 | case kindDeployment: 419 | envResources[kindDeployment] = append(envResources[kindDeployment], envHealthResource{ 420 | Name: aResource.Name, 421 | Health: string(aResource.Health.Status), 422 | Status: string(aResource.Status), 423 | }) 424 | case kindSecret, kindSealedSecret: 425 | secretHealth := "" 426 | if aResource.Health != nil { 427 | secretHealth = string(aResource.Health.Status) 428 | } 429 | envResources[kindSecret] = append(envResources[kindSecret], envHealthResource{ 430 | Name: aResource.Name, 431 | Health: secretHealth, 432 | Status: string(aResource.Status), 433 | }) 434 | case kindRoute: 435 | envResources[kindRoute] = append(envResources[kindRoute], envHealthResource{ 436 | Name: aResource.Name, 437 | Status: string(aResource.Status), 438 | }) 439 | case kindRoleBinding: 440 | envResources[kindRoleBinding] = append(envResources[kindRoleBinding], envHealthResource{ 441 | Name: aResource.Name, 442 | Status: string(aResource.Status), 443 | }) 444 | case kindClusterRole: 445 | envResources[kindClusterRole] = append(envResources[kindClusterRole], envHealthResource{ 446 | Name: aResource.Name, 447 | Status: string(aResource.Status), 448 | }) 449 | case kindClusterRoleBinding: 450 | envResources[kindClusterRoleBinding] = append(envResources[kindClusterRoleBinding], envHealthResource{ 451 | Name: aResource.Name, 452 | Status: string(aResource.Status), 453 | }) 454 | } 455 | } 456 | appEnv := map[string]interface{}{ 457 | "environment": app.Spec.Destination.Namespace, 458 | "cluster": app.Spec.Destination.Server, 459 | "lastDeployed": lastDeployed, 460 | "status": app.Status.Sync.Status, 461 | "revision": revisionMeta, 462 | "services": envResources[kindService], 463 | "secrets": envResources[kindSecret], 464 | "deployments": envResources[kindDeployment], 465 | "routes": envResources[kindRoute], 466 | "roleBindings": envResources[kindRoleBinding], 467 | "clusterRoles": envResources[kindClusterRole], 468 | "clusterRoleBindings": envResources[kindClusterRoleBinding], 469 | } 470 | 471 | marshalResponse(w, appEnv) 472 | } 473 | 474 | func (a *APIRouter) getAuthToken(ctx context.Context, req *http.Request) (string, error) { 475 | token := AuthToken(ctx) 476 | secret, ok := secretRefFromQuery(req.URL.Query()) 477 | if !ok { 478 | secret = a.secretRef 479 | } 480 | // TODO: this should be using a logger implementation. 481 | log.Printf("using secret from %#v", secret) 482 | token, err := a.secretGetter.SecretToken(ctx, token, secret, "token") 483 | if err != nil { 484 | return "", err 485 | } 486 | return token, nil 487 | } 488 | func (a *APIRouter) getAuthenticatedGitClient(fetchURL, token string) (git.SCM, error) { 489 | return a.gitClientFactory.Create(fetchURL, token) 490 | } 491 | 492 | func parseURL(s string) (string, *url.URL, error) { 493 | parsed, err := url.Parse(s) 494 | if err != nil { 495 | return "", nil, fmt.Errorf("failed to parse %#v: %w", s, err) 496 | } 497 | return strings.TrimLeft(strings.TrimSuffix(parsed.Path, ".git"), "/"), parsed, nil 498 | } 499 | 500 | func secretRefFromQuery(v url.Values) (types.NamespacedName, bool) { 501 | ns := v.Get("secretNS") 502 | name := v.Get("secretName") 503 | if ns != "" && name != "" { 504 | return types.NamespacedName{ 505 | Name: name, 506 | Namespace: ns, 507 | }, true 508 | } 509 | return types.NamespacedName{}, false 510 | } 511 | 512 | func refFromQuery(v url.Values) string { 513 | if ref := v.Get("ref"); ref != "" { 514 | return ref 515 | } 516 | return defaultRef 517 | } 518 | 519 | func marshalResponse(w http.ResponseWriter, v interface{}) { 520 | w.Header().Set("Content-Type", "application/json") 521 | w.Header().Set("Access-Control-Allow-Origin", "*") 522 | if err := json.NewEncoder(w).Encode(v); err != nil { 523 | log.Printf("failed to encode response: %s", err) 524 | } 525 | } 526 | 527 | func (a *APIRouter) getCommitInfo(app, revision string) (map[string]string, error) { 528 | client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} 529 | argocdCreds := &corev1.Secret{} 530 | err := a.k8sClient.Get(context.TODO(), 531 | types.NamespacedName{ 532 | Name: defaultArgoCDInstance + "-cluster", 533 | Namespace: defaultArgocdNamespace, 534 | }, argocdCreds) 535 | if err != nil { 536 | return nil, err 537 | } 538 | 539 | payload := map[string]string{ 540 | "username": "admin", 541 | "password": string(argocdCreds.Data["admin.password"]), 542 | } 543 | payloadBytes, err := json.Marshal(payload) 544 | if err != nil { 545 | return nil, err 546 | } 547 | 548 | resp, err := client.Post(fmt.Sprintf("%s/api/v1/session", baseURL), 549 | "application/json", bytes.NewBuffer(payloadBytes)) 550 | if err != nil { 551 | return nil, err 552 | } 553 | defer resp.Body.Close() 554 | bodyBytes, err := ioutil.ReadAll(resp.Body) 555 | if err != nil { 556 | return nil, err 557 | } 558 | 559 | m := make(map[string]string) 560 | err = json.Unmarshal(bodyBytes, &m) 561 | if err != nil { 562 | return nil, err 563 | } 564 | 565 | if token, ok := m["token"]; !ok || token == "" { 566 | return nil, fmt.Errorf("failed to retrieve JWT from the api-server") 567 | } 568 | 569 | u := fmt.Sprintf("%s/api/v1/applications/%s/revisions/%s/metadata", baseURL, app, revision) 570 | req, err := http.NewRequest("GET", u, nil) 571 | if err != nil { 572 | return nil, err 573 | } 574 | 575 | req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", m["token"])) 576 | req.Header.Add("content-type", "application/json") 577 | 578 | resp, err = client.Do(req) 579 | if err != nil { 580 | return nil, err 581 | } 582 | 583 | defer resp.Body.Close() 584 | bodyBytes, err = ioutil.ReadAll(resp.Body) 585 | if err != nil { 586 | return nil, err 587 | } 588 | 589 | err = json.Unmarshal(bodyBytes, &m) 590 | if err != nil { 591 | return nil, err 592 | } 593 | return m, nil 594 | } 595 | -------------------------------------------------------------------------------- /pkg/httpapi/api_test.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io/ioutil" 9 | "net/http" 10 | "net/http/httptest" 11 | "net/url" 12 | "strings" 13 | "testing" 14 | "time" 15 | 16 | argoV1aplha1 "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1" 17 | gogit "github.com/go-git/go-git/v5" 18 | "github.com/google/go-cmp/cmp" 19 | "github.com/redhat-developer/gitops-backend/pkg/git" 20 | "github.com/redhat-developer/gitops-backend/pkg/parser" 21 | "github.com/redhat-developer/gitops-backend/test" 22 | corev1 "k8s.io/api/core/v1" 23 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 24 | "k8s.io/apimachinery/pkg/types" 25 | "k8s.io/client-go/kubernetes/scheme" 26 | ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" 27 | "sigs.k8s.io/controller-runtime/pkg/client/fake" 28 | "sigs.k8s.io/yaml" 29 | ) 30 | 31 | const ( 32 | testRef = "7638417db6d59f3c431d3e1f261cc637155684cd" 33 | ) 34 | 35 | func TestGetPipelines(t *testing.T) { 36 | ts, c := makeServer(t) 37 | c.addContents("example/gitops", "pipelines.yaml", "HEAD", "testdata/pipelines.yaml") 38 | pipelinesURL := "https://github.com/example/gitops.git" 39 | 40 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/pipelines?url=%s", ts.URL, pipelinesURL)) 41 | res, err := ts.Client().Do(req) 42 | if err != nil { 43 | t.Fatal(err) 44 | } 45 | 46 | assertJSONResponse(t, res, map[string]interface{}{ 47 | "applications": []interface{}{ 48 | map[string]interface{}{ 49 | "name": "taxi", 50 | "repo_url": "https://example.com/demo/gitops.git", 51 | "environments": []interface{}{"dev"}, 52 | }, 53 | }, 54 | }) 55 | } 56 | 57 | func TestGetPipelinesWithASpecificRef(t *testing.T) { 58 | ts, c := makeServer(t) 59 | c.addContents("example/gitops", "pipelines.yaml", testRef, "testdata/pipelines.yaml") 60 | pipelinesURL := fmt.Sprintf("https://github.com/example/gitops.git?ref=%s", testRef) 61 | 62 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/pipelines?url=%s", ts.URL, pipelinesURL)) 63 | res, err := ts.Client().Do(req) 64 | if err != nil { 65 | t.Fatal(err) 66 | } 67 | 68 | assertJSONResponse(t, res, map[string]interface{}{ 69 | "applications": []interface{}{ 70 | map[string]interface{}{ 71 | "name": "taxi", 72 | "repo_url": "https://example.com/demo/gitops.git", 73 | "environments": []interface{}{"dev"}, 74 | }, 75 | }, 76 | }) 77 | } 78 | 79 | func TestGetPipelinesWithNoURL(t *testing.T) { 80 | ts, _ := makeServer(t) 81 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/pipelines", ts.URL)) 82 | res, err := ts.Client().Do(req) 83 | if err != nil { 84 | t.Fatal(err) 85 | } 86 | assertHTTPError(t, res, http.StatusBadRequest, "missing parameter 'url'") 87 | } 88 | 89 | func TestGetPipelinesWithBadURL(t *testing.T) { 90 | ts, c := makeServer(t) 91 | c.addContents("example/gitops", "pipelines.yaml", "main", "testdata/pipelines.yaml") 92 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/pipelines?url=%%%%test.html", ts.URL)) 93 | res, err := ts.Client().Do(req) 94 | if err != nil { 95 | t.Fatal(err) 96 | } 97 | assertHTTPError(t, res, http.StatusBadRequest, "missing parameter 'url'") 98 | } 99 | 100 | func TestGetPipelinesWithNoAuthorizationHeader(t *testing.T) { 101 | ts, _ := makeServer(t) 102 | req := makeClientRequest(t, "", fmt.Sprintf("%s/pipelines", ts.URL)) 103 | 104 | res, err := ts.Client().Do(req) 105 | if err != nil { 106 | t.Fatal(err) 107 | } 108 | assertHTTPError(t, res, http.StatusForbidden, "Authentication required") 109 | } 110 | 111 | func TestGetPipelinesWithNamespaceAndNameInURL(t *testing.T) { 112 | secretRef := types.NamespacedName{ 113 | Name: "other-name", 114 | Namespace: "other-ns", 115 | } 116 | sg := &stubSecretGetter{ 117 | testToken: "test-token", 118 | testName: secretRef, 119 | testAuthToken: "testing", 120 | testKey: "token", 121 | } 122 | ts, c := makeServer(t, func(a *APIRouter) { 123 | a.secretGetter = sg 124 | }) 125 | c.addContents("example/gitops", "pipelines.yaml", "HEAD", "testdata/pipelines.yaml") 126 | pipelinesURL := "https://github.com/example/gitops.git" 127 | options := url.Values{ 128 | "url": []string{pipelinesURL}, 129 | "secretName": []string{"other-name"}, 130 | "secretNS": []string{"other-ns"}, 131 | } 132 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/pipelines?%s", ts.URL, options.Encode())) 133 | 134 | res, err := ts.Client().Do(req) 135 | 136 | if err != nil { 137 | t.Fatal(err) 138 | } 139 | assertJSONResponse(t, res, map[string]interface{}{ 140 | "applications": []interface{}{ 141 | map[string]interface{}{ 142 | "name": "taxi", 143 | "repo_url": "https://example.com/demo/gitops.git", 144 | "environments": []interface{}{"dev"}, 145 | }, 146 | }, 147 | }) 148 | } 149 | 150 | func TestGetPipelinesWithUnknownSecret(t *testing.T) { 151 | ts, c := makeServer(t) 152 | c.addContents("example/gitops", "pipelines.yaml", "main", "testdata/pipelines.yaml") 153 | pipelinesURL := "https://github.com/example/gitops.git" 154 | options := url.Values{ 155 | "url": []string{pipelinesURL}, 156 | "secretName": []string{"other-name"}, 157 | "secretNS": []string{"other-ns"}, 158 | } 159 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/pipelines?%s", ts.URL, options.Encode())) 160 | res, err := ts.Client().Do(req) 161 | if err != nil { 162 | t.Fatal(err) 163 | } 164 | 165 | assertErrorResponse(t, res, http.StatusBadRequest, "unable to authenticate request") 166 | } 167 | 168 | func TestGetPipelineApplication(t *testing.T) { 169 | testResource := &parser.Resource{ 170 | Group: "", 171 | Version: "v1", 172 | Kind: "Deployment", 173 | Name: "test-deployment", 174 | Namespace: "test-ns", 175 | Labels: map[string]string{ 176 | nameLabel: "gitops-demo", 177 | }, 178 | } 179 | 180 | ts, c := makeServer(t, func(a *APIRouter) { 181 | a.resourceParser = stubResourceParser(testResource) 182 | }) 183 | c.addContents("example/gitops", "pipelines.yaml", "HEAD", "testdata/pipelines.yaml") 184 | pipelinesURL := "https://github.com/example/gitops.git" 185 | options := url.Values{ 186 | "url": []string{pipelinesURL}, 187 | } 188 | req := makeClientRequest(t, "Bearer testing", 189 | fmt.Sprintf("%s/environments/%s/application/%s?%s", ts.URL, "dev", "taxi", options.Encode())) 190 | res, err := ts.Client().Do(req) 191 | if err != nil { 192 | t.Fatal(err) 193 | } 194 | 195 | assertJSONResponse(t, res, map[string]interface{}{ 196 | "environment": "dev", 197 | "cluster": "https://dev.testing.svc", 198 | "services": []interface{}{ 199 | map[string]interface{}{ 200 | "name": "gitops-demo", 201 | "resources": []interface{}{ 202 | map[string]interface{}{ 203 | "group": "", 204 | "kind": "Deployment", 205 | "name": "test-deployment", 206 | "namespace": "test-ns", 207 | "version": "v1", 208 | }, 209 | }, 210 | "source": map[string]interface{}{ 211 | "type": "example.com", 212 | "url": "https://example.com/demo/gitops-demo.git", 213 | }, 214 | }, 215 | }, 216 | }) 217 | } 218 | 219 | func TestGetPipelineApplicationWithRef(t *testing.T) { 220 | testResource := &parser.Resource{ 221 | Group: "", 222 | Version: "v1", 223 | Kind: "Deployment", 224 | Name: "test-deployment", 225 | Namespace: "test-ns", 226 | Labels: map[string]string{ 227 | nameLabel: "gitops-demo", 228 | }, 229 | } 230 | 231 | ts, c := makeServer(t, func(a *APIRouter) { 232 | a.resourceParser = stubResourceParser(testResource) 233 | }) 234 | c.addContents("example/gitops", "pipelines.yaml", testRef, "testdata/pipelines.yaml") 235 | pipelinesURL := fmt.Sprintf("https://github.com/example/gitops.git?ref=%s", testRef) 236 | options := url.Values{ 237 | "url": []string{pipelinesURL}, 238 | } 239 | req := makeClientRequest(t, "Bearer testing", 240 | fmt.Sprintf("%s/environments/%s/application/%s?%s", ts.URL, "dev", "taxi", options.Encode())) 241 | res, err := ts.Client().Do(req) 242 | if err != nil { 243 | t.Fatal(err) 244 | } 245 | 246 | assertJSONResponse(t, res, map[string]interface{}{ 247 | "environment": "dev", 248 | "cluster": "https://dev.testing.svc", 249 | "services": []interface{}{ 250 | map[string]interface{}{ 251 | "name": "gitops-demo", 252 | "resources": []interface{}{ 253 | map[string]interface{}{ 254 | "group": "", 255 | "kind": "Deployment", 256 | "name": "test-deployment", 257 | "namespace": "test-ns", 258 | "version": "v1", 259 | }, 260 | }, 261 | "source": map[string]interface{}{ 262 | "type": "example.com", 263 | "url": "https://example.com/demo/gitops-demo.git", 264 | }, 265 | }, 266 | }, 267 | }) 268 | } 269 | 270 | func TestParseURL(t *testing.T) { 271 | urlTests := []struct { 272 | u string 273 | wantRepo string 274 | wantErr string 275 | }{ 276 | {"https://github.com/example/gitops.git?ref=main", "example/gitops", ""}, 277 | {"%%foo.html", "", "invalid URL escape"}, 278 | {"https://github.com/example/testing.git", "example/testing", ""}, 279 | } 280 | 281 | for _, tt := range urlTests { 282 | repo, got, err := parseURL(tt.u) 283 | if !test.MatchError(t, tt.wantErr, err) { 284 | t.Errorf("got an unexpected error: %v", err) 285 | continue 286 | } 287 | if err == nil { 288 | want, err := url.Parse(tt.u) 289 | assertNoError(t, err) 290 | if got.String() != want.String() { 291 | t.Errorf("Parsed URL mismatch: got %v, want %v", got.String(), want.String()) 292 | } 293 | } 294 | if repo != tt.wantRepo { 295 | t.Errorf("repo got %s, want %s", repo, tt.wantRepo) 296 | } 297 | } 298 | } 299 | 300 | func TestListApplications(t *testing.T) { 301 | err := argoV1aplha1.AddToScheme(scheme.Scheme) 302 | if err != nil { 303 | t.Fatal(err) 304 | } 305 | 306 | builder := fake.NewClientBuilder() 307 | kc := builder.Build() 308 | 309 | ts, _ := makeServer(t, func(router *APIRouter) { 310 | router.k8sClient = kc 311 | }) 312 | 313 | var createOptions []ctrlclient.CreateOption 314 | app, _ := testArgoApplication("testdata/application.yaml") 315 | err = kc.Create(context.TODO(), app, createOptions...) 316 | if err != nil { 317 | t.Fatal(err) 318 | } 319 | 320 | url := "https://github.com/test-repo/gitops.git?ref=HEAD" 321 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/applications?url=%s", ts.URL, url)) 322 | res, err := ts.Client().Do(req) 323 | if err != nil { 324 | t.Fatal(err) 325 | } 326 | 327 | assertJSONResponse(t, res, map[string]interface{}{ 328 | "applications": []interface{}{ 329 | map[string]interface{}{ 330 | "name": "test-app", 331 | "repo_url": "https://github.com/test-repo/gitops.git", 332 | "environments": []interface{}{"dev"}, 333 | "sync_status": []interface{}{"Synced"}, 334 | "last_deployed": []interface{}{time.Date(2021, time.Month(5), 15, 2, 12, 13, 0, time.UTC).Local().String()}, 335 | }, 336 | }, 337 | }) 338 | } 339 | 340 | func TestListApplicationsWIthTwoApps(t *testing.T) { 341 | err := argoV1aplha1.AddToScheme(scheme.Scheme) 342 | if err != nil { 343 | t.Fatal(err) 344 | } 345 | 346 | builder := fake.NewClientBuilder() 347 | kc := builder.Build() 348 | 349 | ts, _ := makeServer(t, func(router *APIRouter) { 350 | router.k8sClient = kc 351 | }) 352 | 353 | var createOptions []ctrlclient.CreateOption 354 | app, _ := testArgoApplication("testdata/application.yaml") 355 | err = kc.Create(context.TODO(), app, createOptions...) 356 | if err != nil { 357 | t.Fatal(err) 358 | } 359 | 360 | app2, _ := testArgoApplication("testdata/application2.yaml") 361 | err = kc.Create(context.TODO(), app2, createOptions...) 362 | if err != nil { 363 | t.Fatal(err) 364 | } 365 | 366 | url := "https://github.com/test-repo/gitops.git?ref=HEAD" 367 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/applications?url=%s", ts.URL, url)) 368 | res, err := ts.Client().Do(req) 369 | if err != nil { 370 | t.Fatal(err) 371 | } 372 | 373 | assertJSONResponse(t, res, map[string]interface{}{ 374 | "applications": []interface{}{ 375 | map[string]interface{}{ 376 | "name": "test-app", 377 | "repo_url": "https://github.com/test-repo/gitops.git", 378 | "environments": []interface{}{"dev", "production"}, 379 | "sync_status": []interface{}{"Synced", "OutOfSync"}, 380 | "last_deployed": []interface{}{time.Date(2021, time.Month(5), 15, 2, 12, 13, 0, time.UTC).Local().String(), 381 | time.Date(2021, time.Month(5), 16, 1, 10, 35, 0, time.UTC).Local().String(), 382 | }, 383 | }, 384 | }, 385 | }) 386 | } 387 | 388 | func TestListApplications_badURL(t *testing.T) { 389 | builder := fake.NewClientBuilder() 390 | kc := builder.Build() 391 | 392 | ts, _ := makeServer(t, func(router *APIRouter) { 393 | router.k8sClient = kc 394 | }) 395 | 396 | req := makeClientRequest(t, "Bearer testing", fmt.Sprintf("%s/applications", ts.URL)) 397 | resp, err := ts.Client().Do(req) 398 | if err != nil { 399 | t.Fatal(err) 400 | } 401 | 402 | assertHTTPError(t, resp, http.StatusBadRequest, "please provide a valid GitOps repo URL") 403 | } 404 | 405 | func TestGetApplicationDetails(t *testing.T) { 406 | err := argoV1aplha1.AddToScheme(scheme.Scheme) 407 | if err != nil { 408 | t.Fatal(err) 409 | } 410 | 411 | builder := fake.NewClientBuilder() 412 | kc := builder.Build() 413 | 414 | ts, _ := makeServer(t, func(router *APIRouter) { 415 | router.k8sClient = kc 416 | }) 417 | 418 | // create test ArgoCD Server to handle http requests 419 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 420 | u := r.URL.String() 421 | if strings.Contains(u, "session") { 422 | m := map[string]string{ 423 | "token": "testing", 424 | } 425 | marshalResponse(w, m) 426 | } else if strings.Contains(u, "metadata") { 427 | m := map[string]string{ 428 | "author": "test", 429 | "message": "testMessage", 430 | } 431 | marshalResponse(w, m) 432 | } 433 | })) 434 | defer server.Close() 435 | tmp := baseURL 436 | baseURL = server.URL 437 | 438 | var createOptions []ctrlclient.CreateOption 439 | app, _ := testArgoApplication("testdata/application.yaml") 440 | // create argocd test-app 441 | err = kc.Create(context.TODO(), app, createOptions...) 442 | if err != nil { 443 | t.Fatal(err) 444 | } 445 | 446 | // create argocd instance creds secret 447 | secret := &corev1.Secret{ 448 | ObjectMeta: metav1.ObjectMeta{ 449 | Name: defaultArgoCDInstance + "-cluster", 450 | Namespace: defaultArgocdNamespace, 451 | }, 452 | Data: map[string][]byte{ 453 | "admin.password": []byte("abc"), 454 | }, 455 | } 456 | err = kc.Create(context.TODO(), secret, createOptions...) 457 | if err != nil { 458 | t.Fatal(err) 459 | } 460 | 461 | options := url.Values{ 462 | "url": []string{"https://github.com/test-repo/gitops.git"}, 463 | } 464 | req := makeClientRequest(t, "Bearer testing", 465 | fmt.Sprintf("%s/environment/%s/application/%s?%s", ts.URL, "dev", "test-app", options.Encode())) 466 | res, err := ts.Client().Do(req) 467 | if err != nil { 468 | t.Fatal(err) 469 | } 470 | 471 | assertJSONResponse(t, res, map[string]interface{}{ 472 | "cluster": "https://kubernetes.default.svc", 473 | "environment": "dev", 474 | "status": "Synced", 475 | "lastDeployed": time.Date(2021, time.Month(5), 15, 2, 12, 13, 0, time.UTC).Local().String(), 476 | "revision": map[string]interface{}{ 477 | "author": "test", 478 | "message": "testMessage", 479 | "revision": "123456789", 480 | }, 481 | "deployments": []interface{}{ 482 | map[string]interface{}{"health": string("Healthy"), "name": string("taxi"), "status": string("Synced")}, 483 | }, 484 | "secrets": []interface{}{ 485 | map[string]interface{}{ 486 | "health": string("Missing"), 487 | "name": string("testsecret"), 488 | "status": string("OutOfSync"), 489 | }, 490 | }, 491 | "services": []interface{}{ 492 | map[string]interface{}{"health": string("Healthy"), "name": string("taxi"), "status": string("Synced")}, 493 | }, 494 | "routes": []interface{}{ 495 | map[string]interface{}{"name": string("taxi"), "status": string("Synced")}, 496 | }, 497 | "clusterRoleBindings": []interface{}{ 498 | map[string]interface{}{"name": string("pipelines-service-role-binding"), "status": string("Synced")}, 499 | }, 500 | "clusterRoles": []interface{}{ 501 | map[string]interface{}{"name": string("pipelines-clusterrole"), "status": string("Synced")}, 502 | }, 503 | "roleBindings": []interface{}{ 504 | map[string]interface{}{"name": string("argocd-admin"), "status": string("Synced")}, 505 | }, 506 | }) 507 | 508 | //reset BaseURL 509 | baseURL = tmp 510 | } 511 | 512 | func TestGetApplicationHistory(t *testing.T) { 513 | err := argoV1aplha1.AddToScheme(scheme.Scheme) 514 | if err != nil { 515 | t.Fatal(err) 516 | } 517 | 518 | builder := fake.NewClientBuilder() 519 | kc := builder.Build() 520 | 521 | ts, _ := makeServer(t, func(router *APIRouter) { 522 | router.k8sClient = kc 523 | }) 524 | 525 | // create test ArgoCD Server to handle http requests 526 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 527 | u := r.URL.String() 528 | if strings.Contains(u, "session") { 529 | m := map[string]string{ 530 | "token": "testing", 531 | } 532 | marshalResponse(w, m) 533 | } else if strings.Contains(u, "metadata") { 534 | m := map[string]string{ 535 | "author": "test", 536 | "message": "testMessage", 537 | } 538 | marshalResponse(w, m) 539 | } 540 | })) 541 | defer server.Close() 542 | tmp := baseURL 543 | baseURL = server.URL 544 | 545 | var createOptions []ctrlclient.CreateOption 546 | app, _ := testArgoApplication("testdata/application3.yaml") 547 | // create argocd test-app 548 | err = kc.Create(context.TODO(), app, createOptions...) 549 | if err != nil { 550 | t.Fatal(err) 551 | } 552 | 553 | // create argocd instance creds secret 554 | secret := &corev1.Secret{ 555 | ObjectMeta: metav1.ObjectMeta{ 556 | Name: defaultArgoCDInstance + "-cluster", 557 | Namespace: defaultArgocdNamespace, 558 | }, 559 | Data: map[string][]byte{ 560 | "admin.password": []byte("abc"), 561 | }, 562 | } 563 | err = kc.Create(context.TODO(), secret, createOptions...) 564 | if err != nil { 565 | t.Fatal(err) 566 | } 567 | 568 | options := url.Values{ 569 | "url": []string{"https://github.com/test-repo/gitops.git"}, 570 | } 571 | req := makeClientRequest(t, "Bearer testing", 572 | fmt.Sprintf("%s/history/environment/%s/application/%s?%s", ts.URL, "dev", "app-taxi", options.Encode())) 573 | res, err := ts.Client().Do(req) 574 | if err != nil { 575 | t.Fatal(err) 576 | } 577 | fmt.Println("history res is ", res) 578 | 579 | want := []envHistory{ 580 | { 581 | Author: "test", 582 | Message: "testMessage", 583 | Revision: "a0c7298faead28f7f60a5106afbb18882ad220a7", 584 | Environment: "dev", 585 | RepoUrl: "https://github.com/test-repo/gitops.git", 586 | DeployedAt: time.Date(2022, time.Month(4), 22, 17, 11, 29, 0, time.UTC).Local().String(), 587 | }, 588 | { 589 | Author: "test", 590 | Message: "testMessage", 591 | Revision: "3f6965bd65d9294b8fec5d6e2dc3dad08e33a8fe", 592 | Environment: "dev", 593 | RepoUrl: "https://github.com/test-repo/gitops.git", 594 | DeployedAt: time.Date(2022, time.Month(4), 21, 14, 17, 49, 0, time.UTC).Local().String(), 595 | }, 596 | { 597 | Author: "test", 598 | Message: "testMessage", 599 | Revision: "e5585fcf22366e2d066e0936cbd8a0508756d02d", 600 | Environment: "dev", 601 | RepoUrl: "https://github.com/test-repo/gitops.git", 602 | DeployedAt: time.Date(2022, time.Month(4), 21, 14, 16, 51, 0, time.UTC).Local().String(), 603 | }, 604 | { 605 | Author: "test", 606 | Message: "testMessage", 607 | Revision: "3f6965bd65d9294b8fec5d6e2dc3dad08e33a8fe", 608 | Environment: "dev", 609 | RepoUrl: "https://github.com/test-repo/gitops.git", 610 | DeployedAt: time.Date(2022, time.Month(4), 21, 14, 16, 50, 0, time.UTC).Local().String(), 611 | }, 612 | { 613 | Author: "test", 614 | Message: "testMessage", 615 | Revision: "e5585fcf22366e2d066e0936cbd8a0508756d02d", 616 | Environment: "dev", 617 | RepoUrl: "https://github.com/test-repo/gitops.git", 618 | DeployedAt: time.Date(2022, time.Month(4), 21, 14, 14, 27, 0, time.UTC).Local().String(), 619 | }, 620 | { 621 | Author: "test", 622 | Message: "testMessage", 623 | Revision: "e5585fcf22366e2d066e0936cbd8a0508756d02d", 624 | Environment: "dev", 625 | RepoUrl: "https://github.com/test-repo/gitops.git", 626 | DeployedAt: time.Date(2022, time.Month(4), 19, 18, 19, 52, 0, time.UTC).Local().String(), 627 | }, 628 | } 629 | assertJSONResponseHistory(t, res, want) 630 | 631 | //reset BaseURL 632 | baseURL = tmp 633 | } 634 | 635 | func testArgoApplication(appCr string) (*argoV1aplha1.Application, error) { 636 | applicationYaml, _ := ioutil.ReadFile(appCr) 637 | app := &argoV1aplha1.Application{} 638 | err := yaml.Unmarshal(applicationYaml, app) 639 | if err != nil { 640 | return nil, err 641 | } 642 | 643 | return app, err 644 | } 645 | 646 | func newClient() *stubClient { 647 | return &stubClient{files: make(map[string]string)} 648 | } 649 | 650 | type stubClient struct { 651 | files map[string]string 652 | } 653 | 654 | func (s stubClient) FileContents(ctx context.Context, repo, path, ref string) ([]byte, error) { 655 | f, ok := s.files[key(repo, path, ref)] 656 | if !ok { 657 | return nil, git.SCMError{Status: http.StatusNotFound} 658 | } 659 | return ioutil.ReadFile(f) 660 | } 661 | 662 | func (s *stubClient) addContents(repo, path, ref, filename string) { 663 | s.files[key(repo, path, ref)] = filename 664 | } 665 | 666 | func parseYAMLToConfig(t *testing.T, path string) *config { 667 | t.Helper() 668 | b, err := ioutil.ReadFile(path) 669 | if err != nil { 670 | t.Fatal(err) 671 | } 672 | response := &config{} 673 | err = yaml.Unmarshal(b, &response) 674 | if err != nil { 675 | t.Fatal(err) 676 | } 677 | return response 678 | } 679 | 680 | func key(s ...string) string { 681 | return strings.Join(s, "#") 682 | } 683 | 684 | func makeClientRequest(t *testing.T, token, path string) *http.Request { 685 | r, err := http.NewRequest("GET", path, nil) 686 | if err != nil { 687 | t.Fatal(err) 688 | } 689 | r.Header.Set(authHeader, token) 690 | return r 691 | } 692 | 693 | type routerOptionFunc func(*APIRouter) 694 | 695 | func makeServer(t *testing.T, opts ...routerOptionFunc) (*httptest.Server, *stubClient) { 696 | sg := &stubSecretGetter{ 697 | testToken: "test-token", 698 | testName: DefaultSecretRef, 699 | testAuthToken: "testing", 700 | testKey: "token", 701 | } 702 | sf := &stubClientFactory{client: newClient()} 703 | var kc ctrlclient.Client 704 | router := NewRouter(sf, sg, kc) 705 | for _, o := range opts { 706 | o(router) 707 | } 708 | 709 | ts := httptest.NewTLSServer(AuthenticationMiddleware(router)) 710 | t.Cleanup(ts.Close) 711 | return ts, sf.client 712 | } 713 | 714 | func readBody(t *testing.T, res *http.Response) []byte { 715 | t.Helper() 716 | if res.StatusCode != http.StatusOK { 717 | defer res.Body.Close() 718 | errMsg, err := ioutil.ReadAll(res.Body) 719 | if err != nil { 720 | t.Fatal(err) 721 | } 722 | t.Fatalf("didn't get a successful response: %v (%s)", res.StatusCode, strings.TrimSpace(string(errMsg))) 723 | } 724 | defer res.Body.Close() 725 | b, err := ioutil.ReadAll(res.Body) 726 | if err != nil { 727 | t.Fatal(err) 728 | } 729 | if h := res.Header.Get("Content-Type"); h != "application/json" { 730 | t.Fatalf("wanted 'application/json' got %s", h) 731 | } 732 | if h := res.Header.Get("Access-Control-Allow-Origin"); h != "*" { 733 | t.Fatalf("wanted '*' got %s", h) 734 | } 735 | return b 736 | } 737 | 738 | func assertJSONResponse(t *testing.T, res *http.Response, want map[string]interface{}) { 739 | b := readBody(t, res) 740 | got := map[string]interface{}{} 741 | 742 | err := json.Unmarshal(b, &got) 743 | if err != nil { 744 | t.Fatalf("failed to parse %s: %s", b, err) 745 | } 746 | if diff := cmp.Diff(want, got); diff != "" { 747 | t.Fatalf("JSON response failed:\n%s", diff) 748 | } 749 | } 750 | 751 | func assertJSONResponseHistory(t *testing.T, res *http.Response, want []envHistory) { 752 | b := readBody(t, res) 753 | got := make([]envHistory, 0) 754 | err := json.Unmarshal(b, &got) 755 | if err != nil { 756 | t.Fatalf("failed to parse %s: %s", b, err) 757 | } 758 | if diff := cmp.Diff(want, got); diff != "" { 759 | t.Fatalf("JSON response failed:\n%s", diff) 760 | } 761 | } 762 | 763 | func assertErrorResponse(t *testing.T, res *http.Response, status int, want string) { 764 | t.Helper() 765 | if res.StatusCode != status { 766 | defer res.Body.Close() 767 | errMsg, err := ioutil.ReadAll(res.Body) 768 | if err != nil { 769 | t.Fatal(err) 770 | } 771 | t.Fatalf("status code didn't match: %v (%s)", res.StatusCode, strings.TrimSpace(string(errMsg))) 772 | } 773 | defer res.Body.Close() 774 | b, err := ioutil.ReadAll(res.Body) 775 | if err != nil { 776 | t.Fatal(err) 777 | } 778 | if got := strings.TrimSpace(string(b)); got != want { 779 | t.Fatalf("got %s, want %s", got, want) 780 | } 781 | } 782 | 783 | type stubSecretGetter struct { 784 | testAuthToken string 785 | testToken string 786 | testName types.NamespacedName 787 | testKey string 788 | } 789 | 790 | func (f *stubSecretGetter) SecretToken(ctx context.Context, authToken string, id types.NamespacedName, key string) (string, error) { 791 | if id == f.testName && authToken == f.testAuthToken && key == f.testKey { 792 | return f.testToken, nil 793 | } 794 | return "", errors.New("failed to get a secret token") 795 | } 796 | 797 | type stubClientFactory struct { 798 | client *stubClient 799 | } 800 | 801 | func (s stubClientFactory) Create(url, token string) (git.SCM, error) { 802 | // TODO: this should match on the URL/token combo. 803 | return s.client, nil 804 | } 805 | 806 | func stubResourceParser(r ...*parser.Resource) parser.ResourceParser { 807 | return func(path string, opts *gogit.CloneOptions) ([]*parser.Resource, error) { 808 | return r, nil 809 | } 810 | } 811 | -------------------------------------------------------------------------------- /pkg/httpapi/application.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | "path" 7 | "sort" 8 | 9 | "github.com/go-git/go-git/v5" 10 | "github.com/go-git/go-git/v5/plumbing/transport/http" 11 | "github.com/redhat-developer/gitops-backend/pkg/parser" 12 | ) 13 | 14 | const nameLabel = "app.kubernetes.io/name" 15 | 16 | // TODO: if the environment doesn't exist, this should return a not found error. 17 | func (a *APIRouter) environmentApplication(authToken string, c *config, envName, appName string) (map[string]interface{}, error) { 18 | if c.GitOpsURL == "" { 19 | return nil, nil 20 | } 21 | env := c.findEnvironment(envName) 22 | if env == nil { 23 | return nil, fmt.Errorf("failed to find environment %#v", envName) 24 | } 25 | co := &git.CloneOptions{ 26 | Auth: &http.BasicAuth{ 27 | Username: "gitops", 28 | Password: authToken, 29 | }, 30 | URL: c.GitOpsURL, 31 | } 32 | res, err := a.resourceParser(pathForApplication(appName, envName), co) 33 | if err != nil { 34 | return nil, err 35 | } 36 | services, err := parseServicesFromResources(env, res) 37 | if err != nil { 38 | return nil, err 39 | } 40 | appEnv := map[string]interface{}{ 41 | "environment": envName, 42 | "cluster": c.findEnvironment(envName).Cluster, 43 | "services": services, 44 | } 45 | return appEnv, nil 46 | } 47 | 48 | func pathForApplication(appName, envName string) string { 49 | return path.Join("environments", envName, "apps", appName) 50 | } 51 | 52 | func parseServicesFromResources(env *environment, res []*parser.Resource) ([]responseService, error) { 53 | serviceImages := map[string]map[string]bool{} 54 | serviceResources := map[string][]*parser.Resource{} 55 | for _, v := range res { 56 | name := serviceFromLabels(v.Labels) 57 | images, ok := serviceImages[name] 58 | if !ok { 59 | images = map[string]bool{} 60 | } 61 | for _, n := range v.Images { 62 | images[n] = true 63 | } 64 | serviceImages[name] = images 65 | resources, ok := serviceResources[name] 66 | if !ok { 67 | resources = []*parser.Resource{} 68 | } 69 | resources = append(resources, v) 70 | serviceResources[name] = resources 71 | } 72 | 73 | services := []responseService{} 74 | for k, v := range serviceImages { 75 | svc := env.findService(k) 76 | // If the extracted service name is not known within this environment, 77 | // this drops it from the response. 78 | if svc == nil { 79 | continue 80 | } 81 | svcRepo := "" 82 | if svc != nil { 83 | svcRepo = svc.SourceURL 84 | } 85 | // This skips services where we haven't extracted a name from the 86 | // labels. 87 | if k == "" { 88 | continue 89 | } 90 | rs := responseService{ 91 | Name: k, 92 | Images: keys(v), 93 | Resources: serviceResources[k], 94 | } 95 | if svcRepo != "" { 96 | domain, err := hostFromURL(svcRepo) 97 | if err != nil { 98 | return nil, err 99 | } 100 | rs.Source = source{URL: svcRepo, Type: domain} 101 | } 102 | services = append(services, rs) 103 | } 104 | return services, nil 105 | } 106 | 107 | func serviceFromLabels(l map[string]string) string { 108 | return l[nameLabel] 109 | } 110 | 111 | type responseService struct { 112 | Name string `json:"name"` 113 | Source source `json:"source,omitempty"` 114 | Images []string `json:"images,omitempty"` 115 | Resources []*parser.Resource `json:"resources,omitempty"` 116 | } 117 | 118 | type source struct { 119 | URL string `json:"url"` 120 | Type string `json:"type"` 121 | } 122 | 123 | func hostFromURL(u string) (string, error) { 124 | parsed, err := url.Parse(u) 125 | if err != nil { 126 | return "", fmt.Errorf("failed to parse Git repo URL %q: %w", u, err) 127 | } 128 | return parsed.Host, nil 129 | } 130 | 131 | func keys(v map[string]bool) []string { 132 | keys := []string{} 133 | for k := range v { 134 | keys = append(keys, k) 135 | } 136 | sort.Strings(keys) 137 | return keys 138 | } 139 | -------------------------------------------------------------------------------- /pkg/httpapi/application_test.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "sort" 5 | "testing" 6 | 7 | "github.com/google/go-cmp/cmp" 8 | "github.com/redhat-developer/gitops-backend/pkg/parser" 9 | ) 10 | 11 | const ( 12 | partOfLabel = "app.kubernetes.io/part-of" 13 | ) 14 | 15 | const testSourceURL = "https://github.com/rhd-example-gitops/gitops-demo.git" 16 | 17 | func TestParseServicesFromResources(t *testing.T) { 18 | goDemoResources := []*parser.Resource{ 19 | { 20 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "go-demo-http", 21 | Labels: map[string]string{ 22 | nameLabel: "go-demo", 23 | partOfLabel: "go-demo", 24 | }, 25 | Images: []string{"bigkevmcd/go-demo:876ecb3"}, 26 | }, 27 | { 28 | Version: "v1", Kind: "Service", Name: "go-demo-http", 29 | Labels: map[string]string{ 30 | nameLabel: "go-demo", 31 | partOfLabel: "go-demo", 32 | }, 33 | }, 34 | { 35 | Version: "v1", Kind: "ConfigMap", Name: "go-demo-config", 36 | Labels: map[string]string{ 37 | nameLabel: "go-demo", 38 | partOfLabel: "go-demo", 39 | }, 40 | }, 41 | } 42 | 43 | redisResources := []*parser.Resource{ 44 | { 45 | Version: "v1", Kind: "Service", Name: "redis", 46 | Labels: map[string]string{ 47 | nameLabel: "redis", 48 | partOfLabel: "go-demo", 49 | }, 50 | }, 51 | { 52 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "redis", 53 | Labels: map[string]string{ 54 | nameLabel: "redis", 55 | partOfLabel: "go-demo", 56 | }, 57 | Images: []string{"redis:6-alpine"}, 58 | }, 59 | } 60 | env := &environment{ 61 | Name: "test-env", 62 | Cluster: "https://cluster.local", 63 | Apps: []*application{ 64 | { 65 | Name: "my-app", 66 | Services: []service{ 67 | { 68 | Name: "go-demo", 69 | SourceURL: testSourceURL, 70 | }, 71 | { 72 | Name: "redis", 73 | }, 74 | }, 75 | }, 76 | }, 77 | } 78 | res := append(goDemoResources, redisResources...) 79 | 80 | svcs, err := parseServicesFromResources(env, res) 81 | if err != nil { 82 | t.Fatal(err) 83 | } 84 | 85 | sort.Slice(svcs, func(i, j int) bool { 86 | return svcs[i].Name < svcs[j].Name 87 | }) 88 | 89 | want := []responseService{ 90 | { 91 | Name: "go-demo", 92 | Source: source{ 93 | URL: testSourceURL, 94 | Type: "github.com", 95 | }, 96 | Images: []string{"bigkevmcd/go-demo:876ecb3"}, 97 | Resources: goDemoResources, 98 | }, 99 | { 100 | Name: "redis", 101 | Source: source{}, 102 | Images: []string{"redis:6-alpine"}, 103 | Resources: redisResources, 104 | }, 105 | } 106 | if diff := cmp.Diff(want, svcs); diff != "" { 107 | t.Fatalf("parseServicesFromResources got\n%s", diff) 108 | } 109 | } 110 | 111 | func TestParseServicesFromResourcesReturnsSetOfImages(t *testing.T) { 112 | res := []*parser.Resource{ 113 | { 114 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "go-demo-http", 115 | Labels: map[string]string{ 116 | nameLabel: "go-demo", 117 | partOfLabel: "go-demo", 118 | }, 119 | Images: []string{"bigkevmcd/go-demo:876ecb3"}, 120 | }, 121 | { 122 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "go-demo-cmd", 123 | Labels: map[string]string{ 124 | nameLabel: "go-demo", 125 | partOfLabel: "go-demo", 126 | }, 127 | Images: []string{"bigkevmcd/testing:a29fcef", "bigkevmcd/go-demo:876ecb3"}, 128 | }, 129 | } 130 | env := &environment{ 131 | Name: "test-env", 132 | Cluster: "https://cluster.local", 133 | Apps: []*application{ 134 | { 135 | Name: "my-app", 136 | Services: []service{ 137 | { 138 | Name: "go-demo", 139 | SourceURL: testSourceURL, 140 | }, 141 | }, 142 | }, 143 | }, 144 | } 145 | 146 | svcs, err := parseServicesFromResources(env, res) 147 | if err != nil { 148 | t.Fatal(err) 149 | } 150 | 151 | sort.Slice(svcs, func(i, j int) bool { 152 | return svcs[i].Name < svcs[j].Name 153 | }) 154 | 155 | want := []responseService{ 156 | { 157 | Name: "go-demo", 158 | Source: source{ 159 | URL: testSourceURL, 160 | Type: "github.com", 161 | }, 162 | Images: []string{ 163 | "bigkevmcd/go-demo:876ecb3", 164 | "bigkevmcd/testing:a29fcef", 165 | }, 166 | Resources: res, 167 | }, 168 | } 169 | if diff := cmp.Diff(want, svcs); diff != "" { 170 | t.Fatalf("parseServicesFromResources got\n%s", diff) 171 | } 172 | } 173 | 174 | func TestParseServicesFromResourcesIgnoresEmptyServices(t *testing.T) { 175 | res := []*parser.Resource{ 176 | { 177 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "go-demo-http", 178 | Labels: map[string]string{}, 179 | Images: []string{"bigkevmcd/go-demo:876ecb3"}, 180 | }, 181 | { 182 | Version: "v1", Kind: "Service", Name: "go-demo-http", 183 | Labels: map[string]string{}, 184 | }, 185 | } 186 | env := &environment{ 187 | Name: "test-env", 188 | Cluster: "https://cluster.local", 189 | Apps: []*application{ 190 | { 191 | Name: "my-app", 192 | Services: []service{ 193 | { 194 | Name: "go-demo", 195 | SourceURL: testSourceURL, 196 | }, 197 | }, 198 | }, 199 | }, 200 | } 201 | 202 | svcs, err := parseServicesFromResources(env, res) 203 | if err != nil { 204 | t.Fatal(err) 205 | } 206 | 207 | want := []responseService{} 208 | if diff := cmp.Diff(want, svcs); diff != "" { 209 | t.Fatalf("parseServicesFromResources got\n%s", diff) 210 | } 211 | } 212 | 213 | func TestParseServicesFromResourcesIgnoresUnknownServices(t *testing.T) { 214 | res := []*parser.Resource{ 215 | { 216 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "go-demo-http", 217 | Labels: map[string]string{ 218 | nameLabel: "unknown", 219 | partOfLabel: "unknown", 220 | }, 221 | Images: []string{"bigkevmcd/go-demo:876ecb3"}, 222 | }, 223 | } 224 | 225 | env := &environment{ 226 | Name: "test-env", 227 | Cluster: "https://cluster.local", 228 | Apps: []*application{ 229 | { 230 | Name: "my-app", 231 | Services: []service{ 232 | { 233 | Name: "go-demo", 234 | SourceURL: testSourceURL, 235 | }, 236 | }, 237 | }, 238 | }, 239 | } 240 | 241 | svcs, err := parseServicesFromResources(env, res) 242 | if err != nil { 243 | t.Fatal(err) 244 | } 245 | 246 | want := []responseService{} 247 | if diff := cmp.Diff(want, svcs); diff != "" { 248 | t.Fatalf("parseServicesFromResources got\n%s", diff) 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /pkg/httpapi/authorization.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "strings" 7 | ) 8 | 9 | const ( 10 | authHeader = "Authorization" 11 | ) 12 | 13 | type authTokenCtxKey struct{} 14 | 15 | // AuthToken gets the auth token from the context. 16 | func AuthToken(ctx context.Context) string { 17 | return ctx.Value(authTokenCtxKey{}).(string) 18 | } 19 | 20 | // WithAuthToken sets the auth token into the context. 21 | func WithAuthToken(ctx context.Context, t string) context.Context { 22 | return context.WithValue(ctx, authTokenCtxKey{}, t) 23 | } 24 | 25 | // AuthenticationMiddleware wraps an http.Handler and checks for the presence of 26 | // an 'Authorization' header with a bearer token. 27 | // 28 | // This token is placed into the context, and is accessible via the AuthToken 29 | // function. 30 | // 31 | // No attempt to validate the actual token is made. 32 | func AuthenticationMiddleware(next http.Handler) http.Handler { 33 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 34 | headerValue := extractToken(r.Header.Get(authHeader)) 35 | if headerValue == "" { 36 | http.Error(w, "Authentication required", http.StatusForbidden) 37 | return 38 | } 39 | next.ServeHTTP(w, r.Clone(WithAuthToken(r.Context(), headerValue))) 40 | }) 41 | } 42 | 43 | func extractToken(s string) string { 44 | parts := strings.Split(s, " ") 45 | if len(parts) != 2 { 46 | return "" 47 | } 48 | if strings.TrimSpace(parts[0]) != "Bearer" { 49 | return "" 50 | } 51 | return strings.TrimSpace(parts[1]) 52 | } 53 | -------------------------------------------------------------------------------- /pkg/httpapi/authorization_test.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "net/http" 7 | "net/http/httptest" 8 | "strings" 9 | "testing" 10 | ) 11 | 12 | func TestRequestWithNoAuthorizationHeader(t *testing.T) { 13 | handler := AuthenticationMiddleware(makeTestFunc("")) 14 | req := makeTokenRequest("") 15 | w := httptest.NewRecorder() 16 | 17 | handler.ServeHTTP(w, req) 18 | 19 | resp := w.Result() 20 | assertHTTPError(t, resp, http.StatusForbidden, "Authentication required") 21 | } 22 | 23 | func TestRequestWithBadHeader(t *testing.T) { 24 | handler := AuthenticationMiddleware(makeTestFunc("")) 25 | req := makeTokenRequest("Bearer ") 26 | w := httptest.NewRecorder() 27 | 28 | handler.ServeHTTP(w, req) 29 | 30 | resp := w.Result() 31 | 32 | assertHTTPError(t, resp, http.StatusForbidden, "Authentication required") 33 | } 34 | 35 | func TestRequestWithBadPrefix(t *testing.T) { 36 | handler := AuthenticationMiddleware(makeTestFunc("")) 37 | req := makeTokenRequest("Authentication token") 38 | w := httptest.NewRecorder() 39 | 40 | handler.ServeHTTP(w, req) 41 | 42 | resp := w.Result() 43 | 44 | assertHTTPError(t, resp, http.StatusForbidden, "Authentication required") 45 | } 46 | 47 | func TestRequestWithAuthorizationHeader(t *testing.T) { 48 | handler := AuthenticationMiddleware(makeTestFunc("testing-token")) 49 | req := makeTokenRequest("Bearer testing-token") 50 | 51 | w := httptest.NewRecorder() 52 | 53 | handler.ServeHTTP(w, req) 54 | 55 | resp := w.Result() 56 | if resp.StatusCode != http.StatusOK { 57 | t.Fatalf("got %v, want %v", resp.StatusCode, http.StatusOK) 58 | } 59 | } 60 | 61 | func TestRequestWithAuthorizationHeaderSetsTokenInContext(t *testing.T) { 62 | handler := AuthenticationMiddleware(makeTestFunc("testing-token")) 63 | req := makeTokenRequest("Bearer testing-token") 64 | 65 | w := httptest.NewRecorder() 66 | handler.ServeHTTP(w, req) 67 | 68 | resp := w.Result() 69 | 70 | if resp.StatusCode != http.StatusOK { 71 | t.Fatalf("incorrect status code, got %d, want %d", resp.StatusCode, http.StatusOK) 72 | } 73 | body, err := ioutil.ReadAll(resp.Body) 74 | assertNoError(t, err) 75 | if s := strings.TrimSpace(string(body)); s != "testing-token" { 76 | t.Fatalf("got %s, want %s", s, "testing-token\n") 77 | } 78 | 79 | } 80 | 81 | func makeTokenRequest(token string) *http.Request { 82 | req := httptest.NewRequest("GET", "http://example.com/", nil) 83 | if token != "" { 84 | req.Header.Set(authHeader, token) 85 | } 86 | return req 87 | } 88 | 89 | func makeTestFunc(wantedToken string) http.HandlerFunc { 90 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 91 | token := AuthToken(r.Context()) 92 | if token == "" { 93 | token = "failed" 94 | } 95 | fmt.Fprintln(w, token) 96 | }) 97 | } 98 | 99 | func assertHTTPError(t *testing.T, resp *http.Response, code int, want string) { 100 | t.Helper() 101 | if resp.StatusCode != code { 102 | t.Errorf("status code didn't match, got %d, want %d", resp.StatusCode, code) 103 | } 104 | b, err := ioutil.ReadAll(resp.Body) 105 | assertNoError(t, err) 106 | if s := strings.TrimSpace(string(b)); s != want { 107 | t.Fatalf("got %s, want %s", s, want) 108 | } 109 | } 110 | 111 | func assertNoError(t *testing.T, err error) { 112 | t.Helper() 113 | if err != nil { 114 | t.Fatal(err) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /pkg/httpapi/conversion.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | log "github.com/sirupsen/logrus" 5 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 6 | "sort" 7 | "strings" 8 | 9 | argoV1aplha1 "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1" 10 | ) 11 | 12 | // TODO: this should really import the config from the upstream and use it to 13 | // unmarshal. 14 | func pipelinesToAppsResponse(cfg *config) *appsResponse { 15 | appSet := map[string][]string{} 16 | for _, env := range cfg.Environments { 17 | for _, app := range env.Apps { 18 | envs, ok := appSet[app.Name] 19 | if !ok { 20 | envs = []string{} 21 | } 22 | envs = append(envs, env.Name) 23 | appSet[app.Name] = envs 24 | } 25 | } 26 | 27 | apps := []appResponse{} 28 | for k, v := range appSet { 29 | sort.Strings(v) 30 | apps = append(apps, appResponse{Name: k, RepoURL: cfg.GitOpsURL, Environments: v}) 31 | } 32 | return &appsResponse{Apps: apps} 33 | } 34 | 35 | func applicationsToAppsResponse(appSet []*argoV1aplha1.Application, repoURL string) *appsResponse { 36 | appsMap := make(map[string]appResponse) 37 | var appName string 38 | repoURL = strings.TrimSuffix(repoURL, ".git") 39 | 40 | for _, app := range appSet { 41 | appName = "" // Reset at beginning of the loop so no duplicates are added 42 | if repoURL != strings.TrimSuffix(app.Spec.Source.RepoURL, ".git") { 43 | log.Printf("repoURL[%v], does not match with Source Repo URL[%v]", repoURL, strings.TrimSuffix(app.Spec.Source.RepoURL, ".git")) 44 | continue 45 | } 46 | if app.ObjectMeta.Labels != nil { 47 | appName = app.ObjectMeta.Labels["app.kubernetes.io/name"] 48 | } 49 | 50 | if appName == "" { 51 | log.Println("AppName is empty") 52 | continue 53 | } 54 | 55 | var lastDeployed metav1.Time 56 | size := len(app.Status.History) 57 | if size > 0 { 58 | lastDeployed = app.Status.History[size-1].DeployedAt 59 | } 60 | var lastDeployedTime = lastDeployed.String() 61 | if lastDeployed.IsZero() { 62 | lastDeployedTime = "" 63 | } 64 | if appResp, ok := appsMap[appName]; !ok { 65 | appsMap[appName] = appResponse{ 66 | Name: appName, 67 | RepoURL: app.Spec.Source.RepoURL, 68 | Environments: []string{app.Spec.Destination.Namespace}, 69 | SyncStatus: []string{string(app.Status.Sync.Status)}, 70 | LastDeployed: []string{lastDeployedTime}, 71 | } 72 | } else { 73 | appResp.Environments = append(appResp.Environments, app.Spec.Destination.Namespace) 74 | appResp.SyncStatus = append(appResp.SyncStatus, string(app.Status.Sync.Status)) 75 | appResp.LastDeployed = append(appResp.LastDeployed, lastDeployed.String()) 76 | appsMap[appName] = appResp 77 | } 78 | } 79 | 80 | var apps []appResponse 81 | for _, app := range appsMap { 82 | apps = append(apps, app) 83 | } 84 | 85 | return &appsResponse{Apps: apps} 86 | } 87 | -------------------------------------------------------------------------------- /pkg/httpapi/conversion_test.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "fmt" 5 | argoV1aplha1 "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1" 6 | "testing" 7 | "time" 8 | 9 | "github.com/google/go-cmp/cmp" 10 | ) 11 | 12 | func TestPipelinesToAppsResponse(t *testing.T) { 13 | raw := parseYAMLToConfig(t, "testdata/pipelines.yaml") 14 | 15 | apps := pipelinesToAppsResponse(raw) 16 | 17 | want := &appsResponse{ 18 | Apps: []appResponse{ 19 | { 20 | Name: "taxi", RepoURL: "https://example.com/demo/gitops.git", 21 | Environments: []string{"dev"}, 22 | SyncStatus: nil, 23 | LastDeployed: nil, 24 | }, 25 | }, 26 | } 27 | if diff := cmp.Diff(want, apps); diff != "" { 28 | t.Fatalf("failed to parse:\n%s", diff) 29 | } 30 | } 31 | 32 | func TestApplicationsToAppsResponse(t *testing.T) { 33 | var apps []*argoV1aplha1.Application 34 | app, _ := testArgoApplication("testdata/application.yaml") 35 | apps = append(apps, app) 36 | 37 | want := &appsResponse{ 38 | Apps: []appResponse{ 39 | { 40 | Name: "test-app", 41 | RepoURL: "https://github.com/test-repo/gitops.git", 42 | Environments: []string{"dev"}, 43 | SyncStatus: []string{"Synced"}, 44 | LastDeployed: []string{time.Date(2021, time.Month(5), 15, 2, 12, 13, 0, time.UTC).Local().String()}, 45 | }, 46 | }, 47 | } 48 | 49 | resp := applicationsToAppsResponse(apps, "https://github.com/test-repo/gitops") 50 | 51 | if diff := cmp.Diff(want, resp); diff != "" { 52 | t.Fatal(fmt.Errorf("WANT[%v] != RECEIVED[%v], diff=%s", want, resp, diff)) 53 | } 54 | 55 | resp = applicationsToAppsResponse(apps, "https://github.com/test-repo/gitops.git") 56 | 57 | if diff := cmp.Diff(want, resp); diff != "" { 58 | t.Fatal(fmt.Errorf("WANT[%v] != RECEIVED[%v], diff=%s", want, resp, diff)) 59 | } 60 | } 61 | 62 | func TestApplicationsToAppsResponseForTwoApps(t *testing.T) { 63 | var apps []*argoV1aplha1.Application 64 | app, _ := testArgoApplication("testdata/application.yaml") 65 | apps = append(apps, app) 66 | app2, _ := testArgoApplication("testdata/application2.yaml") 67 | apps = append(apps, app2) 68 | 69 | want := &appsResponse{ 70 | Apps: []appResponse{ 71 | { 72 | Name: "test-app", 73 | RepoURL: "https://github.com/test-repo/gitops.git", 74 | Environments: []string{"dev", "production"}, 75 | SyncStatus: []string{"Synced", "OutOfSync"}, 76 | LastDeployed: []string{time.Date(2021, time.Month(5), 15, 2, 12, 13, 0, time.UTC).Local().String(), 77 | time.Date(2021, time.Month(5), 16, 1, 10, 35, 0, time.UTC).Local().String()}, 78 | }, 79 | }, 80 | } 81 | 82 | resp := applicationsToAppsResponse(apps, "https://github.com/test-repo/gitops") 83 | 84 | if diff := cmp.Diff(want, resp); diff != "" { 85 | t.Fatal(fmt.Errorf("WANT[%v] != RECEIVED[%v], diff=%s", want, resp, diff)) 86 | } 87 | 88 | resp = applicationsToAppsResponse(apps, "https://github.com/test-repo/gitops.git") 89 | 90 | if diff := cmp.Diff(want, resp); diff != "" { 91 | t.Fatal(fmt.Errorf("WANT[%v] != RECEIVED[%v], diff=%s", want, resp, diff)) 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /pkg/httpapi/manifest.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | type appResponse struct { 4 | Name string `json:"name,omitempty"` 5 | RepoURL string `json:"repo_url,omitempty"` 6 | Environments []string `json:"environments,omitempty"` 7 | SyncStatus []string `json:"sync_status,omitempty"` 8 | LastDeployed []string `json:"last_deployed,omitempty"` 9 | } 10 | 11 | type appsResponse struct { 12 | Apps []appResponse `json:"applications"` 13 | } 14 | 15 | type config struct { 16 | GitOpsURL string `json:"gitops_url"` 17 | Environments []*environment `json:"environments,omitempty"` 18 | } 19 | 20 | type environment struct { 21 | Name string `json:"name,omitempty"` 22 | Cluster string `json:"cluster,omitempty"` 23 | Apps []*application `json:"apps,omitempty"` 24 | } 25 | 26 | type application struct { 27 | Name string `json:"name,omitempty"` 28 | Services []service `json:"services,omitempty"` 29 | } 30 | 31 | type envHealthResource struct { 32 | Name string `json:"name,omitempty"` 33 | Health string `json:"health,omitempty"` 34 | Status string `json:"status,omitempty"` 35 | } 36 | 37 | type envHistory struct { 38 | Author string `json:"author,omitempty"` 39 | Message string `json:"message,omitempty"` 40 | Revision string `json:"revision,omitempty"` 41 | Environment string `json:"environment,omitempty"` 42 | RepoUrl string `json:"repo_url,omitempty"` 43 | DeployedAt string `json:"deployed_at,omitempty"` 44 | } 45 | 46 | func (e environment) findService(n string) *service { 47 | for _, a := range e.Apps { 48 | for _, s := range a.Services { 49 | if s.Name == n { 50 | return &s 51 | } 52 | } 53 | } 54 | return nil 55 | } 56 | 57 | type service struct { 58 | Name string `json:"name"` 59 | SourceURL string `json:"source_url"` 60 | } 61 | 62 | func (c *config) findEnvironment(n string) *environment { 63 | for _, e := range c.Environments { 64 | if e.Name == n { 65 | return e 66 | } 67 | } 68 | return nil 69 | } 70 | -------------------------------------------------------------------------------- /pkg/httpapi/manifest_test.go: -------------------------------------------------------------------------------- 1 | package httpapi 2 | 3 | import ( 4 | "io/ioutil" 5 | "testing" 6 | 7 | "github.com/google/go-cmp/cmp" 8 | "sigs.k8s.io/yaml" 9 | ) 10 | 11 | func TestParse(t *testing.T) { 12 | b, err := ioutil.ReadFile("testdata/pipelines.yaml") 13 | if err != nil { 14 | t.Fatal(err) 15 | } 16 | 17 | parsed := &config{} 18 | err = yaml.Unmarshal(b, parsed) 19 | if err != nil { 20 | t.Fatal(err) 21 | } 22 | 23 | want := &config{ 24 | GitOpsURL: "https://example.com/demo/gitops.git", 25 | Environments: []*environment{ 26 | { 27 | Name: "dev", 28 | Cluster: "https://dev.testing.svc", 29 | Apps: []*application{ 30 | { 31 | Name: "taxi", 32 | Services: []service{ 33 | { 34 | Name: "gitops-demo", 35 | SourceURL: "https://example.com/demo/gitops-demo.git", 36 | }, 37 | }, 38 | }, 39 | }, 40 | }, 41 | {Name: "stage"}, 42 | }, 43 | } 44 | 45 | if diff := cmp.Diff(want, parsed); diff != "" { 46 | t.Fatalf("parsed:\n%s", diff) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /pkg/httpapi/secrets/config_factory.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "k8s.io/client-go/rest" 5 | ) 6 | 7 | // K8sRESTConfigFactory is an implementation of the RESTConfigFactory interface 8 | // that doles out configs based on a base one. 9 | type K8sRESTConfigFactory struct { 10 | insecure bool 11 | cfg *rest.Config 12 | } 13 | 14 | // Create implements the RESTConfigFactory interface. 15 | func (r *K8sRESTConfigFactory) Create(token string) (*rest.Config, error) { 16 | shallowCopy := *r.cfg 17 | shallowCopy.BearerToken = token 18 | if r.insecure { 19 | shallowCopy.TLSClientConfig = rest.TLSClientConfig{ 20 | Insecure: r.insecure, 21 | } 22 | } 23 | return &shallowCopy, nil 24 | } 25 | 26 | // NewRestConfigFactory creates and returns a RESTConfigFactory with a known 27 | // config. 28 | func NewRESTConfigFactory(cfg *rest.Config, insecure bool) *K8sRESTConfigFactory { 29 | return &K8sRESTConfigFactory{cfg: cfg, insecure: insecure} 30 | } 31 | -------------------------------------------------------------------------------- /pkg/httpapi/secrets/config_factory_test.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/google/go-cmp/cmp" 7 | "k8s.io/client-go/rest" 8 | ) 9 | 10 | var _ RESTConfigFactory = (*K8sRESTConfigFactory)(nil) 11 | 12 | func TestCreateClientFromToken(t *testing.T) { 13 | f := NewRESTConfigFactory(&rest.Config{}, false) 14 | 15 | cfg, err := f.Create("test-token") 16 | assertNoError(t, err) 17 | 18 | want := &rest.Config{BearerToken: "test-token"} 19 | if diff := cmp.Diff(want, cfg); diff != "" { 20 | t.Fatalf("incorrect client config:\n%s", diff) 21 | } 22 | } 23 | 24 | func TestCreateInsecureClientFromToken(t *testing.T) { 25 | f := NewRESTConfigFactory(&rest.Config{}, true) 26 | 27 | cfg, err := f.Create("new-token") 28 | assertNoError(t, err) 29 | 30 | want := &rest.Config{ 31 | BearerToken: "new-token", 32 | TLSClientConfig: rest.TLSClientConfig{ 33 | Insecure: true, 34 | }, 35 | } 36 | if diff := cmp.Diff(want, cfg); diff != "" { 37 | t.Fatalf("incorrect client config:\n%s", diff) 38 | } 39 | } 40 | 41 | func assertNoError(t *testing.T, err error) { 42 | t.Helper() 43 | if err != nil { 44 | t.Fatal(err) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /pkg/httpapi/secrets/interface.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "context" 5 | 6 | "k8s.io/apimachinery/pkg/types" 7 | "k8s.io/client-go/rest" 8 | ) 9 | 10 | // SecretGetter takes a namespaced name and finds a secret with that name, or 11 | // returns an error. 12 | type SecretGetter interface { 13 | SecretToken(ctx context.Context, authToken string, id types.NamespacedName, key string) (string, error) 14 | } 15 | 16 | // RESTConfigFactory creates and returns new Kubernetes client configurations 17 | // for accessing the API. 18 | type RESTConfigFactory interface { 19 | Create(token string) (*rest.Config, error) 20 | } 21 | -------------------------------------------------------------------------------- /pkg/httpapi/secrets/mock.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "strings" 7 | 8 | "k8s.io/apimachinery/pkg/types" 9 | ) 10 | 11 | var _ SecretGetter = (*MockSecret)(nil) 12 | 13 | // NewMock returns a simple secret getter. 14 | func NewMock() MockSecret { 15 | return MockSecret{} 16 | } 17 | 18 | // MockSecret implements the SecretGetter interface. 19 | type MockSecret struct { 20 | secrets map[string]string 21 | } 22 | 23 | // Secret implements the SecretGetter interface. 24 | func (k MockSecret) SecretToken(ctx context.Context, authToken string, secretID types.NamespacedName, key string) (string, error) { 25 | token, ok := k.secrets[mockKey(authToken, secretID, key)] 26 | if !ok { 27 | return "", fmt.Errorf("mock not found") 28 | } 29 | return token, nil 30 | } 31 | 32 | // AddStubResponse is a mock method that sets up a token to be returned. 33 | func (k MockSecret) AddStubResponse(authToken string, secretID types.NamespacedName, token, key string) { 34 | k.secrets[mockKey(authToken, secretID, key)] = token 35 | } 36 | 37 | func mockKey(token string, n types.NamespacedName, key string) string { 38 | return strings.Join([]string{token, n.Name, n.Namespace, key}, ":") 39 | } 40 | -------------------------------------------------------------------------------- /pkg/httpapi/secrets/secrets.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | 7 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 8 | "k8s.io/apimachinery/pkg/types" 9 | "k8s.io/client-go/kubernetes" 10 | "k8s.io/client-go/rest" 11 | ) 12 | 13 | // KubeSecretGetter is an implementation of SecretGetter. 14 | type KubeSecretGetter struct { 15 | configFactory RESTConfigFactory 16 | clientFactory func(*rest.Config) (kubernetes.Interface, error) 17 | } 18 | 19 | // NewFromConfig creates a secret getter from a rest.Config. 20 | func NewFromConfig(cfg *rest.Config, insecure bool) *KubeSecretGetter { 21 | return New(NewRESTConfigFactory(cfg, insecure)) 22 | } 23 | 24 | // New creates and returns a KubeSecretGetter that looks up secrets in k8s. 25 | func New(c RESTConfigFactory) *KubeSecretGetter { 26 | return &KubeSecretGetter{ 27 | configFactory: c, 28 | clientFactory: func(c *rest.Config) (kubernetes.Interface, error) { 29 | return kubernetes.NewForConfig(c) 30 | }, 31 | } 32 | } 33 | 34 | // SecretToken looks for a namespaced secret, and returns the 'token' key from 35 | // it, or an error if not found. 36 | func (k KubeSecretGetter) SecretToken(ctx context.Context, authToken string, id types.NamespacedName, key string) (string, error) { 37 | cfg, err := k.configFactory.Create(authToken) 38 | if err != nil { 39 | return "", fmt.Errorf("failed to create a REST config: %w", err) 40 | } 41 | coreClient, err := k.clientFactory(cfg) 42 | if err != nil { 43 | return "", fmt.Errorf("failed to create a client from the config: %w", err) 44 | } 45 | 46 | secret, err := coreClient.CoreV1().Secrets(id.Namespace).Get(ctx, id.Name, metav1.GetOptions{}) 47 | if err != nil { 48 | return "", fmt.Errorf("error getting secret %s/%s: %w", id.Namespace, id.Name, err) 49 | } 50 | token, ok := secret.Data[key] 51 | if !ok { 52 | return "", fmt.Errorf("secret invalid, no 'token' key in %s/%s", id.Namespace, id.Name) 53 | } 54 | return string(token), nil 55 | } 56 | -------------------------------------------------------------------------------- /pkg/httpapi/secrets/secrets_test.go: -------------------------------------------------------------------------------- 1 | package secrets 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "testing" 7 | 8 | corev1 "k8s.io/api/core/v1" 9 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 10 | "k8s.io/apimachinery/pkg/types" 11 | "k8s.io/client-go/kubernetes" 12 | "k8s.io/client-go/kubernetes/fake" 13 | "k8s.io/client-go/rest" 14 | ) 15 | 16 | var _ SecretGetter = (*KubeSecretGetter)(nil) 17 | 18 | var testID = types.NamespacedName{Name: "test-secret", Namespace: "test-ns"} 19 | 20 | func TestSecret(t *testing.T) { 21 | g := New(&stubConfigFactory{}) 22 | g.clientFactory = func(c *rest.Config) (kubernetes.Interface, error) { 23 | if c.BearerToken == "auth token" { 24 | return fake.NewSimpleClientset(createSecret(testID, "secret-token")), nil 25 | } 26 | return nil, errors.New("failed") 27 | } 28 | 29 | secret, err := g.SecretToken(context.TODO(), "auth token", testID, "token") 30 | if err != nil { 31 | t.Fatal(err) 32 | } 33 | 34 | if secret != "secret-token" { 35 | t.Fatalf("got %s, want secret-token", secret) 36 | } 37 | } 38 | 39 | func TestSecretWithMissingSecret(t *testing.T) { 40 | g := New(&stubConfigFactory{}) 41 | g.clientFactory = func(c *rest.Config) (kubernetes.Interface, error) { 42 | if c.BearerToken == "auth token" { 43 | return fake.NewSimpleClientset(), nil 44 | } 45 | return nil, errors.New("failed") 46 | } 47 | 48 | _, err := g.SecretToken(context.TODO(), "auth token", testID, "token") 49 | if err.Error() != `error getting secret test-ns/test-secret: secrets "test-secret" not found` { 50 | t.Fatal(err) 51 | } 52 | } 53 | 54 | func createSecret(id types.NamespacedName, token string) *corev1.Secret { 55 | return &corev1.Secret{ 56 | TypeMeta: metav1.TypeMeta{ 57 | Kind: "Secret", 58 | APIVersion: "v1", 59 | }, 60 | ObjectMeta: metav1.ObjectMeta{ 61 | Name: id.Name, 62 | Namespace: id.Namespace, 63 | }, 64 | Type: corev1.SecretTypeOpaque, 65 | Data: map[string][]byte{ 66 | "token": []byte(token), 67 | }, 68 | } 69 | } 70 | 71 | type stubConfigFactory struct { 72 | } 73 | 74 | func (s *stubConfigFactory) Create(token string) (*rest.Config, error) { 75 | return &rest.Config{BearerToken: token}, nil 76 | } 77 | -------------------------------------------------------------------------------- /pkg/httpapi/testdata/application.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: argoproj.io/v1alpha1 2 | kind: Application 3 | metadata: 4 | labels: 5 | app.kubernetes.io/name: test-app 6 | name: dev-test-app 7 | namespace: test-namespace 8 | spec: 9 | destination: 10 | namespace: dev 11 | server: https://kubernetes.default.svc 12 | project: default 13 | source: 14 | path: environments/dev/apps/app-taxi/overlays 15 | repoURL: https://github.com/test-repo/gitops.git 16 | status: 17 | history: 18 | - deployedAt: "2021-05-15T02:12:13Z" 19 | revision: "123456789" 20 | sync: 21 | status: Synced 22 | resources: 23 | - health: 24 | status: Healthy 25 | kind: Service 26 | name: taxi 27 | namespace: dev 28 | status: Synced 29 | version: v1 30 | - group: apps 31 | health: 32 | status: Healthy 33 | kind: Deployment 34 | name: taxi 35 | namespace: dev 36 | status: Synced 37 | version: v1 38 | - group: route.openshift.io 39 | kind: Route 40 | name: taxi 41 | namespace: dev 42 | status: Synced 43 | version: v1 44 | - group: apps 45 | health: 46 | status: Missing 47 | kind: Secret 48 | name: testsecret 49 | namespace: dev 50 | status: OutOfSync 51 | version: v1 52 | - group: rbac.authorization.k8s.io 53 | kind: ClusterRole 54 | name: pipelines-clusterrole 55 | status: Synced 56 | version: v1 57 | - group: rbac.authorization.k8s.io 58 | kind: ClusterRoleBinding 59 | name: pipelines-service-role-binding 60 | status: Synced 61 | version: v1 62 | - group: rbac.authorization.k8s.io 63 | kind: RoleBinding 64 | name: argocd-admin 65 | namespace: cicd 66 | status: Synced 67 | version: v1 68 | -------------------------------------------------------------------------------- /pkg/httpapi/testdata/application2.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: argoproj.io/v1alpha1 2 | kind: Application 3 | metadata: 4 | labels: 5 | app.kubernetes.io/name: test-app 6 | name: production-test-app 7 | namespace: test-namespace 8 | spec: 9 | destination: 10 | namespace: production 11 | server: https://kubernetes.default.svc 12 | project: default 13 | source: 14 | path: environments/production/apps/app-taxi/overlays 15 | repoURL: https://github.com/test-repo/gitops.git 16 | status: 17 | history: 18 | - deployedAt: "2021-05-10T01:10:35Z" 19 | - deployedAt: "2021-05-16T01:10:35Z" 20 | sync: 21 | status: OutOfSync 22 | -------------------------------------------------------------------------------- /pkg/httpapi/testdata/application3.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: argoproj.io/v1alpha1 2 | kind: Application 3 | metadata: 4 | labels: 5 | app.kubernetes.io/instance: argo-app 6 | app.kubernetes.io/name: app-taxi 7 | name: dev-app-taxi 8 | namespace: test-namespace 9 | spec: 10 | destination: 11 | namespace: dev 12 | server: https://kubernetes.default.svc 13 | project: default 14 | source: 15 | path: environments/dev/apps/app-taxi/overlays 16 | repoURL: https://github.com/test-repo/gitops.git 17 | status: 18 | health: 19 | status: Healthy 20 | history: 21 | - deployStartedAt: "2022-04-19T18:19:50Z" 22 | deployedAt: "2022-04-19T18:19:52Z" 23 | id: 0 24 | revision: e5585fcf22366e2d066e0936cbd8a0508756d02d 25 | source: 26 | path: environments/dev/apps/app-taxi/overlays 27 | repoURL: https://github.com/test-repo/gitops.git 28 | - deployStartedAt: "2022-04-21T14:14:25Z" 29 | deployedAt: "2022-04-21T14:14:27Z" 30 | id: 1 31 | revision: e5585fcf22366e2d066e0936cbd8a0508756d02d 32 | source: 33 | path: environments/dev/apps/app-taxi/overlays 34 | repoURL: https://github.com/test-repo/gitops.git 35 | - deployStartedAt: "2022-04-21T14:16:46Z" 36 | deployedAt: "2022-04-21T14:16:50Z" 37 | id: 2 38 | revision: 3f6965bd65d9294b8fec5d6e2dc3dad08e33a8fe 39 | source: 40 | path: environments/dev/apps/app-taxi/overlays 41 | repoURL: https://github.com/test-repo/gitops.git 42 | - deployStartedAt: "2022-04-21T14:16:50Z" 43 | deployedAt: "2022-04-21T14:16:51Z" 44 | id: 3 45 | revision: e5585fcf22366e2d066e0936cbd8a0508756d02d 46 | source: 47 | path: environments/dev/apps/app-taxi/overlays 48 | repoURL: https://github.com/test-repo/gitops.git 49 | - deployStartedAt: "2022-04-21T14:17:48Z" 50 | deployedAt: "2022-04-21T14:17:49Z" 51 | id: 4 52 | revision: 3f6965bd65d9294b8fec5d6e2dc3dad08e33a8fe 53 | source: 54 | path: environments/dev/apps/app-taxi/overlays 55 | repoURL: https://github.com/test-repo/gitops.git 56 | - deployStartedAt: "2022-04-22T17:11:29Z" 57 | deployedAt: "2022-04-22T17:11:29Z" 58 | id: 5 59 | revision: a0c7298faead28f7f60a5106afbb18882ad220a7 60 | source: 61 | path: environments/dev/apps/app-taxi/overlays 62 | repoURL: https://github.com/test-repo/gitops.git 63 | operationState: 64 | finishedAt: "2022-04-22T17:11:29Z" 65 | message: successfully synced (all tasks run) 66 | operation: 67 | initiatedBy: 68 | automated: true 69 | retry: 70 | limit: 5 71 | sync: 72 | prune: true 73 | revision: a0c7298faead28f7f60a5106afbb18882ad220a7 74 | phase: Succeeded 75 | startedAt: "2022-04-22T17:11:29Z" 76 | syncResult: 77 | resources: 78 | - group: "" 79 | hookPhase: Running 80 | kind: Service 81 | message: service/taxi configured 82 | name: taxi 83 | namespace: dev 84 | status: Synced 85 | syncPhase: Sync 86 | version: v1 87 | - group: apps 88 | hookPhase: Running 89 | kind: Deployment 90 | message: deployment.apps/taxi configured 91 | name: taxi 92 | namespace: dev 93 | status: Synced 94 | syncPhase: Sync 95 | version: v1 96 | - group: route.openshift.io 97 | hookPhase: Running 98 | kind: Route 99 | message: route.route.openshift.io/taxi unchanged 100 | name: taxi 101 | namespace: dev 102 | status: Synced 103 | syncPhase: Sync 104 | version: v1 105 | revision: a0c7298faead28f7f60a5106afbb18882ad220a7 106 | source: 107 | path: environments/dev/apps/app-taxi/overlays 108 | repoURL: https://github.com/test-repo/gitops.git 109 | reconciledAt: "2022-04-28T18:36:56Z" 110 | resources: 111 | - health: 112 | status: Healthy 113 | kind: Service 114 | name: taxi 115 | namespace: dev 116 | status: Synced 117 | version: v1 118 | - group: apps 119 | health: 120 | status: Healthy 121 | kind: Deployment 122 | name: taxi 123 | namespace: dev 124 | status: Synced 125 | version: v1 126 | - group: route.openshift.io 127 | health: 128 | message: Route is healthy 129 | status: Healthy 130 | kind: Route 131 | name: taxi 132 | namespace: dev 133 | status: Synced 134 | version: v1 135 | sourceType: Kustomize 136 | summary: 137 | images: 138 | - nginxinc/nginx-unprivileged:latest 139 | sync: 140 | comparedTo: 141 | destination: 142 | namespace: dev 143 | server: https://kubernetes.default.svc 144 | source: 145 | path: environments/dev/apps/app-taxi/overlays 146 | repoURL: https://github.com/test-repo/gitops.git 147 | revision: a0c7298faead28f7f60a5106afbb18882ad220a7 148 | status: Synced 149 | -------------------------------------------------------------------------------- /pkg/httpapi/testdata/pipelines.yaml: -------------------------------------------------------------------------------- 1 | config: 2 | argocd: 3 | namespace: argocd 4 | pipelines: 5 | name: cicd 6 | environments: 7 | - cluster: https://dev.testing.svc 8 | apps: 9 | - name: taxi 10 | services: 11 | - name: gitops-demo 12 | pipelines: 13 | integration: 14 | bindings: 15 | - dev-app-gitops-demo-gitops-demo-binding 16 | - github-push-binding 17 | source_url: https://example.com/demo/gitops-demo.git 18 | webhook: 19 | secret: 20 | name: webhook-secret-dev-gitops-demo 21 | namespace: cicd 22 | name: dev 23 | pipelines: 24 | integration: 25 | bindings: 26 | - github-push-binding 27 | template: app-ci-template 28 | - name: stage 29 | gitops_url: https://example.com/demo/gitops.git 30 | -------------------------------------------------------------------------------- /pkg/logger/interface.go: -------------------------------------------------------------------------------- 1 | package logger 2 | 3 | // Logger is the interface that defines the behaviour for logging throughout 4 | // this service. 5 | type Logger interface { 6 | Infof(template string, args ...interface{}) 7 | Infow(msg string, keysAndValues ...interface{}) 8 | Errorf(template string, args ...interface{}) 9 | Errorw(msg string, keysAndValues ...interface{}) 10 | } 11 | -------------------------------------------------------------------------------- /pkg/logger/sugar.go: -------------------------------------------------------------------------------- 1 | package logger 2 | 3 | import ( 4 | "log" 5 | 6 | "go.uber.org/zap" 7 | ) 8 | 9 | func MakeLogger() Logger { 10 | logger, _ := zap.NewProduction() 11 | defer func() { 12 | err := logger.Sync() // flushes buffer, if any 13 | if err != nil { 14 | log.Fatal(err) 15 | } 16 | }() 17 | return logger.Sugar() 18 | } 19 | -------------------------------------------------------------------------------- /pkg/metrics/interface.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | // Interface implementations provide metrics for the system. 4 | type Interface interface { 5 | // CountAPICall records API calls to the upstream hosting service. 6 | CountAPICall(name string) 7 | 8 | // CountFailedAPICall records failed API calls to the upstream hosting service. 9 | CountFailedAPICall(name string) 10 | } 11 | -------------------------------------------------------------------------------- /pkg/metrics/metrics.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "github.com/prometheus/client_golang/prometheus" 5 | ) 6 | 7 | // PrometheusMetrics is a wrapper around Prometheus metrics for counting 8 | // events in the system. 9 | type PrometheusMetrics struct { 10 | apiCalls *prometheus.CounterVec 11 | failedAPICalls *prometheus.CounterVec 12 | } 13 | 14 | // New creates and returns a PrometheusMetrics initialised with prometheus 15 | // counters. 16 | func New(ns string, reg prometheus.Registerer) *PrometheusMetrics { 17 | pm := &PrometheusMetrics{} 18 | if reg == nil { 19 | reg = prometheus.DefaultRegisterer 20 | } 21 | 22 | pm.apiCalls = prometheus.NewCounterVec(prometheus.CounterOpts{ 23 | Namespace: ns, 24 | Name: "api_calls_total", 25 | Help: "Count of API Calls made", 26 | }, []string{"kind"}) 27 | 28 | pm.failedAPICalls = prometheus.NewCounterVec(prometheus.CounterOpts{ 29 | Namespace: ns, 30 | Name: "failed_api_calls_total", 31 | Help: "Count of failed API Calls made", 32 | }, []string{"kind"}) 33 | 34 | reg.MustRegister(pm.apiCalls) 35 | reg.MustRegister(pm.failedAPICalls) 36 | return pm 37 | } 38 | 39 | // CountAPICall records outgoing API calls to upstream services. 40 | func (m *PrometheusMetrics) CountAPICall(name string) { 41 | m.apiCalls.With(prometheus.Labels{"kind": name}).Inc() 42 | } 43 | 44 | // CountFailedAPICall records failled outgoing API calls to upstream services. 45 | func (m *PrometheusMetrics) CountFailedAPICall(name string) { 46 | m.failedAPICalls.With(prometheus.Labels{"kind": name}).Inc() 47 | } 48 | -------------------------------------------------------------------------------- /pkg/metrics/metrics_test.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | 7 | "github.com/prometheus/client_golang/prometheus" 8 | "github.com/prometheus/client_golang/prometheus/testutil" 9 | ) 10 | 11 | var _ Interface = (*PrometheusMetrics)(nil) 12 | 13 | func TestCountAPICall(t *testing.T) { 14 | m := New("dsl", prometheus.NewRegistry()) 15 | m.CountAPICall("file_contents") 16 | 17 | err := testutil.CollectAndCompare(m.apiCalls, strings.NewReader(` 18 | # HELP dsl_api_calls_total Count of API Calls made 19 | # TYPE dsl_api_calls_total counter 20 | dsl_api_calls_total{kind="file_contents"} 1 21 | `)) 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | } 26 | 27 | func TestCountFailedAPICall(t *testing.T) { 28 | m := New("dsl", prometheus.NewRegistry()) 29 | m.CountFailedAPICall("commit_status") 30 | 31 | err := testutil.CollectAndCompare(m.failedAPICalls, strings.NewReader(` 32 | # HELP dsl_failed_api_calls_total Count of failed API Calls made 33 | # TYPE dsl_failed_api_calls_total counter 34 | dsl_failed_api_calls_total{kind="commit_status"} 1 35 | `)) 36 | if err != nil { 37 | t.Fatal(err) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /pkg/metrics/mock.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | var _ Interface = (*MockMetrics)(nil) 4 | 5 | // MockMetrics is a type that provides a simple counter for metrics for test 6 | // purposes. 7 | type MockMetrics struct { 8 | APICalls int 9 | FailedAPICalls int 10 | } 11 | 12 | // NewMock creates and returns a MockMetrics. 13 | func NewMock() *MockMetrics { 14 | return &MockMetrics{} 15 | } 16 | 17 | // CountAPICall records outgoing API calls to upstream services. 18 | func (m *MockMetrics) CountAPICall(name string) { 19 | m.APICalls++ 20 | } 21 | 22 | // CountFailedAPICall records failed outgoing API calls to upstream services. 23 | func (m *MockMetrics) CountFailedAPICall(name string) { 24 | m.FailedAPICalls++ 25 | } 26 | -------------------------------------------------------------------------------- /pkg/parser/converter.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | ocpappsv1 "github.com/openshift/api/apps/v1" 5 | appsv1 "k8s.io/api/apps/v1" 6 | batchv1 "k8s.io/api/batch/v1" 7 | batchv1beta1 "k8s.io/api/batch/v1beta1" 8 | corev1 "k8s.io/api/core/v1" 9 | 10 | "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 11 | "k8s.io/apimachinery/pkg/runtime" 12 | ) 13 | 14 | // unstructuredConverter handles conversions between unstructured.Unstructured 15 | // and some core Kubernetes resource types. 16 | type unstructuredConverter struct { 17 | scheme *runtime.Scheme 18 | } 19 | 20 | // newUnstructuredConverter creates and returns a new UnstructuredConverter. 21 | func newUnstructuredConverter() (*unstructuredConverter, error) { 22 | schemeBuilder := runtime.SchemeBuilder{ 23 | corev1.AddToScheme, 24 | appsv1.AddToScheme, 25 | batchv1.AddToScheme, 26 | batchv1beta1.AddToScheme, 27 | ocpappsv1.AddToScheme, 28 | } 29 | 30 | uc := &unstructuredConverter{ 31 | scheme: runtime.NewScheme(), 32 | } 33 | 34 | if err := schemeBuilder.AddToScheme(uc.scheme); err != nil { 35 | return nil, err 36 | } 37 | return uc, nil 38 | } 39 | 40 | // fromUnstructured converts an unstructured.Unstructured to typed struct. 41 | // 42 | // If unable to convert using the Kind of obj, then an error is returned. 43 | func (c *unstructuredConverter) fromUnstructured(o *unstructured.Unstructured) (interface{}, error) { 44 | newObj, err := c.scheme.New(o.GetObjectKind().GroupVersionKind()) 45 | if err != nil { 46 | return nil, err 47 | } 48 | return newObj, c.scheme.Convert(o, newObj, nil) 49 | } 50 | -------------------------------------------------------------------------------- /pkg/parser/extracts.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | ocpappsv1 "github.com/openshift/api/apps/v1" 5 | appsv1 "k8s.io/api/apps/v1" 6 | batchv1 "k8s.io/api/batch/v1" 7 | batchv1beta1 "k8s.io/api/batch/v1beta1" 8 | corev1 "k8s.io/api/core/v1" 9 | 10 | "github.com/redhat-developer/gitops-backend/internal/sets" 11 | ) 12 | 13 | // Deployments, DeploymentConfigs, StatefulSets, DaemonSets, Jobs, CronJobs 14 | func extractImages(v interface{}) []string { 15 | switch k := v.(type) { 16 | case *appsv1.Deployment: 17 | return extractImagesFromPodTemplateSpec(k.Spec.Template) 18 | case *appsv1.StatefulSet: 19 | return extractImagesFromPodTemplateSpec(k.Spec.Template) 20 | case *appsv1.DaemonSet: 21 | return extractImagesFromPodTemplateSpec(k.Spec.Template) 22 | case *batchv1.Job: 23 | return extractImagesFromPodTemplateSpec(k.Spec.Template) 24 | case *batchv1beta1.CronJob: 25 | return extractImagesFromPodTemplateSpec(k.Spec.JobTemplate.Spec.Template) 26 | case *ocpappsv1.DeploymentConfig: 27 | return extractImagesFromPodTemplateSpec(*k.Spec.Template) 28 | } 29 | return nil 30 | } 31 | 32 | func extractImagesFromPodTemplateSpec(p corev1.PodTemplateSpec) []string { 33 | images := sets.NewStringSet() 34 | for _, c := range p.Spec.InitContainers { 35 | images.Add(c.Image) 36 | } 37 | for _, c := range p.Spec.Containers { 38 | images.Add(c.Image) 39 | } 40 | return images.Elements() 41 | } 42 | -------------------------------------------------------------------------------- /pkg/parser/extracts_test.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/google/go-cmp/cmp" 7 | corev1 "k8s.io/api/core/v1" 8 | ) 9 | 10 | func TestExtractImagesFromPodTemplateSpec(t *testing.T) { 11 | spec := corev1.PodTemplateSpec{ 12 | Spec: corev1.PodSpec{ 13 | InitContainers: []corev1.Container{ 14 | {Name: "redis", Image: "redis:6-alpine"}, 15 | {Name: "redis-test", Image: "redis:6-alpine"}, 16 | }, 17 | Containers: []corev1.Container{ 18 | {Name: "http", Image: "example/http-api"}, 19 | }, 20 | }, 21 | } 22 | 23 | images := extractImagesFromPodTemplateSpec(spec) 24 | 25 | want := []string{"example/http-api", "redis:6-alpine"} 26 | if diff := cmp.Diff(want, images); diff != "" { 27 | t.Fatalf("set failed:\n%s", diff) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /pkg/parser/interfaces.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "github.com/go-git/go-git/v5" 5 | ) 6 | 7 | // ResourceParser implementations should fetch the source using the CloneOptions and 8 | // parse the resources in the path into a set of resource.Resource values. 9 | type ResourceParser func(path string, opts *git.CloneOptions) ([]*Resource, error) 10 | -------------------------------------------------------------------------------- /pkg/parser/parser.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "github.com/go-git/go-git/v5" 5 | 6 | "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 7 | "sigs.k8s.io/kustomize/k8sdeps" 8 | "sigs.k8s.io/kustomize/pkg/fs" 9 | "sigs.k8s.io/kustomize/pkg/loader" 10 | "sigs.k8s.io/kustomize/pkg/resource" 11 | "sigs.k8s.io/kustomize/pkg/target" 12 | 13 | "github.com/redhat-developer/gitops-backend/pkg/gitfs" 14 | ) 15 | 16 | // ParseFromGit takes a go-git CloneOptions struct and a filepath, and extracts 17 | // the service configuration from there. 18 | func ParseFromGit(path string, opts *git.CloneOptions) ([]*Resource, error) { 19 | gfs, err := gitfs.NewInMemoryFromOptions(opts) 20 | if err != nil { 21 | return nil, err 22 | } 23 | return parseConfig(path, gfs) 24 | } 25 | 26 | func parseConfig(path string, files fs.FileSystem) ([]*Resource, error) { 27 | k8sfactory := k8sdeps.NewFactory() 28 | ldr, err := loader.NewLoader(path, files) 29 | if err != nil { 30 | return nil, err 31 | } 32 | defer func() { 33 | err = ldr.Cleanup() 34 | if err != nil { 35 | panic(err) 36 | } 37 | }() 38 | kt, err := target.NewKustTarget(ldr, k8sfactory.ResmapF, k8sfactory.TransformerF) 39 | if err != nil { 40 | return nil, err 41 | } 42 | r, err := kt.MakeCustomizedResMap() 43 | if err != nil { 44 | return nil, err 45 | } 46 | if len(r) == 0 { 47 | return nil, nil 48 | } 49 | 50 | conv, err := newUnstructuredConverter() 51 | if err != nil { 52 | return nil, err 53 | } 54 | resources := []*Resource{} 55 | for _, v := range r { 56 | resources = append(resources, extractResource(conv, v)) 57 | } 58 | return resources, nil 59 | } 60 | 61 | // convert the Kustomize Resource into an internal representation, extracting 62 | // the images if possible. 63 | // 64 | // If this is an unknown type (to the converter) no images will be extracted. 65 | func extractResource(conv *unstructuredConverter, res *resource.Resource) *Resource { 66 | c := convert(res) 67 | g := c.GroupVersionKind() 68 | r := &Resource{ 69 | Name: c.GetName(), 70 | Namespace: c.GetNamespace(), 71 | Group: g.Group, 72 | Version: g.Version, 73 | Kind: g.Kind, 74 | Labels: c.GetLabels(), 75 | } 76 | t, err := conv.fromUnstructured(c) 77 | if err != nil { 78 | return r 79 | } 80 | r.Images = extractImages(t) 81 | return r 82 | } 83 | 84 | // convert converts a Kustomize resource into a generic Unstructured resource 85 | // which which the unstructured converter uses to create resources from. 86 | func convert(r *resource.Resource) *unstructured.Unstructured { 87 | return &unstructured.Unstructured{ 88 | Object: r.Map(), 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /pkg/parser/parser_test.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "sort" 5 | "strings" 6 | "testing" 7 | 8 | "github.com/go-git/go-git/v5" 9 | "github.com/google/go-cmp/cmp" 10 | 11 | "github.com/redhat-developer/gitops-backend/test" 12 | ) 13 | 14 | const ( 15 | nameLabel = "app.kubernetes.io/name" 16 | partOfLabel = "app.kubernetes.io/part-of" 17 | ) 18 | 19 | func TestParseNoFile(t *testing.T) { 20 | res, err := ParseFromGit( 21 | "testdata", 22 | &git.CloneOptions{ 23 | URL: "../..", 24 | Depth: 1, 25 | }) 26 | 27 | if res != nil { 28 | t.Errorf("did not expect to parse resources: %#v", res) 29 | } 30 | if err == nil { 31 | t.Fatal("expected to get an error") 32 | } 33 | } 34 | 35 | func resKey(r *Resource) string { 36 | return strings.Join([]string{r.Name, r.Namespace, r.Group, r.Kind, r.Version}, "-") 37 | } 38 | 39 | func TestParseFromGit(t *testing.T) { 40 | res, err := ParseFromGit( 41 | "pkg/parser/testdata/go-demo", 42 | test.MakeCloneOptions()) 43 | if err != nil { 44 | t.Fatal(err) 45 | } 46 | sort.SliceStable(res, func(i, j int) bool { return resKey(res[i]) < resKey(res[j]) }) 47 | 48 | want := []*Resource{ 49 | { 50 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "go-demo-http", 51 | Labels: map[string]string{ 52 | nameLabel: "go-demo", 53 | partOfLabel: "go-demo", 54 | }, 55 | Images: []string{"bigkevmcd/go-demo:876ecb3"}, 56 | }, 57 | { 58 | Version: "v1", Kind: "Service", Name: "go-demo-http", 59 | Labels: map[string]string{ 60 | nameLabel: "go-demo", 61 | partOfLabel: "go-demo", 62 | }, 63 | }, 64 | { 65 | Version: "v1", Kind: "ConfigMap", Name: "go-demo-config", 66 | Labels: map[string]string{ 67 | partOfLabel: "go-demo", 68 | }, 69 | }, 70 | { 71 | Version: "v1", Kind: "Service", Name: "redis", 72 | Labels: map[string]string{ 73 | nameLabel: "redis", 74 | partOfLabel: "go-demo", 75 | }, 76 | }, 77 | { 78 | Group: "apps", Version: "v1", Kind: "Deployment", Name: "redis", 79 | Labels: map[string]string{ 80 | nameLabel: "redis", 81 | partOfLabel: "go-demo", 82 | }, 83 | Images: []string{"redis:6-alpine"}, 84 | }, 85 | { 86 | Group: "apps", 87 | Version: "v1", 88 | Kind: "StatefulSet", 89 | Name: "go-demo-web", 90 | Labels: map[string]string{ 91 | partOfLabel: "go-demo", 92 | nameLabel: "go-demo", 93 | }, 94 | Images: []string{"bigkevmcd/go-demo-api:v0.0.1"}, 95 | }, 96 | { 97 | Group: "batch", 98 | Version: "v1", 99 | Kind: "Job", 100 | Name: "demo-job", 101 | Labels: map[string]string{ 102 | nameLabel: "go-demo", 103 | partOfLabel: "go-demo", 104 | }, 105 | Images: []string{"bigkevmcd/go-demo:876ecb3"}, 106 | }, 107 | { 108 | Group: "batch", 109 | Version: "v1beta1", 110 | Kind: "CronJob", 111 | Name: "hello", 112 | Labels: map[string]string{ 113 | nameLabel: "go-demo", 114 | partOfLabel: "go-demo"}, 115 | Images: []string{"alpine:latest"}, 116 | }, 117 | { 118 | Version: "v1", 119 | Group: "apps.openshift.io", 120 | Kind: "DeploymentConfig", 121 | Name: "frontend", 122 | Labels: map[string]string{ 123 | nameLabel: "go-demo", 124 | partOfLabel: "go-demo"}, 125 | Images: []string{"demo/demo-config:v5"}, 126 | }, 127 | } 128 | sort.SliceStable(want, func(i, j int) bool { return resKey(want[i]) < resKey(want[j]) }) 129 | assertCmp(t, want, res, "failed to match parsed resources") 130 | } 131 | 132 | func assertCmp(t *testing.T, want, got interface{}, msg string) { 133 | t.Helper() 134 | if diff := cmp.Diff(want, got); diff != "" { 135 | t.Fatalf(msg+":\n%s", diff) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /pkg/parser/resource.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | // Object a basic object for a Kubernetes object. 4 | type Resource struct { 5 | Group string `json:"group"` 6 | Version string `json:"version"` 7 | Kind string `json:"kind"` 8 | Name string `json:"name"` 9 | Namespace string `json:"namespace"` 10 | Labels map[string]string `json:"-"` 11 | Images []string `json:"-"` 12 | } 13 | -------------------------------------------------------------------------------- /pkg/parser/testdata/app1/kustomization.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/redhat-developer/gitops-backend/d83d568a6131e2564353a6ec1294d28635783616/pkg/parser/testdata/app1/kustomization.yaml -------------------------------------------------------------------------------- /pkg/parser/testdata/app2/kustomization.yaml: -------------------------------------------------------------------------------- 1 | bases: 2 | - https://github.com/bigkevmcd/taxi/deploy 3 | images: 4 | - name: quay.io/kmcdermo/taxi 5 | newTag: "147036" 6 | patchesJson6902: 7 | - target: 8 | version: v1 9 | group: apps 10 | kind: Deployment 11 | name: taxi 12 | path: staging_patch.yaml 13 | -------------------------------------------------------------------------------- /pkg/parser/testdata/app2/staging_patch.yaml: -------------------------------------------------------------------------------- 1 | - op: replace 2 | path: /spec/template/spec/volumes/0/configMap/name 3 | value: stage-www-files 4 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/configMap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: go-demo-config 5 | data: 6 | REDIS_URL: redis://redis:6379/0 7 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/cron_job.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: batch/v1beta1 2 | kind: CronJob 3 | metadata: 4 | name: hello 5 | labels: 6 | app.kubernetes.io/name: go-demo 7 | spec: 8 | schedule: "*/1 * * * *" 9 | jobTemplate: 10 | spec: 11 | template: 12 | spec: 13 | containers: 14 | - name: hello 15 | image: alpine:latest 16 | restartPolicy: OnFailure 17 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: go-demo-http 5 | labels: 6 | app.kubernetes.io/name: go-demo 7 | spec: 8 | selector: 9 | matchLabels: 10 | app.kubernetes.io/name: go-demo 11 | replicas: 1 12 | template: 13 | metadata: 14 | labels: 15 | app.kubernetes.io/name: go-demo 16 | spec: 17 | containers: 18 | - name: http 19 | image: bigkevmcd/go-demo:876ecb3 20 | ports: 21 | - containerPort: 8080 22 | envFrom: 23 | - configMapRef: 24 | name: go-demo-config 25 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/deployment_config.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps.openshift.io/v1 2 | kind: DeploymentConfig 3 | metadata: 4 | name: frontend 5 | labels: 6 | app.kubernetes.io/name: go-demo 7 | spec: 8 | replicas: 5 9 | selector: 10 | app.kubernetes.io/name: go-demo 11 | template: 12 | metadata: 13 | labels: 14 | app.kubernetes.io/name: go-demo 15 | spec: 16 | containers: 17 | - image: demo/demo-config:v5 18 | name: demo-service 19 | triggers: 20 | - type: ConfigChange 21 | - imageChangeParams: 22 | automatic: true 23 | containerNames: 24 | - helloworld 25 | from: 26 | kind: ImageStreamTag 27 | name: hello-openshift:latest 28 | type: ImageChange 29 | strategy: 30 | type: Rolling 31 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/job.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: batch/v1 2 | kind: Job 3 | metadata: 4 | name: demo-job 5 | labels: 6 | app.kubernetes.io/name: go-demo 7 | spec: 8 | template: 9 | spec: 10 | containers: 11 | - name: demo-job-executor 12 | image: bigkevmcd/go-demo:876ecb3 13 | restartPolicy: Never 14 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/kustomization.yaml: -------------------------------------------------------------------------------- 1 | commonLabels: 2 | app.kubernetes.io/part-of: go-demo 3 | resources: 4 | - deployment.yaml 5 | - service.yaml 6 | - configMap.yaml 7 | - redis_service.yaml 8 | - redis_deployment.yaml 9 | - job.yaml 10 | - cron_job.yaml 11 | - stateful_set.yaml 12 | - deployment_config.yaml 13 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/redis_deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: redis 5 | labels: 6 | app.kubernetes.io/name: redis 7 | spec: 8 | selector: 9 | matchLabels: 10 | app.kubernetes.io/name: redis 11 | replicas: 1 12 | template: 13 | metadata: 14 | labels: 15 | app.kubernetes.io/name: redis 16 | spec: 17 | containers: 18 | - name: redis 19 | image: redis:6-alpine 20 | resources: 21 | requests: 22 | cpu: 100m 23 | memory: 100Mi 24 | ports: 25 | - containerPort: 6379 26 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/redis_service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: redis 5 | labels: 6 | app.kubernetes.io/name: redis 7 | spec: 8 | type: ClusterIP 9 | ports: 10 | - port: 6379 11 | selector: 12 | app.kubernetes.io/name: redis 13 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: go-demo-http 5 | labels: 6 | app.kubernetes.io/name: go-demo 7 | spec: 8 | ports: 9 | - port: 8080 10 | selector: 11 | app.kubernetes.io/name: go-demo 12 | -------------------------------------------------------------------------------- /pkg/parser/testdata/go-demo/stateful_set.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: StatefulSet 3 | metadata: 4 | name: go-demo-web 5 | labels: 6 | app.kubernetes.io/name: go-demo 7 | spec: 8 | selector: 9 | matchLabels: 10 | app.kubernetes.io/name: go-demo 11 | serviceName: go-demo-api 12 | replicas: 3 # by default is 1 13 | template: 14 | metadata: 15 | labels: 16 | app.kubernetes.io/name: go-demo 17 | spec: 18 | terminationGracePeriodSeconds: 10 19 | containers: 20 | - name: go-demo 21 | image: bigkevmcd/go-demo-api:v0.0.1 22 | ports: 23 | - containerPort: 80 24 | name: web 25 | volumeMounts: 26 | - name: www 27 | mountPath: /usr/share/api/html 28 | volumeClaimTemplates: 29 | - metadata: 30 | name: www 31 | spec: 32 | accessModes: [ "ReadWriteOnce" ] 33 | storageClassName: "my-storage-class" 34 | resources: 35 | requests: 36 | storage: 1Gi 37 | -------------------------------------------------------------------------------- /scripts/openshiftci-presubmit-all-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # fail if some commands fails 4 | set -e 5 | 6 | # Do not show token in CI log 7 | set +x 8 | 9 | # show commands 10 | set -x 11 | export CI="prow" 12 | go mod vendor 13 | 14 | export PATH="$PATH:$(pwd)" 15 | 16 | # Reference e2e test(s) 17 | echo "Please reference the E2E test script(s) here" 18 | -------------------------------------------------------------------------------- /scripts/openshiftci-presubmit-unittests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # fail if some commands fails 4 | set -e 5 | # show commands 6 | set -x 7 | 8 | export PATH=$PATH:$GOPATH/bin 9 | 10 | go env 11 | go mod vendor 12 | if [[ $(go fmt `go list ./... | grep -v vendor`) ]]; then 13 | echo "not well formatted sources are found" 14 | exit 1 15 | fi 16 | go version 17 | go mod tidy 18 | if [[ ! -z $(git status -s) ]] 19 | then 20 | echo "Go mod state is not clean." 21 | exit 1 22 | fi 23 | 24 | # Unit tests to be referenced here 25 | make test 26 | -------------------------------------------------------------------------------- /test/clone_options.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/go-git/go-git/v5" 7 | "github.com/go-git/go-git/v5/plumbing" 8 | ) 9 | 10 | // MakeCloneOptions determines if we are running in GitHub, 11 | // and ensures that it's using the correct branch. 12 | // 13 | // This is because the codebase that the tests run in is not a clone, so we have 14 | // to clone the upstream. 15 | // 16 | // For local development, you're working on the branch, and we can use that 17 | // branch correctly. 18 | func MakeCloneOptions() *git.CloneOptions { 19 | o := &git.CloneOptions{ 20 | URL: "../..", 21 | Depth: 1, 22 | } 23 | if b := os.Getenv("GITHUB_BASE_REF"); b != "" { 24 | o.ReferenceName = plumbing.NewBranchReferenceName(b) 25 | o.URL = "https://github.com/redhat-developer/gitops-backend.git" 26 | } 27 | return o 28 | } 29 | -------------------------------------------------------------------------------- /test/errors.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "regexp" 5 | "testing" 6 | ) 7 | 8 | // MatchError checks errors against a regexp. 9 | // 10 | // Returns true if the string is empty and the error is nil. 11 | // Returns false if the string is not empty and the error is nil. 12 | // Otherwise returns the result of a regexp match against the string. 13 | func MatchError(t *testing.T, s string, e error) bool { 14 | t.Helper() 15 | if s == "" && e == nil { 16 | return true 17 | } 18 | if s != "" && e == nil { 19 | return false 20 | } 21 | match, err := regexp.MatchString(s, e.Error()) 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | return match 26 | } 27 | -------------------------------------------------------------------------------- /test/logger.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "testing" 5 | 6 | "go.uber.org/zap" 7 | "go.uber.org/zap/zaptest" 8 | ) 9 | 10 | // MakeTestLogger creates a logger than uses zaptest. 11 | func MakeTestLogger(t *testing.T) *zap.SugaredLogger { 12 | logger := zaptest.NewLogger(t, zaptest.Level(zap.WarnLevel)) 13 | return logger.Sugar() 14 | } 15 | --------------------------------------------------------------------------------