Files
oikos/internal/mcp/secrets_tools_test.go
dtoro 9e3783734e
Some checks failed
ci / build-test (push) Has been cancelled
ci / docker-build (push) Has been cancelled
feat: Phase 3b — EntityService, postgres EntityRepository, converged mutations
Problem: entity mutations (create/update/state) existed as three drifted
copies — HTTP CreateEntity/PatchEntity, MCP create_entity/
update_entity_attributes/set_entity_state — each with its own inline
SQL, its own validation subset (MCP validated lifecycle states, HTTP
did not; HTTP patched attributes without regenerating derived checks,
MCP did; MCP wrote no audit trail), the exact drift ADR 0016's first
vertical slice exists to collapse.

Change:
- internal/core/ports: DerivedCheck, Idempotency (adapter-owned request
  hash + cached-body renderer so the replay record commits in the
  create's transaction), IdempotentResponse + GetIdempotent read,
  AuditEntry gains Method/Path/CorrelationID, Event gains
  CorrelationID; EntityUpdateInput carries ExpectedVersion +
  RederiveChecks (derivation for updates runs repo-side: the graph
  host fallback reads relationships through the open tx).
- internal/adapters/postgres/repositories.go: EntityRepo (Create/
  Update/SetState/reads/idempotency) preserving the load-bearing
  check-then-act invariants in-tx: version WHERE-clause, declared
  transitions + preconditions (ValidateTransition), duplicate-slug
  mapping, audit/event/writeCheck all inside one BEGIN…COMMIT.
  OntologyRepo: TTL-cached OntologyStore.
- internal/core/app/entities.go: EntityService — ontology validation
  (type exists, concrete, state declared — the stricter MCP rule now
  governs both surfaces), default-state resolution, id generation,
  derivation for creates, audit/event construction, idempotency
  pass-through.
- httpapi CreateEntity/PatchEntity rewired to the service; PATCH now
  regenerates derived checks (the A2 parity gap). MCP create/update/
  set-state tools call the same service — and now write audit + event
  rows like the HTTP surface always did.
- Integration-test seed paths fixed for the adapters/postgres package
  depth (../../../seeds).

Pre-existing failures documented: TestAPIEndToEnd (entity_types 60 vs
59; 501-endpoint now 200), TestClientLifecycleEndToEnd, TestPhase3*
rows — verified failing identically at ec11956 (scratch approval-
notifier commit test drift), unrelated to this change. All mutation
integration tests (create/patch/idempotency/audit/regeneration) pass.

Verification: make test-db (postgres + mcp green, httpapi green except
the pre-existing set), full non-DB suite (19 pkgs), golangci on new
packages — 0 issues.
2026-08-15 23:38:21 +02:00

199 lines
5.5 KiB
Go

package mcp
import (
"context"
"encoding/json"
"testing"
"github.com/dtoro/oikos/internal/secrets"
"github.com/google/uuid"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
type mockSecretBackend struct {
data map[string]string
}
func (m *mockSecretBackend) Get(ctx context.Context, key string) (string, error) {
v, ok := m.data[key]
if !ok {
return "", secrets.ErrNotFound
}
return v, nil
}
func (m *mockSecretBackend) Set(ctx context.Context, key string, value string) error {
m.data[key] = value
return nil
}
func (m *mockSecretBackend) List(ctx context.Context) ([]string, error) {
keys := make([]string, 0, len(m.data))
for k := range m.data {
keys = append(keys, k)
}
return keys, nil
}
func (m *mockSecretBackend) Name() string { return "mock" }
// findToolHandler locates a tool's handler from allTools by name.
func findToolHandler(t *testing.T, pool interface{}, name string, sec secrets.Backend) func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
t.Helper()
for _, r := range allTools(nil, uuid.Nil, sec, nil) {
if r.tool.Name == name {
return r.handler
}
}
t.Fatalf("tool %q not found", name)
return nil
}
func callToolJSON(t *testing.T, name string, sec secrets.Backend, args map[string]any) any {
t.Helper()
handler := findToolHandler(t, nil, name, sec)
argBytes, _ := json.Marshal(args)
req := &mcp.CallToolRequest{
Params: &mcp.CallToolParamsRaw{Arguments: argBytes},
}
result, err := handler(context.Background(), req)
if err != nil {
t.Fatalf("tool %q error: %v", name, err)
}
if len(result.Content) == 0 {
t.Fatalf("tool %q returned no content", name)
}
tc := result.Content[0].(*mcp.TextContent)
var out any
if err := json.Unmarshal([]byte(tc.Text), &out); err != nil {
// Not JSON — return raw string
return tc.Text
}
return out
}
func callToolText(t *testing.T, name string, sec secrets.Backend, args map[string]any) string {
t.Helper()
handler := findToolHandler(t, nil, name, sec)
argBytes, _ := json.Marshal(args)
req := &mcp.CallToolRequest{
Params: &mcp.CallToolParamsRaw{Arguments: argBytes},
}
result, err := handler(context.Background(), req)
if err != nil {
t.Fatalf("tool %q error: %v", name, err)
}
if len(result.Content) == 0 {
t.Fatalf("tool %q returned no content", name)
}
return result.Content[0].(*mcp.TextContent).Text
}
func TestGetSecret(t *testing.T) {
sec := &mockSecretBackend{
data: map[string]string{
"matrix-token": "bot-token-123",
"clients/host:hubris/age-key": "AGE-SECRET-KEY",
},
}
// Get existing key
val := callToolText(t, "get_secret", sec, map[string]any{"key": "matrix-token"})
if val != "bot-token-123" {
t.Errorf("get_secret = %q, want bot-token-123", val)
}
// Get missing key
errText := callToolText(t, "get_secret", sec, map[string]any{"key": "nonexistent"})
if errText == "" {
t.Error("expected error for missing key")
}
// Missing key arg
errText = callToolText(t, "get_secret", sec, map[string]any{})
if errText != "error: key is required" {
t.Errorf("missing key error = %q, want error: key is required", errText)
}
}
func TestListSecrets(t *testing.T) {
sec := &mockSecretBackend{
data: map[string]string{
"clients/host:hubris/age-key": "val1",
"clients/host:strong/age-key": "val2",
"shared/matrix-token": "val3",
},
}
// List all
out := callToolJSON(t, "list_secrets", sec, map[string]any{})
keys, ok := out.([]any)
if !ok {
t.Fatalf("list_secrets returned non-array: %T", out)
}
if len(keys) != 3 {
t.Errorf("list_secrets count = %d, want 3", len(keys))
}
// List with prefix filter
out = callToolJSON(t, "list_secrets", sec, map[string]any{"path_prefix": "clients/"})
keys, ok = out.([]any)
if !ok {
t.Fatalf("filtered list returned non-array: %T", out)
}
if len(keys) != 2 {
t.Errorf("filtered list count = %d, want 2", len(keys))
}
}
func TestSetSecret(t *testing.T) {
sec := &mockSecretBackend{
data: map[string]string{},
}
// Set a key
result := callToolText(t, "set_secret", sec, map[string]any{"key": "test-key", "value": "test-value"})
if result != "secret test-key stored" {
t.Errorf("set_secret = %q, want 'secret test-key stored'", result)
}
// Verify it was stored
val, err := sec.Get(context.Background(), "test-key")
if err != nil {
t.Fatalf("verify get: %v", err)
}
if val != "test-value" {
t.Errorf("stored value = %q, want test-value", val)
}
// Missing key
errText := callToolText(t, "set_secret", sec, map[string]any{})
if errText != "error: key is required" {
t.Errorf("missing key error = %q", errText)
}
// Missing value
errText = callToolText(t, "set_secret", sec, map[string]any{"key": "x"})
if errText != "error: value is required" {
t.Errorf("missing value error = %q", errText)
}
}
func TestSecretToolsNilBackend(t *testing.T) {
// All tools should return a graceful error when no backend is configured
errText := callToolText(t, "get_secret", nil, map[string]any{"key": "x"})
if errText != "error: no secrets backend configured (set OIKOS_INFISICAL_SITE_URL)" {
t.Errorf("nil backend get_secret = %q", errText)
}
errText = callToolText(t, "list_secrets", nil, map[string]any{})
if errText != "error: no secrets backend configured (set OIKOS_INFISICAL_SITE_URL)" {
t.Errorf("nil backend list_secrets = %q", errText)
}
errText = callToolText(t, "set_secret", nil, map[string]any{"key": "x", "value": "y"})
if errText != "error: no secrets backend configured (set OIKOS_INFISICAL_SITE_URL)" {
t.Errorf("nil backend set_secret = %q", errText)
}
}