package dfcmd import ( "cmp" "context" "errors" "fmt" "os" "strings" "github.com/MakeNowJust/heredoc/v2" "github.com/spf13/cobra" gitlab "gitlab.com/gitlab-org/api/client-go/v3" "gitlab.com/gitlab-org/cli/internal/cmdutils" "gitlab.com/gitlab-org/cli/internal/config" "gitlab.com/gitlab-org/cli/internal/dependencyfirewall/pm" "gitlab.com/gitlab-org/cli/internal/iostreams" "gitlab.com/gitlab-org/cli/internal/mcpannotations" "gitlab.com/gitlab-org/cli/internal/text" ) // ProxySpec describes one package-manager wrapper command. The wrapper // forwards all args to the package manager binary through the Dependency // Firewall inspection proxy. type ProxySpec struct { Manager func() pm.PackageManager Use string Short string Long string Example string // Environment replaces the help for the outbound proxy variables, for a // manager that doesn't reach registries through the firewall proxy. Environment string } var proxyEnvironmentHelp = heredoc.Doc(` HTTPS_PROXY: outbound proxy glab uses to reach package registries. Credentials in the URL are sent to the proxy. HTTP_PROXY: outbound proxy for plain-HTTP registries. When it's unset, glab uses HTTPS_PROXY. NO_PROXY: hosts glab reaches directly instead of through an outbound proxy. `) var httpsFirstProxyEnvironmentHelp = heredoc.Doc(` HTTPS_PROXY: outbound proxy glab uses to reach package registries, plain-HTTP registries included. Credentials in the URL are sent to the proxy. HTTP_PROXY: outbound proxy for plain-HTTP registries when HTTPS_PROXY is unset. NO_PROXY: hosts glab reaches directly instead of through an outbound proxy. `) func environmentHelp(name string, manager pm.PackageManager) string { help := proxyEnvironmentHelp if pm.PlainHTTPUsesHTTPSProxy(manager) { help = httpsFirstProxyEnvironmentHelp } vars := pm.OwnProxyVariables(manager) files := pm.OwnProxyConfigFiles(manager) var own string switch { case len(vars) == 1: own = fmt.Sprintf("%s: proxy setting for %s. glab reads it first, so the outbound proxy can differ from HTTPS_PROXY and HTTP_PROXY.", vars[0], name) case len(vars) > 1: own = fmt.Sprintf("%s: proxy settings for %s. glab reads them first, so the outbound proxy can differ from HTTPS_PROXY and HTTP_PROXY.", strings.Join(vars, ", "), name) case len(files) > 0: own = fmt.Sprintf("glab reads the proxy settings for %s from your user and global config files first (%s), so the outbound proxy can differ from HTTPS_PROXY and HTTP_PROXY.", name, strings.Join(files, ", ")) default: return help } if len(files) > 0 { if len(vars) > 0 { own += fmt.Sprintf(" glab also reads the same settings from your user and global config files (%s).", strings.Join(files, ", ")) } own += " glab doesn't read proxy settings from files inside the project." } if note := pm.OwnProxyHelpNote(manager); note != "" { own += " " + note } return help + own + "\n" } type options struct { io *iostreams.IOStreams executor cmdutils.Executor baseRepo func() (host, projectID string, err error) gitlabClient func() (*gitlab.Client, error) config func() config.Config manager func() pm.PackageManager name string args []string baseDir string } // NewProxyCmd builds a df package-manager wrapper command from spec. func NewProxyCmd(f cmdutils.Factory, spec ProxySpec) *cobra.Command { opts := &options{ io: f.IO(), executor: f.Executor(), baseRepo: func() (string, string, error) { r, err := f.BaseRepo() if err != nil { return "", "", err } return r.RepoHost(), r.FullName(), nil }, gitlabClient: f.GitLabClient, config: f.Config, manager: spec.Manager, name: firstWord(spec.Use), } return &cobra.Command{ Use: spec.Use, Short: spec.Short + " (BETA)", Annotations: map[string]string{ mcpannotations.Exclude: "true", "help:environment": cmp.Or(spec.Environment, environmentHelp(opts.name, spec.Manager())), }, DisableFlagParsing: true, Long: spec.Long + text.BetaString, Example: spec.Example, RunE: func(cmd *cobra.Command, args []string) error { opts.args = args if err := opts.complete(); err != nil { return err } return opts.run(cmd.Context()) }, } } // firstWord returns the command name from a cobra Use string, e.g. // "npm " -> "npm". func firstWord(use string) string { name, _, _ := strings.Cut(use, " ") return name } func (o *options) complete() error { wd, err := os.Getwd() if err != nil { return err } o.baseDir = wd return nil } func (o *options) run(ctx context.Context) error { host, projectID, err := o.baseRepo() if err != nil { return cmdutils.WrapError(cmdutils.WithGitRequiredHint(o.executor, err), "failed to resolve GitLab project from the git remote.") } client, err := o.gitlabClient() if err != nil { return cmdutils.WrapError(err, "failed to create a GitLab API client.") } caCert, err := o.config().Get(host, "ca_cert") if err != nil { return cmdutils.WrapError(err, "failed to read ca_cert from the glab configuration.") } clientCert, err := o.config().Get(host, "client_cert") if err != nil { return cmdutils.WrapError(err, "failed to read client_cert from the glab configuration.") } clientKey, err := o.config().Get(host, "client_key") if err != nil { return cmdutils.WrapError(err, "failed to read client_key from the glab configuration.") } if err := pm.Run(ctx, o.manager(), pm.RunOptions{ IO: o.io, Executor: o.executor, BaseDir: o.baseDir, Client: client, ProjectID: projectID, Args: o.args, CACertPath: caCert, ClientCertPath: clientCert, ClientKeyPath: clientKey, ClientCertPassword: func() (string, error) { password, err := o.config().Get(host, "client_cert_password") if err != nil { return "", fmt.Errorf("failed to read client_cert_password for %q: %w", host, err) } return password, nil }, }); err != nil { if ee, ok := errors.AsType[*pm.ExitError](err); ok { if ee.ChildExited { // The child actually ran, so the Dependency Firewall summary // already tells the user what happened (including any blocked // packages that made it exit non-zero). Wrap SilentError to // preserve the exit code without letting fang render a // duplicate ERROR block after the summary. return cmdutils.WrapErrorWithCode(cmdutils.SilentError, ee.Code, ee.Error()) } // The child never ran (e.g. fork/exec failure), so no summary was // rendered. Surface a visible error instead of exiting silently. return cmdutils.WrapErrorWithCode(ee.Unwrap(), ee.Code, ee.Error()) } return cmdutils.WrapError(err, fmt.Sprintf("failed to run %s through the Dependency Firewall.", o.name)) } return nil }