Compare commits

...
Author SHA1 Message Date
BaaRai e7cceae63f Keep transcripts and noa archives owner-only, stop Norma ripgrep auto-install
Norma writes transcripts and noa archives with 0755 directories and 0644
files, so any other uid on the host, the executor that runs the agent's
commands included, could read every conversation.

LockDownPrivateDataDirs walks <data>/transcripts and <data>/noa under an
os.Root at the data directory: each directory keeps at most 0700 and each
regular file at most 0600, a narrower mode is kept, and every change goes
through the descriptor that was checked. A symlink, a hard-linked file, any
other entry and a directory not owned by the server are refused and left as
they are. cmd/artex runs it with the key directory lockdown, so a refusal or
a failed chmod fails the start unless ARTEX_ALLOW_UNISOLATED=1 is set;
NewManager runs it too and only logs.

Norma's Grep runs an unpinned npm install of @vscode/ripgrep when rg is
missing unless NORMA_RIPGREP_NO_INSTALL is non-empty. NewManager now always
sets it to 1, so an empty value cannot re-enable the install.
2026-12-04 12:20:25 +01:00
BaaRai c8c83e2862 Merge pull request #959 from BaaRai/fix/llm-runtime-url-guard
fix(server): guard saved LLM profiles and run-time completions like the connection test
2026-12-04 12:20:17 +01:00
9 changed files with 522 additions and 1 deletions
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **Transcripts and noa archives are owner-only, and Norma's Grep no longer installs ripgrep.** Norma writes `<data>/transcripts` and the noa compression archives under `<data>/noa` with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation (prompts, model output, tool results). At startup every directory in these two trees, the top ones included, now keeps at most its owner bits (0700) and every regular file at most owner read and write (0600); a narrower mode is never widened, and a missing top directory is created 0700. As for the key directory, nothing is changed by path: the trees are walked under an `os.Root` at the data directory, each entry is checked without following symlinks and changed through the descriptor that was checked, and a symlink (`transcripts` or `noa` themselves included), a hard-linked file or any other non-regular entry is refused and left as it is. A refusal or a failed mode change fails the start like a key directory that cannot be locked down: the error joins the isolation self-test, and only `ARTEX_ALLOW_UNISOLATED=1` (or `-dev-insecure-no-isolation`) starts anyway. Only the server reads these trees: the sandbox and Kubernetes workers mount only their task directory, the executor's shells and file tools work inside run directories, and archive export and the workspace file manager read them as the server. Files Norma writes later are still 0644 but sit under 0700 directories. Norma's Grep ran an unpinned `npm install -g @vscode/ripgrep` (install scripts enabled) when `rg` was missing; `NORMA_RIPGREP_NO_INSTALL` is now always set to `1` at startup, so no value, an empty one included, lets a Norma Grep install a package at run time (ARTEX's own Grep never starts ripgrep). Behaviour change: archiving the data directory as a non-root host user (`scripts/backup.sh --with-data`, which already asks for root) cannot read these two trees, and a data directory the server cannot change (for example an NFS export with root squashing, or a tree owned by another uid) fails the start until it is fixed or the opt-out is set.
- **Saved LLM profiles and run-time completions go through the model URL guard.** The connection test refused a `base_url` or proxy on a loopback, private or instance-metadata address, but saving a profile accepted it, and every completion of a task, chat or Agent bound to that profile was sent there with the profile's stored API key. Saving a profile (`POST /api/llm/profiles`) and the legacy `POST /api/llm` now refuse what the connection test refuses, and every completion provider the server builds validates the proxy and each request URL before sending, checks every connection on the address it dials (so a name that later resolves to a refused address is still refused), validates redirects and keeps them on the configured origin. The existing allowances are unchanged: an exact `host:port` listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` (for example Ollama or vLLM on the host or the Docker network) is accepted at save and at run time, and an Ollama profile on the built-in default `http://127.0.0.1:11434/v1` (an empty base URL) keeps working without it. Behaviour change: a stored profile, or an `ARTEX_LLM_*` environment config, whose endpoint or proxy points at a loopback, LAN or Docker-network address not listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` stops working (each request fails with the guard's refusal) until its `host:port` is added there; a SOCKS5 proxy on a profile is refused, as the connection test already refused it; and a profile host that does not resolve cannot be saved.
- **Chat bridge excerpts drop nested code fences whole.** `chatbridge.SafeText` paired any run of three backticks or tildes with the next one of either kind, so a longer fence quoting markdown (a four-backtick fence around a three-backtick `http` block, a `markdown` fence holding inline triple backticks, a backtick block inside a tilde fence) was closed at the first inner run, and the rest of the quoted evidence went to the chat provider as prose when excerpts or shared text were on. Fences now follow the CommonMark rules: a fence line has at most three spaces before its run, and its block ends only on a line holding a run of the same character at least as long and nothing else; an unclosed fence still drops everything to the end. A run elsewhere is dropped: after text, or in a title collapsed to one line, up to the latest end a code span could have; on a line inside a list item or a blockquote, only a closing line of the same character and at least the same length ends the fence, so a list item's continuation lines are content of it, and an unclosed one drops to the end. Ambiguous markdown errs toward dropping: a fence opened on the same line as a list marker, for example, may drop the list items after it.
- **`GET /api/traffic` no longer returns the global proxy password.** With traffic capture off, its `proxy` field was the saved global egress proxy URL with its `user:pass` in clear, although `GET /api/settings` masks the same setting, and the dashboard requests it on every load. The field now shows `__masked__` when a global proxy is set (sending it back to `PUT /api/settings` keeps the stored proxy, as before), and still shows the local recording proxy address with capture on. Proxy validation errors returned by `PUT /api/settings` no longer quote the submitted address.
+3 -1
View File
@@ -221,7 +221,9 @@ func run() int {
}
// Tighten an existing key directory before running the isolation self-test:
// a host bind mount (typically 0755) masks the image's 0700.
keyLockErr := errors.Join(server.LockDownKeyDir(keyDir), server.LockDownCAKey(*dataDir))
// The transcripts and noa archives (whole conversations) too: Norma leaves
// them 0755/0644, readable by the executor.
keyLockErr := errors.Join(server.LockDownKeyDir(keyDir), server.LockDownCAKey(*dataDir), server.LockDownPrivateDataDirs(*dataDir))
// Before the stores open and any agent runs: check that the isolation above holds
// (server/isolation.go). Startup is fail-closed unless ARTEX_ALLOW_UNISOLATED=1
// (or -dev-insecure-no-isolation) is explicitly set.
+19
View File
@@ -0,0 +1,19 @@
package server
import "os"
// privateDataDirs are the data subdirectories only the server process reads:
// Norma's transcripts and the noa compression archives. They hold whole
// conversations (prompts, model output, tool results), and Norma creates the
// directories below them 0755 and the files 0644 (LockDownPrivateDataDirs).
var privateDataDirs = []string{"transcripts", "noa"}
// disableNormaRipgrepInstall stops Norma's Grep from installing ripgrep: with no
// rg on PATH it runs an unpinned `npm install -g @vscode/ripgrep`, install
// scripts included, unless NORMA_RIPGREP_NO_INSTALL is non-empty. ARTEX's own
// Grep never starts ripgrep. The variable is set to "1" whatever its value: an
// empty value, which Norma reads as unset, cannot re-enable the install, and no
// value is meant to.
func disableNormaRipgrepInstall() {
_ = os.Setenv("NORMA_RIPGREP_NO_INSTALL", "1")
}
@@ -0,0 +1,72 @@
//go:build unix
package server
import (
"os"
"path/filepath"
"testing"
)
// mkModeDir creates dir with exactly mode (the umask does not apply).
func mkModeDir(t *testing.T, dir string, mode os.FileMode) {
t.Helper()
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.Chmod(dir, mode); err != nil {
t.Fatal(err)
}
}
// newManagerAnyDB starts a manager on dir and closes it. The data directories
// are settled before the database is opened, so the outcome does not depend on
// PostgreSQL.
func newManagerAnyDB(dir string) {
if m, err := NewManager(dir, ""); err == nil {
m.Close()
}
}
// Starting the manager leaves no transcript or noa content readable by another
// uid: directories an earlier version left 0755 become 0700, their 0644 files
// 0600, a narrower file keeps its mode, and noa is created 0700.
func TestNewManagerKeepsTranscriptsAndNoaPrivate(t *testing.T) {
dir := t.TempDir()
tr := filepath.Join(dir, "transcripts")
mkModeDir(t, filepath.Join(tr, "exp1-main"), 0o755)
mkModeDir(t, tr, 0o755)
writeMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o644)
writeMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o644)
writeMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
newManagerAnyDB(dir)
wantMode(t, tr, 0o700)
wantMode(t, filepath.Join(tr, "exp1-main"), 0o700)
wantMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
fi, err := os.Stat(filepath.Join(dir, "noa"))
if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 {
t.Fatalf("noa: %v %v, want a 0700 directory", fi, err)
}
}
// A transcripts or noa directory replaced by a symlink is not followed by the
// manager's start: the outside directory and its files keep their modes.
func TestNewManagerDoesNotFollowSymlinkedPrivateDirs(t *testing.T) {
for _, name := range []string{"transcripts", "noa"} {
t.Run(name, func(t *testing.T) {
dir, outside := t.TempDir(), t.TempDir()
mkModeDir(t, outside, 0o755)
writeMode(t, filepath.Join(outside, "f.jsonl"), 0o644)
if err := os.Symlink(outside, filepath.Join(dir, name)); err != nil {
t.Fatal(err)
}
newManagerAnyDB(dir)
wantMode(t, outside, 0o755)
wantMode(t, filepath.Join(outside, "f.jsonl"), 0o644)
})
}
}
+22
View File
@@ -0,0 +1,22 @@
//go:build !unix
package server
import (
"os"
"path/filepath"
)
// LockDownPrivateDataDirs creates the private data directories if missing;
// POSIX mode enforcement is Unix-only, as for LockDownKeyDir.
func LockDownPrivateDataDirs(dataDir string) error {
if dataDir == "" {
return nil
}
for _, name := range privateDataDirs {
if err := os.MkdirAll(filepath.Join(dataDir, name), 0o700); err != nil {
return err
}
}
return nil
}
+172
View File
@@ -0,0 +1,172 @@
//go:build unix
package server
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/Autumn-27/artex/traffic"
)
// LockDownPrivateDataDirs keeps <dataDir>/transcripts and <dataDir>/noa
// owner-only. Each directory in them, the top one included, keeps at most its
// owner bits (0700), and each regular file at most owner read and write (0600);
// a mode already narrower is left as it is. A missing top directory is created
// 0700.
//
// As in LockDownKeyDir, nothing is changed by path: the tree is walked under an
// os.Root at dataDir, every directory must be a real directory, not a symlink,
// the one opened being the one checked (traffic.OpenRealDir), and its mode is
// changed through that descriptor before its entries are read. A file is
// checked with Lstat (a regular file with a single link), opened under the
// root without following a symlink, checked again on the descriptor, and its
// mode is changed through that descriptor. A symlink, a hard-linked file or any
// other entry is refused and left as it is, so the server (root) never changes
// the mode of a file outside the tree; the walk goes on and the refusals are
// returned together.
//
// Each directory must be owned by the server's uid, and it is narrowed before
// its entries are read: from then on only the server can add, rename, link or
// unlink an entry in it, which is what a swap between a check and the chmod,
// or a hard link whose other name is unlinked meanwhile, would need. That is
// why a file is changed in place, not replaced by a copy as LockDownKeyDir's
// keys are: the copy would rewrite every transcript at each start. A directory
// owned by another uid is refused and its tree left as it is.
func LockDownPrivateDataDirs(dataDir string) error {
if strings.TrimSpace(dataDir) == "" {
return nil
}
if err := os.MkdirAll(dataDir, 0o755); err != nil {
return fmt.Errorf("create data dir %s: %w", dataDir, err)
}
root, err := os.OpenRoot(dataDir)
if err != nil {
return fmt.Errorf("open data dir %s: %w", dataDir, err)
}
defer root.Close()
var errs []error
for _, name := range privateDataDirs {
shown := filepath.Join(dataDir, name)
if err := root.Mkdir(name, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
errs = append(errs, fmt.Errorf("create %s: %w", shown, err))
continue
}
dir, err := traffic.OpenRealDir(root, name)
if err != nil {
errs = append(errs, fmt.Errorf("open %s: %w", shown, err))
continue
}
errs = append(errs, lockDownPrivateTree(dir, shown))
dir.Close()
}
return errors.Join(errs...)
}
// lockDownPrivateTree narrows the directory dir (shown in errors) and everything
// in it, as LockDownPrivateDataDirs describes.
func lockDownPrivateTree(dir *os.Root, shown string) error {
d, err := dir.Open(".")
if err != nil {
return fmt.Errorf("open %s: %w", shown, err)
}
defer d.Close()
fi, err := d.Stat()
if err != nil {
return fmt.Errorf("stat %s: %w", shown, err)
}
if st, ok := fi.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != os.Geteuid() {
return fmt.Errorf("%s is not owned by the server's uid %d: left as it is", shown, os.Geteuid())
}
var errs []error
if err := narrowMode(d, 0o700); err != nil {
errs = append(errs, fmt.Errorf("chmod %s: %w", shown, err))
}
entries, err := d.ReadDir(-1)
if err != nil {
return errors.Join(append(errs, fmt.Errorf("read %s: %w", shown, err))...)
}
for _, e := range entries {
name, p := e.Name(), filepath.Join(shown, e.Name())
fi, err := dir.Lstat(name)
if errors.Is(err, fs.ErrNotExist) {
continue
}
switch {
case err != nil:
errs = append(errs, fmt.Errorf("lstat %s: %w", p, err))
case fi.IsDir():
sub, err := traffic.OpenRealDir(dir, name)
if err != nil {
errs = append(errs, fmt.Errorf("open %s: %w", p, err))
continue
}
errs = append(errs, lockDownPrivateTree(sub, p))
sub.Close()
case fi.Mode().IsRegular():
errs = append(errs, lockDownPrivateFile(dir, name, p, fi))
default:
errs = append(errs, fmt.Errorf("%s is not a regular file or a directory (%s): left as it is", p, fi.Mode().Type()))
}
}
return errors.Join(errs...)
}
// lockDownPrivateFile narrows dir/name to at most 0600 through a descriptor,
// provided it is the regular, single-link file want describes.
func lockDownPrivateFile(dir *os.Root, name, shown string, want os.FileInfo) error {
if err := privateSingleLinkFile(shown, want); err != nil {
return err
}
// O_NONBLOCK: should a FIFO replace the file after the Lstat, the open does not
// wait for a writer; the checks below refuse it.
f, err := dir.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK|syscall.O_NOCTTY, 0)
if err != nil {
return fmt.Errorf("open %s: %w", shown, err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return fmt.Errorf("stat %s: %w", shown, err)
}
if !os.SameFile(want, fi) {
return fmt.Errorf("%s changed while it was opened: left as it is", shown)
}
if err := privateSingleLinkFile(shown, fi); err != nil {
return err
}
if err := narrowMode(f, 0o600); err != nil {
return fmt.Errorf("chmod %s: %w", shown, err)
}
return nil
}
// privateSingleLinkFile refuses anything but a regular file with a single link:
// a hard link shares its inode, and so its mode, with a file elsewhere.
func privateSingleLinkFile(shown string, fi os.FileInfo) error {
if !fi.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file (%s): left as it is", shown, fi.Mode().Type())
}
if st, ok := fi.Sys().(*syscall.Stat_t); !ok || st.Nlink != 1 {
return fmt.Errorf("%s is hard-linked: it shares its mode with another file, left as it is", shown)
}
return nil
}
// narrowMode clears the permission bits of f outside allowed, never adding one.
func narrowMode(f *os.File, allowed os.FileMode) error {
fi, err := f.Stat()
if err != nil {
return err
}
perm := fi.Mode().Perm()
if perm&allowed == perm {
return nil
}
return f.Chmod(fi.Mode()&^os.ModePerm | perm&allowed)
}
+149
View File
@@ -0,0 +1,149 @@
//go:build unix
package server
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// Every directory under transcripts and noa keeps at most 0700 and every file
// at most 0600; a narrower mode is never widened; a missing noa is created 0700.
func TestLockDownPrivateDataDirsNarrowsTree(t *testing.T) {
dir := t.TempDir()
tr := filepath.Join(dir, "transcripts")
mkModeDir(t, filepath.Join(tr, "exp1-main"), 0o755)
mkModeDir(t, tr, 0o755)
writeMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o644)
writeMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o664)
writeMode(t, filepath.Join(tr, "script.sh"), 0o755)
writeMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
mkModeDir(t, filepath.Join(tr, "narrow"), 0o500)
if err := LockDownPrivateDataDirs(dir); err != nil {
t.Fatal(err)
}
wantMode(t, tr, 0o700)
wantMode(t, filepath.Join(tr, "exp1-main"), 0o700)
wantMode(t, filepath.Join(tr, "exp1-worker.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "exp1-main", "part.jsonl"), 0o600)
wantMode(t, filepath.Join(tr, "script.sh"), 0o600)
wantMode(t, filepath.Join(tr, "read-only.jsonl"), 0o400)
wantMode(t, filepath.Join(tr, "narrow"), 0o500)
wantMode(t, filepath.Join(dir, "noa"), 0o700)
// A second start finds nothing to change.
if err := LockDownPrivateDataDirs(dir); err != nil {
t.Fatal(err)
}
}
// A symlink or a hard link never leads the chmod outside the tree: transcripts
// or noa replaced by a symlink is refused, and so is a symlinked file, a
// symlinked subdirectory or a hard-linked file inside; the outside modes stay
// as they were, and the rest of the tree is still narrowed.
func TestLockDownPrivateDataDirsRefusesLinks(t *testing.T) {
dir := t.TempDir()
outside := t.TempDir()
outDir := filepath.Join(outside, "dir")
mkModeDir(t, outDir, 0o755)
writeMode(t, filepath.Join(outDir, "secret.jsonl"), 0o644)
outFile := filepath.Join(outside, "file.jsonl")
writeMode(t, outFile, 0o644)
outLinked := filepath.Join(outside, "linked.jsonl")
writeMode(t, outLinked, 0o644)
// transcripts itself is a symlink to an outside directory.
if err := os.Symlink(outDir, filepath.Join(dir, "transcripts")); err != nil {
t.Fatal(err)
}
// noa is real; inside it a symlinked file, a symlinked subdirectory, a
// hard-linked file and an ordinary file.
noa := filepath.Join(dir, "noa")
mkModeDir(t, noa, 0o755)
if err := os.Symlink(outFile, filepath.Join(noa, "link.jsonl")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outDir, filepath.Join(noa, "linkdir")); err != nil {
t.Fatal(err)
}
if err := os.Link(outLinked, filepath.Join(noa, "hard.jsonl")); err != nil {
t.Fatal(err)
}
writeMode(t, filepath.Join(noa, "own.jsonl"), 0o644)
err := LockDownPrivateDataDirs(dir)
if err == nil {
t.Fatal("links were accepted")
}
for _, want := range []string{"transcripts is not a directory", "link.jsonl is not a regular file or a directory", "linkdir is not a regular file or a directory", "hard.jsonl is hard-linked"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("error %q does not mention %q", err, want)
}
}
wantMode(t, outDir, 0o755)
wantMode(t, filepath.Join(outDir, "secret.jsonl"), 0o644)
wantMode(t, outFile, 0o644)
wantMode(t, outLinked, 0o644)
wantMode(t, noa, 0o700)
wantMode(t, filepath.Join(noa, "own.jsonl"), 0o600)
if fi, err := os.Lstat(filepath.Join(dir, "transcripts")); err != nil || fi.Mode()&os.ModeSymlink == 0 {
t.Errorf("the transcripts symlink was replaced: %v %v", fi, err)
}
}
// While the lockdown runs, a file and a subdirectory under noa keep being
// swapped for symlinks to a file and a directory elsewhere, and back. The
// outside file and directory keep their modes however the swaps land.
func TestLockDownPrivateDataDirsSymlinkSwapRace(t *testing.T) {
if testing.Short() {
t.Skip("long race test")
}
outside := t.TempDir()
victim := filepath.Join(outside, "host-file")
writeMode(t, victim, 0o644)
victimDir := filepath.Join(outside, "host-dir")
mkModeDir(t, victimDir, 0o755)
dir := t.TempDir()
noa := filepath.Join(dir, "noa")
mkModeDir(t, noa, 0o700)
file, sub := filepath.Join(noa, "s.jsonl"), filepath.Join(noa, "sess")
ownFile, ownDir, link := filepath.Join(noa, "own.tmp"), filepath.Join(noa, "own.dir"), filepath.Join(noa, "link.tmp")
race := func() {
_ = os.WriteFile(ownFile, []byte("own"), 0o644)
_ = os.Rename(ownFile, file)
_ = os.Symlink(victim, link)
_ = os.Rename(link, file)
_ = os.Mkdir(ownDir, 0o755)
_ = os.Rename(ownDir, sub)
_ = os.Symlink(victimDir, link)
_ = os.Remove(sub) // the directory, now empty, or nothing
_ = os.Rename(link, sub)
_ = os.Remove(sub)
}
stop, done := make(chan struct{}), make(chan struct{})
go func() {
defer close(done)
for {
select {
case <-stop:
return
default:
}
race()
}
}()
start := time.Now()
iter := 0
for ; iter < keyDirRaceIter && time.Since(start) < keyDirRaceBudget; iter++ {
_ = LockDownPrivateDataDirs(dir)
if !wantUntouched(t, victim, 0o644, "key") || !wantUntouched(t, victimDir, 0o755, "") {
break
}
}
close(stop)
<-done
t.Logf("%d iterations in %v, outside file and directory unchanged", iter, time.Since(start).Round(time.Millisecond))
}
+9
View File
@@ -417,6 +417,8 @@ func (m *Manager) Enrich() *enrich.Engine { return m.enrich }
// NewManager connects to PostgreSQL and, if proxyAddr is non-empty, starts the
// traffic-recording proxy. PostgreSQL is required (it is the single data source).
func NewManager(dir, proxyAddr string) (*Manager, error) {
// Before any agent or tool exists (datadir_private.go).
disableNormaRipgrepInstall()
cfg, err := config.Load()
if err != nil {
return nil, err
@@ -433,6 +435,13 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
// cmd/artex runs this before the isolation self-test and fails the start on
// an error unless the operator opts out (ARTEX_ALLOW_UNISOLATED=1), as for the
// key directory. Here it covers every other way a Manager is built, and only
// logs: the start decision is made there.
if err := LockDownPrivateDataDirs(dir); err != nil {
log.Printf("[data] keep transcripts and noa owner-only: %v", err)
}
dsn, source, err := pgdb.DSN()
if err != nil {
return nil, err
+75
View File
@@ -0,0 +1,75 @@
//go:build unix
package server
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/norma/tool"
)
const normaRipgrepChildEnv = "ARTEX_TEST_NORMA_RIPGREP_CHILD"
// Norma's Grep never installs ripgrep once a manager exists, whatever
// NORMA_RIPGREP_NO_INSTALL held before: unset, empty or blank. Norma resolves
// ripgrep once per process, so each case runs in a fresh test process whose
// PATH holds only a fake npm that records its arguments: no rg, no real npm,
// and the tests run without a network.
func TestNewManagerStopsNormaRipgrepInstall(t *testing.T) {
if os.Getenv(normaRipgrepChildEnv) == "1" {
normaRipgrepChild(t)
return
}
for name, value := range map[string]*string{"unset": nil, "empty": new(string), "blank": normaStrPtr(" ")} {
t.Run(name, func(t *testing.T) {
bin := t.TempDir()
record := filepath.Join(t.TempDir(), "npm-calls")
npm := "#!/bin/sh\necho \"$*\" >> " + record + "\nexit 1\n"
if err := os.WriteFile(filepath.Join(bin, "npm"), []byte(npm), 0o755); err != nil {
t.Fatal(err)
}
var env []string
for _, kv := range os.Environ() {
k, _, _ := strings.Cut(kv, "=")
switch k {
case "PATH", "NORMA_RIPGREP_NO_INSTALL", "NORMA_DISABLE_RIPGREP", "ARTEX_PG_DSN":
continue
}
env = append(env, kv)
}
// An unreachable database: the child's TestMain and NewManager give up
// on it at once instead of waiting for this suite's advisory lock.
env = append(env, "PATH="+bin, normaRipgrepChildEnv+"=1",
"ARTEX_PG_DSN=postgres://artex@127.0.0.1:1/none?sslmode=disable&connect_timeout=2")
if value != nil {
env = append(env, "NORMA_RIPGREP_NO_INSTALL="+*value)
}
cmd := exec.Command(os.Args[0], "-test.run=^TestNewManagerStopsNormaRipgrepInstall$", "-test.count=1")
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("child: %v\n%s", err, out)
}
if !strings.Contains(string(out), `RG env="1" path=""`) {
t.Errorf("child did not end with the install disabled and no ripgrep:\n%s", out)
}
if calls, err := os.ReadFile(record); err == nil {
t.Errorf("npm was run: %q", calls)
}
})
}
}
func normaStrPtr(s string) *string { return &s }
// normaRipgrepChild builds a manager, then resolves ripgrep the way Norma's Grep
// does on its first call.
func normaRipgrepChild(t *testing.T) {
newManagerAnyDB(t.TempDir())
fmt.Printf("RG env=%q path=%q\n", os.Getenv("NORMA_RIPGREP_NO_INSTALL"), tool.RipgrepPath())
}