Skip to content

Commit 59bba18

Browse files
trlyampagent
andcommitted
feat/search-contexts: add src context import to create a search context from an SBOM
Adds `src context import`, which uploads an SPDX 3.0 or CycloneDX SBOM to the searchcontexts.v1.Service/ImportSbom API and creates a search context that pins each package's repository to the revision the SBOM references. Skipped packages and, when nothing could be imported, the server's per-package reasons are printed. Amp-Thread-ID: https://ampcode.com/threads/T-01a1fadb-1fc9-71ed-b299-b28bea8a28b5 Co-authored-by: Amp <amp@ampcode.com>
1 parent f2901d1 commit 59bba18

8 files changed

Lines changed: 356 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ All notable changes to `src-cli` are documented in this file.
1414
### Added
1515

1616
- `src` now prints a warning to stderr when it is older than the version recommended by your Sourcegraph instance. The recommended version is looked up at most once every 24 hours per instance. To disable the check, set the `SRC_SKIP_VERSION_CHECK` environment variable to any non-blank string. [#930](https://github.com/sourcegraph/src-cli/issues/930)
17+
- `src context import` creates a search context from an SPDX 3.0 or CycloneDX SBOM, pinning each package's repository to the revision the SBOM references. Requires a Sourcegraph instance with the `searchcontexts.v1.Service/ImportSbom` API.
1718

1819
### Changed
1920

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ Is your Sourcegraph instance behind a custom auth proxy? See [auth proxy configu
174174
- `src code-intel` - manage code intelligence data
175175
- `src codeowners` - manage ingested code ownership data
176176
- `src config` - manage global, org, and user settings
177+
- `src context` - manage search contexts, such as creating one from an SBOM
177178
- `src debug` - gather and bundle debug data from a Sourcegraph deployment for troubleshooting
178179
- `src extsvc` - manage external services (repository configuration)
179180
- `src login` - authenticate to a Sourcegraph instance with your user credentials

‎cmd/src/context.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package main
2+
3+
import (
4+
"github.com/sourcegraph/src-cli/internal/clicompat"
5+
"github.com/urfave/cli/v3"
6+
)
7+
8+
var contextCommand = clicompat.Wrap(&cli.Command{
9+
Name: "context",
10+
Usage: "manages search contexts",
11+
UsageText: "src context [command options]",
12+
Description: contextExamples,
13+
HideVersion: true,
14+
Commands: []*cli.Command{
15+
contextImportCommand,
16+
},
17+
})
18+
19+
const contextExamples = `'src context' is a tool that manages search contexts on a Sourcegraph instance.
20+
21+
Usage:
22+
23+
src context command [command options]
24+
25+
The commands are:
26+
27+
import creates a search context from an SBOM
28+
29+
Use "src context [command] -h" for more information about a command.
30+
`

‎cmd/src/context_import.go‎

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
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+
}

‎cmd/src/context_import_test.go‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/base64"
7+
"encoding/json"
8+
"io"
9+
"net/http"
10+
"net/http/httptest"
11+
"net/url"
12+
"testing"
13+
14+
"github.com/stretchr/testify/require"
15+
"google.golang.org/genproto/googleapis/rpc/errdetails"
16+
"google.golang.org/protobuf/proto"
17+
18+
"github.com/sourcegraph/src-cli/internal/api"
19+
)
20+
21+
func TestRunContextImport(t *testing.T) {
22+
newClient := func(t *testing.T, handler http.HandlerFunc) api.Client {
23+
server := httptest.NewServer(handler)
24+
t.Cleanup(server.Close)
25+
endpoint, err := url.Parse(server.URL)
26+
require.NoError(t, err)
27+
return api.NewClient(api.ClientOpts{
28+
EndpointURL: endpoint,
29+
AccessToken: "abc",
30+
Flags: api.NewFlagsFromValues(false, false, false, false, false),
31+
Out: io.Discard,
32+
})
33+
}
34+
35+
t.Run("creates search context and lists skipped packages", func(t *testing.T) {
36+
client := newClient(t, func(w http.ResponseWriter, r *http.Request) {
37+
require.Equal(t, http.MethodPost, r.Method)
38+
require.Equal(t, "/api/searchcontexts.v1.Service/ImportSbom", r.URL.Path)
39+
require.Equal(t, "application/json", r.Header.Get("Content-Type"))
40+
require.Equal(t, "token abc", r.Header.Get("Authorization"))
41+
42+
var body map[string]any
43+
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
44+
require.Equal(t, map[string]any{
45+
"searchContextId": "spring-sbom",
46+
"sbom": `{"bomFormat":"CycloneDX"}`,
47+
"visibility": "VISIBILITY_PUBLIC",
48+
}, body)
49+
50+
_, _ = io.WriteString(w, `{
51+
"searchContext": {
52+
"name": "users/1/searchContexts/spring-sbom",
53+
"spec": "@alice/spring-sbom",
54+
"visibility": "VISIBILITY_PUBLIC",
55+
"repositories": [
56+
{"repository": "github.com/spring-projects/spring-boot", "revisions": ["refs/tags/v4.1.1"]},
57+
{"repository": "github.com/spring-projects/spring-framework", "revisions": ["v7.0.0"]}
58+
]
59+
},
60+
"skippedPackages": [
61+
{"id": "left-pad", "displayName": "left-pad@1.3.0", "reason": "REASON_MISSING_VCS_REFERENCE"}
62+
]
63+
}`)
64+
})
65+
66+
var out bytes.Buffer
67+
err := runContextImport(context.Background(), client, importSbomRequest{
68+
SearchContextID: "spring-sbom",
69+
SBOM: `{"bomFormat":"CycloneDX"}`,
70+
Visibility: "VISIBILITY_PUBLIC",
71+
}, &out)
72+
require.NoError(t, err)
73+
require.Equal(t, `Search context "@alice/spring-sbom" created with 2 repositories.
74+
75+
Skipped 1 packages:
76+
left-pad@1.3.0 (id "left-pad"): no Git repository reference
77+
`, out.String())
78+
})
79+
80+
t.Run("reports why nothing could be imported", func(t *testing.T) {
81+
detail, err := proto.Marshal(&errdetails.BadRequest{FieldViolations: []*errdetails.BadRequest_FieldViolation{
82+
{Field: "sbom", Description: `left-pad@1.3.0 (id "left-pad"): REASON_MISSING_VCS_REFERENCE`},
83+
{Field: "sbom", Description: `internal-lib@2.0 (id "internal-lib"): REASON_REPOSITORY_NOT_FOUND`},
84+
}})
85+
require.NoError(t, err)
86+
87+
client := newClient(t, func(w http.ResponseWriter, r *http.Request) {
88+
w.Header().Set("Content-Type", "application/json")
89+
w.WriteHeader(http.StatusBadRequest)
90+
_ = json.NewEncoder(w).Encode(map[string]any{
91+
"code": "failed_precondition",
92+
"message": "none of the 2 packages in the SBOM has a Git repository and revision on this Sourcegraph instance",
93+
"details": []map[string]string{{
94+
"type": "google.rpc.BadRequest",
95+
"value": base64.RawStdEncoding.EncodeToString(detail),
96+
}},
97+
})
98+
})
99+
100+
var out bytes.Buffer
101+
err = runContextImport(context.Background(), client, importSbomRequest{SearchContextID: "x", SBOM: "{}"}, &out)
102+
require.EqualError(t, err, `none of the 2 packages in the SBOM has a Git repository and revision on this Sourcegraph instance
103+
left-pad@1.3.0 (id "left-pad"): REASON_MISSING_VCS_REFERENCE
104+
internal-lib@2.0 (id "internal-lib"): REASON_REPOSITORY_NOT_FOUND`)
105+
require.Empty(t, out.String())
106+
})
107+
}

‎cmd/src/doc_test.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ var expectedDocFiles = []string{
4848
"config/get.md",
4949
"config/index.md",
5050
"config/list.md",
51+
"context/import.md",
52+
"context/index.md",
5153
"debug/compose.md",
5254
"debug/index.md",
5355
"debug/kube.md",

‎cmd/src/run_migration_compat.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ var migratedCommands = map[string]*cli.Command{
2424
"codeowners": codeownersCommand,
2525
// instead of writing lots of plumbing to handle an alias, lets just register it explicitly for now
2626
"codeowner": codeownersCommand,
27+
"context": contextCommand,
2728
"login": loginCommand,
2829
"orgs": orgsCommand,
2930
"org": orgsCommand,

0 commit comments

Comments
 (0)