Bootstrap secrets for shared configuration acquisition

This commit is contained in:
2026-11-23 04:20:31 +00:00
parent f87c45331c
commit 1ca5011049
13 changed files with 422 additions and 24 deletions

View File

@@ -40,7 +40,8 @@ func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct
} else {
source = ck.SearchConfig("audita", ck.Searches(ck.WorkingDirectory(), ck.UserConfigDirectory(), ck.UnixSystemDirectories()))
}
return appconfig.Load(ck.Input{Source: source}, selection.Overlay.Value, selection.Overrides...)
loaded, report, err := appconfig.Load(ctx, ck.Input{Source: source}, selection.Overlay.Value, selection.Overrides...)
return loaded, reportBootstrap(ctx, report, err)
}
func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input struct{}, state *invocationState) (*pk.Engine, error) {
@@ -80,7 +81,8 @@ func buildApplication(extra ...commandkit.Declaration) (*commandkit.App, error)
func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declaration) (*commandkit.App, error) {
appScope := ckconfig.FromConfigKit("app", "Audita application settings.", loadApplication)
appScope.Features.Overrides = true
promptScope := ckprompt.ConfigScope(loadPromptEngine)
appScope = withBootstrapContext(appScope)
promptScope := withBootstrapContext(ckprompt.ConfigScope(loadPromptEngine))
configCommand := ckconfig.Command(ckconfig.Suite[struct{}, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Scopes: []ckconfig.Scope[struct{}, *invocationState]{appScope, promptScope}})
definitions := ckprompt.WithNamespaces(ckprompt.FromEngine(capturePromptEngine), pk.Namespaces{})
definitions.NewState = func() *invocationState { return &invocationState{client: client} }
@@ -91,7 +93,8 @@ func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declara
return applicationPromptRequest(seed.Request, seed.Namespaces), nil
})
definitions = ckprompt.WithSmokeTesting(definitions, capturePromptEngine, nil)
declarations := []commandkit.Declaration{configCommand, commandkit.Completion("audita"), processCommand()}
definitions = withPromptBootstrapContext(definitions)
declarations := []commandkit.Declaration{configCommand, commandkit.Completion("audita"), commandkit.WithInvocationFeature(processCommand(), bootstrapFeature())}
declarations = append(declarations, ckprompt.Declarations(definitions)...)
declarations = append(declarations, extra...)
return commandkit.New(commandkit.Identity{Name: "audita", Version: buildinfo.Version()}, declarations...)

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
@@ -14,6 +15,7 @@ import (
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/ckprompt"
commandkit "go.maximumdirect.net/commandkit"
ck "go.maximumdirect.net/configkit"
pk "go.maximumdirect.net/promptkit"
)
@@ -230,3 +232,38 @@ func TestRequestDefaultsRespectNamespaceAndCallerVariables(t *testing.T) {
t.Fatalf("generic request changed: %v", result.Vars)
}
}
func TestConfigurationBootstrapReportsAndPreservesFailure(t *testing.T) {
dir := t.TempDir()
secrets := filepath.Join(dir, "secrets")
if err := os.Mkdir(secrets, 0700); err != nil {
t.Fatal(err)
}
t.Setenv("AUDITA_BOOTSTRAP_TEST", "prior")
if err := os.WriteFile(filepath.Join(secrets, "AUDITA_BOOTSTRAP_TEST"), []byte("synthetic-secret"), 0600); err != nil {
t.Fatal(err)
}
main := filepath.Join(dir, "config.yml")
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n"), 0600); err != nil {
t.Fatal(err)
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
var out, stderr bytes.Buffer
result := app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--verbose"}, commandkit.Streams{Out: &out, Err: &stderr})
if result.Status != 0 || os.Getenv("AUDITA_BOOTSTRAP_TEST") != "synthetic-secret" || !strings.Contains(stderr.String(), "AUDITA_BOOTSTRAP_TEST") || strings.Contains(stderr.String(), "synthetic-secret") {
t.Fatalf("status=%d stdout=%q stderr=%q", result.Status, out.String(), stderr.String())
}
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
t.Fatal(err)
}
out.Reset()
stderr.Reset()
result = app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--quiet"}, commandkit.Streams{Out: &out, Err: &stderr})
var native *ck.SecretsError
if result.Status != 1 || !errors.As(result.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") || strings.Contains(stderr.String(), "synthetic-secret") {
t.Fatalf("status=%d cause=%v stdout=%q stderr=%q", result.Status, result.Cause, out.String(), stderr.String())
}
}

117
internal/cli/bootstrap.go Normal file
View File

@@ -0,0 +1,117 @@
package cli
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/ckprompt"
commandkit "go.maximumdirect.net/commandkit"
ck "go.maximumdirect.net/configkit"
)
type bootstrapReporterKey struct{}
func bootstrapFeature() commandkit.InvocationFeature {
return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[struct{}]{
Start: func(inv commandkit.Invocation, _ struct{}) (context.Context, func() commandkit.Report) {
return context.WithValue(inv.Context, bootstrapReporterKey{}, inv.Reporter()), nil
},
})
}
type bootstrapError struct {
cause error
report *ck.SecretsReport
}
func (e *bootstrapError) Error() string {
var output bytes.Buffer
fmt.Fprintln(&output, e.cause)
var native *ck.SecretsError
if errors.As(e.cause, &native) {
for _, diagnostic := range native.Diagnostics() {
fmt.Fprintf(&output, "%s: %s\n", diagnostic.Code, diagnostic.Message)
}
}
if e.report != nil {
_, _ = e.report.WriteTo(&output)
}
return output.String()
}
func (e *bootstrapError) Unwrap() error { return e.cause }
func reportBootstrap(ctx context.Context, report *ck.SecretsReport, err error) error {
var native *ck.SecretsError
if errors.As(err, &native) {
return &bootstrapError{cause: err, report: report}
}
if report != nil && len(report.Entries()) > 0 {
if reporter, ok := ctx.Value(bootstrapReporterKey{}).(*commandkit.Reporter); ok {
_ = reporter.Info("Secrets bootstrap", func(w io.Writer) error {
_, writeErr := report.WriteTo(w)
return writeErr
})
}
}
return err
}
// withBootstrapContext retains safe bootstrap evidence in configuration outcomes.
func withBootstrapContext[I, S any](scope ckconfig.Scope[I, S]) ckconfig.Scope[I, S] {
acquire := scope.Acquire
scope.Acquire = func(ctx context.Context, request ckconfig.Request, input I, state S) (commandkit.Acquired[ckconfig.View], error) {
result, err := acquire(ctx, request, input, state)
result.Explanation = bootstrapExplanation(result.Explanation, err)
return result, err
}
compare := scope.Compare
scope.Compare = func(ctx context.Context, request ckconfig.ComparisonRequest[I], state S) (commandkit.Acquired[[]ck.Difference], error) {
result, err := compare(ctx, request, state)
result.Explanation = bootstrapExplanation(result.Explanation, err)
return result, err
}
return scope
}
func bootstrapExplanation(explanation commandkit.Explanation, err error) commandkit.Explanation {
var failure *bootstrapError
if errors.As(err, &failure) {
explanation.Details = append(explanation.Details, func(w io.Writer) error {
_, writeErr := io.WriteString(w, failure.Error())
return writeErr
})
}
return explanation
}
func withBootstrapAcquisition[R, I, S, T any](load func(context.Context, R, I, S) (commandkit.Acquired[T], error)) func(context.Context, R, I, S) (commandkit.Acquired[T], error) {
if load == nil {
return nil
}
return func(ctx context.Context, request R, input I, state S) (commandkit.Acquired[T], error) {
result, err := load(ctx, request, input, state)
result.Explanation = bootstrapExplanation(result.Explanation, err)
return result, err
}
}
func withPromptBootstrapContext[I, S any](suite ckprompt.Suite[I, S]) ckprompt.Suite[I, S] {
suite.InspectPrompt = withBootstrapAcquisition(suite.InspectPrompt)
suite.InspectProfile = withBootstrapAcquisition(suite.InspectProfile)
suite.InspectBackend = withBootstrapAcquisition(suite.InspectBackend)
suite.InspectRequirements = withBootstrapAcquisition(suite.InspectRequirements)
suite.ValidateRequest = withBootstrapAcquisition(suite.ValidateRequest)
suite.PrepareRequest = withBootstrapAcquisition(suite.PrepareRequest)
suite.SmokeTest = withBootstrapAcquisition(suite.SmokeTest)
suite.ListPrompts = withBootstrapAcquisition(suite.ListPrompts)
suite.ListProfiles = withBootstrapAcquisition(suite.ListProfiles)
suite.ListBackends = withBootstrapAcquisition(suite.ListBackends)
suite.ListNamespaces = withBootstrapAcquisition(suite.ListNamespaces)
suite.ListCollections = withBootstrapAcquisition(suite.ListCollections)
return suite
}

View File

@@ -0,0 +1,133 @@
package cli
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"go.maximumdirect.net/ckconfig"
"go.maximumdirect.net/ckprompt"
commandkit "go.maximumdirect.net/commandkit"
ck "go.maximumdirect.net/configkit"
pk "go.maximumdirect.net/promptkit"
)
func TestBootstrapConfigurationOutcomes(t *testing.T) {
dir := t.TempDir()
if err := os.Mkdir(filepath.Join(dir, "secrets"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("AUDITA_BOOTSTRAP_OUTCOME", "previous")
if err := os.WriteFile(filepath.Join(dir, "secrets", "AUDITA_BOOTSTRAP_OUTCOME"), []byte("private-value"), 0600); err != nil {
t.Fatal(err)
}
main := filepath.Join(dir, "config.yml")
writeMain := func(directory string) {
t.Helper()
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: "+directory+"\n secrets_overwrite: true\n"), 0600); err != nil {
t.Fatal(err)
}
}
writeMain("secrets")
loads := 0
load := func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*ck.Result[appconfig.Config], error) {
loads++
result, report, err := appconfig.Load(ctx, ck.Input{Source: ck.File(selection.Config.Value)}, "")
return result, reportBootstrap(ctx, report, err)
}
scope := withBootstrapContext(ckconfig.FromConfigKit("app", "Application settings", load))
command := ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{scope}})
app, err := commandkit.New(commandkit.Identity{Name: "test"}, commandkit.WithInvocationFeature(command, bootstrapFeature()))
if err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
for _, args := range [][]string{{"--help"}, {"version"}, {"config", "show", "--help"}, {"config", "explain"}} {
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &stdout, Err: &stderr})
if outcome.Status != 0 || loads != 0 || os.Getenv("AUDITA_BOOTSTRAP_OUTCOME") != "previous" {
t.Fatalf("help %v: outcome=%+v loads=%d", args, outcome, loads)
}
stdout.Reset()
stderr.Reset()
}
result := app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--verbose"}, commandkit.Streams{Out: &stdout, Err: &stderr})
if result.Status != 0 || os.Getenv("AUDITA_BOOTSTRAP_OUTCOME") != "private-value" || !strings.Contains(stderr.String(), "AUDITA_BOOTSTRAP_OUTCOME") || strings.Contains(stderr.String(), "private-value") {
t.Fatalf("success: status=%d stderr=%q", result.Status, stderr.String())
}
stdout.Reset()
stderr.Reset()
before := loads
result = app.Execute(context.Background(), []string{"config", "diff", "--scope=app", "--config", main, "--against-config", main}, commandkit.Streams{Out: &stdout, Err: &stderr})
if result.Status != 0 || loads-before != 2 {
t.Fatalf("comparison: status=%d acquisitions=%d stderr=%q", result.Status, loads-before, stderr.String())
}
failedWrite := errors.New("diagnostic destination failed")
stdout.Reset()
result = app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--verbose"}, commandkit.Streams{Out: &stdout, Err: bootstrapFailWriter{err: failedWrite}})
if result.Status != 1 || !errors.Is(result.Presentation.Diagnostics.WriteError, failedWrite) {
t.Fatalf("diagnostic write failure: %+v", result)
}
writeMain("missing")
stdout.Reset()
stderr.Reset()
result = app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--quiet"}, commandkit.Streams{Out: &stdout, Err: &stderr})
var native *ck.SecretsError
if result.Status != 1 || !errors.As(result.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") || strings.Contains(stderr.String(), "private-value") {
t.Fatalf("failure: status=%d cause=%v stderr=%q", result.Status, result.Cause, stderr.String())
}
}
func TestBootstrapPreservesJoinedCancellation(t *testing.T) {
main := filepath.Join(t.TempDir(), "config.yml")
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
t.Fatal(err)
}
_, report, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
joined := errors.Join(err, context.Canceled)
wrapped := reportBootstrap(context.Background(), report, joined)
var native *ck.SecretsError
if !errors.As(wrapped, &native) || !errors.Is(wrapped, context.Canceled) {
t.Fatalf("cause = %v", wrapped)
}
explanation := bootstrapExplanation(commandkit.Explanation{}, wrapped)
var detail bytes.Buffer
if len(explanation.Details) != 1 {
t.Fatalf("details = %d", len(explanation.Details))
}
if err := explanation.Details[0](&detail); err != nil || !strings.Contains(detail.String(), "secrets.") {
t.Fatalf("detail = %q error = %v", detail.String(), err)
}
}
func TestPromptBootstrapFailureReportsTerminalDetails(t *testing.T) {
main := filepath.Join(t.TempDir(), "config.yml")
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
t.Fatal(err)
}
load := func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*pk.Engine, error) {
_, report, err := appconfig.Load(ctx, ck.Input{Source: ck.File(selection.Config.Value)}, "")
return nil, reportBootstrap(ctx, report, err)
}
suite := withPromptBootstrapContext(ckprompt.FromEngine(load))
commands := ckprompt.Declarations(suite)
commands = append(commands, commandkit.WithInvocationFeature(commandkit.Group("auxiliary", ""), bootstrapFeature()))
app, err := commandkit.New(commandkit.Identity{Name: "test"}, commands...)
if err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
outcome := app.Execute(context.Background(), []string{"promptkit", "list", "prompts", "--config", main, "--quiet"}, commandkit.Streams{Out: &stdout, Err: &stderr})
var native *ck.SecretsError
if outcome.Status != 1 || !errors.As(outcome.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") {
t.Fatalf("outcome=%+v stderr=%q", outcome, stderr.String())
}
}
type bootstrapFailWriter struct{ err error }
func (w bootstrapFailWriter) Write([]byte) (int, error) { return 0, w.err }

View File

@@ -37,6 +37,10 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom
}
return commandkit.Failure(loadErr.Error(), explanation.Details...).WithCause(err)
}
var secretsErr *bootstrapError
if errors.As(err, &secretsErr) {
return commandkit.Failure(secretsErr.Error()).WithCause(err)
}
if inv.Context.Err() != nil || llm.IsAssetError(err) {
return commandkit.Failure("Could not prepare processing.").WithCause(err)
}
@@ -65,7 +69,7 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom
warn(debug.WriteSourceTranscript(loaded.Source, loaded.RawTranscript))
}
loaded.RawTranscript = nil
cfg := &loaded.Configuration.Config
cfg := &loaded.Configuration.Config.Application
normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{
MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap,
MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens,

View File

@@ -11,7 +11,7 @@ import (
"path/filepath"
"time"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
coreio "gitea.maximumdirect.net/eric/audita/v4/internal/core/io"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
@@ -26,7 +26,7 @@ import (
)
type processInputs struct {
Configuration *ck.Result[config.Config]
Configuration *ck.Result[appconfig.Config]
Runtime *llm.Runtime
Source *schema.SourceTranscript
RawTranscript []byte
@@ -80,7 +80,7 @@ type preparedProcess struct {
}
func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) {
cfg := &loaded.Configuration.Config
cfg := &loaded.Configuration.Config.Application
reportDir := ""
reportDirSet := false
for _, override := range input.Overrides {

View File

@@ -16,7 +16,7 @@ import (
)
func executePipeline(ctx context.Context, loaded *processInputs, prepared *preparedProcess, normalized *schema.Transcript, warn func(error), progress func(string)) (processResult, error) {
cfg := &loaded.Configuration.Config
cfg := &loaded.Configuration.Config.Application
specs := prepared.Prepared.Specs
debug := prepared.Prepared.Debug
evidence := runner.EvidenceSelection{Reports: cfg.Reporting.Enabled, Debug: debug != nil}