diff --git a/dev/sg/BUILD.bazel b/dev/sg/BUILD.bazel index 3fbd30b0af1..e6a84fdd282 100644 --- a/dev/sg/BUILD.bazel +++ b/dev/sg/BUILD.bazel @@ -15,6 +15,7 @@ go_library( "sg_backport.go", "sg_bazel.go", "sg_cloud.go", + "sg_cody_gateway.go", "sg_db.go", "sg_deploy.go", "sg_doctor.go", @@ -82,6 +83,7 @@ go_library( "//dev/sg/root", "//dev/sg/sams", "//dev/team", + "//internal/accesstoken", "//internal/database", "//internal/database/basestore", "//internal/database/connections/live", diff --git a/dev/sg/main.go b/dev/sg/main.go index d551bba5d58..e53e7d5e6ae 100644 --- a/dev/sg/main.go +++ b/dev/sg/main.go @@ -9,9 +9,8 @@ import ( "time" hashstructure "github.com/mitchellh/hashstructure/v2" - "github.com/urfave/cli/v2" - "github.com/sourcegraph/log" + "github.com/urfave/cli/v2" "github.com/sourcegraph/sourcegraph/dev/sg/ci" "github.com/sourcegraph/sourcegraph/dev/sg/internal/analytics" @@ -312,6 +311,7 @@ var sg = &cli.App{ release.Command, updateCommand, versionCommand, + codyGatewayCommand, }, ExitErrHandler: func(cmd *cli.Context, err error) { interrupt.Wait() diff --git a/dev/sg/sg_cody_gateway.go b/dev/sg/sg_cody_gateway.go new file mode 100644 index 00000000000..a22538d855e --- /dev/null +++ b/dev/sg/sg_cody_gateway.go @@ -0,0 +1,47 @@ +package main + +import ( + "os" + "strings" + + "github.com/urfave/cli/v2" + + "github.com/sourcegraph/sourcegraph/dev/sg/internal/category" + "github.com/sourcegraph/sourcegraph/dev/sg/internal/std" + "github.com/sourcegraph/sourcegraph/internal/accesstoken" + "github.com/sourcegraph/sourcegraph/lib/errors" +) + +var codyGatewayCommand = &cli.Command{ + Name: "cody-gateway", + Usage: "set of commands that are helpful for working with Cody Gateway locally", + Category: category.Util, + Subcommands: []*cli.Command{{ + Name: "gen-token", + Usage: "generate a new token for use with Cody Gateway", + UsageText: "sg cody-gateway gen-token [sg token]", + Description: "generates a token with the given `sg token` - which should be prefixed with `sgp_`", + Action: genGatewayAccessTokenExec, + }}, +} + +func genGatewayAccessTokenExec(c *cli.Context) error { + out := std.NewOutput(os.Stderr, false) + if c.NArg() == 0 { + out.WriteWarningf("The first argument should be a Sourcegraph private access token - see --help for more information") + return errors.New("missing private access token argument") + } + + out.WriteNoticef("Generating new gateway access token ...") + privateToken := c.Args().Get(0) + if !strings.HasPrefix(privateToken, "sgp_") { + out.WriteWarningf("Token must be prefixed with \"sgp_\"") + return errors.New("invalid token: not prefixed with sgp_") + } + accessToken, err := accesstoken.GenerateDotcomUserGatewayAccessToken(privateToken) + if err != nil { + return errors.Newf("failed to generate gateway access token: %s", err) + } + std.Out.Write(accessToken) + return nil +}