Skip to content

Commit

Permalink
Included Tests for Bad
Browse files Browse the repository at this point in the history
Signed-off-by: nathannaveen <[email protected]>
  • Loading branch information
nathannaveen committed Nov 6, 2023
1 parent 2453297 commit 33cf8c0
Show file tree
Hide file tree
Showing 4 changed files with 132 additions and 6 deletions.
23 changes: 21 additions & 2 deletions cmd/guacrest/bad.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
//
// Copyright 2023 The GUAC Authors.
//
// 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.

package main

import (
Expand All @@ -13,6 +28,7 @@ import (
model "github.com/guacsec/guac/pkg/assembler/clients/generated"
)

// badHandler is a function that returns a gin.HandlerFunc. It handles requests to the /bad endpoint.
func badHandler(ctx context.Context) func(c *gin.Context) {
return func(c *gin.Context) {
graphqlEndpoint, searchDepth, err := parseBadQueryParameters(c)
Expand All @@ -31,7 +47,9 @@ func badHandler(ctx context.Context) func(c *gin.Context) {
return
}

// Iterate over the bad certifications.
for _, certifyBad := range certifyBadResponse.CertifyBad {
// Handle the different types of subjects.
switch subject := certifyBad.Subject.(type) {
case *model.AllCertifyBadSubjectPackage:
var path []string
Expand Down Expand Up @@ -178,6 +196,7 @@ func badHandler(ctx context.Context) func(c *gin.Context) {
}
}

// parseBadQueryParameters is a helper function that parses the query parameters from a request.
func parseBadQueryParameters(c *gin.Context) (string, int, error) {
graphqlEndpoint := c.Query("gql_addr")

Expand All @@ -188,12 +207,12 @@ func parseBadQueryParameters(c *gin.Context) (string, int, error) {
var searchDepth int
var err error

// if the search depth is not specified, we will use the default value of 0
// Parse the search depth from the query parameters.
searchDepthString := c.Query("search_depth")
if searchDepthString != "" {
searchDepth, err = strconv.Atoi(searchDepthString)
if err != nil && searchDepthString != "" {
// if the search depth is not an integer, we will return an error
// If the search depth is not an integer, return an error.
return "", 0, errors.New("invalid search depth")
}
}
Expand Down
95 changes: 95 additions & 0 deletions cmd/guacrest/bad_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//
// Copyright 2023 The GUAC Authors.
//
// 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.

//go:build e2e

package main

import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)

func TestBadHandler(t *testing.T) {
type args struct {
gqlAddr string
searchDepth string
}
tests := []struct {
name string
args args
wantStatusCode int
wantBody string
}{
{
name: "default",
args: args{
gqlAddr: "http://localhost:8080/query",
searchDepth: "1",
},
wantStatusCode: 200,
},
{
name: "invalid search depth",
args: args{
gqlAddr: "http://localhost:8080/query",
searchDepth: "invalid",
},
wantStatusCode: 400,
},
}

r := gin.Default()
ctx := context.Background()

r.GET("/bad", badHandler(ctx))

ts := httptest.NewServer(r)
defer ts.Close()

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest("GET", "/bad?gql_addr="+tt.args.gqlAddr+"&search_depth="+tt.args.searchDepth, nil)
w := httptest.NewRecorder()

r.ServeHTTP(w, req)

resp, err := http.Get(ts.URL + "/bad?gql_addr=" + tt.args.gqlAddr + "&search_depth=" + tt.args.searchDepth)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
tt.wantBody = string(body)

if diff := cmp.Diff(tt.wantStatusCode, w.Code); diff != "" {
t.Errorf("code mismatch (-want +got):\n%s", diff)
}
if diff := cmp.Diff(tt.wantBody, w.Body.String(), cmpopts.SortSlices(func(x, y string) bool { return x < y })); diff != "" {
t.Errorf("body mismatch (-want +got):\n%s", diff)
}
})
}
}
12 changes: 12 additions & 0 deletions cmd/guacrest/known.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ import (
func artifactHandlerForArtifact(ctx context.Context) func(c *gin.Context) {
return func(c *gin.Context) {
graphqlEndpoint, err := parseKnownQueryParameters(c)
if err != nil {
c.String(http.StatusBadRequest, "error parsing query parameters: %v", err)
return
}

httpClient := &http.Client{Timeout: httpTimeout}
gqlclient := graphql.NewClient(graphqlEndpoint, httpClient)
Expand Down Expand Up @@ -75,6 +79,10 @@ func artifactHandlerForArtifact(ctx context.Context) func(c *gin.Context) {
func sourceHandlerForVCS(ctx context.Context) func(c *gin.Context) {
return func(c *gin.Context) {
graphqlEndpoint, err := parseKnownQueryParameters(c)
if err != nil {
c.String(http.StatusBadRequest, "error parsing query parameters: %v", err)
return
}

httpClient := &http.Client{Timeout: httpTimeout}
gqlclient := graphql.NewClient(graphqlEndpoint, httpClient)
Expand Down Expand Up @@ -125,6 +133,10 @@ func sourceHandlerForVCS(ctx context.Context) func(c *gin.Context) {
func packageHandlerForHash(ctx context.Context) func(c *gin.Context) {
return func(c *gin.Context) {
graphqlEndpoint, err := parseKnownQueryParameters(c)
if err != nil {
c.String(http.StatusBadRequest, "error parsing query parameters: %v", err)
return
}

httpClient := &http.Client{Timeout: httpTimeout}
gqlclient := graphql.NewClient(graphqlEndpoint, httpClient)
Expand Down
8 changes: 4 additions & 4 deletions cmd/guacrest/vulnerability.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ func handleVulnerabilityIDQuery(ctx context.Context, c *gin.Context, gqlclient g
if len(path) > 0 {
c.IndentedJSON(200, gin.H{
"vulnerabilities": vulnResponse.Vulnerabilities,
"Visualizer url": fmt.Sprintf("http://localhost:3000/?path=%v", strings.Join(removeDuplicateValuesFromPath(path), `,`)),
"Visualizer url": fmt.Sprintf("http://localhost:3000/?path=%v", strings.Join(removeDuplicateValuesFromPath(path), `,`)),
})
} else {
c.String(404, "no path to vulnerability ID found")
Expand Down Expand Up @@ -175,14 +175,14 @@ func handleNoVulnerabilityIDQuery(ctx context.Context, c *gin.Context, gqlclient

c.IndentedJSON(200, gin.H{
"vulnerabilities": res,
"Visualizer url": fmt.Sprintf("http://localhost:3000/?path=%v", strings.Join(removeDuplicateValuesFromPath(path), `,`)),
"Visualizer url": fmt.Sprintf("http://localhost:3000/?path=%v", strings.Join(removeDuplicateValuesFromPath(path), `,`)),
})
} else {
c.String(404, "no path to vulnerabilities found")
}
}

// QueryVulnsViaVulnNodeNeighbors is a function that queries for vulnerabilities via node neighbors.
// QueryVulnsViaVulnNodeNeighbors is a function that queries for vulnerabilities via node neighbors.
// This function traverses through the graph with searchDependencyPackagesReverse.
// It takes a context, a GraphQL client, a package response, a list of vulnerabilities, an edge type, a search depth, and a number of paths to return.
// It returns a list of paths to the vulnerabilities and an error if the query fails.
Expand Down Expand Up @@ -471,7 +471,7 @@ func searchDependencyPackagesReverse(ctx context.Context, gqlclient graphql.Clie
if err != nil {
return nil, fmt.Errorf("failed getting package parent:%v", err)
}

// Iterate over the dependencies of the package
for _, neighbor := range isDependencyNeighborResponses.Neighbors {
if isDependency, ok := neighbor.(*model.NeighborsNeighborsIsDependency); ok && now != isDependency.Package.Namespaces[0].Names[0].Versions[0].Id {
Expand Down

0 comments on commit 33cf8c0

Please sign in to comment.