Files
archie/internal/app/archied/openshell_model_egress_test.go
sam 9c04b74e6f docs: fix Vale prose findings across comments, docs and prompts
Run Vale over every tracked Go, Markdown and template file and fix the remaining findings: long sentences, repetition, UI verbs, identifiers that should be backticked, and migration narration in comments.

AGENTS.md and CLAUDE.md keep their absolute rules; the prompt heuristic against repeated absolutes is disabled for rule files.
2026-11-24 03:26:16 +11:00

198 lines
7.1 KiB
Go

package archied
import (
"context"
"log/slog"
"maps"
"strings"
"testing"
v1 "github.com/ai-openshell/sdk-go/openshell/v1"
"github.com/ai-openshell/sdk-go/openshell/v1/fake"
"github.com/ai-openshell/sdk-go/openshell/v1/types"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/openshell"
"github.com/samcharles93/archie-core/internal/secret"
)
// stubProfiles stands in for the profile API the SDK fake leaves unimplemented.
type stubProfiles struct {
v1.ProfileInterface
known map[string]bool
items *[]v1.ProviderProfile
}
func (s stubProfiles) Get(_ context.Context, _, id string) (*v1.ProviderProfile, error) {
if s.known[id] {
return &v1.ProviderProfile{ID: id}, nil
}
return nil, &types.StatusError{Code: types.ErrorNotFound, Message: "no such profile"}
}
func (s stubProfiles) Import(_ context.Context, _ string, items []v1.ProfileImportItem) (*v1.ImportResult, error) {
for _, it := range items {
s.known[it.Profile.ID] = true
*s.items = append(*s.items, it.Profile)
}
return &v1.ImportResult{Imported: true}, nil
}
type stubProviders struct {
v1.ProviderInterface
profiles stubProfiles
}
func (s stubProviders) Profiles() v1.ProfileInterface { return s.profiles }
type fakeGateway struct{ providers stubProviders }
func (g fakeGateway) Providers() v1.ProviderInterface { return g.providers }
type fixedBindings string
func (f fixedBindings) Resolve(context.Context, string, string) (string, error) {
return string(f), nil
}
// The OpenShell model session registers each keyed provider's real key on the
// gateway, hands the sandbox no key, and removes the provider when the task
// ends. Guards a key leaking into the session or outliving its task.
func TestOpenShellModelEgressHoldsKeysOnTheGateway(t *testing.T) {
cases := []struct {
name string
providers map[string]config.Provider
wantKeys map[string]string // key env -> real key held on the gateway
wantHosts []string
wantPorts []int // defaults to 443 for each host
wantHeader string // header that carries the key; empty means a bearer token
}{
{
name: "secret reference",
providers: map[string]config.Provider{
"alpha": {Class: "openai", BaseURL: "https://api.alpha.example", APIKey: config.SecretRef{Engine: "env", Key: "ALPHA_SECRET"}},
},
wantKeys: map[string]string{config.ProviderKeyEnvName("alpha"): "alpha-fake-key"},
wantHosts: []string{"api.alpha.example"},
},
{
name: "org binding",
providers: map[string]config.Provider{
"beta": {Class: "openai", BaseURL: "https://api.beta.example", APIKeyEnv: "BETA_KEY"},
},
wantKeys: map[string]string{"BETA_KEY": "bound-fake-key"},
wantHosts: []string{"api.beta.example"},
},
{
name: "a keyless provider is reached on its base URL's host and port, holding no key",
providers: map[string]config.Provider{
"local": {Class: "openai", BaseURL: "http://192.0.2.7:8080/v1"},
},
wantKeys: map[string]string{},
wantHosts: []string{"192.0.2.7"},
wantPorts: []int{8080},
},
{
name: "anthropic keys travel in x-api-key",
providers: map[string]config.Provider{"claude": {Class: "anthropic", APIKeyEnv: "CLAUDE_KEY"}},
wantKeys: map[string]string{"CLAUDE_KEY": "bound-fake-key"},
wantHosts: []string{"api.anthropic.com"},
wantHeader: "x-api-key",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("ALPHA_SECRET", "alpha-fake-key")
var imported []v1.ProviderProfile
fc := fake.NewClient()
t.Cleanup(func() { _ = fc.Close() })
gw := fakeGateway{stubProviders{ProviderInterface: fc.Providers(), profiles: stubProfiles{known: map[string]bool{}, items: &imported}}}
m := newOpenShellModelEgress(gw, "ws", "Test Inst", secret.NewRegistry(), fixedBindings("bound-fake-key"), slog.New(slog.DiscardHandler))
session, err := m.Open(t.Context(), "run-credential", "org-test", tc.providers, nil)
if err != nil {
t.Fatal(err)
}
if len(session.Env) != 0 || len(session.Mounts) != 0 {
t.Fatalf("session carries env %v mounts %v, want none: the gateway sets placeholders", session.Env, session.Mounts)
}
if len(session.Providers) != len(tc.wantHosts) {
t.Fatalf("session providers = %+v, want hosts %v", session.Providers, tc.wantHosts)
}
held := map[string]string{}
for i, mp := range session.Providers {
wantPort := 443
if tc.wantPorts != nil {
wantPort = tc.wantPorts[i]
}
if mp.Host != tc.wantHosts[i] || mp.Port != wantPort {
t.Errorf("provider %d = %s:%d, want %s:%d", i, mp.Host, mp.Port, tc.wantHosts[i], wantPort)
}
if mp.Gateway == "" {
continue
}
if strings.Contains(mp.Gateway, "run-credential") || strings.Contains(mp.Gateway, "fake-key") {
t.Errorf("gateway name %q leaks the credential or key", mp.Gateway)
}
got, err := fc.Providers().Get(t.Context(), "ws", mp.Gateway)
if err != nil {
t.Fatalf("gateway provider %q: %v", mp.Gateway, err)
}
maps.Copy(held, got.Spec.Credentials)
}
for env, key := range tc.wantKeys {
if held[env] != key {
t.Errorf("gateway holds %q = %q, want the real key", env, held[env])
}
}
for _, p := range imported {
if got := p.Credentials[0].HeaderName; got != tc.wantHeader {
t.Errorf("profile %s places the key in header %q, want %q", p.ID, got, tc.wantHeader)
}
}
m.Close(t.Context(), "run-credential")
left, err := fc.Providers().ListAll(t.Context(), "ws")
if err != nil {
t.Fatal(err)
}
if len(left) != 0 {
t.Fatalf("%d gateway providers remain after Close, want none", len(left))
}
})
}
}
// A daemon that died mid-task leaves its providers, and their keys, on the
// gateway. The boot sweep removes this instance's and keeps other instances'.
// Guards keys outliving a crash, and one instance deleting another's providers.
func TestOpenShellModelEgressSweepsOnlyItsOwnLeftovers(t *testing.T) {
fc := fake.NewClient()
t.Cleanup(func() { _ = fc.Close() })
gw := fakeGateway{stubProviders{ProviderInterface: fc.Providers(), profiles: stubProfiles{known: map[string]bool{}, items: &[]v1.ProviderProfile{}}}}
log := slog.New(slog.DiscardHandler)
providers := map[string]config.Provider{"claude": {Class: "anthropic", APIKeyEnv: "CLAUDE_KEY"}}
other := newOpenShellModelEgress(gw, "ws", "other", secret.NewRegistry(), fixedBindings("fake-key"), log)
if _, err := other.Open(t.Context(), "run-other", "org-test", providers, nil); err != nil {
t.Fatal(err)
}
crashed := newOpenShellModelEgress(gw, "ws", "mine", secret.NewRegistry(), fixedBindings("fake-key"), log)
if _, err := crashed.Open(t.Context(), "run-mine", "org-test", providers, nil); err != nil {
t.Fatal(err)
}
restarted := newOpenShellModelEgress(gw, "ws", "mine", secret.NewRegistry(), fixedBindings("fake-key"), log)
if err := restarted.Sweep(t.Context()); err != nil {
t.Fatal(err)
}
left, err := fc.Providers().ListAll(t.Context(), "ws")
if err != nil {
t.Fatal(err)
}
if len(left) != 1 || left[0].Labels[openshell.InstanceLabel] != "other" {
t.Fatalf("providers after sweep = %+v, want only the other instance's", left)
}
}