|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/base64" |
| 7 | + "encoding/json" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "net/http" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/sourcegraph/sourcegraph/lib/errors" |
| 14 | + "google.golang.org/genproto/googleapis/rpc/errdetails" |
| 15 | + "google.golang.org/protobuf/proto" |
| 16 | + |
| 17 | + "github.com/sourcegraph/src-cli/internal/api" |
| 18 | + "github.com/sourcegraph/src-cli/internal/clicompat" |
| 19 | + "github.com/urfave/cli/v3" |
| 20 | +) |
| 21 | + |
| 22 | +const contextImportExamples = ` |
| 23 | +Create a search context from a software bill of materials (SBOM). |
| 24 | +
|
| 25 | +Each package in the SBOM must reference its Git repository and revision. In an |
| 26 | +SPDX 3.0 SBOM, give the package an external reference of type "vcs" whose |
| 27 | +locator is "<clone URL>@<revision>". In a CycloneDX SBOM, give the component an |
| 28 | +external reference of type "vcs" whose URL is "<clone URL>@<revision>". Packages |
| 29 | +without a repository and revision, or whose repository is not on the Sourcegraph |
| 30 | +instance, are skipped and listed in the output. |
| 31 | +
|
| 32 | +The search context is owned by the current user. Search it with |
| 33 | +"context:@<username>/<name>". |
| 34 | +
|
| 35 | +Examples: |
| 36 | +
|
| 37 | + Create a private search context named spring-sbom from an SBOM file: |
| 38 | +
|
| 39 | + $ src context import -name=spring-sbom -f=sbom.cdx.json |
| 40 | +
|
| 41 | + Create a public search context with a description from an SBOM read from stdin: |
| 42 | +
|
| 43 | + $ cat sbom.spdx.json | src context import -name=spring-sbom -description='Spring Boot sources' -public -f=- |
| 44 | +` |
| 45 | + |
| 46 | +var contextImportCommand = clicompat.Wrap(&cli.Command{ |
| 47 | + Name: "import", |
| 48 | + Usage: "creates a search context from an SBOM", |
| 49 | + UsageText: "src context import [options]", |
| 50 | + Description: contextImportExamples, |
| 51 | + HideVersion: true, |
| 52 | + Flags: clicompat.WithAPIFlags( |
| 53 | + &cli.StringFlag{ |
| 54 | + Name: "name", |
| 55 | + Usage: "The name of the new search context", |
| 56 | + Required: true, |
| 57 | + Validator: requiresNotEmpty("provide a search context name using -name"), |
| 58 | + }, |
| 59 | + &cli.StringFlag{ |
| 60 | + Name: "file", |
| 61 | + Aliases: []string{"f"}, |
| 62 | + Usage: "SPDX 3.0 or CycloneDX JSON SBOM file to import (- for stdin)", |
| 63 | + TakesFile: true, |
| 64 | + Required: true, |
| 65 | + Validator: requiresNotEmpty("provide an SBOM file using -file"), |
| 66 | + }, |
| 67 | + &cli.StringFlag{ |
| 68 | + Name: "description", |
| 69 | + Usage: "The description of the new search context", |
| 70 | + }, |
| 71 | + &cli.BoolFlag{ |
| 72 | + Name: "public", |
| 73 | + Usage: "Make the search context visible to everyone instead of only you", |
| 74 | + }, |
| 75 | + ), |
| 76 | + Action: func(ctx context.Context, cmd *cli.Command) error { |
| 77 | + sbom, err := readFile(cmd.String("file")) |
| 78 | + if err != nil { |
| 79 | + return err |
| 80 | + } |
| 81 | + |
| 82 | + visibility := "VISIBILITY_PRIVATE" |
| 83 | + if cmd.Bool("public") { |
| 84 | + visibility = "VISIBILITY_PUBLIC" |
| 85 | + } |
| 86 | + |
| 87 | + client := cfg.apiClient(clicompat.APIFlagsFromCmd(cmd), cmd.Writer) |
| 88 | + return runContextImport(ctx, client, importSbomRequest{ |
| 89 | + SearchContextID: cmd.String("name"), |
| 90 | + SBOM: string(sbom), |
| 91 | + Description: cmd.String("description"), |
| 92 | + Visibility: visibility, |
| 93 | + }, cmd.Writer) |
| 94 | + }, |
| 95 | +}) |
| 96 | + |
| 97 | +// importSbomRequest is the JSON form of searchcontexts.v1.ImportSbomRequest. |
| 98 | +type importSbomRequest struct { |
| 99 | + SearchContextID string `json:"searchContextId"` |
| 100 | + SBOM string `json:"sbom"` |
| 101 | + Description string `json:"description,omitempty"` |
| 102 | + Visibility string `json:"visibility"` |
| 103 | +} |
| 104 | + |
| 105 | +// importSbomResponse is the JSON form of searchcontexts.v1.ImportSbomResponse. |
| 106 | +type importSbomResponse struct { |
| 107 | + SearchContext struct { |
| 108 | + Spec string `json:"spec"` |
| 109 | + Repositories []struct { |
| 110 | + Repository string `json:"repository"` |
| 111 | + Revisions []string `json:"revisions"` |
| 112 | + } `json:"repositories"` |
| 113 | + } `json:"searchContext"` |
| 114 | + SkippedPackages []struct { |
| 115 | + ID string `json:"id"` |
| 116 | + DisplayName string `json:"displayName"` |
| 117 | + VCSURL string `json:"vcsUrl"` |
| 118 | + Reason string `json:"reason"` |
| 119 | + } `json:"skippedPackages"` |
| 120 | +} |
| 121 | + |
| 122 | +var skippedPackageReasons = map[string]string{ |
| 123 | + "REASON_MISSING_VCS_REFERENCE": "no Git repository reference", |
| 124 | + "REASON_INVALID_VCS_REFERENCE": "invalid Git repository reference", |
| 125 | + "REASON_MISSING_REVISION": "no revision in the Git repository reference", |
| 126 | + "REASON_REPOSITORY_NOT_FOUND": "repository not found on this Sourcegraph instance", |
| 127 | +} |
| 128 | + |
| 129 | +func runContextImport(ctx context.Context, client api.Client, input importSbomRequest, out io.Writer) error { |
| 130 | + body, err := json.Marshal(input) |
| 131 | + if err != nil { |
| 132 | + return err |
| 133 | + } |
| 134 | + req, err := client.NewHTTPRequest(ctx, http.MethodPost, "api/searchcontexts.v1.Service/ImportSbom", bytes.NewReader(body)) |
| 135 | + if err != nil { |
| 136 | + return err |
| 137 | + } |
| 138 | + req.Header.Set("Connect-Protocol-Version", "1") |
| 139 | + |
| 140 | + resp, err := client.Do(req) |
| 141 | + if err != nil { |
| 142 | + return err |
| 143 | + } |
| 144 | + defer resp.Body.Close() |
| 145 | + |
| 146 | + respBody, err := io.ReadAll(resp.Body) |
| 147 | + if err != nil { |
| 148 | + return err |
| 149 | + } |
| 150 | + if resp.StatusCode != http.StatusOK { |
| 151 | + return connectError(resp.Status, respBody) |
| 152 | + } |
| 153 | + |
| 154 | + var result importSbomResponse |
| 155 | + if err := json.Unmarshal(respBody, &result); err != nil { |
| 156 | + return errors.Wrap(err, "decoding response") |
| 157 | + } |
| 158 | + |
| 159 | + fmt.Fprintf(out, "Search context %q created with %d repositories.\n", result.SearchContext.Spec, len(result.SearchContext.Repositories)) |
| 160 | + if len(result.SkippedPackages) > 0 { |
| 161 | + fmt.Fprintf(out, "\nSkipped %d packages:\n", len(result.SkippedPackages)) |
| 162 | + for _, p := range result.SkippedPackages { |
| 163 | + reason := skippedPackageReasons[p.Reason] |
| 164 | + if reason == "" { |
| 165 | + reason = p.Reason |
| 166 | + } |
| 167 | + fmt.Fprintf(out, " %s (id %q): %s\n", p.DisplayName, p.ID, reason) |
| 168 | + } |
| 169 | + } |
| 170 | + return nil |
| 171 | +} |
| 172 | + |
| 173 | +// connectError turns a Connect protocol error response into an error that |
| 174 | +// includes the per-package reasons the server attaches as a google.rpc.BadRequest |
| 175 | +// detail when nothing in the SBOM could be imported. |
| 176 | +func connectError(status string, body []byte) error { |
| 177 | + var connectErr struct { |
| 178 | + Code string `json:"code"` |
| 179 | + Message string `json:"message"` |
| 180 | + Details []struct { |
| 181 | + Type string `json:"type"` |
| 182 | + Value string `json:"value"` |
| 183 | + } `json:"details"` |
| 184 | + } |
| 185 | + if err := json.Unmarshal(body, &connectErr); err != nil || connectErr.Code == "" { |
| 186 | + if len(body) > 1024 { |
| 187 | + body = body[:1024] |
| 188 | + } |
| 189 | + return errors.Newf("error: %s\n\n%s", status, body) |
| 190 | + } |
| 191 | + |
| 192 | + var msg strings.Builder |
| 193 | + msg.WriteString(connectErr.Message) |
| 194 | + for _, d := range connectErr.Details { |
| 195 | + if d.Type != "google.rpc.BadRequest" { |
| 196 | + continue |
| 197 | + } |
| 198 | + // Connect encodes details as base64 without padding but accepts both forms. |
| 199 | + value, err := base64.RawStdEncoding.DecodeString(strings.TrimRight(d.Value, "=")) |
| 200 | + if err != nil { |
| 201 | + continue |
| 202 | + } |
| 203 | + var badRequest errdetails.BadRequest |
| 204 | + if err := proto.Unmarshal(value, &badRequest); err != nil { |
| 205 | + continue |
| 206 | + } |
| 207 | + for _, v := range badRequest.GetFieldViolations() { |
| 208 | + msg.WriteString("\n ") |
| 209 | + msg.WriteString(v.GetDescription()) |
| 210 | + } |
| 211 | + } |
| 212 | + return errors.New(msg.String()) |
| 213 | +} |
0 commit comments