diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..5ac39ed --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,27 @@ +--- +name: 🐞 Bug report +about: Create a report to help us improve +title: "" +labels: bug +assignees: "" +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Versions** + +- JFrog Applications Config schema version: +- Operating system: + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..9bc2730 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,19 @@ +--- +name: ⭐️ Feature request +about: Suggest an idea for this project +title: "" +labels: feature request +assignees: "" +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like to see** +A clear and concise description of the new feature. + +**Describe alternatives you've considered** +If applicable, a clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000..3750fd7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,7 @@ +--- +name: ❓ Question +about: Ask a question +title: "" +labels: question +assignees: "" +--- diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..d623ab7 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,4 @@ +- [ ] All [tests](https://github.com/jfrog/jfrog-apps-config/actions/workflows/test.yml) passed. If this feature is not already covered by the tests, I added new tests. +- [ ] I used `go fmt ./...` for formatting the code before submitting the pull request. + +--- diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..5021017 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,20 @@ +changelog: + exclude: + labels: + - ignore for release + categories: + - title: Breaking Changes 🚨 + labels: + - breaking change + - title: Exciting New Features 🎉 + labels: + - new feature + - title: Improvements 🌱 + labels: + - improvement + - title: Bug Fixes 🛠 + labels: + - bug + - title: Other Changes 📚 + labels: + - "*" diff --git a/.github/workflows/analysis.yml b/.github/workflows/analysis.yml new file mode 100644 index 0000000..ab6010a --- /dev/null +++ b/.github/workflows/analysis.yml @@ -0,0 +1,44 @@ +name: "Static Analysis" +on: + push: + branches: + - "**" + tags-ignore: + - "**" + pull_request: +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}-${{ github.ref }} + cancel-in-progress: true +jobs: + Static-Check: + name: Static Check + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v3 + - name: Install Go + uses: actions/setup-go@v3 + with: + go-version: 1.20.x + - name: Static Code Analysis + uses: golangci/golangci-lint-action@v3 + with: + working-directory: go + args: | + --timeout 5m --out-${NO_FUTURE}format colored-line-number --enable errcheck,gosimple,govet,ineffassign,staticcheck,typecheck,unused,gocritic,asasalint,asciicheck,errchkjson,exportloopref,forcetypeassert,makezero,nilerr,unparam,unconvert,wastedassign,usestdlibvars + + Go-Sec: + name: Go-Sec + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v3 + - name: Install Go + uses: actions/setup-go@v3 + with: + go-version: 1.20.x + - name: Install gosec + run: curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s -- -b $(go env GOPATH)/bin + - name: Run gosec + working-directory: go + run: gosec -tests ./... diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml new file mode 100644 index 0000000..7d79367 --- /dev/null +++ b/.github/workflows/cla.yml @@ -0,0 +1,35 @@ +name: "CLA Assistant" +on: + # issue_comment triggers this action on each comment on issues and pull requests + issue_comment: + types: [created] + pull_request_target: + types: [opened,synchronize] + +jobs: + CLAssistant: + runs-on: ubuntu-latest + steps: + - uses: actions-ecosystem/action-regex-match@v2 + id: sign-or-recheck + with: + text: ${{ github.event.comment.body }} + regex: '\s*(I have read the CLA Document and I hereby sign the CLA)|(recheck)\s*' + + - name: "CLA Assistant" + if: ${{ steps.sign-or-recheck.outputs.match != '' || github.event_name == 'pull_request_target' }} + # Alpha Release + uses: cla-assistant/github-action@v2.3.0 + env: + # Generated and maintained by github + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # JFrog organization secret + PERSONAL_ACCESS_TOKEN : ${{ secrets.CLA_SIGN_TOKEN }} + with: + path-to-signatures: 'signed_clas.json' + path-to-document: 'https://jfrog.com/cla/' + remote-organization-name: 'jfrog' + remote-repository-name: 'jfrog-signed-clas' + # branch should not be protected + branch: 'master' + allowlist: bot* diff --git a/.github/workflows/frogbot-scan-pr.yml b/.github/workflows/frogbot-scan-pr.yml new file mode 100644 index 0000000..f09cc9b --- /dev/null +++ b/.github/workflows/frogbot-scan-pr.yml @@ -0,0 +1,44 @@ +name: "Frogbot Scan Pull Request" +on: + pull_request_target: + types: [opened, synchronize] +permissions: + pull-requests: write + contents: read +jobs: + scan-pull-request: + runs-on: ubuntu-latest + # A pull request needs to be approved, before Frogbot scans it. Any GitHub user who is associated with the + # "frogbot" GitHub environment can approve the pull request to be scanned. + environment: frogbot + steps: + - uses: jfrog/frogbot@v2 + env: + # [Mandatory] + # JFrog platform URL (This functionality requires version 3.29.0 or above of Xray) + JF_URL: ${{ secrets.FROGBOT_URL }} + + # [Mandatory if JF_USER and JF_PASSWORD are not provided] + # JFrog access token with 'read' permissions on Xray service + JF_ACCESS_TOKEN: ${{ secrets.FROGBOT_ACCESS_TOKEN }} + + # [Mandatory] + # The GitHub token automatically generated for the job + JF_GIT_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # [Optional, default: "."] + # Relative path to the root of the project in the Git repository + JF_WORKING_DIR: "go" + + # [Optional] + # Configure the SMTP server to enable Frogbot to send emails with detected secrets in pull request scans. + # SMTP server URL including should the relevant port: (Example: smtp.server.com:8080) + JF_SMTP_SERVER: ${{ secrets.JF_SMTP_SERVER }} + + # [Mandatory if JF_SMTP_SERVER is set] + # The username required for authenticating with the SMTP server. + JF_SMTP_PASSWORD: ${{ secrets.JF_SMTP_PASSWORD }} + + # [Mandatory if JF_SMTP_SERVER is set] + # The password associated with the username required for authentication with the SMTP server. + JF_SMTP_USER: ${{ secrets.JF_SMTP_USER }} diff --git a/.github/workflows/frogbot-scan-repository.yml b/.github/workflows/frogbot-scan-repository.yml new file mode 100644 index 0000000..7c9a0bf --- /dev/null +++ b/.github/workflows/frogbot-scan-repository.yml @@ -0,0 +1,34 @@ +name: "Frogbot Scan Repository" +on: + schedule: + # The repository will be scanned once a day at 00:00 GMT. + - cron: "0 0 * * *" +permissions: + contents: write + pull-requests: write + security-events: write +jobs: + create-fix-pull-requests: + runs-on: ubuntu-latest + strategy: + matrix: + # The repository scanning will be triggered periodically on the following branches. + branch: ["main"] + steps: + - uses: jfrog/frogbot@v2 + env: + # [Mandatory] + # JFrog platform URL (This functionality requires version 3.29.0 or above of Xray) + JF_URL: ${{ secrets.FROGBOT_URL }} + + # [Mandatory if JF_USER and JF_PASSWORD are not provided] + # JFrog access token with 'read' permissions on Xray service + JF_ACCESS_TOKEN: ${{ secrets.FROGBOT_ACCESS_TOKEN }} + + # [Mandatory] + # The GitHub token automatically generated for the job + JF_GIT_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + # [Optional, default: "."] + # Relative path to the root of the project in the Git repository + JF_WORKING_DIR: "go" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..7a689c5 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,22 @@ +name: Test + +on: [push, pull_request] + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + steps: + - uses: actions/checkout@v3 + - name: Setup Go + uses: actions/setup-go@v3 + with: + go-version: 1.20.x + + # Run tests + - name: Tests + run: go test -v -race + working-directory: go diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a06f485 --- /dev/null +++ b/README.md @@ -0,0 +1,66 @@ +# JFrog Applications Config + +The JFrog Applications Config schema is used to define the configuration schema used by some for the JFrog applications, such as JFrog CLI, JFrog Frogbot and the JFrog IDE integrations. This configuration schema is used to define the rules and settings for the JFrog source code scanning tools. + +By consolidating the relevant settings, rules and policies into a single file, developers and security teams can easily manage and update scanning configurations, ensuring consistent and effective code analysis. + +## Project status + +[![Scanned by Frogbot](https://raw.github.com/jfrog/frogbot/master/images/frogbot-badge.svg)](https://github.com/jfrog/frogbot#readme) +[![Test](https://github.com/jfrog/jfrog-apps-config/actions/workflows/test.yml/badge.svg)](https://github.com/jfrog/jfrog-apps-config/actions/workflows/test.yml) +[![Static Analysis](https://github.com/jfrog/jfrog-apps-config/actions/workflows/analysis.yml/badge.svg)](https://github.com/jfrog/jfrog-apps-config/actions/workflows/analysis.yml) + +## Schema: + +```yaml +# [Required] JFrog Applications Config version +version: "1.0" + +modules: + # [Required] Module name + - name: FrogLeapApp + # [Optional, default: "."] Application's root directory + source_root: "src" + # [Optional] Directories to exclude from scanning across all scanners + exclude_patterns: + - "docs/" + # [Optional] Scanners to exclude from JFrog Advanced Security (Options: "secrets", "sast", "iac") + exclude_scanners: + - secrets + # [Optional] Customize scanner configurations + scanners: + # [Optional] Configuration for Static Application Security Testing (SAST) + sast: + # [Optional] Specify the programming language for SAST + language: java + # [Optional] Working directories specific to SAST (Relative to source_root) + working_dirs: + - "src/module1" + - "src/module2" + # [Optional] Additional exclude patterns for this scanner + exclude_patterns: + - "src/module1/test" + # [Optional] List of specific scan rules to exclude from the scan + excluded_rules: + - xss-injection + + # [Optional] Configuration for secrets scan + secrets: + # [Optional] Working directories specific to the secret scanner (Relative to source_root) + working_dirs: + - "src/module1" + - "src/module2" + # [Optional] Additional exclude patterns for this scanner + exclude_patterns: + - "src/module1/test" + + # [Optional] Configuration for Infrastructure as Code scan (IaC) + iac: + # [Optional] Working directories specific to IaC (Relative to source_root) + working_dirs: + - "src/module1" + - "src/module2" + # [Optional] Additional exclude patterns for this Scanner + exclude_patterns: + - "src/module1/test" +``` diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..724f399 --- /dev/null +++ b/go/go.mod @@ -0,0 +1,16 @@ +module github.com/jfrog/jfrog-apps-config/go + +go 1.20 + +require ( + github.com/stretchr/testify v1.8.4 + github.com/xeipuuv/gojsonschema v1.2.0 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect +) diff --git a/go/go.sum b/go/go.sum new file mode 100644 index 0000000..0cde767 --- /dev/null +++ b/go/go.sum @@ -0,0 +1,19 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/go/schema.go b/go/schema.go new file mode 100644 index 0000000..a10a87b --- /dev/null +++ b/go/schema.go @@ -0,0 +1,60 @@ +package jfrogappsconfig + +import ( + "errors" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" +) + +const ( + version = "1.0" + dotJFrogDir = ".jfrog" + configFileName = "jfrog-apps-config.yml" +) + +type JFrogAppsConfig struct { + Version string `yaml:"version,omitempty"` + Modules []Module `yaml:"modules,omitempty"` +} + +type Module struct { + Name string `yaml:"name,omitempty"` + SourceRoot string `yaml:"source_root,omitempty"` + ExcludePatterns []string `yaml:"exclude_patterns,omitempty"` + ExcludeScanners []string `yaml:"exclude_scanners,omitempty"` + Scanners Scanners `yaml:"scanners,omitempty"` +} + +type Scanners struct { + Secrets *Scanner `yaml:"secrets,omitempty"` + Iac *Scanner `yaml:"iac,omitempty"` + Sast *SastScanner `yaml:"sast,omitempty"` +} + +type Scanner struct { + WorkingDirs []string `yaml:"working_dirs,omitempty"` + ExcludePatterns []string `yaml:"exclude_patterns,omitempty"` +} + +type SastScanner struct { + Scanner `yaml:",inline"` + Language string `yaml:"language,omitempty"` + ExcludedRules []string `yaml:"excluded_rules,omitempty"` +} + +func LoadConfigIfExist() (*JFrogAppsConfig, error) { + jfrogAppsConfigBytes, err := os.ReadFile(filepath.Join(dotJFrogDir, configFileName)) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + // File does not exist + return nil, nil + } + return nil, err + } + + jfrogAppsConfig := &JFrogAppsConfig{} + err = yaml.Unmarshal(jfrogAppsConfigBytes, jfrogAppsConfig) + return jfrogAppsConfig, err +} diff --git a/go/schema_test.go b/go/schema_test.go new file mode 100644 index 0000000..afed006 --- /dev/null +++ b/go/schema_test.go @@ -0,0 +1,171 @@ +package jfrogappsconfig + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/xeipuuv/gojsonschema" + "gopkg.in/yaml.v3" +) + +var loadConfigIfExistCases = []struct { + fileName string + expectedConfig JFrogAppsConfig +}{ + {fileName: "no-scanners.yml", expectedConfig: JFrogAppsConfig{ + Version: "1.0", + Modules: []Module{{ + Name: "NoScanners", + SourceRoot: "src", + ExcludePatterns: []string{"docs/"}, + ExcludeScanners: []string{"secrets"}}, + }}, + }, + {fileName: "sast.yml", expectedConfig: JFrogAppsConfig{ + Version: "1.0", + Modules: []Module{{ + Name: "Sast", + Scanners: Scanners{Sast: &SastScanner{ + Language: "java", + Scanner: Scanner{ + WorkingDirs: []string{"src/module1", "src/module2"}, + ExcludePatterns: []string{"src/module1/test"}, + }, + ExcludedRules: []string{"xss-injection"}, + }}, + }}}, + }, + {fileName: "all-scanners.yml", expectedConfig: JFrogAppsConfig{ + Version: "1.0", + Modules: []Module{{ + Name: "AllScanners", + Scanners: Scanners{Sast: &SastScanner{ + Language: "java", + Scanner: Scanner{WorkingDirs: []string{"src/module1"}}}, + Iac: &Scanner{WorkingDirs: []string{"src/module2"}}, + Secrets: &Scanner{WorkingDirs: []string{"src/module3"}}, + }, + }}}, + }, +} + +func TestLoadConfigIfExist(t *testing.T) { + tempDir, err := os.MkdirTemp("", "load-config-test") + assert.NoError(t, err) + defer func() { + assert.NoError(t, os.RemoveAll(tempDir)) + }() + assert.NoError(t, os.Mkdir(filepath.Join(tempDir, dotJFrogDir), 0750)) + + cwd, err := os.Getwd() + assert.NoError(t, err) + defer func() { + assert.NoError(t, os.Chdir(cwd)) + }() + + for _, testCase := range loadConfigIfExistCases { + t.Run(testCase.fileName, func(t *testing.T) { + assert.NoError(t, os.Chdir(cwd)) + + content, err := os.ReadFile(filepath.Join("testdata", "goodschemas", testCase.fileName)) + assert.NoError(t, err) + + assert.NoError(t, os.Chdir(tempDir)) + assert.NoError(t, os.WriteFile(filepath.Join(dotJFrogDir, configFileName), content, 0600)) + + jfrogAppsConfig, err := LoadConfigIfExist() + assert.NoError(t, err) + + assert.Equal(t, testCase.expectedConfig, *jfrogAppsConfig) + }) + } +} + +func TestJFrogYamlSchema(t *testing.T) { + // Load JFrog Apps Config schema + schema, err := os.ReadFile(filepath.Join("..", "schema.json")) + assert.NoError(t, err) + schemaLoader := gojsonschema.NewBytesLoader(schema) + + // Validate all JFrog Apps Configs in testdata + validateYamlsInDirectory(t, filepath.Join("testdata", "goodschemas"), schemaLoader) + + // Validate bad schema + validateYamlSchema(t, schemaLoader, filepath.Join("testdata", "badschemas", "bad-schema.yml"), "Invalid type. Expected: string, given: integer") +} + +// Validate all yml files in the given directory against the input schema +// t - Testing object +// schemaLoader - JFrog Apps Config schema +// path - Yaml directory path +func validateYamlsInDirectory(t *testing.T, path string, schemaLoader gojsonschema.JSONLoader) { + err := filepath.Walk(path, func(jfrogAppConfigFilePath string, info os.FileInfo, err error) error { + assert.NoError(t, err) + if strings.HasSuffix(info.Name(), "yml") { + validateYamlSchema(t, schemaLoader, jfrogAppConfigFilePath, "") + } + return nil + }) + assert.NoError(t, err) +} + +// Validate a Yaml file against the input Yaml schema +// t - Testing object +// schemaLoader - JFrog Apps Config schema +// yamlFilePath - Yaml file path +// expectError - Expected error or an empty string if error is not expected +func validateYamlSchema(t *testing.T, schemaLoader gojsonschema.JSONLoader, yamlFilePath, expectError string) { + t.Run(filepath.Base(yamlFilePath), func(t *testing.T) { + // Read JFrog Apps Config + // #nosec G304 - false positive + yamlFile, err := os.ReadFile(yamlFilePath) + assert.NoError(t, err) + + // Unmarshal JFrog Apps Config + var jfrogAppsConfigYaml interface{} + err = yaml.Unmarshal(yamlFile, &jfrogAppsConfigYaml) + assert.NoError(t, err) + + // Convert the Yaml config to JSON config to help the json parser validate it. + // The reason we don't do the convert by as follows: + // YAML -> Unmarshall -> Go Struct -> Marshal -> JSON + // is because the config's struct includes only YAML annotations. + jfrogAppsConfigJson := convertYamlToJson(jfrogAppsConfigYaml) + + // Load and validate JFrog Apps Config + documentLoader := gojsonschema.NewGoLoader(jfrogAppsConfigJson) + result, err := gojsonschema.Validate(schemaLoader, documentLoader) + assert.NoError(t, err) + if expectError != "" { + assert.False(t, result.Valid()) + assert.Contains(t, result.Errors()[0].String(), expectError) + } else { + assert.True(t, result.Valid(), result.Errors()) + } + }) +} + +// Recursively convert yaml interface to JSON interface +func convertYamlToJson(yamlValue interface{}) interface{} { + switch yamlMapping := yamlValue.(type) { + case map[interface{}]interface{}: + jsonMapping := map[string]interface{}{} + for key, value := range yamlMapping { + if key == true { + // "on" is considered a true value for the Yaml Unmarshaler. To work around it, we set the true to be "on". + key = "on" + } + jsonMapping[fmt.Sprint(key)] = convertYamlToJson(value) + } + return jsonMapping + case []interface{}: + for i, value := range yamlMapping { + yamlMapping[i] = convertYamlToJson(value) + } + } + return yamlValue +} diff --git a/go/testdata/badschemas/bad-schema.yml b/go/testdata/badschemas/bad-schema.yml new file mode 100644 index 0000000..b93897b --- /dev/null +++ b/go/testdata/badschemas/bad-schema.yml @@ -0,0 +1,9 @@ +version: "1.0" + +modules: + - name: NoScanners + source_root: 123 + exclude_patterns: + - "docs/" + exclude_scanners: + - secrets \ No newline at end of file diff --git a/go/testdata/goodschemas/all-scanners.yml b/go/testdata/goodschemas/all-scanners.yml new file mode 100644 index 0000000..721310e --- /dev/null +++ b/go/testdata/goodschemas/all-scanners.yml @@ -0,0 +1,15 @@ +version: "1.0" + +modules: + - name: AllScanners + scanners: + sast: + language: java + working_dirs: + - "src/module1" + iac: + working_dirs: + - "src/module2" + secrets: + working_dirs: + - "src/module3" diff --git a/go/testdata/goodschemas/no-scanners.yml b/go/testdata/goodschemas/no-scanners.yml new file mode 100644 index 0000000..b283de2 --- /dev/null +++ b/go/testdata/goodschemas/no-scanners.yml @@ -0,0 +1,9 @@ +version: "1.0" + +modules: + - name: NoScanners + source_root: "src" + exclude_patterns: + - "docs/" + exclude_scanners: + - secrets \ No newline at end of file diff --git a/go/testdata/goodschemas/sast.yml b/go/testdata/goodschemas/sast.yml new file mode 100644 index 0000000..c79f16c --- /dev/null +++ b/go/testdata/goodschemas/sast.yml @@ -0,0 +1,14 @@ +version: "1.0" + +modules: + - name: Sast + scanners: + sast: + language: java + working_dirs: + - "src/module1" + - "src/module2" + exclude_patterns: + - "src/module1/test" + excluded_rules: + - xss-injection diff --git a/schema.json b/schema.json new file mode 100644 index 0000000..819ff90 --- /dev/null +++ b/schema.json @@ -0,0 +1,105 @@ +{ + "title": "JFrog Applications Configuration schema", + "description": "The configuration file allows you to refine your scan behavior according to your specific project needs and structures, leading to better and more accurate scan results.", + "$schema": "https://json-schema.org/draft-07/schema#", + "type": "object", + "required": ["version", "modules"], + "additionalProperties": false, + "properties": { + "version": { + "type": "string", + "description": "JFrog Applications Config version" + }, + "modules": { + "type": "array", + "description": "An array of modules.", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the module." + }, + "source_root": { + "type": "string", + "default": ".", + "description": "Directories to exclude from Scanning Across All Scanners (optional)." + }, + "exclude_patterns": { + "type": "array", + "description": "Directories to exclude from Scanning Across All Scanners (optional).", + "items": { "type": "string" } + }, + "exclude_scanners": { + "type": "array", + "description": "Scanners to exclude from JFrog Advanced Security (optional).", + "items": { "type": "string" } + }, + "scanners": { + "type": "object", + "description": "An object containing scanner configurations.", + "properties": { + "secrets": { + "type": "object", + "description": "Scanner configuration for secrets scanner.", + "properties": { + "working_dirs": { + "type": "array", + "description": "Working directories Specific to the secrets scanner (Relative to source_root)", + "items": { "type": "string" } + }, + "exclude_patterns": { + "type": "array", + "description": "Additional exclude patterns for this scanner (optional).", + "items": { "type": "string" } + } + } + }, + "iac": { + "type": "object", + "description": "Scanner configuration for infrastructure as code (IAC).", + "properties": { + "working_dirs": { + "type": "array", + "description": "Working directories Specific to IaC (Relative to source_root)", + "items": { "type": "string" } + }, + "exclude_patterns": { + "type": "array", + "description": "Additional exclude patterns for this scanner (optional).", + "items": { "type": "string" } + } + } + }, + "sast": { + "type": "object", + "description": "Configuration for Static Application Security Testing (SAST).", + "properties": { + "working_dirs": { + "type": "array", + "description": "Working directories Specific to SAST (Relative to source_root)", + "items": { "type": "string" } + }, + "exclude_patterns": { + "type": "array", + "description": "Additional exclude patterns for this scanner (optional).", + "items": { "type": "string" } + }, + "language": { + "type": "string", + "description": "Specify the Programming Language for SAST (optional)." + }, + "excluded_rules": { + "type": "array", + "description": "List of specific scan rules to exclude from the scan (optional).", + "items": { "type": "string" } + } + } + } + } + } + } + } + } + } +}