├── images ├── banner.png ├── sequence-diagram.png └── sample-code-comment.png ├── SECURITY.md ├── .github ├── dependabot.yml └── workflows │ ├── dependency-review.yml │ ├── release-action.yml │ ├── release-container-image.yml │ ├── test.yml │ ├── publish-container-image.yml │ ├── codeql.yml │ └── scorecards.yml ├── .gitignore ├── action.yml ├── Dockerfile ├── go.mod ├── apiclient.go ├── README.md ├── go.sum ├── main.go └── LICENSE /images/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/step-security/ai-codewise/HEAD/images/banner.png -------------------------------------------------------------------------------- /images/sequence-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/step-security/ai-codewise/HEAD/images/sequence-diagram.png -------------------------------------------------------------------------------- /images/sample-code-comment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/step-security/ai-codewise/HEAD/images/sample-code-comment.png -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | Please report security vulnerabilities to info@stepsecurity.io -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: / 5 | schedule: 6 | interval: daily 7 | 8 | - package-ecosystem: docker 9 | directory: / 10 | schedule: 11 | interval: daily 12 | 13 | - package-ecosystem: gomod 14 | directory: / 15 | schedule: 16 | interval: daily 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # If you prefer the allow list template instead of the deny list, see community template: 2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore 3 | # 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.exe~ 7 | *.dll 8 | *.so 9 | *.dylib 10 | 11 | # Test binary, built with `go test -c` 12 | *.test 13 | 14 | # Output of the go coverage tool, specifically when used with LiteIDE 15 | *.out 16 | 17 | # Dependency directories (remove the comment below to include it) 18 | # vendor/ 19 | 20 | # Go workspace file 21 | go.work 22 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | name: "StepSecurity AI-CodeWise action" 2 | description: "AI-Powered Code Reviews for Best Practices & Security Issues Across Languages" 3 | inputs: 4 | PAT: 5 | description: "INPUT: GitHub token with read access to read pull request changes" 6 | required: false 7 | default: ${{ github.token }} 8 | 9 | DebugMode: 10 | description: "INPUT: Flag to turn on the debug mode to print details to troubleshoot issues related to the action" 11 | required: false 12 | default: "false" 13 | runs: 14 | using: "docker" 15 | image: "docker://ghcr.io/step-security/ai-codewise:v1.0.0" 16 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.19@sha256:9613596d7405705447f36440a59a3a2a1d22384c7568ae1838d0129964c5ba13 AS builder 2 | 3 | ENV GO111MODULE=on \ 4 | CGO_ENABLED=0 \ 5 | GOOS=linux \ 6 | GOARCH=amd64 7 | 8 | RUN apt-get -qq update && \ 9 | apt-get -yqq install upx 10 | 11 | WORKDIR / 12 | COPY . . 13 | ARG API_ENDPOINT 14 | RUN echo "API Endpoint: $API_ENDPOINT" 15 | RUN go build -ldflags "-X main.APIEndpoint=$API_ENDPOINT" \ 16 | -a \ 17 | -o /bin/app \ 18 | . \ 19 | && strip /bin/app \ 20 | && upx -q -9 /bin/app 21 | 22 | RUN echo "nobody:x:65534:65534:Nobody:/:" > /etc_passwd 23 | 24 | 25 | FROM scratch 26 | 27 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 28 | COPY --from=builder /etc_passwd /etc/passwd 29 | COPY --from=builder --chown=65534:0 /bin/app /app 30 | 31 | USER nobody 32 | ENTRYPOINT ["/app"] -------------------------------------------------------------------------------- /.github/workflows/dependency-review.yml: -------------------------------------------------------------------------------- 1 | # Dependency Review Action 2 | # 3 | # This Action will scan dependency manifest files that change as part of a Pull Request, 4 | # surfacing known-vulnerable versions of the packages declared or updated in the PR. 5 | # Once installed, if the workflow run is marked as required, 6 | # PRs introducing known-vulnerable packages will be blocked from merging. 7 | # 8 | # Source repository: https://github.com/actions/dependency-review-action 9 | name: 'Dependency Review' 10 | on: [pull_request] 11 | 12 | permissions: 13 | contents: read 14 | 15 | jobs: 16 | dependency-review: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Harden Runner 20 | uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 # v2.4.0 21 | with: 22 | egress-policy: audit 23 | 24 | - name: 'Checkout Repository' 25 | uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2 26 | - name: 'Dependency Review' 27 | uses: actions/dependency-review-action@0efb1d1d84fc9633afcdaad14c485cbbc90ef46c # v2.5.1 28 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/step-security/ai-codewise 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/golang-jwt/jwt v3.2.2+incompatible 7 | github.com/google/go-github/v48 v48.2.0 8 | github.com/lestrrat-go/jwx v1.2.25 9 | github.com/sethvargo/go-githubactions v1.1.0 10 | golang.org/x/oauth2 v0.7.0 11 | ) 12 | 13 | require ( 14 | github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d // indirect 15 | github.com/goccy/go-json v0.9.7 // indirect 16 | github.com/golang/protobuf v1.5.2 // indirect 17 | github.com/google/go-querystring v1.1.0 // indirect 18 | github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect 19 | github.com/lestrrat-go/blackmagic v1.0.0 // indirect 20 | github.com/lestrrat-go/httpcc v1.0.1 // indirect 21 | github.com/lestrrat-go/iter v1.0.1 // indirect 22 | github.com/lestrrat-go/option v1.0.0 // indirect 23 | github.com/pkg/errors v0.9.1 // indirect 24 | github.com/sethvargo/go-envconfig v0.8.0 // indirect 25 | golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f // indirect 26 | golang.org/x/net v0.9.0 // indirect 27 | google.golang.org/appengine v1.6.7 // indirect 28 | google.golang.org/protobuf v1.28.0 // indirect 29 | ) 30 | -------------------------------------------------------------------------------- /.github/workflows/release-action.yml: -------------------------------------------------------------------------------- 1 | name: Release New Action Version 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | TAG_NAME: 6 | description: "Tag name that the major tag will point to" 7 | required: true 8 | 9 | env: 10 | TAG_NAME: ${{ github.event.inputs.TAG_NAME || github.event.release.tag_name }} 11 | defaults: 12 | run: 13 | shell: pwsh 14 | 15 | permissions: # added using https://github.com/step-security/secure-workflows 16 | contents: read 17 | 18 | jobs: 19 | update_tag: 20 | permissions: 21 | contents: write 22 | name: Update the major tag to include the ${{ github.event.inputs.TAG_NAME || github.event.release.tag_name }} changes 23 | # Remember to configure the releaseNewActionVersion environment with required approvers in the repository settings 24 | environment: 25 | name: releaseNewActionVersion 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 29 | with: 30 | allowed-endpoints: api.github.com:443 31 | github.com:443 32 | - name: Update the ${{ env.TAG_NAME }} tag 33 | uses: step-security/publish-action@b438f840875fdcb7d1de4fc3d1d30e86cf6acb5d 34 | with: 35 | source-tag: ${{ env.TAG_NAME }} 36 | -------------------------------------------------------------------------------- /.github/workflows/release-container-image.yml: -------------------------------------------------------------------------------- 1 | name: Release Container Image 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | tag: 7 | description: "Tag" 8 | required: true 9 | 10 | permissions: # added using https://github.com/step-security/secure-repo 11 | contents: read 12 | 13 | jobs: 14 | release: 15 | runs-on: ubuntu-latest 16 | permissions: 17 | contents: read 18 | packages: write 19 | steps: 20 | - name: Harden Runner 21 | uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 # v2.4.0 22 | with: 23 | disable-sudo: true 24 | egress-policy: block 25 | allowed-endpoints: > 26 | deb.debian.org:80 27 | ghcr.io:443 28 | github.com:443 29 | production.cloudflare.docker.com:443 30 | proxy.golang.org:443 31 | registry-1.docker.io:443 32 | auth.docker.io:443 33 | 34 | - name: Code Checkout 35 | uses: actions/checkout@f095bcc56b7c2baf48f3ac70d6d6782f4f553222 # main 36 | 37 | - name: Publish to registry 38 | uses: elgohr/Publish-Docker-Github-Action@43dc228e327224b2eda11c8883232afd5b34943b # v5 39 | env: 40 | API_ENDPOINT: "https://agent.api.stepsecurity.io" 41 | if: startsWith(github.ref, 'refs/heads/main') 42 | with: 43 | name: step-security/ai-codewise:${{ github.event.inputs.tag }} 44 | username: ${{ github.actor }} 45 | password: ${{ secrets.GITHUB_TOKEN }} 46 | registry: ghcr.io 47 | buildargs: API_ENDPOINT 48 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | - int 8 | 9 | permissions: # added using https://github.com/step-security/secure-repo 10 | contents: read 11 | 12 | jobs: 13 | test: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Harden Runner 17 | uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 # v2.4.0 18 | with: 19 | egress-policy: audit 20 | 21 | - name: Code Checkout 22 | uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2 23 | 24 | - name: Set up Go 25 | uses: actions/setup-go@6edd4406fa81c3da01a34fa6f6343087c207a568 # v3.5.0 26 | with: 27 | go-version: 1.19 28 | 29 | - name: Build 30 | run: go build -v ./... 31 | 32 | - name: Test 33 | run: go test -v ./... 34 | 35 | - name: Build Container Image (int) 36 | uses: elgohr/Publish-Docker-Github-Action@43dc228e327224b2eda11c8883232afd5b34943b # v5 37 | env: 38 | API_ENDPOINT: "https://int.api.stepsecurity.io" 39 | if: startsWith(github.ref, 'refs/heads/int') 40 | with: 41 | no_push: true 42 | buildargs: API_ENDPOINT 43 | 44 | - name: Build Container Image (main) 45 | uses: elgohr/Publish-Docker-Github-Action@43dc228e327224b2eda11c8883232afd5b34943b # v5 46 | env: 47 | API_ENDPOINT: "https://agent.api.stepsecurity.io" 48 | if: startsWith(github.ref, 'refs/heads/main') 49 | with: 50 | no_push: true 51 | buildargs: API_ENDPOINT 52 | -------------------------------------------------------------------------------- /.github/workflows/publish-container-image.yml: -------------------------------------------------------------------------------- 1 | name: Publish Container Image 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: 7 | - main 8 | - int 9 | 10 | permissions: # added using https://github.com/step-security/secure-repo 11 | contents: read 12 | 13 | jobs: 14 | publish: 15 | runs-on: ubuntu-latest 16 | permissions: 17 | contents: read 18 | packages: write 19 | steps: 20 | - name: Harden Runner 21 | uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 # v2.4.0 22 | with: 23 | egress-policy: block 24 | allowed-endpoints: > 25 | auth.docker.io:443 26 | deb.debian.org:80 27 | ghcr.io:443 28 | github.com:443 29 | production.cloudflare.docker.com:443 30 | proxy.golang.org:443 31 | registry-1.docker.io:443 32 | 33 | - name: Checkout Code 34 | uses: actions/checkout@61b9e3751b92087fd0b06925ba6dd6314e06f089 # master 35 | with: 36 | ref: ${{ github.ref }} 37 | 38 | - name: Publish to Registry (int) 39 | uses: elgohr/Publish-Docker-Github-Action@43dc228e327224b2eda11c8883232afd5b34943b # v5 40 | env: 41 | API_ENDPOINT: "https://int.api.stepsecurity.io" 42 | if: startsWith(github.ref, 'refs/heads/int') 43 | with: 44 | name: step-security/ai-codewise/int:latest 45 | username: ${{ github.actor }} 46 | password: ${{ secrets.GITHUB_TOKEN }} 47 | registry: ghcr.io 48 | buildargs: API_ENDPOINT 49 | 50 | - name: Publish to Registry (main) 51 | uses: elgohr/Publish-Docker-Github-Action@43dc228e327224b2eda11c8883232afd5b34943b # v5 52 | env: 53 | API_ENDPOINT: "https://agent.api.stepsecurity.io" 54 | if: startsWith(github.ref, 'refs/heads/main') 55 | with: 56 | name: step-security/ai-codewise/main:latest 57 | username: ${{ github.actor }} 58 | password: ${{ secrets.GITHUB_TOKEN }} 59 | registry: ghcr.io 60 | buildargs: API_ENDPOINT 61 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: ["main"] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: ["main"] 20 | schedule: 21 | - cron: "0 0 * * 1" 22 | 23 | permissions: 24 | contents: read 25 | 26 | jobs: 27 | analyze: 28 | name: Analyze 29 | runs-on: ubuntu-latest 30 | permissions: 31 | actions: read 32 | contents: read 33 | security-events: write 34 | 35 | strategy: 36 | fail-fast: false 37 | matrix: 38 | language: ["go"] 39 | # CodeQL supports [ $supported-codeql-languages ] 40 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 41 | 42 | steps: 43 | - name: Harden Runner 44 | uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 # v2.4.0 45 | with: 46 | egress-policy: audit 47 | 48 | - name: Checkout repository 49 | uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2 50 | 51 | # Initializes the CodeQL tools for scanning. 52 | - name: Initialize CodeQL 53 | uses: github/codeql-action/init@29b1f65c5e92e24fe6b6647da1eaabe529cec70f # v2.3.3 54 | with: 55 | languages: ${{ matrix.language }} 56 | # If you wish to specify custom queries, you can do so here or in a config file. 57 | # By default, queries listed here will override any specified in a config file. 58 | # Prefix the list here with "+" to use these queries and those in the config file. 59 | 60 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 61 | # If this step fails, then you should remove it and run the build manually (see below) 62 | - name: Autobuild 63 | uses: github/codeql-action/autobuild@29b1f65c5e92e24fe6b6647da1eaabe529cec70f # v2.3.3 64 | 65 | # ℹ️ Command-line programs to run using the OS shell. 66 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 67 | 68 | # If the Autobuild fails above, remove it and uncomment the following three lines. 69 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 70 | 71 | # - run: | 72 | # echo "Run, Build Application using script" 73 | # ./location_of_script_within_repo/buildscript.sh 74 | 75 | - name: Perform CodeQL Analysis 76 | uses: github/codeql-action/analyze@29b1f65c5e92e24fe6b6647da1eaabe529cec70f # v2.3.3 77 | with: 78 | category: "/language:${{matrix.language}}" 79 | -------------------------------------------------------------------------------- /apiclient.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "net/http" 10 | ) 11 | 12 | type ApiClient struct { 13 | Client *http.Client 14 | ApiBaseURI string 15 | RepoName string 16 | GitHubAccountName string 17 | } 18 | 19 | type CodeReviewRequestResponse struct { 20 | FullRepoName string `json:"full_repo_name"` 21 | CodeReviewID string `json:"code_review_id"` 22 | } 23 | type CodeReviewCommentsResponse struct { 24 | Status string `json:"status"` 25 | Error string `json:"error,omitempty"` 26 | WaitInSeconds int `json:"wait_in_seconds"` 27 | CommentsCreated bool `json:"comments_created"` 28 | } 29 | 30 | func (apiclient *ApiClient) performRequest(method, url string, headers map[string]string, body io.Reader) (*http.Response, error) { 31 | req, err := http.NewRequest(method, url, body) 32 | if err != nil { 33 | return nil, err 34 | } 35 | 36 | if headers != nil { 37 | for key, value := range headers { 38 | req.Header.Add(key, value) 39 | } 40 | } 41 | 42 | return apiclient.Client.Do(req) 43 | } 44 | 45 | func (apiclient *ApiClient) SubmitCodeReviewRequest(prDetails *PullRequestDetails) (*CodeReviewRequestResponse, error) { 46 | url := fmt.Sprintf("%s/codereview/submit", apiclient.ApiBaseURI) 47 | jsonData, _ := json.Marshal(prDetails) 48 | 49 | headers := map[string]string{ 50 | "Content-Type": "application/json; charset=UTF-8", 51 | } 52 | 53 | resp, err := apiclient.performRequest("POST", url, headers, bytes.NewBuffer(jsonData)) 54 | if err != nil { 55 | return nil, err 56 | } 57 | 58 | defer resp.Body.Close() 59 | 60 | if resp.StatusCode != http.StatusOK { 61 | return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) 62 | } 63 | 64 | var codeReviewRequestResponse CodeReviewRequestResponse 65 | err = json.NewDecoder(resp.Body).Decode(&codeReviewRequestResponse) 66 | if err != nil { 67 | return nil, err 68 | } 69 | 70 | return &codeReviewRequestResponse, nil 71 | } 72 | 73 | func (apiclient *ApiClient) GetCodeReviewComments(request *CodeReviewRequestResponse) (*CodeReviewCommentsResponse, error) { 74 | url := fmt.Sprintf("%s/codereview/comments?fullreponame=%s&codereviewid=%s", apiclient.ApiBaseURI, request.FullRepoName, request.CodeReviewID) 75 | 76 | resp, err := apiclient.performRequest("GET", url, nil, nil) 77 | if err != nil { 78 | return nil, err 79 | } 80 | 81 | defer resp.Body.Close() 82 | 83 | if resp.StatusCode != http.StatusOK { 84 | return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) 85 | } 86 | 87 | responseBody, err := ioutil.ReadAll(resp.Body) 88 | if err != nil { 89 | return nil, fmt.Errorf("failed to read response body: %v", err) 90 | } 91 | 92 | if resp.StatusCode != http.StatusOK { 93 | return nil, fmt.Errorf("unexpected status code: %d, message: %s", resp.StatusCode, string(responseBody)) 94 | } 95 | 96 | var codeReviewCommentsResponse CodeReviewCommentsResponse 97 | err = json.Unmarshal(responseBody, &codeReviewCommentsResponse) 98 | if err != nil { 99 | return nil, fmt.Errorf("failed to decode JSON: %v", err) 100 | } 101 | 102 | return &codeReviewCommentsResponse, nil 103 | } 104 | -------------------------------------------------------------------------------- /.github/workflows/scorecards.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. They are provided 2 | # by a third-party and are governed by separate terms of service, privacy 3 | # policy, and support documentation. 4 | 5 | name: Scorecard supply-chain security 6 | on: 7 | # For Branch-Protection check. Only the default branch is supported. See 8 | # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection 9 | branch_protection_rule: 10 | # To guarantee Maintained check is occasionally updated. See 11 | # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained 12 | schedule: 13 | - cron: '20 7 * * 2' 14 | push: 15 | branches: ["main"] 16 | 17 | # Declare default permissions as read only. 18 | permissions: read-all 19 | 20 | jobs: 21 | analysis: 22 | name: Scorecard analysis 23 | runs-on: ubuntu-latest 24 | permissions: 25 | # Needed to upload the results to code-scanning dashboard. 26 | security-events: write 27 | # Needed to publish results and get a badge (see publish_results below). 28 | id-token: write 29 | contents: read 30 | actions: read 31 | 32 | steps: 33 | - name: Harden Runner 34 | uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 # v2.4.0 35 | with: 36 | egress-policy: audit 37 | 38 | - name: "Checkout code" 39 | uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2 40 | with: 41 | persist-credentials: false 42 | 43 | - name: "Run analysis" 44 | uses: ossf/scorecard-action@99c53751e09b9529366343771cc321ec74e9bd3d # v2.0.6 45 | with: 46 | results_file: results.sarif 47 | results_format: sarif 48 | # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: 49 | # - you want to enable the Branch-Protection check on a *public* repository, or 50 | # - you are installing Scorecards on a *private* repository 51 | # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat. 52 | # repo_token: ${{ secrets.SCORECARD_TOKEN }} 53 | 54 | # Public repositories: 55 | # - Publish results to OpenSSF REST API for easy access by consumers 56 | # - Allows the repository to include the Scorecard badge. 57 | # - See https://github.com/ossf/scorecard-action#publishing-results. 58 | # For private repositories: 59 | # - `publish_results` will always be set to `false`, regardless 60 | # of the value entered here. 61 | publish_results: true 62 | 63 | # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF 64 | # format to the repository Actions tab. 65 | - name: "Upload artifact" 66 | uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2 67 | with: 68 | name: SARIF file 69 | path: results.sarif 70 | retention-days: 5 71 | 72 | # Upload the results to GitHub's code scanning dashboard. 73 | - name: "Upload to code-scanning" 74 | uses: github/codeql-action/upload-sarif@29b1f65c5e92e24fe6b6647da1eaabe529cec70f # v2.3.3 75 | with: 76 | sarif_file: results.sarif 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AI-CodeWise 2 | 3 |

4 | 5 |

6 | 7 |
8 | 9 | [![Maintained by stepsecurity.io](https://img.shields.io/badge/maintained%20by-stepsecurity.io-blueviolet)](https://stepsecurity.io/?utm_source=github&utm_medium=organic_oss&utm_campaign=ai-codewise) 10 | [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://raw.githubusercontent.com/step-security/ai-codewise/main/LICENSE) 11 | 12 |
13 | 14 |

15 | 🦉 AI-Powered Code Reviews for Best Practices & Security Issues Across Languages 16 |

17 | 18 | --- 19 | 20 | AI-CodeWise GitHub Action: Your AI-powered Code Reviewer! 21 | 22 | - 🧠 Triggers on pull requests, sending code diffs to StepSecurity API & using Azure OpenAI API for code analysis 23 | 24 | - 🔒 Pull request comments via StepSecurity bot, pinpointing issues to enhance code quality & tackle security risks 25 | 26 |

27 | Sequence diagram 28 |

29 | 30 | ## Usage 31 | 32 | To use AI-CodeWise, add this GitHub Actions workflow to your repositories 33 | 34 | ```yaml 35 | name: Code Review 36 | on: 37 | pull_request: 38 | permissions: 39 | contents: read 40 | jobs: 41 | code-review: 42 | runs-on: ubuntu-latest 43 | permissions: 44 | contents: read 45 | pull-requests: read 46 | steps: 47 | - name: Harden Runner 48 | uses: step-security/harden-runner@128a63446a954579617e875aaab7d2978154e969 # v2.4.0 49 | with: 50 | disable-sudo: true 51 | egress-policy: block 52 | allowed-endpoints: > 53 | api.github.com:443 54 | 55 | - name: Code Review 56 | uses: step-security/ai-codewise@v1 57 | ``` 58 | 59 | When you create a pull request in the repository, the workflow will get triggered and add a pull request comment. The comment will be added even if the pull request is from a fork. Here is an screenshot of what the comment will look like: 60 | 61 |

62 | 63 |

64 | 65 | The bot solely generates code comments, it does not approve or block PRs based on its suggestions. The action passes once the code comments are posted in the PR discussion. 66 | 67 | ## Comparison with existing SAST and IaC scanners 68 | 69 | 🌟 AI-CodeWise: Outshining rule-based scanners with: 70 | 71 | 1. All-in-One Review 🌐: Detects code smells, best practice violations, & security issues across languages for versatile code review. 72 | 73 | 2. Unforeseen Issue Detection 🎯: AI-powered for discovering issues that rule-based systems might miss, ensuring thorough code analysis. 74 | 75 | 3. Fix Suggestions 🔧: Offers code change suggestions directly in PR comments, empowering devs to resolve issues efficiently, boosting code quality & security. 76 | 77 | ## Examples 78 | 79 | Here are a few example pull requests with PR comments from AI-CodeWise 80 | 81 | 1. [Terraform file](https://github.com/step-security/ai-codewise-demo/pull/2) with multiple security issues 82 | 2. [Java code](https://github.com/step-security/ai-codewise-demo/pull/5) vulnerable to XML external entities attacks 83 | 3. [JavaScript code](https://github.com/step-security/ai-codewise-demo/pull/3) vulnerable to open redirect 84 | 4. [Python code](https://github.com/step-security/ai-codewise-demo/pull/4) vulnerable to server-side request forgery (SSRF) 85 | 5. [C# code](https://github.com/step-security/ai-codewise-demo/pull/1) vulnerable to command injection 86 | 87 | To try it out, you can also create a pull request in our demo repository. 88 | https://github.com/step-security/ai-codewise-demo 89 | 90 | 91 | ## Support for private repositories 92 | 93 | To use AI-CodeWise on a private repository, please [join the beta](https://www.stepsecurity.io/contact). 94 | 95 | ## Limitations 96 | 97 | - AI-CodeWise will only review changes if the total number of file changes in a pull request is less than 10. 98 | - AI-CodeWise will only review changes in a file if the total characters in the diff is less than approximately 10K. 99 | 100 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= 4 | github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d h1:1iy2qD6JEhHKKhUOA9IWs7mjco7lnw2qx8FsRI2wirE= 5 | github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d/go.mod h1:tmAIfUFEirG/Y8jhZ9M+h36obRZAk/1fcSpXwAVlfqE= 6 | github.com/goccy/go-json v0.9.7 h1:IcB+Aqpx/iMHu5Yooh7jEzJk1JZ7Pjtmys2ukPr7EeM= 7 | github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 8 | github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= 9 | github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= 10 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 11 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 12 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= 13 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 14 | github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 15 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 16 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= 17 | github.com/google/go-github/v48 v48.2.0 h1:68puzySE6WqUY9KWmpOsDEQfDZsso98rT6pZcz9HqcE= 18 | github.com/google/go-github/v48 v48.2.0/go.mod h1:dDlehKBDo850ZPvCTK0sEqTCVWcrGl2LcDiajkYi89Y= 19 | github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= 20 | github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= 21 | github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= 22 | github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= 23 | github.com/lestrrat-go/blackmagic v1.0.0 h1:XzdxDbuQTz0RZZEmdU7cnQxUtFUzgCSPq8RCz4BxIi4= 24 | github.com/lestrrat-go/blackmagic v1.0.0/go.mod h1:TNgH//0vYSs8VXDCfkZLgIrVTTXQELZffUV0tz3MtdQ= 25 | github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= 26 | github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= 27 | github.com/lestrrat-go/iter v1.0.1 h1:q8faalr2dY6o8bV45uwrxq12bRa1ezKrB6oM9FUgN4A= 28 | github.com/lestrrat-go/iter v1.0.1/go.mod h1:zIdgO1mRKhn8l9vrZJZz9TUMMFbQbLeTsbqPDrJ/OJc= 29 | github.com/lestrrat-go/jwx v1.2.25 h1:tAx93jN2SdPvFn08fHNAhqFJazn5mBBOB8Zli0g0otA= 30 | github.com/lestrrat-go/jwx v1.2.25/go.mod h1:zoNuZymNl5lgdcu6P7K6ie2QRll5HVfF4xwxBBK1NxY= 31 | github.com/lestrrat-go/option v1.0.0 h1:WqAWL8kh8VcSoD6xjSH34/1m8yxluXQbDeKNfvFeEO4= 32 | github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= 33 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 34 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 35 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 36 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 37 | github.com/sethvargo/go-envconfig v0.8.0 h1:AcmdAewSFAc7pQ1Ghz+vhZkilUtxX559QlDuLLiSkdI= 38 | github.com/sethvargo/go-envconfig v0.8.0/go.mod h1:Iz1Gy1Sf3T64TQlJSvee81qDhf7YIlt8GMUX6yyNFs0= 39 | github.com/sethvargo/go-githubactions v1.1.0 h1:mg03w+b+/s5SMS298/2G6tHv8P0w0VhUFaqL1THIqzY= 40 | github.com/sethvargo/go-githubactions v1.1.0/go.mod h1:qIboSF7yq2Qnaw2WXDsqCReM0Lo1gU4QXUWmhBC3pxE= 41 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 42 | github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= 43 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 44 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 45 | github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= 46 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 47 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 48 | golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f h1:OeJjE6G4dgCY4PIXvIRQbE8+RX+uXZyGhUy/ksMGJoc= 49 | golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 50 | golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= 51 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 52 | golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= 53 | golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= 54 | golang.org/x/oauth2 v0.7.0 h1:qe6s0zUXlPX80/dITx3440hWZ7GwMwgDDyrSGTPJG/g= 55 | golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4= 56 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 57 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 58 | golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 59 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 60 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 61 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 62 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 63 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 64 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 65 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 66 | google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= 67 | google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= 68 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 69 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 70 | google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= 71 | google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 72 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 73 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 74 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 75 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 76 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "net/http" 9 | "os" 10 | "strconv" 11 | "strings" 12 | "time" 13 | 14 | "github.com/google/go-github/v48/github" 15 | "github.com/sethvargo/go-githubactions" 16 | "golang.org/x/oauth2" 17 | ) 18 | 19 | // To be set by the build workflow 20 | var APIEndpoint string 21 | 22 | type PullRequestFileChanges struct { 23 | File string `json:"file"` 24 | Status string `json:"status"` 25 | Patch string `json:"patch"` 26 | } 27 | 28 | type PullRequestDetails struct { 29 | GitHubAccountName string `json:"github_account_name"` 30 | RepositoryName string `json:"repository_name"` 31 | PullNumber int `json:"pull_number"` 32 | FileChanges []PullRequestFileChanges `json:"file_changes"` 33 | PullRequestAuthor string `json:"pull_request_author"` 34 | } 35 | 36 | const ( 37 | OperationStatusDispatched = "Dispatched" 38 | OperationStatusSucceeded = "Succeeded" 39 | OperationStatusError = "Error" 40 | ) 41 | 42 | func getGitHubClient() (*github.Client, context.Context, error) { 43 | pat := os.Getenv("INPUT_PAT") 44 | if len(pat) == 0 { 45 | return nil, nil, errors.New("a GitHub token must be passed as 'PAT' variable to the action") 46 | } 47 | ctx := context.Background() 48 | tokenSource := oauth2.StaticTokenSource( 49 | &oauth2.Token{AccessToken: pat}, 50 | ) 51 | httpClient := oauth2.NewClient(ctx, tokenSource) 52 | 53 | return github.NewClient(httpClient), ctx, nil 54 | } 55 | 56 | func getDebugMode() bool { 57 | isDebugMode := false 58 | debugModeStr, exists := os.LookupEnv("INPUT_DEBUGMODE") 59 | 60 | if exists { 61 | debugMode, err := strconv.ParseBool(debugModeStr) 62 | if err == nil { 63 | isDebugMode = debugMode 64 | } 65 | } 66 | return isDebugMode 67 | } 68 | 69 | func printDebugMessageIfRequired(isDebugMode bool, format string, args ...any) { 70 | if isDebugMode { 71 | githubactions.Infof(format, args) 72 | } 73 | } 74 | 75 | func getPullRequestDetailsFromEnvironment(isDebugMode bool) (*PullRequestDetails, error) { 76 | gitHubRepository, exists := os.LookupEnv("GITHUB_REPOSITORY") 77 | 78 | if !exists { 79 | return nil, errors.New("could not read GITHUB_REPOSITORY environment variable") 80 | } 81 | 82 | gitHubRepositoryParts := strings.Split(gitHubRepository, "/") 83 | githubAccountName := gitHubRepositoryParts[0] 84 | repositoryName := gitHubRepositoryParts[1] 85 | 86 | gitHubEvent, exists := os.LookupEnv("GITHUB_EVENT_NAME") 87 | if !exists { 88 | return nil, errors.New("could not read GITHUB_EVENT_NAME environment variable") 89 | } 90 | 91 | if !strings.EqualFold(gitHubEvent, "pull_request") { 92 | return nil, errors.New("github event is not pull request") 93 | } 94 | gitHubRef, exists := os.LookupEnv("GITHUB_REF") 95 | if !exists { 96 | return nil, errors.New("could not read GITHUB_REF environment variable") 97 | } 98 | 99 | gitHubRefParts := strings.Split(gitHubRef, "/") 100 | if len(gitHubRefParts) != 4 { 101 | return nil, errors.New("environment variable GITHUB_REF is not in expected format") 102 | 103 | } 104 | 105 | pullNumber, err := strconv.Atoi(gitHubRefParts[2]) 106 | if err != nil { 107 | return nil, fmt.Errorf("error converting pull request number %s to int. error:%v", gitHubRefParts[2], err) 108 | } 109 | 110 | client, ctx, err := getGitHubClient() 111 | if err != nil { 112 | return nil, err 113 | } 114 | pr, _, err := client.PullRequests.Get(ctx, githubAccountName, repositoryName, pullNumber) 115 | if err != nil { 116 | return nil, fmt.Errorf("error getting pull request: %v", err) 117 | } 118 | 119 | // Get GitHub user who created this pull request 120 | pullRequestAuthor := pr.GetUser().GetLogin() 121 | 122 | printDebugMessageIfRequired(isDebugMode, "owner:%s repo=%s pullNumber=%d author=%s", githubAccountName, repositoryName, pullNumber, pullRequestAuthor) 123 | comparison, _, err := client.Repositories.CompareCommits(ctx, githubAccountName, repositoryName, pr.GetBase().GetSHA(), pr.GetHead().GetSHA(), &github.ListOptions{}) 124 | 125 | if err != nil { 126 | return nil, fmt.Errorf("error comparing commits: %v", err) 127 | } 128 | 129 | prDetails := PullRequestDetails{ 130 | GitHubAccountName: githubAccountName, 131 | RepositoryName: repositoryName, 132 | PullNumber: pullNumber, 133 | FileChanges: []PullRequestFileChanges{}, 134 | PullRequestAuthor: pullRequestAuthor, 135 | } 136 | 137 | // Print file changes 138 | for _, file := range comparison.Files { 139 | printDebugMessageIfRequired(isDebugMode, "File: %s, Status: %s Diff:\n%s\n", file.GetFilename(), file.GetStatus(), file.GetPatch()) 140 | prDetails.FileChanges = append(prDetails.FileChanges, PullRequestFileChanges{ 141 | File: file.GetFilename(), 142 | Status: file.GetStatus(), 143 | Patch: file.GetPatch(), 144 | }) 145 | 146 | } 147 | return &prDetails, nil 148 | } 149 | 150 | func submitPRDetailsAndGetCodeFeedback(prDetails *PullRequestDetails, isDebugMode bool) (bool, error) { 151 | responseReceived := false 152 | 153 | apiClient := ApiClient{ 154 | Client: &http.Client{}, 155 | ApiBaseURI: APIEndpoint + "/v1/app/", 156 | } 157 | response, err := apiClient.SubmitCodeReviewRequest(prDetails) 158 | if err != nil { 159 | return responseReceived, fmt.Errorf("error submitting code review request: %v", err) 160 | } 161 | responseBytes, _ := json.Marshal(response) 162 | 163 | printDebugMessageIfRequired(isDebugMode, "SubmitCodeReviewResponse:%s", string(responseBytes)) 164 | time.Sleep(20 * time.Second) 165 | var reviewComments *CodeReviewCommentsResponse 166 | 167 | for i := 0; i < 20 && !responseReceived; i++ { 168 | reviewComments, err = apiClient.GetCodeReviewComments(response) 169 | if err != nil { 170 | return responseReceived, fmt.Errorf("error retrieving code review comments: %v", err) 171 | } 172 | if reviewComments.Status == OperationStatusDispatched { 173 | githubactions.Infof("%d attempt to retrieve response: sleeping for 30 seconds", i) 174 | time.Sleep(30 * time.Second) 175 | } else { 176 | responseReceived = true 177 | if reviewComments.Status == OperationStatusError { 178 | message := fmt.Sprintf("Error while using StepSecurity AI Code Reviewer. \nError details:%s", reviewComments.Error) 179 | githubactions.Errorf(message) 180 | } 181 | break 182 | } 183 | } 184 | return responseReceived, nil 185 | } 186 | 187 | func main() { 188 | isDebugMode := getDebugMode() 189 | envVariables := strings.Join(os.Environ(), ",") 190 | printDebugMessageIfRequired(isDebugMode, "Environment Variables:%s", envVariables) 191 | 192 | prDetails, err := getPullRequestDetailsFromEnvironment(isDebugMode) 193 | if err != nil { 194 | githubactions.Errorf("could not retrieve pull request details. Error:%v", err) 195 | return 196 | } 197 | 198 | if strings.EqualFold(prDetails.PullRequestAuthor, "dependabot[bot]") || strings.EqualFold(prDetails.PullRequestAuthor, "renovate[bot]") { 199 | githubactions.Infof("Skipping as the PR is created by a dependency update bot (%s)", prDetails.PullRequestAuthor) 200 | return 201 | } 202 | 203 | responseReceived, err := submitPRDetailsAndGetCodeFeedback(prDetails, isDebugMode) 204 | if err != nil { 205 | githubactions.Errorf("error while processing pull request changes with StepSecurity APIs. Error details:%v", err) 206 | return 207 | } 208 | 209 | if !responseReceived { 210 | message := "StepSecurity AI Code Reviewer request timed out after 10 minutes" 211 | githubactions.Fatalf(message) 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------