Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <command> …` runs `nrc-<command> …` from the
plugin directory (`NORCUBE_PLUGIN_DIR`, by default
`<config dir>/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
Expand Down
9 changes: 9 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<command>`; the endpoint can wait until its
platform API is public. The CLI then has a `norcube <command>` 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 `<service> <resource> <verb>`: plural resources, verbs `list`,
Expand Down
87 changes: 87 additions & 0 deletions docs/PLUGINS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Plugins

Some Norcube products ship their command-line engine as a separate
executable, a **plugin**. `norcube <command> …` 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-<command>` (`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 `<user config dir>/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> __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] <command> [args…]` runs `<plugin> [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 <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.
28 changes: 16 additions & 12 deletions internal/cli/authcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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))
Expand Down
20 changes: 20 additions & 0 deletions internal/cli/authcmd_audience_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
5 changes: 3 additions & 2 deletions internal/cli/contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)?\(`)
Expand Down
4 changes: 4 additions & 0 deletions internal/cli/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
95 changes: 95 additions & 0 deletions internal/cli/plugin.go
Original file line number Diff line number Diff line change
@@ -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 <config dir>/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 <aud>`.
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
}
64 changes: 64 additions & 0 deletions internal/cli/plugin_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
1 change: 1 addition & 0 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ func NewRootCmd() *cobra.Command {
monitor.NewCmd(),
cms.NewCmd(),
)
cmd.AddCommand(newPluginCmds()...)
markUsageErrors(cmd)
completion.Bind(flags)
registerCompletions(cmd)
Expand Down
7 changes: 7 additions & 0 deletions internal/clierr/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Loading
Loading