diff --git a/CHANGELOG.md b/CHANGELOG.md index 041409a..b473fb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,23 @@ this file collects what users and scripts need to know. ## Unreleased +### New + +- Plugins: a product whose engine ships as its own executable can add a + command group. `norcube …` runs `nrc- …` from the + plugin directory (`NORCUBE_PLUGIN_DIR`, by default + `/norcube/plugins`) or `PATH`. Only plugins named in the + service registry run, an executable other users can write is refused, + and a version handshake comes first. Plugins get short-lived tokens from + `norcube auth token`, never stored credentials. Contract: + `docs/PLUGINS.md`. +- `norcube pentest` runs the Norcube Pentest engine (`nrc-pentest`), the + first plugin. The engine is installed separately; until it is, + `norcube pentest` says how to install it. +- `norcube auth token --audience` accepts every service the CLI knows, + taken from its service registry (new: `pentest`). The names it accepted + before are unchanged. + ## 0.29.0 (2026-11-26) ### New diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f5ae874..4991683 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -124,6 +124,15 @@ cached for a day in the user cache directory. 4. **Wire it** into `NewRootCmd` in `internal/cli/root.go`, and register dynamic completions for the resource ids it takes. + +## Adding a plugin service + +A product whose engine ships as its own executable adds an entry with +`command` and `plugin: nrc-`; the endpoint can wait until its +platform API is public. The CLI then has a `norcube ` that runs the +plugin (internal/plugin, internal/cli/plugin.go). The contract the plugin +implements is [PLUGINS.md](PLUGINS.md). + ## Adding a command - Name it ` `: plural resources, verbs `list`, diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md new file mode 100644 index 0000000..a577641 --- /dev/null +++ b/docs/PLUGINS.md @@ -0,0 +1,87 @@ +# Plugins + +Some Norcube products ship their command-line engine as a separate +executable, a **plugin**. `norcube …` then runs that executable +with the arguments that follow, so the product's commands sit next to every +other `norcube` command while the engine is built and released on its own. + +This document is the contract between the CLI and a plugin. **Protocol +version: 1.** + +## Which plugins run + +- Only plugins named in the service registry + (`internal/registry/services.yaml`, field `plugin`) ever run. The CLI never + discovers executables by a name prefix, so a file called + `nrc-something` on `PATH` does nothing. +- A plugin's executable is named `nrc-` (`nrc-example` for + `norcube example`). The registry refuses any other name. +- Lookup order: the plugin directory, then `PATH`. The plugin directory is + `NORCUBE_PLUGIN_DIR`, else `/norcube/plugins` + (`~/Library/Application Support/norcube/plugins` on macOS, + `~/.config/norcube/plugins` on Linux, `%AppData%\norcube\plugins` on + Windows). +- An executable, or the directory it is in, that other users may write is + refused. Anyone who could replace it could run code as you. + +## Handshake + +Before running a plugin the CLI runs ` __plugin-info` (5-second +limit) and expects one JSON object on stdout: + +```json +{"name": "nrc-example", "version": "1.4.0", "protocol": 1} +``` + +The CLI refuses a plugin whose `name` differs from the registry's, or whose +`protocol` differs from its own, and names the side that needs an update. + +## Running + +`norcube [global flags] [args…]` runs ` [args…]`: + +- **Arguments.** Everything after the command goes to the plugin + unchanged, including `--help`. Global flags before the command + (`--profile`, `--org`, `-o`, `--debug`) are applied by the CLI and passed + to the plugin in the environment. +- **Streams.** stdin, stdout and stderr are the terminal's. The plugin + prints its own result and errors; the CLI adds nothing. +- **Exit code.** The CLI exits with the plugin's exit code. Codes 2 + (usage), 4 (login required), 5 (permission denied) and 130 (interrupted) + mean the same as in the CLI; others are the plugin's own and documented + by it. +- **Signals.** Ctrl-C cancels the plugin; after 5 seconds it is killed. + +## Environment + +| Variable | Meaning | +|---|---| +| `NRC_PLUGIN_PROTOCOL` | The protocol version, `1` | +| `NRC_BIN` | Absolute path of the running CLI, for calling it back | +| `NRC_PROFILE` | `--profile`, when given | +| `NRC_ORG` | `--org`, when given | +| `NRC_OUTPUT` | `-o`, when given (`table`, `json`, `yaml`, `text`, `id`) | +| `NRC_DEBUG` | `1` with `--debug` | + +The rest of the environment is passed through (`NO_COLOR`, `NORCUBE_*`). + +## Credentials + +The CLI never hands a plugin a token or a refresh token. A plugin that +calls a Norcube API asks the CLI for a short-lived access token each time: + +```sh +"$NRC_BIN" auth token --audience -o json +``` + +That works with every way of signing in (browser login, device login, a CI +token in `NORCUBE_TOKEN`), honours the profile, organization and scopes, and +leaves storage and refresh to the CLI. A plugin must not store tokens. + +## Compatibility + +- A new protocol version is introduced only for a change a plugin must + react to. Additions (a new environment variable) keep version 1. +- The CLI speaks exactly one protocol version. When it moves to version 2, + plugins answer the handshake with the version they speak and the CLI + tells the person which side to update. diff --git a/internal/cli/authcmd.go b/internal/cli/authcmd.go index 2a36dc1..985911b 100644 --- a/internal/cli/authcmd.go +++ b/internal/cli/authcmd.go @@ -18,6 +18,7 @@ import ( "github.com/norcubeplatform/cli/internal/cmdutil" "github.com/norcubeplatform/cli/internal/config" "github.com/norcubeplatform/cli/internal/output" + "github.com/norcubeplatform/cli/internal/registry" "github.com/norcubeplatform/cli/internal/resolve" "github.com/norcubeplatform/cli/internal/term" ) @@ -353,18 +354,21 @@ func checkSession(ctx context.Context, flags *clictx.Flags, cfg *config.Config) return ts.CheckSession(ctx) } -// audiences maps the names `auth token --audience` accepts to Norcube -// audiences. -var audiences = map[string]string{ - "auth": auth.AudienceAuth, - "billing": auth.AudienceBilling, - "backup": auth.AudienceSnapDB, - "snapdb": auth.AudienceSnapDB, - "langsync": auth.AudienceLangsync, - "domainradar": auth.AudienceDomainradar, - "prompthub": auth.AudiencePrompthub, - "monitor": auth.AudienceMonitor, -} +// audiences maps the names `auth token --audience` accepts (each service's +// command, key and aliases) to its Norcube audience, from the service +// registry, so a new service is never a second edit here. +var audiences = func() map[string]string { + out := map[string]string{} + for _, s := range registry.All() { + if s.Audience == "" { + continue + } + for _, n := range s.Names() { + out[n] = s.Audience + } + } + return out +}() func audienceNames() []string { names := make([]string, 0, len(audiences)) diff --git a/internal/cli/authcmd_audience_test.go b/internal/cli/authcmd_audience_test.go new file mode 100644 index 0000000..3bb782a --- /dev/null +++ b/internal/cli/authcmd_audience_test.go @@ -0,0 +1,20 @@ +package cli + +import ( + "testing" + + "github.com/norcubeplatform/cli/internal/auth" +) + +// The audience names users already type keep working, and come from the registry. +func TestAuthTokenAudiencesComeFromTheRegistry(t *testing.T) { + for name, want := range map[string]string{ + "auth": auth.AudienceAuth, "billing": auth.AudienceBilling, "backup": auth.AudienceSnapDB, "snapdb": auth.AudienceSnapDB, + "langsync": auth.AudienceLangsync, "domainradar": auth.AudienceDomainradar, "prompthub": auth.AudiencePrompthub, + "monitor": auth.AudienceMonitor, "pentest": "pentest", + } { + if got := audiences[name]; got != want { + t.Errorf("--audience %s → %q, want %q", name, got, want) + } + } +} diff --git a/internal/cli/contract_test.go b/internal/cli/contract_test.go index 0ced623..3baba1a 100644 --- a/internal/cli/contract_test.go +++ b/internal/cli/contract_test.go @@ -37,8 +37,9 @@ func TestEveryCommandHasAnExample(t *testing.T) { // through cmdutil.Print, which honors -o and --query. These are the // places allowed to touch stdout directly. var stdoutAllowed = map[string]string{ - "authcmd.go": "term.IsTerminal(cmd.OutOrStdout())", // only asks whether it is a terminal - "config.go": "os.Stdin, os.Stdout, os.Stderr", // the user's editor runs on the terminal + "authcmd.go": "term.IsTerminal(cmd.OutOrStdout())", // only asks whether it is a terminal + "config.go": "os.Stdin, os.Stdout, os.Stderr", // the user's editor runs on the terminal + "plugin.go": "cmd.OutOrStdout(), cmd.ErrOrStderr()", // a plugin prints its own result (docs/PLUGINS.md) } var stdoutWrite = regexp.MustCompile(`OutOrStdout\(\)|os\.Stdout|fmt\.Print(f|ln)?\(`) diff --git a/internal/cli/errors.go b/internal/cli/errors.go index de39cc2..fcea62b 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -166,6 +166,10 @@ func outputFromArgs(args []string) string { // PrintError writes err to w, as {"error": {...}} when asJSON, otherwise as // the message and, on its own line, the hint. It returns the exit code. func PrintError(w io.Writer, err error, asJSON bool) int { + var passthrough clierr.PassthroughExit + if errors.As(err, &passthrough) { + return passthrough.Code + } e := Describe(err) if asJSON { enc := json.NewEncoder(w) diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go new file mode 100644 index 0000000..9235ae1 --- /dev/null +++ b/internal/cli/plugin.go @@ -0,0 +1,95 @@ +package cli + +import ( + "errors" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/norcubeplatform/cli/internal/clictx" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/plugin" + "github.com/norcubeplatform/cli/internal/registry" +) + +// newPluginCmds returns a command for every registry service implemented by a plugin. +func newPluginCmds() []*cobra.Command { + var out []*cobra.Command + for _, s := range registry.All() { + if s.Plugin != "" { + out = append(out, newPluginCmd(s)) + } + } + return out +} + +func newPluginCmd(s registry.Service) *cobra.Command { + cmd := &cobra.Command{ + Use: s.Command + " [args...]", + Aliases: s.Aliases, + Short: fmt.Sprintf("Norcube %s (plugin %s)", s.Name, s.Plugin), + Long: fmt.Sprintf(`Runs the Norcube %[1]s plugin, %[2]s, with the arguments that follow. + +The plugin is installed separately: put the %[2]s executable in the plugin +directory (NORCUBE_PLUGIN_DIR, by default /norcube/plugins) or on +PATH. The CLI only ever runs plugins it knows by name, refuses an executable +that other users can write, and checks the plugin protocol version first. +The plugin's own help: norcube %[3]s --help.`, s.Name, s.Plugin, s.Command), + Example: fmt.Sprintf(" norcube %[1]s --help\n norcube %[1]s version", s.Command), + Annotations: cmdutil.Local(), + DisableFlagParsing: true, // every argument belongs to the plugin + RunE: func(cmd *cobra.Command, args []string) error { + ctx := cmd.Context() + path, err := plugin.Locate(s.Plugin) + if errors.Is(err, plugin.ErrNotInstalled) { + dir, _ := plugin.Dir() + return &clierr.Error{ + Code: clierr.CodeNotFound, + Message: fmt.Sprintf("the %s plugin (%s) is not installed", s.Name, s.Plugin), + Hint: fmt.Sprintf("Install %s into %s or anywhere on PATH.", s.Plugin, dir), + Err: err, + } + } + if err != nil { + return &clierr.Error{Code: clierr.CodeError, Message: err.Error(), Err: err} + } + if _, err := plugin.Handshake(ctx, path, s.Plugin); err != nil { + return &clierr.Error{Code: clierr.CodeError, Message: err.Error(), Err: err} + } + code, err := plugin.Run(ctx, path, args, pluginEnv(cmd), cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr()) + if err != nil { + return &clierr.Error{Code: clierr.CodeError, Message: fmt.Sprintf("%s: %v", s.Plugin, err), Err: err} + } + if code != 0 { + return clierr.PassthroughExit{Code: code} + } + return nil + }, + } + return cmd +} + +// pluginEnv is the CLI context a plugin receives (docs/PLUGINS.md). Credentials are never +// passed: a plugin that needs a token runs `$NRC_BIN auth token --audience `. +func pluginEnv(cmd *cobra.Command) []string { + env := []string{fmt.Sprintf("NRC_PLUGIN_PROTOCOL=%d", plugin.Protocol)} + if exe, err := os.Executable(); err == nil { + env = append(env, "NRC_BIN="+exe) + } + if flags := clictx.Get(cmd); flags != nil { + add := func(k, v string) { + if v != "" { + env = append(env, k+"="+v) + } + } + add("NRC_PROFILE", flags.Profile) + add("NRC_ORG", flags.OrgOverride) + add("NRC_OUTPUT", flags.Output) + if flags.Debug { + env = append(env, "NRC_DEBUG=1") + } + } + return env +} diff --git a/internal/cli/plugin_test.go b/internal/cli/plugin_test.go new file mode 100644 index 0000000..9c931a5 --- /dev/null +++ b/internal/cli/plugin_test.go @@ -0,0 +1,64 @@ +package cli + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/plugin" + "github.com/norcubeplatform/cli/internal/registry" +) + +func TestPluginCommandPassesArgsAndExitCode(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell-script plugin") + } + dir := t.TempDir() + _ = os.Chmod(dir, 0o755) // #nosec G302 -- a plugin directory must be traversable; the test checks group/other write bits + script := "#!/bin/sh\nif [ \"$1\" = __plugin-info ]; then echo '{\"name\":\"nrc-demo\",\"version\":\"0.1.0\",\"protocol\":1}'; exit 0; fi\n" + + "echo \"args=$* protocol=$NRC_PLUGIN_PROTOCOL bin=${NRC_BIN:+set}\"\n[ \"$1\" = fail ] && exit 9\nexit 0\n" + if err := os.WriteFile(filepath.Join(dir, "nrc-demo"), []byte(script), 0o755); err != nil { // #nosec G306 -- test executable + t.Fatal(err) + } + t.Setenv(plugin.DirEnv, dir) + svc := registry.Service{Key: "demo", Name: "Demo", Command: "demo", Plugin: "nrc-demo"} + + cmd := newPluginCmd(svc) + var out bytes.Buffer + cmd.SetOut(&out) + cmd.SetArgs([]string{"run", "--flag", "x"}) + if err := cmd.Execute(); err != nil { + t.Fatal(err) + } + if got := out.String(); !strings.Contains(got, "args=run --flag x protocol=1 bin=set") { + t.Errorf("plugin output %q", got) + } + + cmd = newPluginCmd(svc) + cmd.SetOut(&out) + cmd.SetArgs([]string{"fail"}) + var pe clierr.PassthroughExit + if err := cmd.Execute(); !errors.As(err, &pe) || pe.Code != 9 { + t.Fatalf("err %v, want the plugin's exit 9", err) + } + var stderr bytes.Buffer + if code := PrintError(&stderr, pe, false); code != 9 || stderr.Len() != 0 { + t.Errorf("PrintError: code %d, printed %q", code, stderr.String()) + } +} + +func TestPluginCommandNotInstalled(t *testing.T) { + t.Setenv(plugin.DirEnv, t.TempDir()) + t.Setenv("PATH", t.TempDir()) + cmd := newPluginCmd(registry.Service{Key: "demo", Name: "Demo", Command: "demo", Plugin: "nrc-demo"}) + cmd.SetArgs(nil) + var ce *clierr.Error + if err := cmd.Execute(); !errors.As(err, &ce) || ce.Code != clierr.CodeNotFound || ce.Hint == "" { + t.Fatalf("err %v", err) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 9e52eef..879a994 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -111,6 +111,7 @@ func NewRootCmd() *cobra.Command { monitor.NewCmd(), cms.NewCmd(), ) + cmd.AddCommand(newPluginCmds()...) markUsageErrors(cmd) completion.Bind(flags) registerCompletions(cmd) diff --git a/internal/clierr/error.go b/internal/clierr/error.go index be7d65e..ba4745c 100644 --- a/internal/clierr/error.go +++ b/internal/clierr/error.go @@ -129,3 +129,10 @@ func CodeForStatus(status int, serviceType string) string { } return CodeError } + +// PassthroughExit carries the exit code of a plugin (docs/PLUGINS.md). The plugin has +// already printed its own result and errors, so nothing more is printed; the CLI exits +// with the plugin's code. +type PassthroughExit struct{ Code int } + +func (e PassthroughExit) Error() string { return fmt.Sprintf("plugin exited with status %d", e.Code) } diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go new file mode 100644 index 0000000..57baf87 --- /dev/null +++ b/internal/plugin/plugin.go @@ -0,0 +1,142 @@ +// Package plugin runs the executables that implement a service's commands outside this +// repository, such as a closed-source engine. The protocol is in +// docs/PLUGINS.md. +// +// Safety rules: +// - only executables named in the service registry run; nothing is discovered by prefix; +// - an executable, or the directory it is in, that other users may write is refused; +// - before the first run the executable must answer `__plugin-info` with a matching name +// and a supported protocol version. +package plugin + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "time" +) + +// Protocol is the plugin protocol version this CLI speaks. +const Protocol = 1 + +// InfoArg is the argument a plugin answers with its Info as JSON on stdout. +const InfoArg = "__plugin-info" + +// DirEnv overrides the plugin directory. +const DirEnv = "NORCUBE_PLUGIN_DIR" + +// infoTimeout bounds the protocol handshake. +const infoTimeout = 5 * time.Second + +// Info is a plugin's answer to InfoArg. +type Info struct { + Name string `json:"name"` + Version string `json:"version"` + Protocol int `json:"protocol"` +} + +// ErrNotInstalled means the executable was found neither in the plugin directory nor on PATH. +var ErrNotInstalled = errors.New("plugin not installed") + +// Dir is the directory plugins are installed into: NORCUBE_PLUGIN_DIR, else +// /norcube/plugins. +func Dir() (string, error) { + if d := os.Getenv(DirEnv); d != "" { + return d, nil + } + base, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(base, "norcube", "plugins"), nil +} + +// Locate finds the executable: the plugin directory first, then PATH. +func Locate(name string) (string, error) { + file := name + if runtime.GOOS == "windows" { + file += ".exe" + } + if dir, err := Dir(); err == nil { + p := filepath.Join(dir, file) + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p, checkPermissions(p) + } + } + p, err := exec.LookPath(name) + if err != nil { + return "", fmt.Errorf("%w: %s", ErrNotInstalled, name) + } + abs, err := filepath.Abs(p) + if err != nil { + return "", err + } + return abs, checkPermissions(abs) +} + +// checkPermissions refuses an executable or directory that other users can write: anyone +// who can replace it could run code as the person who types the command. +func checkPermissions(path string) error { + if runtime.GOOS == "windows" { + return nil + } + for _, p := range []string{path, filepath.Dir(path)} { + st, err := os.Stat(p) + if err != nil { + return err + } + if st.Mode().Perm()&0o022 != 0 { + return fmt.Errorf("%s is writable by other users (mode %v); refusing to run it", p, st.Mode().Perm()) + } + } + return nil +} + +// Handshake runs ` __plugin-info` and checks the answer. +func Handshake(ctx context.Context, path, name string) (Info, error) { + ctx, cancel := context.WithTimeout(ctx, infoTimeout) + defer cancel() + var out bytes.Buffer + cmd := exec.CommandContext(ctx, path, InfoArg) // #nosec G204 -- path from the registry-bound lookup + cmd.Stdout = &out + if err := cmd.Run(); err != nil { + return Info{}, fmt.Errorf("%s %s: %w", name, InfoArg, err) + } + var info Info + if err := json.Unmarshal(out.Bytes(), &info); err != nil { + return Info{}, fmt.Errorf("%s %s: invalid answer: %w", name, InfoArg, err) + } + if info.Name != name { + return info, fmt.Errorf("%s answered as %q", name, info.Name) + } + if info.Protocol != Protocol { + return info, fmt.Errorf("%s speaks plugin protocol %d, this CLI speaks %d: update the one that is older", name, info.Protocol, Protocol) + } + return info, nil +} + +// Run executes the plugin with args and the CLI's context in env, wiring the standard +// streams, and returns its exit code. +func Run(ctx context.Context, path string, args, env []string, stdin io.Reader, stdout, stderr io.Writer) (int, error) { + cmd := exec.CommandContext(ctx, path, args...) // #nosec G204 -- path from the registry-bound lookup + cmd.Env = append(os.Environ(), env...) + cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr + cmd.WaitDelay = 5 * time.Second + err := cmd.Run() + var exit *exec.ExitError + switch { + case err == nil: + return 0, nil + case errors.As(err, &exit): + return exit.ExitCode(), nil + default: + return 0, err + } +} diff --git a/internal/plugin/plugin_test.go b/internal/plugin/plugin_test.go new file mode 100644 index 0000000..683ae02 --- /dev/null +++ b/internal/plugin/plugin_test.go @@ -0,0 +1,87 @@ +package plugin + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// fakePlugin writes a shell-script plugin into a fresh plugin directory. +func fakePlugin(t *testing.T, name, info string) string { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("shell-script plugins") + } + dir := t.TempDir() + if err := os.Chmod(dir, 0o755); err != nil { // #nosec G302 -- a plugin directory must be traversable + t.Fatal(err) + } + script := `#!/bin/sh +if [ "$1" = "__plugin-info" ]; then echo '` + info + `'; exit 0; fi +echo "args:$*" +echo "protocol:$NRC_PLUGIN_PROTOCOL profile:$NRC_PROFILE" +if [ "$1" = "fail" ]; then exit 7; fi +` + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(script), 0o755); err != nil { // #nosec G306 -- test executable + t.Fatal(err) + } + t.Setenv(DirEnv, dir) + return p +} + +func TestLocateHandshakeRun(t *testing.T) { + fakePlugin(t, "nrc-example", `{"name":"nrc-example","version":"1.2.3","protocol":1}`) + path, err := Locate("nrc-example") + if err != nil { + t.Fatal(err) + } + info, err := Handshake(context.Background(), path, "nrc-example") + if err != nil || info.Version != "1.2.3" { + t.Fatalf("handshake: %+v %v", info, err) + } + var out bytes.Buffer + code, err := Run(context.Background(), path, []string{"authz", "run"}, []string{"NRC_PLUGIN_PROTOCOL=1", "NRC_PROFILE=work"}, nil, &out, &out) + if err != nil || code != 0 { + t.Fatalf("run: %d %v", code, err) + } + if !strings.Contains(out.String(), "args:authz run") || !strings.Contains(out.String(), "protocol:1 profile:work") { + t.Errorf("output %q", out.String()) + } + code, _ = Run(context.Background(), path, []string{"fail"}, nil, nil, &out, &out) + if code != 7 { + t.Errorf("exit code %d, want the plugin's 7", code) + } +} + +func TestHandshakeRefusesWrongNameOrProtocol(t *testing.T) { + for _, info := range []string{`{"name":"other","protocol":1}`, `{"name":"nrc-example","protocol":99}`, `not json`} { + p := fakePlugin(t, "nrc-example", info) + if _, err := Handshake(context.Background(), p, "nrc-example"); err == nil { + t.Errorf("%s accepted", info) + } + } +} + +func TestRefusesWritableByOthers(t *testing.T) { + p := fakePlugin(t, "nrc-example", `{"name":"nrc-example","protocol":1}`) + if err := os.Chmod(filepath.Dir(p), 0o777); err != nil { // #nosec G302 -- the condition under test + t.Fatal(err) + } + if _, err := Locate("nrc-example"); err == nil || !strings.Contains(err.Error(), "writable by other users") { + t.Errorf("world-writable directory accepted: %v", err) + } +} + +func TestNotInstalled(t *testing.T) { + t.Setenv(DirEnv, t.TempDir()) + t.Setenv("PATH", t.TempDir()) + if _, err := Locate("nrc-example"); !errors.Is(err, ErrNotInstalled) { + t.Errorf("err %v, want ErrNotInstalled", err) + } +} diff --git a/internal/registry/registry.go b/internal/registry/registry.go index 00c84d5..a03e5c5 100644 --- a/internal/registry/registry.go +++ b/internal/registry/registry.go @@ -42,6 +42,10 @@ type Service struct { // Package is the generated client under internal/api/; // empty when no client is generated yet. Package string `yaml:"package"` + // Plugin is the executable that implements the service's commands + // (`nrc …` runs ` …`, see docs/PLUGINS.md); empty + // for services built into the CLI. Only plugins named here ever run. + Plugin string `yaml:"plugin"` } // Spec is where a service's API description lives in the backend @@ -109,22 +113,24 @@ func Lookup(name string) (Service, bool) { return Service{}, false } -// Keys returns every service key in manifest order. +// Keys returns the key of every service with an endpoint, in manifest +// order (a plugin without a public platform API has none). func Keys() []string { - all := All() - out := make([]string, len(all)) - for i, s := range all { - out[i] = s.Key + var out []string + for _, s := range All() { + if s.Endpoint != "" { + out = append(out, s.Key) + } } return out } // Callable returns the services `nrc api` can call: those with an -// audience and a command name, sorted by command. +// audience, a command name and an endpoint, sorted by command. func Callable() []Service { var out []Service for _, s := range All() { - if s.Audience != "" && s.Command != "" { + if s.Audience != "" && s.Command != "" && s.Endpoint != "" { out = append(out, s) } } @@ -167,9 +173,12 @@ func Parse(data []byte) ([]Service, error) { return nil, err } } - u, err := url.Parse(s.Endpoint) - if err != nil || u.Scheme != "https" || u.Host == "" { - return nil, fmt.Errorf("service %s: endpoint must be an https URL, got %q", s.Key, s.Endpoint) + // A plugin whose platform API isn't public yet has no endpoint. + if s.Endpoint != "" || s.Plugin == "" { + u, err := url.Parse(s.Endpoint) + if err != nil || u.Scheme != "https" || u.Host == "" { + return nil, fmt.Errorf("service %s: endpoint must be an https URL, got %q", s.Key, s.Endpoint) + } } if s.Package != "" && (s.Spec == nil || s.Spec.App == "" || s.Spec.File == "") { return nil, fmt.Errorf("service %s: a generated package needs a spec", s.Key) @@ -177,6 +186,9 @@ func Parse(data []byte) ([]Service, error) { if s.Package != "" && !namePattern.MatchString(s.Package) { return nil, fmt.Errorf("service %s: invalid package %q", s.Key, s.Package) } + if s.Plugin != "" && (s.Command == "" || s.Plugin != "nrc-"+s.Command) { + return nil, fmt.Errorf("service %s: plugin must be named nrc-, got %q", s.Key, s.Plugin) + } } return doc.Services, nil } diff --git a/internal/registry/registry_test.go b/internal/registry/registry_test.go index 8a139c6..d0f7bbf 100644 --- a/internal/registry/registry_test.go +++ b/internal/registry/registry_test.go @@ -58,9 +58,30 @@ func TestParseRejects(t *testing.T) { "duplicate name": "services:\n - key: a\n name: A\n endpoint: https://a.example\n - key: b\n name: B\n aliases: [a]\n endpoint: https://b.example\n", "package no spec": "services:\n - key: a\n name: A\n endpoint: https://a.example\n package: a\n", "bad key": "services:\n - key: A B\n name: A\n endpoint: https://a.example\n", + "no endpoint": "services:\n - key: a\n name: A\n command: a\n", + "plugin name": "services:\n - key: a\n name: A\n command: a\n plugin: evil\n", + "plugin no cmd": "services:\n - key: a\n name: A\n plugin: nrc-a\n", } { if _, err := Parse([]byte(doc)); err == nil { t.Errorf("%s: accepted", name) } } } + +// A plugin service may have no endpoint yet; it is then left out of the +// endpoint keys (doctor, --endpoint-url, environments) but still has its +// command. +func TestPluginWithoutEndpoint(t *testing.T) { + got, err := Parse([]byte("services:\n - key: a\n name: A\n endpoint: https://a.example\n - key: p\n name: P\n command: p\n plugin: nrc-p\n")) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[1].Plugin != "nrc-p" { + t.Fatalf("got %+v", got) + } + for _, k := range Keys() { + if s, _ := Get(k); s.Endpoint == "" { + t.Errorf("Keys() lists %s, which has no endpoint", k) + } + } +} diff --git a/internal/registry/services.yaml b/internal/registry/services.yaml index aa0e2a0..035bd4b 100644 --- a/internal/registry/services.yaml +++ b/internal/registry/services.yaml @@ -9,6 +9,9 @@ # the backend monorepo, `package` the generated client under # internal/api/. # +# - plugins: `plugin` names the executable that implements a service's +# commands (docs/PLUGINS.md); only plugins listed here ever run. +# # Adding a service: add an entry here, run `make codegen`, then wire its # commands with service.New (see docs/ARCHITECTURE.md). services: @@ -80,3 +83,9 @@ services: spec: app: prompthub file: prompthub_swagger.json + + - key: pentest + name: Pentest + command: pentest + audience: pentest + plugin: nrc-pentest