feat: Phase 9 gaps closed — ApprovalService.Decide convergence, execlog fold, execworker poller
Some checks are pending
ci / build-test (push) Waiting to run
ci / docker-build (push) Waiting to run

- ApprovalService (core/app/approval.go) + ApprovalRepo (postgres adapter) with
  full decide transaction: HMAC token verify, approval flip, execution un-gate,
  session-scoped window keys (+session suffix matching GovernanceStore gate),
  nomos session flip, audit+event on failure abort. httpapi DecideApproval now
  a thin presenter delegating to the service. ListPending payload format fixed
  (json.Unmarshal not raw-wrap).
- execlog folded into postgres adapter: internal/execlog deleted, NewExecutionLog
  / ReadExecutionLog live in the db package, callers updated (mcp, httpapi).
- execworker poller over ExecutionService.DispatchQueued: advisory lock leak
  fixed (defer/recover per execution), correlation_id preserved via Finalize
  event emission (ExecRunRepo.Finalize now emits execution.{status} with
  correlation_id from the row).
- Phase 8 session export-rename completed: Store, New, and all 53 methods
  exported; cmd/nomos/ agent.go fixed to use session.PendingContinuation etc.
- Coverage gates: ExecutionService.Submit 93.1%, PolicyService.Decide 100%.
- Plans index updated, VERSION bumped to 0.36.0.
This commit is contained in:
2026-08-16 12:29:59 +02:00
parent 986937799a
commit b98d7c24bf
27 changed files with 1161 additions and 600 deletions

View File

@@ -0,0 +1,65 @@
package app
import (
"context"
"fmt"
"github.com/dtoro/oikos/internal/core/domain"
"github.com/dtoro/oikos/internal/core/ports"
"github.com/google/uuid"
)
// ApprovalService is the approval-decision use-case: list pending approvals
// and decide (approve/deny/revoke), which un-gates the linked execution and
// persists the audit trail. The driving adapter dispatches the SSH work for
// approved executions after Decide returns.
type ApprovalService struct {
approvals ports.ApprovalRepository
}
// NewApprovalService wires the service.
func NewApprovalService(approvals ports.ApprovalRepository) *ApprovalService {
return &ApprovalService{approvals: approvals}
}
// List returns pending approvals for the given entity.
func (s *ApprovalService) List(ctx context.Context, entityID domain.UUID, limit int) ([]domain.Approval, error) {
return s.approvals.ListPending(ctx, entityID, limit)
}
// ApprovalDecideCmd is one decide-approval request.
type ApprovalDecideCmd struct {
ApprovalID domain.UUID
Token string
Decision string // "approve" | "deny" | "revoke"
Actor string
}
// Decide validates the decision, maps to status, and delegates the
// transactional flip + execution un-gate + audit + event to the repository.
// Returns the updated approval and, on approve, the execution to resume.
func (s *ApprovalService) Decide(ctx context.Context, cmd ApprovalDecideCmd) (ports.ApprovalDecideResult, error) {
var status string
switch cmd.Decision {
case "approve":
status = "approved"
case "deny":
status = "denied"
case "revoke":
status = "revoked"
default:
return ports.ApprovalDecideResult{}, fmt.Errorf("%w: invalid decision %q", domain.ErrInvalidInput, cmd.Decision)
}
aid, err := uuid.Parse(string(cmd.ApprovalID))
if err != nil {
return ports.ApprovalDecideResult{}, fmt.Errorf("parse approval id: %w", err)
}
return s.approvals.Decide(ctx, ports.ApprovalDecideInput{
ApprovalID: domain.UUID(aid.String()),
Token: cmd.Token,
Status: status,
Actor: cmd.Actor,
})
}

View File

@@ -0,0 +1,114 @@
package app
import (
"context"
"errors"
"testing"
"github.com/dtoro/oikos/internal/core/domain"
"github.com/dtoro/oikos/internal/core/ports"
"github.com/dtoro/oikos/internal/core/ports/portstest"
"github.com/google/uuid"
)
func TestApprovalDecideValidDecisions(t *testing.T) {
for _, tc := range []struct {
decision string
want string
}{
{"approve", "approved"},
{"deny", "denied"},
{"revoke", "revoked"},
} {
t.Run(tc.decision, func(t *testing.T) {
repo := portstest.NewApprovalRepo()
repo.Result = ports.ApprovalDecideResult{
Approval: domain.Approval{EntityID: "some-id", Status: tc.want},
}
svc := NewApprovalService(repo)
aid := uuid.New()
got, err := svc.Decide(context.Background(), ApprovalDecideCmd{
ApprovalID: domain.UUID(aid.String()),
Decision: tc.decision,
Actor: "operator",
})
if err != nil {
t.Fatalf("Decide(%s): %v", tc.decision, err)
}
if len(repo.Decided) != 1 {
t.Fatalf("Decide called %d times, want 1", len(repo.Decided))
}
in := repo.Decided[0]
if in.Status != tc.want {
t.Errorf("repo status = %q, want %q", in.Status, tc.want)
}
if in.Actor != "operator" || string(in.ApprovalID) != aid.String() {
t.Errorf("repo input = %+v", in)
}
if got.Approval.Status != tc.want {
t.Errorf("result approval status = %q, want %q", got.Approval.Status, tc.want)
}
})
}
}
func TestApprovalDecideInvalidDecision(t *testing.T) {
repo := portstest.NewApprovalRepo()
svc := NewApprovalService(repo)
_, err := svc.Decide(context.Background(), ApprovalDecideCmd{
ApprovalID: domain.UUID(uuid.New().String()),
Decision: "maybe",
Actor: "operator",
})
if !errors.Is(err, domain.ErrInvalidInput) {
t.Fatalf("err = %v, want ErrInvalidInput", err)
}
if len(repo.Decided) != 0 {
t.Error("repo must not be called on an invalid decision")
}
}
func TestApprovalDecideRepoErrorPropagates(t *testing.T) {
repo := portstest.NewApprovalRepo()
repo.ErrStub = domain.ErrNotFound
svc := NewApprovalService(repo)
_, err := svc.Decide(context.Background(), ApprovalDecideCmd{
ApprovalID: domain.UUID(uuid.New().String()),
Decision: "approve",
})
if !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
func TestApprovalList(t *testing.T) {
repo := portstest.NewApprovalRepo()
repo.Pending = []domain.Approval{{EntityID: "a", Status: "pending"}}
svc := NewApprovalService(repo)
got, err := svc.List(context.Background(), "e1", 10)
if err != nil {
t.Fatalf("List: %v", err)
}
if len(got) != 1 || got[0].Status != "pending" {
t.Fatalf("got %+v", got)
}
}
func TestApprovalDecideTokenForwarded(t *testing.T) {
repo := portstest.NewApprovalRepo()
svc := NewApprovalService(repo)
aid := uuid.New()
_, err := svc.Decide(context.Background(), ApprovalDecideCmd{
ApprovalID: domain.UUID(aid.String()),
Token: "hmac-token",
Decision: "approve",
Actor: "operator",
})
if err != nil {
t.Fatalf("Decide: %v", err)
}
if repo.Decided[0].Token != "hmac-token" {
t.Errorf("token = %q, want forwarded", repo.Decided[0].Token)
}
}

View File

@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
"strings"
"time"
"github.com/dtoro/oikos/internal/core/domain"
@@ -19,10 +20,10 @@ import (
// (MCP `run`/`docker_exec` tools, and any future REST surface) converge
// here — one policy, one audit trail (plan §4.A).
type ExecutionService struct {
policy *PolicyService
exec ports.CommandExecutor
resolver ports.TargetResolver
recorder ports.ExecutionRecorder
policy *PolicyService
exec ports.CommandExecutor
resolver ports.TargetResolver
recorder ports.ExecutionRecorder
}
// NewExecutionService wires the service.
@@ -199,6 +200,31 @@ func (s *ExecutionService) finalize(ctx context.Context, execID domain.UUID, sta
}
}
// DispatchQueued runs a previously-recorded queued execution (status
// 'proposed' or 'approved') over the CommandExecutor port. The command is
// derived from the execution's action column the same way the legacy worker
// did: "action_name:{json_params}" extracts params["command"], else the
// action string is the raw command. Used by the execworker poller adapter.
func (s *ExecutionService) DispatchQueued(ctx context.Context, execID domain.UUID, targetSlug, action string) (string, error) {
return s.dispatch(ctx, execID, targetSlug, queuedCommand(action), nil, nil)
}
// queuedCommand extracts the actual shell command from an execution's action
// column. Format: "action_name:{json_params}" → params["command"]; otherwise
// the action string is itself the raw command.
func queuedCommand(action string) string {
if idx := strings.Index(action, ":"); idx > 0 && idx < len(action)-1 {
rawParams := action[idx+1:]
var params map[string]any
if json.Unmarshal([]byte(rawParams), &params) == nil {
if c, ok := params["command"].(string); ok && c != "" {
return c
}
}
}
return action
}
func jsonOutBytes(out string) []byte {
b, _ := json.Marshal(map[string]any{"output": out})
return b

View File

@@ -281,3 +281,135 @@ func TestExecutionSubmitHostHint(t *testing.T) {
t.Errorf("default hint missing: %s", d.Message)
}
}
func TestQueuedCommandExtraction(t *testing.T) {
cases := map[string]string{
`run:{"command":"df -h","purpose":"check"}`: "df -h",
`systemctl restart caddy`: "systemctl restart caddy",
`pct:{"command":"pct list"}`: "pct list",
`apt_upgrade:not-json`: "apt_upgrade:not-json",
`plain command`: "plain command",
}
for in, want := range cases {
if got := queuedCommand(in); got != want {
t.Errorf("queuedCommand(%q) = %q, want %q", in, got, want)
}
}
}
func TestExecutionDispatchQueued(t *testing.T) {
rec, exec, _ := newExecDeps(t)
exec.Results = []ports.ExecResult{{Output: "uptime output"}}
res, err := svcFor(t, rec, exec).DispatchQueued(context.Background(), targetID, "lxc:x", `run:{"command":"uptime"}`)
if err != nil {
t.Fatalf("DispatchQueued: %v", err)
}
if res != "uptime output" {
t.Errorf("result = %q", res)
}
if len(rec.Running) != 1 || len(rec.Finalized) != 1 {
t.Fatalf("running=%d finalized=%d", len(rec.Running), len(rec.Finalized))
}
if rec.Finalized[0].Status != "completed" {
t.Errorf("finalized = %+v", rec.Finalized[0])
}
}
func TestExecutionDispatchQueuedFailure(t *testing.T) {
rec, exec, _ := newExecDeps(t)
exec.Results = []ports.ExecResult{{Output: "boom", Err: errors.New("exit 2")}}
_, err := svcFor(t, rec, exec).DispatchQueued(context.Background(), targetID, "lxc:x", "uptime")
if err == nil {
t.Fatal("expected dispatch error")
}
if rec.Finalized[0].Status != "failed" {
t.Errorf("finalized = %+v, want failed", rec.Finalized[0])
}
}
func TestExecutionDispatchQueuedResolverFailure(t *testing.T) {
rec, exec, _ := newExecDeps(t)
failing := &portstest.FakeResolver{Err: errors.New("no route")}
svc := NewExecutionService(NewPolicyService(portstest.NewGovernanceStore()), exec, failing, rec)
_, err := svc.DispatchQueued(context.Background(), targetID, "lxc:x", "uptime")
if err == nil {
t.Fatal("expected resolver error")
}
if len(exec.Calls) != 0 {
t.Error("no execution on resolve failure")
}
if rec.Finalized[0].Status != "failed" {
t.Errorf("finalized = %+v, want failed", rec.Finalized[0])
}
}
func TestExecutionSubmitNoSessionGetsCorrelationID(t *testing.T) {
rec, exec, svc := newExecDeps(t)
exec.Results = []ports.ExecResult{{Output: "ok"}}
res := svc.Submit(context.Background(), ExecutionSubmitCmd{
AgentID: agentID, TargetID: targetID, TargetSlug: "lxc:x",
Command: "df -h", // auto-run, no session
})
if res.Err != nil {
t.Fatalf("submit: %v", res.Err)
}
if len(rec.Created) != 1 || rec.Created[0].CorrelationID == "" {
t.Errorf("created = %+v, want a correlation id", rec.Created)
}
}
func TestExecutionSubmitAsyncStarted(t *testing.T) {
rec, exec, _ := newExecDeps(t)
exec.Results = []ports.ExecResult{{Output: "sleeping"}}
store := portstest.NewGovernanceStore()
store.PlanSessions[sessionOK] = true
store.Assent[string(agentID)+"/"+sessionOK] = true
svc := NewExecutionService(NewPolicyService(store), exec, &portstest.FakeResolver{Addr: "10.0.0.1", User: "root"}, rec)
res := svc.Submit(context.Background(), ExecutionSubmitCmd{
AgentID: agentID, TargetID: targetID, TargetSlug: "lxc:x",
Command: "sleep 60", SessionID: sessionOK, Async: true,
})
if !res.AsyncStarted {
t.Fatalf("result = %+v, want async started", res)
}
if res.ExecutionID == "" {
t.Fatal("async submission must return the execution id synchronously")
}
}
func TestExecutionSubmitAutoRunQueueResume(t *testing.T) {
rec, exec, _ := newExecDeps(t)
exec.Results = []ports.ExecResult{{Output: "done"}}
// A gated command queues; the same command with a live assent window
// auto-runs instead — the window route switch in Submit.
store := portstest.NewGovernanceStore()
store.PlanSessions[sessionOK] = true
store.Assent[string(agentID)+"/"+sessionOK] = true
svc := NewExecutionService(NewPolicyService(store), exec, &portstest.FakeResolver{Addr: "10.0.0.1", User: "root"}, rec)
res := svc.Submit(context.Background(), ExecutionSubmitCmd{
AgentID: agentID, TargetID: targetID, TargetSlug: "lxc:x",
Command: "systemctl enable caddy", SessionID: sessionOK,
})
if res.Decision.Action != DecisionAuto {
t.Fatalf("decision = %+v, want auto (via assent window)", res.Decision)
}
if len(rec.Queued) != 0 {
t.Errorf("window route must not queue, got %+v", rec.Queued)
}
}
// svcFor builds a service over the given recorder/executor with a plan-backed
// governance store.
func svcFor(t *testing.T, rec *portstest.ExecutionRecorder, exec *portstest.RecordingExecutor) *ExecutionService {
t.Helper()
store := portstest.NewGovernanceStore()
store.PlanSessions[sessionOK] = true
return NewExecutionService(NewPolicyService(store), exec, &portstest.FakeResolver{Addr: "10.1.1.1", User: "root"}, rec)
}

View File

@@ -83,17 +83,32 @@ type ExecutionRepository interface {
type ApprovalDecideInput struct {
ApprovalID domain.UUID
Token string
Approved bool
Status string // "approved" | "denied" | "revoked"
Actor string
Audit []AuditEntry
Event *Event
}
// ApprovalResume identifies an un-gated execution the driving adapter should
// dispatch after an approved decision (SSH work is adapter-specific).
type ApprovalResume struct {
ExecutionID domain.UUID
TargetSlug string
Action string
}
// ApprovalDecideResult carries the updated approval and, on approve, the
// linked execution to resume.
type ApprovalDecideResult struct {
Approval domain.Approval
Resume *ApprovalResume
}
// ApprovalRepository is the approval aggregate.
type ApprovalRepository interface {
ListPending(ctx context.Context, entityID domain.UUID, limit int) ([]domain.Approval, error)
Decide(ctx context.Context, input ApprovalDecideInput) (domain.Approval, error)
Decide(ctx context.Context, input ApprovalDecideInput) (ApprovalDecideResult, error)
}
// GovernanceStore is the policy read model: the facts the gating decision

View File

@@ -17,11 +17,11 @@ import (
// EntityRepo is an in-memory ports.EntityRepository. Command inputs' audit,
// event, and derived-check fields are recorded for assertion.
type EntityRepo struct {
mu sync.Mutex
byID map[domain.UUID]domain.Entity
bySlug map[string]domain.UUID
order []domain.UUID
nextID int
mu sync.Mutex
byID map[domain.UUID]domain.Entity
bySlug map[string]domain.UUID
order []domain.UUID
nextID int
Audits []ports.AuditEntry
Events []ports.Event
Checks map[domain.UUID][]ports.CheckDef
@@ -34,8 +34,8 @@ type EntityRepo struct {
// NewEntityRepo builds an empty in-memory entity repository.
func NewEntityRepo() *EntityRepo {
return &EntityRepo{
byID: make(map[domain.UUID]domain.Entity),
bySlug: make(map[string]domain.UUID),
byID: make(map[domain.UUID]domain.Entity),
bySlug: make(map[string]domain.UUID),
Checks: make(map[domain.UUID][]ports.CheckDef),
Idempotent: make(map[string]ports.IdempotentResponse),
}
@@ -404,12 +404,12 @@ func (r *FakeResolver) IsGuest(entityType string) bool {
// FakeProvisioner records provision requests and replies with canned
// results (default: a successful create echoing the request's VMID).
type FakeProvisioner struct {
mu sync.Mutex
LXCs []ports.LXCInput
VMs []ports.VMInput
LXCRes ports.ProvisionResult
LXCErr error
VMErr error
mu sync.Mutex
LXCs []ports.LXCInput
VMs []ports.VMInput
LXCRes ports.ProvisionResult
LXCErr error
VMErr error
}
// CreateLXC records the request and replies with the canned result.
@@ -623,7 +623,42 @@ func (r *ExecutionRecorder) QueueApproval(_ context.Context, in ports.QueueAppro
// MuLock exposes the internal mutex for tests that need to inspect state
// racing the async dispatch goroutine.
func (r *ExecutionRecorder) MuLock() { r.mu.Lock() }
func (r *ExecutionRecorder) MuLock() { r.mu.Lock() }
// MuUnlock releases the internal mutex.
func (r *ExecutionRecorder) MuUnlock() { r.mu.Unlock() }
// ApprovalRepo is an in-memory ports.ApprovalRepository. ListPending returns
// the canned pending list; Decide records the input and replies with a canned
// result or the ErrStub.
type ApprovalRepo struct {
mu sync.Mutex
// Pending is returned by ListPending.
Pending []domain.Approval
// Decided records every Decide input for assertion.
Decided []ports.ApprovalDecideInput
// Result is returned by Decide (default: empty approval).
Result ports.ApprovalDecideResult
ErrStub error
}
// NewApprovalRepo builds an empty in-memory approval repository.
func NewApprovalRepo() *ApprovalRepo { return &ApprovalRepo{} }
// ListPending returns the canned pending list.
func (r *ApprovalRepo) ListPending(_ context.Context, _ domain.UUID, _ int) ([]domain.Approval, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.Pending, r.ErrStub
}
// Decide records the input and replies with the canned result.
func (r *ApprovalRepo) Decide(_ context.Context, in ports.ApprovalDecideInput) (ports.ApprovalDecideResult, error) {
r.mu.Lock()
defer r.mu.Unlock()
r.Decided = append(r.Decided, in)
if r.ErrStub != nil {
return ports.ApprovalDecideResult{}, r.ErrStub
}
return r.Result, nil
}