package notarius import ( "context" "encoding/json" "errors" "os" "path/filepath" "reflect" "strings" "testing" "time" sharedsubprocess "gitea.maximumdirect.net/eric/narratio/internal/adapters/subprocess" configkit "go.maximumdirect.net/configkit" ) func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) { tests := []struct { name string supplied bool value string }{ {name: "omitted"}, {name: "empty", supplied: true}, {name: "default", supplied: true, value: "default"}, {name: "named", supplied: true, value: "inexpensive"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { req := validRunRequest(t) if test.supplied { req.ConfigOverlay = &test.value } var captured sharedsubprocess.RunRequest runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { captured = processReq writeNativeCompletion(t, req, false) return sharedsubprocess.RunResult{ExitCode: 0}, nil }} if _, err := runner.Run(context.Background(), req); err != nil { t.Fatalf("Run() error = %v", err) } flagIndex := -1 for index, arg := range captured.Args { if arg == "--overlay" { flagIndex = index break } } if !test.supplied { if flagIndex >= 0 { t.Fatalf("subprocess args unexpectedly contain config overlay: %#v", captured.Args) } return } if flagIndex < 0 || flagIndex+2 >= len(captured.Args) || captured.Args[flagIndex+1] != test.value || captured.Args[flagIndex+2] != "--format" { t.Fatalf("config overlay argument boundary = %#v, want flag, exact value, then --format", captured.Args) } }) } } func TestSubprocessRunnerRejectsInvalidChunkCacheBeforeLaunch(t *testing.T) { for _, mode := range []string{"AUTO", "invalid", " auto "} { t.Run(mode, func(t *testing.T) { req := validRunRequest(t) req.Cache = &mode started := false runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { started = true return sharedsubprocess.RunResult{}, nil }} _, err := runner.Run(context.Background(), req) if err == nil || !strings.Contains(err.Error(), "cache mode") { t.Fatalf("Run() error = %v, want chunk cache validation failure", err) } if started { t.Fatal("subprocess started with invalid chunk cache mode") } }) } } func TestSubprocessRunnerForwardsLoadedCredentialWithoutRereadingEnvironment(t *testing.T) { const envName = "NARRATIO_NOTARIUS_CUSTOM_LLM_KEY" const otherName = "NARRATIO_NOTARIUS_CUSTOM_OTHER_KEY" const loadedValue = "loaded-notarius-credential" const otherValue = "loaded-notarius-other-credential" credential := loadTestCredential(t, envName, loadedValue) otherCredential := loadTestCredential(t, otherName, otherValue) t.Setenv(envName, "changed-parent-credential") t.Setenv(otherName, "changed-parent-other-credential") req := validRunRequest(t) req.Credentials = []configkit.Secret{*credential, *otherCredential} var captured sharedsubprocess.RunRequest runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { captured = processReq writeNativeCompletion(t, req, false) return sharedsubprocess.RunResult{ExitCode: 0}, nil }} if _, err := runner.Run(context.Background(), req); err != nil { t.Fatalf("Run() error = %v", err) } if len(captured.EnvOverrides) != 2 || captured.EnvOverrides[envName] != loadedValue || captured.EnvOverrides[otherName] != otherValue { t.Fatal("subprocess did not receive exactly the loaded credential overrides") } if !reflect.DeepEqual(captured.SensitiveEnvNames, []string{envName, otherName}) { t.Fatalf("sensitive environment names = %#v, want configured reference name", captured.SensitiveEnvNames) } wantArgs := []string{ "run", req.PipelineID, "--config", req.ConfigPath, "--input-file", req.InputPath, "--output-dir", req.OutputRoot, "--debug-dir", req.DebugDirectory, "--format", "json", } if !reflect.DeepEqual(captured.Args, wantArgs) { t.Fatalf("subprocess args = %#v, want %#v", captured.Args, wantArgs) } } func TestSubprocessRunnerRejectsInvalidProgrammaticCredentialBeforeLaunch(t *testing.T) { for _, test := range []struct { name string reference configkit.Secret }{ {name: "unresolved", reference: configkit.SecretEnv("NARRATIO_NOTARIUS_UNRESOLVED_KEY")}, {name: "empty", reference: configkit.SecretEnv("")}, } { t.Run(test.name, func(t *testing.T) { req := validRunRequest(t) req.Credentials = []configkit.Secret{test.reference} started := false runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { started = true return sharedsubprocess.RunResult{}, nil }} _, err := runner.Run(context.Background(), req) if err == nil || !strings.Contains(err.Error(), "resolved and nonempty") { t.Fatalf("Run() error = %v, want credential validation failure", err) } if started { t.Fatal("subprocess started with an invalid credential") } }) } } func TestSubprocessRunnerBuildsOrderedReferenceArguments(t *testing.T) { req := validRunRequest(t) referenceRoot := t.TempDir() req.References = []ReferenceBinding{ {Selector: " party ", Path: filepath.Join(referenceRoot, "party context=primary.json")}, {Selector: " npc-registry . extract . glossary ", Path: filepath.Join(referenceRoot, "glossary.json")}, } originalReferences := append([]ReferenceBinding(nil), req.References...) var captured sharedsubprocess.RunRequest runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { captured = processReq writeNativeCompletion(t, req, false) return sharedsubprocess.RunResult{ExitCode: 0}, nil }} if _, err := runner.Run(context.Background(), req); err != nil { t.Fatalf("Run() error = %v", err) } wantArgs := []string{ "run", req.PipelineID, "--config", req.ConfigPath, "--input-file", req.InputPath, "--output-dir", req.OutputRoot, "--debug-dir", req.DebugDirectory, "--reference", "party=" + req.References[0].Path, "--reference", "npc-registry.extract.glossary=" + req.References[1].Path, "--format", "json", } if !reflect.DeepEqual(captured.Args, wantArgs) { t.Fatalf("subprocess args = %#v, want %#v", captured.Args, wantArgs) } if !reflect.DeepEqual(req.References, originalReferences) { t.Fatalf("Run() mutated caller references = %#v, want %#v", req.References, originalReferences) } } func TestSubprocessRunnerRejectsInvalidReferencesBeforeLaunch(t *testing.T) { tests := []struct { name string references func(string) []ReferenceBinding wantErr string }{ { name: "invalid selector", references: func(root string) []ReferenceBinding { return []ReferenceBinding{{Selector: "lane.prepare.party", Path: filepath.Join(root, "party.json")}} }, wantErr: "selector", }, { name: "duplicate normalized selector", references: func(root string) []ReferenceBinding { return []ReferenceBinding{ {Selector: "lane.party", Path: filepath.Join(root, "party.json")}, {Selector: " lane . party ", Path: filepath.Join(root, "party-2.json")}, } }, wantErr: "duplicated", }, { name: "empty path", references: func(string) []ReferenceBinding { return []ReferenceBinding{{Selector: "party", Path: " "}} }, wantErr: "path is required", }, { name: "relative path", references: func(string) []ReferenceBinding { return []ReferenceBinding{{Selector: "party", Path: "references/party.json"}} }, wantErr: "path must be absolute", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := validRunRequest(t) req.References = tt.references(t.TempDir()) started := false runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { started = true return sharedsubprocess.RunResult{}, nil }} _, err := runner.Run(context.Background(), req) if err == nil || !strings.Contains(err.Error(), tt.wantErr) { t.Fatalf("Run() error = %v, want containing %q", err, tt.wantErr) } if started { t.Fatal("subprocess started after request validation failure") } }) } } func TestSubprocessRunnerUsesMinimalEnvironmentAndSeparatesStreams(t *testing.T) { const envName = "NARRATIO_NOTARIUS_CUSTOM_CAPTURE_KEY" const otherName = "NARRATIO_NOTARIUS_CUSTOM_CAPTURE_OTHER_KEY" const canary = "notarius-captured-stream-canary" const otherCanary = "notarius-captured-stream-other-canary" const unrelated = "NARRATIO_NOTARIUS_UNRELATED_PARENT_KEY" req := validRunRequest(t) req.Credentials = []configkit.Secret{*loadTestCredential(t, envName, canary), *loadTestCredential(t, otherName, otherCanary)} writeNativeCompletion(t, req, false) reportFixture := req.ReportPath + ".fixture" data, err := os.ReadFile(req.ReportPath) if err != nil { t.Fatalf("ReadFile(report) error = %v", err) } var report map[string]any if err := json.Unmarshal(data, &report); err != nil { t.Fatalf("decode report fixture: %v", err) } report["credential_echo"] = canary + " " + otherCanary writeJSONFile(t, reportFixture, report) if err := os.Remove(req.ReportPath); err != nil { t.Fatalf("Remove(report) error = %v", err) } captureDir := filepath.Join(filepath.Dir(req.ReportPath), "capture") if err := os.Mkdir(captureDir, 0o755); err != nil { t.Fatalf("Mkdir(capture) error = %v", err) } script := writeShellScript(t, `#!/bin/sh pwd > "$NOTARIUS_CAPTURE_DIR/working-directory" printf '%s' "$NOTARIUS_INHERITED_VALUE" > "$NOTARIUS_CAPTURE_DIR/environment" if [ "$`+envName+`" != '`+canary+`' ]; then printf 'selected credential mismatch\n' >&2 exit 8 fi if [ "$`+otherName+`" != '`+otherCanary+`' ]; then printf 'other selected credential mismatch\n' >&2 exit 10 fi if [ -n "$`+unrelated+`" ]; then printf 'unrelated credential inherited\n' >&2 exit 9 fi printf '%s\n' "$`+envName+`" >&2 printf '%s\n' "$`+otherName+`" >&2 cat "$NOTARIUS_REPORT_FIXTURE" `) req.Binary = script t.Setenv("NOTARIUS_CAPTURE_DIR", captureDir) t.Setenv("NOTARIUS_INHERITED_VALUE", "inherited-value") t.Setenv("NOTARIUS_REPORT_FIXTURE", reportFixture) t.Setenv(unrelated, "unrelated-parent-credential") if _, err := NewSubprocessRunner().Run(context.Background(), req); err != nil { t.Fatalf("Run() error = %v", err) } assertTextFile(t, filepath.Join(captureDir, "working-directory"), req.WorkingDirectory+"\n") assertTextFile(t, filepath.Join(captureDir, "environment"), "") assertRedactedCredentialFile(t, req.LogPath, canary) assertRedactedCredentialFile(t, req.LogPath, otherCanary) reportBytes, err := os.ReadFile(req.ReportPath) if err != nil { t.Fatalf("ReadFile(report) error = %v", err) } assertRedactedCredentialBytes(t, reportBytes, canary) assertRedactedCredentialBytes(t, reportBytes, otherCanary) } func TestSubprocessRunnerRedactsCredentialOnProcessFailure(t *testing.T) { const envName = "NARRATIO_NOTARIUS_CUSTOM_FAILURE_KEY" const otherName = "NARRATIO_NOTARIUS_CUSTOM_FAILURE_OTHER_KEY" const canary = "notarius-failure-stream-canary" const otherCanary = "notarius-failure-stream-other-canary" req := validRunRequest(t) req.Credentials = []configkit.Secret{*loadTestCredential(t, envName, canary), *loadTestCredential(t, otherName, otherCanary)} req.Binary = writeShellScript(t, `#!/bin/sh printf '%s\n' "$`+envName+`" printf '%s\n' "$`+envName+`" >&2 printf '%s\n' "$`+otherName+`" >&2 exit 7 `) _, err := NewSubprocessRunner().Run(context.Background(), req) if err == nil { t.Fatal("Run() error = nil, want process failure") } if strings.Contains(err.Error(), canary) || strings.Contains(err.Error(), otherCanary) || !strings.Contains(err.Error(), "") { t.Fatal("process failure did not return redacted diagnostics") } assertRedactedCredentialFile(t, req.ReportPath, canary) assertRedactedCredentialFile(t, req.ReportPath, otherCanary) assertRedactedCredentialFile(t, req.LogPath, canary) assertRedactedCredentialFile(t, req.LogPath, otherCanary) } func TestSubprocessRunnerReturnsProcessFailuresWithoutParsingStdout(t *testing.T) { tests := []struct { name string scriptBody string timeout time.Duration cancel bool want string }{ {name: "nonzero", scriptBody: "printf '{malformed report'; printf 'failed\\n' >&2; exit 7\n", timeout: time.Second, want: "exit code 7"}, {name: "timeout", scriptBody: "sleep 5\n", timeout: 20 * time.Millisecond, want: "timed out"}, {name: "cancellation", scriptBody: "sleep 5\n", timeout: time.Second, cancel: true, want: "canceled"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { req := validRunRequest(t) if test.name == "nonzero" { profile := "missing-profile" req.ConfigOverlay = &profile } req.Binary = writeShellScript(t, "#!/bin/sh\n"+test.scriptBody) req.Timeout = test.timeout ctx := context.Background() if test.cancel { cancelCtx, cancel := context.WithCancel(ctx) ctx = cancelCtx time.AfterFunc(20*time.Millisecond, cancel) } _, err := NewSubprocessRunner().Run(ctx, req) if err == nil || !strings.Contains(err.Error(), test.want) { t.Fatalf("Run() error = %v, want fragment %q", err, test.want) } if strings.Contains(err.Error(), "decode notarius report") { t.Fatalf("Run() parsed stdout after process failure: %v", err) } }) } } func TestSubprocessRunnerReturnsSharedSubprocessErrorWithoutReadingReport(t *testing.T) { req := validRunRequest(t) if err := os.WriteFile(req.ReportPath, []byte("not json"), 0o644); err != nil { t.Fatalf("WriteFile(report) error = %v", err) } wantErr := errors.New("process failed") runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { return sharedsubprocess.RunResult{ExitCode: 9}, wantErr }} _, err := runner.Run(context.Background(), req) if !errors.Is(err, wantErr) { t.Fatalf("Run() error = %v, want wrapped process error", err) } if strings.Contains(err.Error(), "decode") { t.Fatalf("Run() parsed report after failure: %v", err) } } func TestValidateBundleRootRejectsEscapesAndSymlinks(t *testing.T) { root := t.TempDir() outputRoot := filepath.Join(root, "output") if err := os.Mkdir(outputRoot, 0o755); err != nil { t.Fatalf("Mkdir(output root) error = %v", err) } validBundle := filepath.Join(outputRoot, "run-1") if err := os.Mkdir(validBundle, 0o755); err != nil { t.Fatalf("Mkdir(bundle) error = %v", err) } if _, err := validateBundleRoot(outputRoot, validBundle); err != nil { t.Fatalf("validateBundleRoot(valid) error = %v", err) } outside := filepath.Join(root, "output-other") if err := os.Mkdir(outside, 0o755); err != nil { t.Fatalf("Mkdir(outside) error = %v", err) } for name, candidate := range map[string]string{"equal root": outputRoot, "escape": root, "prefix confusion": outside} { t.Run(name, func(t *testing.T) { if _, err := validateBundleRoot(outputRoot, candidate); err == nil { t.Fatalf("validateBundleRoot(%q) error = nil", candidate) } }) } symlink := filepath.Join(outputRoot, "linked") if err := os.Symlink(outside, symlink); err != nil { t.Skipf("Symlink() unavailable: %v", err) } if _, err := validateBundleRoot(outputRoot, symlink); err == nil { t.Fatal("validateBundleRoot(symlink) error = nil") } } func TestFakeRunnerCapturesRequestsAndHonorsContextAndError(t *testing.T) { profile := "testing" req := RunRequest{PipelineID: "pipeline", ConfigOverlay: &profile, References: []ReferenceBinding{{Selector: "party", Path: "/references/party.json"}}} want := RunResult{BundleRoot: "/bundle"} fake := &FakeRunner{Result: want} got, err := fake.Run(context.Background(), req) if err != nil || !reflect.DeepEqual(got, want) || !reflect.DeepEqual(fake.Requests, []RunRequest{req}) { t.Fatalf("Run() = %#v, %v; requests = %#v", got, err, fake.Requests) } req.References[0].Path = "/references/changed.json" if fake.Requests[0].References[0].Path != "/references/party.json" { t.Fatalf("fake retained aliased request references: %#v", fake.Requests[0].References) } profile = "changed" if *fake.Requests[0].ConfigOverlay != "testing" { t.Fatalf("fake retained aliased config overlay: %q", *fake.Requests[0].ConfigOverlay) } wantErr := errors.New("configured failure") fake.Err = wantErr if _, err := fake.Run(context.Background(), req); !errors.Is(err, wantErr) { t.Fatalf("Run(configured error) = %v", err) } canceled, cancel := context.WithCancel(context.Background()) cancel() before := len(fake.Requests) if _, err := fake.Run(canceled, req); !errors.Is(err, context.Canceled) || len(fake.Requests) != before { t.Fatalf("Run(canceled) error = %v; requests = %d", err, len(fake.Requests)) } } func validRunRequest(t *testing.T) RunRequest { t.Helper() root := t.TempDir() configPath := filepath.Join(root, "notarius.yml") inputPath := filepath.Join(root, "input.json") outputRoot := filepath.Join(root, "outputs") workingDirectory := filepath.Join(root, "work") diagnostics := filepath.Join(root, "diagnostics") for _, directory := range []string{outputRoot, workingDirectory, diagnostics} { if err := os.Mkdir(directory, 0o755); err != nil { t.Fatalf("Mkdir(%q) error = %v", directory, err) } } if err := os.WriteFile(configPath, []byte("pipelines: {}\n"), 0o644); err != nil { t.Fatalf("WriteFile(config) error = %v", err) } if err := os.WriteFile(inputPath, []byte("{}\n"), 0o644); err != nil { t.Fatalf("WriteFile(input) error = %v", err) } return RunRequest{ Binary: "notarius", ConfigPath: configPath, PipelineID: "dnd-session", InputPath: inputPath, OutputRoot: outputRoot, WorkingDirectory: workingDirectory, ReportPath: filepath.Join(diagnostics, "report.json"), LogPath: filepath.Join(diagnostics, "stderr.log"), Timeout: time.Second, DebugDirectory: filepath.Join(diagnostics, "debug"), } } func loadTestCredential(t *testing.T, envName, value string) *configkit.Secret { t.Helper() t.Setenv(envName, value) type testConfig struct { Credential *configkit.Secret `yaml:"credential"` } result, err := configkit.Load(configkit.Bytes("credential.yml", []byte("credential: "+envName+"\n")), configkit.Options[testConfig]{}) if err != nil { t.Fatalf("load test credential: %v", err) } return result.Config.Credential } func assertRedactedCredentialFile(t *testing.T, path, canary string) { t.Helper() data, err := os.ReadFile(path) if err != nil { t.Fatalf("ReadFile(%q) error = %v", path, err) } assertRedactedCredentialBytes(t, data, canary) } func assertRedactedCredentialBytes(t *testing.T, data []byte, canary string) { t.Helper() text := string(data) if strings.Contains(text, canary) || !strings.Contains(text, "") { t.Fatal("captured stream did not contain the required redaction marker") } } func writeNativeCompletion(t *testing.T, req RunRequest, _ bool) { t.Helper() bundle := filepath.Join(req.OutputRoot, "bundle") if err := os.MkdirAll(bundle, 0755); err != nil { t.Fatal(err) } writeJSONFile(t, req.ReportPath, map[string]any{"pipeline": req.PipelineID, "artifact_count": 1, "output_directory": bundle}) } func writeJSONFile(t *testing.T, path string, value any) { t.Helper() data, err := json.Marshal(value) if err != nil { t.Fatal(err) } if err := os.WriteFile(path, data, 0644); err != nil { t.Fatal(err) } } func writeShellScript(t *testing.T, body string) string { t.Helper() path := filepath.Join(t.TempDir(), "notarius-helper") if err := os.WriteFile(path, []byte(body), 0o755); err != nil { t.Fatalf("WriteFile(script) error = %v", err) } return path } func assertTextFile(t *testing.T, path, want string) { t.Helper() data, err := os.ReadFile(path) if err != nil { t.Fatalf("ReadFile(%q) error = %v", path, err) } if string(data) != want { t.Fatalf("ReadFile(%q) = %q, want %q", path, string(data), want) } } func cloneMap(source map[string]any) map[string]any { result := make(map[string]any, len(source)) for key, value := range source { result[key] = value } return result }