From 415738ea1f104077393c04f0a974e0750c8337aa Mon Sep 17 00:00:00 2001 From: Lebedev Nikita Date: Sun, 25 Oct 2026 12:07:49 +0400 Subject: [PATCH] fix(approval): preserve authority and causal lifecycle timestamps --- internal/app/console_lab_clock_test.go | 134 +++++++++++++ internal/app/console_lab_coordination.go | 18 +- internal/app/console_lab_mutation.go | 7 +- internal/app/console_lab_time_test.go | 32 ++++ internal/app/guest_types.go | 1 + internal/app/recovery.go | 2 + internal/app/recovery_lab_clock_test.go | 71 +++++++ internal/app/recovery_mutation.go | 10 +- internal/app/session_coordination.go | 15 +- internal/approval/consumption_time_test.go | 47 +++++ internal/approval/store.go | 3 + .../daemon/guest_approval_authority_test.go | 176 ++++++++++++++++++ internal/daemon/guest_configuration.go | 4 +- .../guest_configuration_authority_test.go | 55 ++++++ internal/daemon/guest_protocol.go | 4 +- internal/daemon/guest_service_http_test.go | 8 +- internal/sessions/clock_regression_test.go | 70 +++++++ internal/sessions/manager.go | 13 +- internal/sessions/reconcile.go | 3 + 19 files changed, 657 insertions(+), 16 deletions(-) create mode 100644 internal/app/console_lab_clock_test.go create mode 100644 internal/app/recovery_lab_clock_test.go create mode 100644 internal/approval/consumption_time_test.go create mode 100644 internal/daemon/guest_approval_authority_test.go create mode 100644 internal/daemon/guest_configuration_authority_test.go create mode 100644 internal/sessions/clock_regression_test.go diff --git a/internal/app/console_lab_clock_test.go b/internal/app/console_lab_clock_test.go new file mode 100644 index 0000000..11102a8 --- /dev/null +++ b/internal/app/console_lab_clock_test.go @@ -0,0 +1,134 @@ +package app + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "path/filepath" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/approval" + "github.com/Horcag/agent-machine-control/internal/domain" +) + +func TestGuestLabAdmissionSurvivesBackwardClockStep(t *testing.T) { + h := newGuestHarness(t) + h.safety.destructive = true + h.actor.AuthenticatedCaller, h.actor.EffectiveActor = "agent:mcp-local", "agent:mcp-local" + coordinator := h.service.session + authority, operator := persistentGuestAuthority(t, h) + admittedAt := time.Now().UTC() + authority.recovery.nowFn = func() time.Time { return admittedAt } + grant, _, err := authority.IssueLabGrant(t.Context(), operator, ConsoleLabGrantIssueRequest{Mode: ConsoleLabModePersistentVM, Target: "default", Reason: "operate disposable VM", IdempotencyKey: "clock-lab", Beneficiary: "agent:mcp-local", AcknowledgeExternalEffects: true}) + if err != nil { + t.Fatal(err) + } + coordinator.labAuthority = authority + p := h.params("prepare", "clock-step-prepare") + p.Deadline = admittedAt.Add(time.Minute) + digest := sha256.Sum256([]byte(grant.GrantID + "\x00" + string(h.actor.EffectiveActor) + "\x00" + p.IdempotencyKey)) + id := ConsoleLabApprovalPrefix + hex.EncodeToString(digest[:16]) + // A server clock can step backwards between issuance and policy/consumption. + // The separate recovery clock must not choose this admission's issuance time. + authority.recovery.nowFn = func() time.Time { return admittedAt.Add(50 * time.Millisecond) } + coordinator.nowFn = func() time.Time { + if issued, _ := coordinator.approvalStore.LoadIssuedContext(context.Background(), id); issued != nil { + return admittedAt.Add(-50 * time.Millisecond) + } + return admittedAt + } + result, err := h.service.Execute(t.Context(), p, nil, nil) + if err != nil || result.Receipt == nil || result.Receipt.Outcome.Status != domain.OutcomeSuccess || h.transport.executed != 1 { + t.Fatalf("backwards clock denied fresh local authority: result=%+v err=%v dispatches=%d", result, err, h.transport.executed) + } + issued, err := coordinator.approvalStore.LoadIssuedContext(t.Context(), id) + if err != nil || !issued.IssuedAt.Equal(admittedAt) { + t.Fatalf("issuance used a different clock: approval=%+v err=%v", issued, err) + } + loaded, err := approval.LoadFromFile(filepath.Join(filepath.Dir(h.service.store.directory), "approvals", id+".json")) + if err != nil || !loaded.Consumed || loaded.ConsumedAt.Before(loaded.IssuedAt) { + t.Fatalf("invalid durable consumption: approval=%+v err=%v", loaded, err) + } + if _, err := h.service.Execute(t.Context(), p, nil, nil); err != nil || h.transport.executed != 1 { + t.Fatalf("exact retry dispatched again: %v dispatches=%d", err, h.transport.executed) + } +} + +func TestGuestLabClockBoundariesRemainStrict(t *testing.T) { + for _, scenario := range []string{"existing future", "forward expiry", "consumption expiry", "cancelled"} { + t.Run(scenario, func(t *testing.T) { testGuestLabClockBoundary(t, scenario) }) + } +} + +func testGuestLabClockBoundary(t *testing.T, scenario string) { + t.Helper() + h := newGuestHarness(t) + h.safety.destructive = true + h.actor.AuthenticatedCaller, h.actor.EffectiveActor = "agent:mcp-local", "agent:mcp-local" + authority, operator := persistentGuestAuthority(t, h) + admittedAt := time.Now().UTC() + authority.recovery.nowFn = func() time.Time { return admittedAt } + grant, _, err := authority.IssueLabGrant(t.Context(), operator, ConsoleLabGrantIssueRequest{Mode: ConsoleLabModePersistentVM, Target: "default", Reason: "operate disposable VM", IdempotencyKey: "clock-boundaries", Beneficiary: "agent:mcp-local", AcknowledgeExternalEffects: true}) + if err != nil { + t.Fatal(err) + } + coordinator := h.service.session + coordinator.labAuthority = authority + p := h.params("prepare", "clock-boundaries-prepare") + p.Deadline = admittedAt.Add(time.Minute) + digest := sha256.Sum256([]byte(grant.GrantID + "\x00" + string(h.actor.EffectiveActor) + "\x00" + p.IdempotencyKey)) + id := ConsoleLabApprovalPrefix + hex.EncodeToString(digest[:16]) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if scenario == "existing future" { + config, err := h.config.Current(ctx, grant.Target, h.actor) + if err != nil { + t.Fatal(err) + } + op, err := guestOperation(p, grant.Target, config) + if err != nil { + t.Fatal(err) + } + op.Classification = domain.ClassDestructivePrivileged + if _, err := authority.deriveLabApproval(ctx, grant, op, admittedAt.Add(50*time.Millisecond)); err != nil { + t.Fatal(err) + } + } + coordinator.nowFn = guestBoundaryClock(coordinator, id, scenario, admittedAt, p.Deadline, cancel) + _, err = h.service.Execute(ctx, p, nil, nil) + if err == nil || h.transport.executed != 0 { + t.Fatalf("clock boundary dispatched: err=%v dispatches=%d", err, h.transport.executed) + } + if scenario == "existing future" && !errors.Is(err, domain.ErrApprovalNotYetValid) { + var denied *PolicyDeniedError + if !errors.As(err, &denied) || denied.Reason != "approval_record_not_yet_valid" { + t.Fatalf("future authority changed: %v", err) + } + } + consumed, err := coordinator.approvalStore.IsConsumedContext(t.Context(), id) + if err != nil || consumed { + t.Fatalf("rejected authority was consumed: %v %v", consumed, err) + } +} + +func guestBoundaryClock(coordinator *SessionService, id, scenario string, admittedAt, deadline time.Time, cancel context.CancelFunc) func() time.Time { + afterIssuance := 0 + return func() time.Time { + if issued, _ := coordinator.approvalStore.LoadIssuedContext(context.Background(), id); issued != nil { + afterIssuance++ + switch scenario { + case "forward expiry": + return deadline + case "consumption expiry": + if afterIssuance > 1 { + return deadline + } + case "cancelled": + cancel() + } + } + return admittedAt + } +} diff --git a/internal/app/console_lab_coordination.go b/internal/app/console_lab_coordination.go index dc9bd17..f311423 100644 --- a/internal/app/console_lab_coordination.go +++ b/internal/app/console_lab_coordination.go @@ -3,6 +3,7 @@ package app import ( "context" "errors" + "time" "github.com/Horcag/agent-machine-control/internal/domain" "github.com/Horcag/agent-machine-control/internal/target" @@ -57,12 +58,12 @@ func (s *ConsoleService) admitPersistentLab(ctx context.Context, op domain.Opera return &grant, release, nil } -func (s *ConsoleService) derivePersistentLab(ctx context.Context, op domain.Operation) (*domain.Approval, *ConsoleLabGrant, func() error, error) { +func (s *ConsoleService) derivePersistentLab(ctx context.Context, op domain.Operation, admittedAt time.Time) (*domain.Approval, *ConsoleLabGrant, func() error, error) { grant, release, err := s.admitPersistentLab(ctx, op) if err != nil || grant == nil { return nil, grant, release, err } - approval, err := s.deriveLabApproval(ctx, *grant, op) + approval, err := s.deriveLabApproval(ctx, *grant, op, admittedAt) if err != nil { return nil, nil, func() error { return nil }, errors.Join(err, release()) } @@ -86,7 +87,8 @@ func (s *RecoveryService) coordinatePersistentRecovery(ctx context.Context, op d if req.Approval != nil || req.ApprovalID != "" || req.ApprovalError != nil { return req, execute, release, nil } - derived, grant, release, err := s.labAuthority.derivePersistentLab(ctx, op) + admittedAt := s.now() + derived, grant, release, err := s.labAuthority.derivePersistentLab(ctx, op, admittedAt) if err != nil { return req, execute, release, err } @@ -94,8 +96,18 @@ func (s *RecoveryService) coordinatePersistentRecovery(ctx context.Context, op d return req, execute, release, nil } req.Approval, req.ApprovalID = derived, string(derived.ID) + req.labAdmissionAt = admittedAt fenced := func(effectCtx context.Context) error { return s.labAuthority.withPersistentLabEffect(effectCtx, grant, execute) } return req, fenced, release, nil } + +// labAdmissionTime preserves causality only for locally derived authority. +// Fresh forward readings still enforce expiry; external approvals get no floor. +func labAdmissionTime(now, admittedAt time.Time, local bool) time.Time { + if local && now.Before(admittedAt) { + return admittedAt + } + return now +} diff --git a/internal/app/console_lab_mutation.go b/internal/app/console_lab_mutation.go index f0c207e..a021ab4 100644 --- a/internal/app/console_lab_mutation.go +++ b/internal/app/console_lab_mutation.go @@ -36,7 +36,8 @@ func (s *ConsoleService) executeLabMutation(ctx context.Context, actor domain.Ac if err != nil { return result, err } - issued, err := s.deriveLabApproval(ctx, grant, op) + req.labAdmissionAt = s.recovery.now() + issued, err := s.deriveLabApproval(ctx, grant, op, req.labAdmissionAt) if err != nil { return result, err } @@ -63,7 +64,7 @@ func labOperationAllowed(op domain.Operation) bool { op.Classification == domain.ClassDestructivePrivileged && len(op.RequiredScopes) == 1 && op.RequiredScopes[0] == domain.ScopeMachineWrite } -func (s *ConsoleService) deriveLabApproval(ctx context.Context, grant ConsoleLabGrant, op domain.Operation) (*domain.Approval, error) { +func (s *ConsoleService) deriveLabApproval(ctx context.Context, grant ConsoleLabGrant, op domain.Operation, issuedAt time.Time) (*domain.Approval, error) { fingerprint, err := op.Fingerprint() if err != nil { return nil, err @@ -75,7 +76,7 @@ func (s *ConsoleService) deriveLabApproval(ctx context.Context, grant ConsoleLab return nil, err } issued := domain.Approval{ID: id, Actor: op.Actor.EffectiveActor, Target: op.Target, AuthorizedClass: domain.ClassDestructivePrivileged, - Fingerprint: fingerprint, IdempotencyKey: op.IdempotencyKey, IssuedAt: s.recovery.now(), ExpiresAt: op.Deadline} + Fingerprint: fingerprint, IdempotencyKey: op.IdempotencyKey, IssuedAt: issuedAt, ExpiresAt: op.Deadline} if existing != nil { issued.IssuedAt = existing.IssuedAt if !equalIssuedOperationApproval(*existing, issued) { diff --git a/internal/app/console_lab_time_test.go b/internal/app/console_lab_time_test.go index bc5e7a4..9cb7d4b 100644 --- a/internal/app/console_lab_time_test.go +++ b/internal/app/console_lab_time_test.go @@ -2,9 +2,14 @@ package app_test import ( "context" + "crypto/sha256" + "encoding/hex" + "path/filepath" "testing" "time" + "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/approval" "github.com/Horcag/agent-machine-control/internal/domain" ) @@ -44,3 +49,30 @@ func TestConsoleLabEquivalentDeadlineDispatchesOnce(t *testing.T) { }) } } + +func TestNativeLabAdmissionSurvivesBackwardClockStep(t *testing.T) { + f := newConsoleFixture(t) + configureLab(f) + grant := issueLab(t, f) + op, req, providerID := labOperation(t, grant) + digest := sha256.Sum256([]byte(grant.GrantID + "\x00" + string(op.Actor.EffectiveActor) + "\x00" + op.IdempotencyKey)) + id := app.ConsoleLabApprovalPrefix + hex.EncodeToString(digest[:16]) + store := approval.NewStore(filepath.Join(f.root, "approvals")) + *f.now = f.now.Add(time.Second) + admittedAt := *f.now + app.WithRecoveryClock(func() time.Time { + if issued, _ := store.LoadIssuedContext(context.Background(), id); issued != nil { + return admittedAt.Add(-50 * time.Millisecond) + } + return admittedAt + })(f.recovery) + dispatched := 0 + result, err := f.service.ExecuteLabMutation(t.Context(), req.Actor, grant.GrantID, op, req, providerID, func(context.Context) error { dispatched++; return nil }) + if err != nil || result.Outcome.Status != domain.OutcomeSuccess || dispatched != 1 { + t.Fatalf("native lab clock step: result=%+v err=%v dispatches=%d", result, err, dispatched) + } + loaded, err := approval.LoadFromFile(filepath.Join(f.root, "approvals", id+".json")) + if err != nil || !loaded.Consumed || loaded.ConsumedAt.Before(loaded.IssuedAt) { + t.Fatalf("native consumption is invalid: approval=%+v err=%v", loaded, err) + } +} diff --git a/internal/app/guest_types.go b/internal/app/guest_types.go index 421b8d9..3931079 100644 --- a/internal/app/guest_types.go +++ b/internal/app/guest_types.go @@ -21,6 +21,7 @@ var ErrGuestUncertain = errors.New("app: guest operation outcome is uncertain; d // GuestConfiguration is refreshed at admission and at the effect boundary. // Current must revalidate enrollment, credentials and key pins, current actor // authority, and the server-provisioned workspace; Generation binds all of them. +// Caller preserves requested authority without expanding it to the live principal. // WorkspaceIdentity must come from authorized provisioning, never path adoption. type GuestConfiguration struct { Generation string diff --git a/internal/app/recovery.go b/internal/app/recovery.go index 11ce748..a81827f 100644 --- a/internal/app/recovery.go +++ b/internal/app/recovery.go @@ -60,6 +60,8 @@ type MutationRequest struct { // Set only when the normal identity-bound receipt lookup returns a terminal result. cachedReceipt *bool providerDispatched *bool + // Only trusted lab coordination sets this causal floor for local issuance. + labAdmissionAt time.Time } // RecoveryService orchestrates in-process direct recovery operations, policy, leases, and receipts. diff --git a/internal/app/recovery_lab_clock_test.go b/internal/app/recovery_lab_clock_test.go new file mode 100644 index 0000000..826663f --- /dev/null +++ b/internal/app/recovery_lab_clock_test.go @@ -0,0 +1,71 @@ +package app + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/domain" +) + +type clockLabBackend struct { + Backend + onCapabilities func() +} + +func (b clockLabBackend) Capabilities(context.Context, string) (domain.CapabilitySet, error) { + b.onCapabilities() + return domain.NewCapabilitySet(domain.CapabilityConsoleInput), nil +} + +func TestPersistentRecoveryLabClockBoundaries(t *testing.T) { + for _, forward := range []bool{false, true} { + name := "backward step" + if forward { + name = "expiry before consumption" + } + t.Run(name, func(t *testing.T) { testPersistentRecoveryLabClock(t, forward) }) + } +} + +func testPersistentRecoveryLabClock(t *testing.T, forward bool) { + t.Helper() + authority, grant, op, _ := coordinationGrantFixture(t) + recovery := authority.recovery + WithRecoveryLabAuthority(authority)(recovery) + digest := sha256.Sum256([]byte(grant.GrantID + "\x00" + string(op.Actor.EffectiveActor) + "\x00" + op.IdempotencyKey)) + id := ConsoleLabApprovalPrefix + hex.EncodeToString(digest[:16]) + admittedAt := grant.IssuedAt.Add(time.Second) + op.Deadline = admittedAt.Add(time.Minute) + authorized := false + recovery.backend = clockLabBackend{onCapabilities: func() { authorized = true }} + recovery.nowFn = func() time.Time { + if forward && authorized { + return op.Deadline + } + if issued, _ := recovery.approvalStore.LoadIssuedContext(context.Background(), id); issued != nil { + return admittedAt.Add(-50 * time.Millisecond) + } + return admittedAt + } + req := MutationRequest{TargetID: string(op.Target), Actor: op.Actor, Reason: op.Reason, IdempotencyKey: op.IdempotencyKey, Deadline: op.Deadline} + locator, err := domain.ParseMachineLocator(string(op.Target)) + if err != nil { + t.Fatal(err) + } + dispatched := 0 + result, err := recovery.executeMutation(t.Context(), op, req, locator.VMID, func(context.Context) error { dispatched++; return nil }) + if forward { + if err == nil || dispatched != 0 { + t.Fatalf("expired admission dispatched: result=%+v err=%v dispatches=%d", result, err, dispatched) + } + } else if err != nil || result.Outcome.Status != domain.OutcomeSuccess || dispatched != 1 { + t.Fatalf("backwards clock rejected causal admission: result=%+v err=%v dispatches=%d", result, err, dispatched) + } + consumed, err := recovery.approvalStore.IsConsumedContext(t.Context(), id) + if err != nil || consumed == forward { + t.Fatalf("consumption=%v err=%v", consumed, err) + } +} diff --git a/internal/app/recovery_mutation.go b/internal/app/recovery_mutation.go index 5d7d49d..8ad5366 100644 --- a/internal/app/recovery_mutation.go +++ b/internal/app/recovery_mutation.go @@ -130,7 +130,7 @@ func (s *RecoveryService) executeMutation( } defer func() { resultErr = errors.Join(resultErr, releaseGrant()) }() - now := s.now() + now := labAdmissionTime(s.now(), req.labAdmissionAt, !req.labAdmissionAt.IsZero()) // 3. Rollback discovery & 4. Policy evaluation & 5. Approval check decision, rollbackRef, err := s.prepareAndAuthorizeMutation(ctx, op, req, providerTargetID, now) @@ -151,7 +151,8 @@ func (s *RecoveryService) executeMutation( } // 7. Audit Admission Intent & Approval Consumption - approvalConsumed, err := s.recordAdmissionAndConsume(ctx, op, decision, req, now) + consumedAt := labAdmissionTime(s.now(), now, !req.labAdmissionAt.IsZero()) + approvalConsumed, err := s.recordAdmissionAndConsume(ctx, op, decision, req, consumedAt) if err != nil { return s.preProviderFailure(ctx, op, fp, decision, now, errors.Join(err, releaseLease()), rollbackRef, req.ApprovalID) } @@ -219,6 +220,11 @@ func (s *RecoveryService) recordAdmissionAndConsume( req MutationRequest, now time.Time, ) (bool, error) { + if decision.EffectiveClass.RequiresApproval() && req.Approval != nil { + if err := req.Approval.IsActive(now); err != nil { + return false, approvalActivityDenial(err) + } + } if s.auditStore != nil { if err := s.auditStore.RecordAdmissionIntentContext(ctx, op); err != nil { return false, fmt.Errorf("%w: %w", ErrAuditUnavailable, err) diff --git a/internal/app/session_coordination.go b/internal/app/session_coordination.go index 61d0f86..24a29f5 100644 --- a/internal/app/session_coordination.go +++ b/internal/app/session_coordination.go @@ -163,6 +163,11 @@ func (s *SessionService) checkDestructiveApproval(ctx context.Context, approval } func (s *SessionService) prepareAuditAndApproval(ctx context.Context, decision policy.Decision, op domain.Operation, approval *domain.Approval, now time.Time) error { + if decision.EffectiveClass.RequiresApproval() && approval != nil { + if err := approval.IsActive(now); err != nil { + return approvalActivityDenial(err) + } + } if s.auditStore != nil { if err := s.auditStore.RecordAdmissionIntentContext(ctx, op); err != nil { return err @@ -292,6 +297,7 @@ func (s *SessionService) executeMutation( type admittedSessionMutation struct { approval *domain.Approval labGrant *ConsoleLabGrant + admittedAt time.Time op domain.Operation fp domain.Fingerprint idFp domain.Fingerprint @@ -339,19 +345,20 @@ func (s *SessionService) admitSessionMutation( releaseLease: releaseLease, }, nil, nil } + admittedAt := s.now() if labGrant != nil && op.Classification.RequiresApproval() { - approval, err = s.labAuthority.deriveLabApproval(ctx, *labGrant, op) + approval, err = s.labAuthority.deriveLabApproval(ctx, *labGrant, op, admittedAt) if err != nil { return nil, nil, errors.Join(err, releaseLease()) } } - now := s.now() + now := labAdmissionTime(s.now(), admittedAt, labGrant != nil) decision, denialReceipt, err := s.evaluateAndAdmit(ctx, op, safety, approval, now, fp, idFp) if err != nil { return nil, denialReceipt, errors.Join(err, releaseLease()) } return &admittedSessionMutation{ - op: op, fp: fp, idFp: idFp, decision: decision, safety: safety, releaseLease: releaseLease, approval: approval, labGrant: labGrant, + op: op, fp: fp, idFp: idFp, decision: decision, safety: safety, releaseLease: releaseLease, approval: approval, labGrant: labGrant, admittedAt: now, }, nil, nil } @@ -359,7 +366,7 @@ func (s *SessionService) reserveAndPrepareMutation(ctx context.Context, admitted if s.mutationJournal == nil { return errors.Join(errors.New("app: session mutation journal is unavailable"), admitted.releaseLease()) } - now := s.now() + now := labAdmissionTime(s.now(), admitted.admittedAt, admitted.labGrant != nil) if _, err := s.mutationJournal.ReserveContext(ctx, admitted.op, now); err != nil { return errors.Join(err, admitted.releaseLease()) } diff --git a/internal/approval/consumption_time_test.go b/internal/approval/consumption_time_test.go new file mode 100644 index 0000000..2895a5c --- /dev/null +++ b/internal/approval/consumption_time_test.go @@ -0,0 +1,47 @@ +package approval_test + +import ( + "errors" + "path/filepath" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/approval" + "github.com/Horcag/agent-machine-control/internal/domain" +) + +func TestConsumptionRequiresActiveTimeAndPersistsValidRecord(t *testing.T) { + now := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + at time.Time + want error + }{ + {"before issuance", now.Add(-time.Nanosecond), domain.ErrApprovalNotYetValid}, + {"at expiry", now.Add(time.Minute), domain.ErrApprovalExpired}, + {"after expiry", now.Add(2 * time.Minute), domain.ErrApprovalExpired}, + {"at issuance", now, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + directory := t.TempDir() + store := approval.NewStore(directory) + issued := domain.Approval{ID: "app-consumption-time", Actor: "operator:synthetic", Target: "11111111-1111-4111-8111-111111111111", AuthorizedClass: domain.ClassDestructivePrivileged, Fingerprint: "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", IdempotencyKey: "consumption-time", IssuedAt: now, ExpiresAt: now.Add(time.Minute)} + if err := store.Issue(issued); err != nil { + t.Fatal(err) + } + if err := store.MarkConsumed(issued, tc.at); !errors.Is(err, tc.want) { + t.Fatalf("consumption error=%v, want %v", err, tc.want) + } + consumed, err := store.IsConsumed(string(issued.ID)) + if err != nil || consumed != (tc.want == nil) { + t.Fatalf("consumption state=%v err=%v", consumed, err) + } + if tc.want == nil { + loaded, err := approval.LoadFromFile(filepath.Join(directory, string(issued.ID)+".json")) + if err != nil || !loaded.Consumed || !loaded.ConsumedAt.Equal(tc.at) { + t.Fatalf("invalid durable consumption=%+v err=%v", loaded, err) + } + } + }) + } +} diff --git a/internal/approval/store.go b/internal/approval/store.go index 1d7ea15..e3320b9 100644 --- a/internal/approval/store.go +++ b/internal/approval/store.go @@ -198,6 +198,9 @@ func (s *Store) MarkConsumedContext(ctx context.Context, a domain.Approval, cons if err := s.validateIssuedLocked(ctx, a); err != nil { return err } + if err := a.IsActive(consumedAt); err != nil { + return err + } consumed := a.Clone() consumed.Consumed = true diff --git a/internal/daemon/guest_approval_authority_test.go b/internal/daemon/guest_approval_authority_test.go new file mode 100644 index 0000000..7f992e2 --- /dev/null +++ b/internal/daemon/guest_approval_authority_test.go @@ -0,0 +1,176 @@ +package daemon + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/approval" + "github.com/Horcag/agent-machine-control/internal/audit" + "github.com/Horcag/agent-machine-control/internal/auth" + "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/guest/stream" + "github.com/Horcag/agent-machine-control/internal/lease" + "github.com/Horcag/agent-machine-control/internal/receipt" + "github.com/Horcag/agent-machine-control/internal/sessions" +) + +// Exercise the production identity provider: an echoing config fixture conceals +// mismatches between a requested beneficiary and its current authenticated actor. +func TestGuestApprovalUsesCurrentBeneficiaryAuthority(t *testing.T) { + provider, _, _, _ := newGuestConfigurationFixture(t) + sd := provider.server.stateDir + fixture := &guestHTTPServiceFixture{ + root: stream.RootIdentity{Path: `C:\AMC\synthetic`, Volume: 7, FileID: strings.Repeat("a", 32), CreationTime: 100, Owner: "S-1-5-21-synthetic", SDDLHash: strings.Repeat("d", 64)}, + worker: stream.WorkerIdentity{PID: 123, BirthTicks: 638000000000000001, Image: `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`, SID: "S-1-5-21-synthetic"}, + privileged: true, + } + ref := "local:11111111-1111-4111-8111-111111111111" + record, err := provider.workspaceRecord(t.Context(), domain.MachineRef(ref)) + if err != nil { + t.Fatal(err) + } + record.Workspace = fixture.root + data, err := json.Marshal(record) + if err != nil { + t.Fatal(err) + } + digest := sha256.Sum256([]byte(ref)) + name := hex.EncodeToString(digest[:]) + if err := writeGuestPrivateFixture(t, filepath.Join(sd.Root(), "guest-workspaces", name+".json"), data); err != nil { + t.Fatal(err) + } + coordinator := app.NewSessionService(nil, fixture, lease.NewManager(sd.LeasesDir()), audit.NewStore(sd.AuditDir()), receipt.NewStore(sd.ReceiptsDir()), approval.NewStore(sd.ApprovalsDir()), app.WithSessionMutationJournal(sessions.NewMutationJournal(sd.SessionsDir()))) + server := provider.server + server.semaphore = make(chan struct{}, 8) + server.guestService = app.NewGuestService(coordinator, fixture, &provider, fixture, app.NewGuestStore(filepath.Join(sd.Root(), "guest"))) + endpoint := httptest.NewServer(server.authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/approval" { + server.handleGuestApproval(w, r) + return + } + server.handleGuestOperation(w, r) + }))) + t.Cleanup(endpoint.Close) + operator, err := auth.ReadTokenFile(sd.AuthDir(), auth.TokenTypeOperator) + if err != nil { + t.Fatal(err) + } + agent, err := auth.ReadTokenFile(sd.AuthDir(), auth.TokenTypeAgentMCP) + if err != nil { + t.Fatal(err) + } + p := app.GuestOperationParams{Target: ref, Operation: "prepare", Reason: "approve exact guest preparation", IdempotencyKey: "real-beneficiary-prepare"} + request := GuestApprovalRequest{Params: p, Beneficiary: string(auth.AgentMCPPrincipal), ValidForMillis: 60000} + first := issueGuestApprovalTwice(t, endpoint.URL+"/approval", operator, request) + p.ApprovalID, p.Deadline = first.Grant.ApprovalID, first.Grant.Deadline + final, _ := invokeGuestHTTPFixture(t, endpoint.URL+"/operation", agent, p, nil) + if final.Error != "" || final.Result.Receipt == nil || final.Result.Receipt.Outcome.Status != domain.OutcomeSuccess || strings.Join(fixture.operations, ",") != "observe" { + t.Fatalf("issued beneficiary could not execute: %+v operations=%v", final, fixture.operations) + } + final, _ = invokeGuestHTTPFixture(t, endpoint.URL+"/operation", agent, p, nil) + if final.Error != "" || final.Result.Receipt == nil || strings.Join(fixture.operations, ",") != "observe" { + t.Fatalf("exact execution retry dispatched again: %+v operations=%v", final, fixture.operations) + } + assertGuestApprovedPayload(t, endpoint, operator, agent, ref, fixture, request) + request.Params.IdempotencyKey = "agent-cannot-issue" + response := requestGuestApproval(t, endpoint.URL+"/approval", agent, request) + _ = response.Body.Close() + if response.StatusCode != http.StatusForbidden { + t.Fatalf("agent issued operator authority: status=%d", response.StatusCode) + } +} + +func requestGuestApproval(t *testing.T, endpoint, token string, value GuestApprovalRequest) *http.Response { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, endpoint, bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Authorization", "Bearer "+token) + request.Header.Set("Content-Type", "application/json") + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatal(err) + } + return response +} + +func TestGuestApprovalReportsAuthorityFailuresBeforeIssuance(t *testing.T) { + for _, tc := range []struct { + name string + err error + category string + }{ + {"revoked authority", app.ErrGuestAuthority, "guest_authority"}, + {"missing workspace", app.ErrGuestWorkspaceUnprovisioned, "guest_workspace_unprovisioned"}, + } { + t.Run(tc.name, func(t *testing.T) { + endpoint, token, fixture := newGuestHTTPServiceFixture(t) + fixture.configErr = tc.err + request := GuestApprovalRequest{Params: app.GuestOperationParams{Operation: "prepare", Reason: "synthetic approval failure", IdempotencyKey: "failed-approval"}, Beneficiary: "self", ValidForMillis: time.Minute.Milliseconds()} + response := requestGuestApproval(t, endpoint.URL+"/approval", token, request) + var body struct { + Error struct { + Category string `json:"category"` + } `json:"error"` + } + decodeErr := json.NewDecoder(response.Body).Decode(&body) + _ = response.Body.Close() + if response.StatusCode != http.StatusForbidden || decodeErr != nil || body.Error.Category != tc.category || len(fixture.operations) != 0 { + t.Fatalf("known authority failure: status=%d body=%+v operations=%v err=%v", response.StatusCode, body, fixture.operations, decodeErr) + } + }) + } +} + +func issueGuestApprovalTwice(t *testing.T, endpoint, operator string, request GuestApprovalRequest) GuestApprovalResponse { + t.Helper() + var first GuestApprovalResponse + for attempt := range 2 { + response := requestGuestApproval(t, endpoint, operator, request) + var issued GuestApprovalResponse + decodeErr := json.NewDecoder(response.Body).Decode(&issued) + _ = response.Body.Close() + if response.StatusCode != http.StatusOK || decodeErr != nil || issued.Grant == nil || issued.Receipt == nil { + t.Fatalf("issuance attempt %d: status=%d response=%+v err=%v", attempt, response.StatusCode, issued, decodeErr) + } + if attempt == 0 { + first = issued + } else if first.Grant.ApprovalID != issued.Grant.ApprovalID || first.Receipt.ReceiptID != issued.Receipt.ReceiptID { + t.Fatal("exact issuance retry changed authority") + } + } + return first +} + +func assertGuestApprovedPayload(t *testing.T, endpoint *httptest.Server, operator, agent, ref string, fixture *guestHTTPServiceFixture, request GuestApprovalRequest) { + t.Helper() + command, payload := guestHTTPCase("exec", "") + command.Target = ref + request.Params = command + response := requestGuestApproval(t, endpoint.URL+"/approval", operator, request) + var execution GuestApprovalResponse + decodeErr := json.NewDecoder(response.Body).Decode(&execution) + _ = response.Body.Close() + if response.StatusCode != http.StatusOK || decodeErr != nil || execution.Grant == nil { + t.Fatalf("payload approval: status=%d err=%v", response.StatusCode, decodeErr) + } + command.ApprovalID, command.Deadline = execution.Grant.ApprovalID, execution.Grant.Deadline + final, output := invokeGuestHTTPFixture(t, endpoint.URL+"/operation", agent, command, payload) + if final.Error != "" || final.Result.Receipt == nil || final.Result.Receipt.Outcome.Status != domain.OutcomeSuccess || string(output) != "verified command output" || strings.Join(fixture.operations, ",") != "observe,exec" { + t.Fatalf("approved payload failed: %+v operations=%v", final, fixture.operations) + } +} diff --git a/internal/daemon/guest_configuration.go b/internal/daemon/guest_configuration.go index ae6b475..c4f5b02 100644 --- a/internal/daemon/guest_configuration.go +++ b/internal/daemon/guest_configuration.go @@ -81,7 +81,9 @@ func (p *guestConfigurationProvider) Current(ctx context.Context, targetRef doma return zero, err } generation := sha256.Sum256(authority) - return app.GuestConfiguration{Generation: hex.EncodeToString(generation[:]), Caller: *current, WorkspaceIdentity: record.Workspace}, nil + // Generation binds the full live principal; operation authority remains + // attenuated to the caller that was checked against that principal. + return app.GuestConfiguration{Generation: hex.EncodeToString(generation[:]), Caller: caller.Clone(), WorkspaceIdentity: record.Workspace}, nil } func (p *guestConfigurationProvider) currentActor(ctx context.Context, caller domain.ActorContext) (*domain.ActorContext, error) { diff --git a/internal/daemon/guest_configuration_authority_test.go b/internal/daemon/guest_configuration_authority_test.go new file mode 100644 index 0000000..6bf3abc --- /dev/null +++ b/internal/daemon/guest_configuration_authority_test.go @@ -0,0 +1,55 @@ +package daemon + +import ( + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/auth" + "github.com/Horcag/agent-machine-control/internal/domain" +) + +func TestGuestConfigurationPreservesRequestedAuthority(t *testing.T) { + provider, _, _, _ := newGuestConfigurationFixture(t) + server := provider.server + token, err := auth.ReadTokenFile(server.stateDir.AuthDir(), auth.TokenTypeAgentMCP) + if err != nil { + t.Fatal(err) + } + full, _, ok := server.authStore.Authenticate(token) + if !ok { + t.Fatal("fixture authentication failed") + } + ref := domain.MachineRef("local:11111111-1111-4111-8111-111111111111") + baseline, err := provider.Current(t.Context(), ref, *full) + if err != nil { + t.Fatal(err) + } + narrow := full.Clone() + delete(narrow.CallerPermissions, domain.ScopeMachineRead) + delete(narrow.EffectivePermissions, domain.ScopeMachineRead) + delete(narrow.CallerPermissions, domain.ScopeMachineWrite) + delete(narrow.EffectivePermissions, domain.ScopeMachineWrite) + config, err := provider.Current(t.Context(), ref, narrow) + if err != nil || !reflect.DeepEqual(config.Caller, narrow) || config.Generation != baseline.Generation { + t.Fatalf("requested authority expanded or generation changed: caller=%+v err=%v", config.Caller, err) + } + config.Caller.CallerPermissions[domain.ScopeOperationAdmin] = struct{}{} + config.Caller.EffectivePermissions[domain.ScopeOperationAdmin] = struct{}{} + if narrow.HasScope(domain.ScopeOperationAdmin) || full.HasScope(domain.ScopeOperationAdmin) { + t.Fatal("configuration aliases caller or authenticated authority") + } + if _, err := provider.Current(t.Context(), ref, config.Caller); !errors.Is(err, app.ErrGuestAuthority) { + t.Fatalf("requested privilege expansion accepted: %v", err) + } + if err := os.WriteFile(filepath.Join(server.stateDir.AuthDir(), auth.AgentMCPTokenFileName), []byte(strings.Repeat("a", 64)), 0600); err != nil { + t.Fatal(err) + } + if _, err := provider.Current(t.Context(), ref, narrow); !errors.Is(err, app.ErrGuestAuthority) { + t.Fatalf("rotated agent credential accepted: %v", err) + } +} diff --git a/internal/daemon/guest_protocol.go b/internal/daemon/guest_protocol.go index d70f0b3..4e235ba 100644 --- a/internal/daemon/guest_protocol.go +++ b/internal/daemon/guest_protocol.go @@ -202,7 +202,9 @@ func (s *Server) handleGuestApproval(w http.ResponseWriter, r *http.Request) { req.Params.Caller = caller grant, receipt, err := s.guestService.IssueApprovalFor(r.Context(), req.Params, time.Duration(req.ValidForMillis)*time.Millisecond, req.Beneficiary) if err != nil { - s.mapSessionError(w, err) + if !writeGuestEarlyError(w, guestFailureCategory(err), app.GuestOperationResult{}, false) { + s.mapSessionError(w, err) + } return } writeJSON(w, 200, GuestApprovalResponse{grant, receipt}) diff --git a/internal/daemon/guest_service_http_test.go b/internal/daemon/guest_service_http_test.go index dc63a6f..414c373 100644 --- a/internal/daemon/guest_service_http_test.go +++ b/internal/daemon/guest_service_http_test.go @@ -219,7 +219,13 @@ func newGuestHTTPServiceFixture(t *testing.T) (*httptest.Server, string, *guestH session := app.NewSessionService(nil, fixture, lease.NewManager(sd.LeasesDir()), audit.NewStore(sd.AuditDir()), receipt.NewStore(sd.ReceiptsDir()), approval.NewStore(sd.ApprovalsDir()), app.WithSessionMutationJournal(sessions.NewMutationJournal(sd.SessionsDir()))) svc := app.NewGuestService(session, fixture, fixture, fixture, app.NewGuestStore(filepath.Join(sd.Root(), "guest"))) server := &Server{guestService: svc, authStore: store, semaphore: make(chan struct{}, 8)} - httpServer := httptest.NewServer(server.authMiddleware(http.HandlerFunc(server.handleGuestOperation))) + httpServer := httptest.NewServer(server.authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/approval" { + server.handleGuestApproval(w, r) + return + } + server.handleGuestOperation(w, r) + }))) t.Cleanup(httpServer.Close) return httpServer, token, fixture } diff --git a/internal/sessions/clock_regression_test.go b/internal/sessions/clock_regression_test.go new file mode 100644 index 0000000..5ca2612 --- /dev/null +++ b/internal/sessions/clock_regression_test.go @@ -0,0 +1,70 @@ +package sessions_test + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/sessions" +) + +func TestManagerLifecycleSurvivesBackwardClockStep(t *testing.T) { + createdAt := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) + var wall atomic.Int64 + wall.Store(createdAt.UnixNano()) + directory := testSessionsDir(t) + transport := &deadlineGuardTransport{channel: newDeadlineGuardChannel()} + manager := sessions.NewManager(directory, transport, func() time.Time { return time.Unix(0, wall.Load()) }) + t.Cleanup(func() { _ = manager.Shutdown(context.Background()) }) + actor := deadlineGuardActor(t) + opened, err := manager.Open(t.Context(), deadlineGuardOperation(actor, "backward-clock"), 80, 24, "xterm") + if err != nil { + t.Fatal(err) + } + wall.Add(time.Minute.Nanoseconds()) + _, _, _, _, advanced, err := manager.Read(t.Context(), opened.ID, actor, 0, 100) + if err != nil || !advanced.LastActivityAt.Equal(createdAt.Add(time.Minute)) { + t.Fatalf("forward activity did not advance: %+v err=%v", advanced, err) + } + wall.Add(-time.Hour.Nanoseconds()) + if _, err := manager.Write(t.Context(), opened.ID, actor, "synthetic", "clock test", "clock-write"); err != nil { + t.Fatal(err) + } + if _, err := manager.Control(t.Context(), opened.ID, actor, domain.ControlKeyCtrlC, "clock test", "clock-control"); err != nil { + t.Fatal(err) + } + _, _, _, _, observed, err := manager.Read(t.Context(), opened.ID, actor, 0, 100) + if err != nil || observed.LastActivityAt.Before(advanced.LastActivityAt) { + t.Fatalf("activity moved before creation: %+v err=%v", observed, err) + } + wall.Store(createdAt.Add(2 * time.Minute).UnixNano()) + _, _, _, _, forward, err := manager.Read(t.Context(), opened.ID, actor, 0, 100) + if err != nil || !forward.LastActivityAt.Equal(createdAt.Add(2*time.Minute)) { + t.Fatalf("clock recovery did not advance: %+v err=%v", forward, err) + } + wall.Store(createdAt.UnixNano()) + closed, err := manager.Close(t.Context(), opened.ID, actor, "clock test cleanup") + if err != nil || closed.Validate() != nil || closed.ClosedAt.Before(forward.LastActivityAt) { + t.Fatalf("clock step corrupted closure: %+v err=%v", closed, err) + } + loaded, err := sessions.NewManager(directory, nil, nil).Get(t.Context(), opened.ID, actor) + if err != nil || loaded.State != domain.SessionStateClosed { + t.Fatalf("clock step corrupted durable state: %+v err=%v", loaded, err) + } +} + +func TestReconcileCrashedSessionSurvivesBackwardClockStep(t *testing.T) { + directory := testSessionsDir(t) + obs := testSessionObservation("sess-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4", domain.SessionStateActive) + obs.LastActivityAt = obs.CreatedAt.Add(time.Minute) + writeSessionObservation(t, directory, obs) + if _, err := sessions.ReconcileCrashedSessions(t.Context(), directory, obs.CreatedAt.Add(-time.Hour)); err != nil { + t.Fatal(err) + } + loaded, err := sessions.NewManager(directory, nil, nil).Get(t.Context(), obs.ID, testSessionActor(t, obs.OwnerActor)) + if err != nil || loaded.Validate() != nil || loaded.ClosedAt.Before(obs.LastActivityAt) { + t.Fatalf("restart clock step corrupted durable state: %+v err=%v", loaded, err) + } +} diff --git a/internal/sessions/manager.go b/internal/sessions/manager.go index 90dbd66..a0c54c9 100644 --- a/internal/sessions/manager.go +++ b/internal/sessions/manager.go @@ -36,6 +36,8 @@ type Manager struct { sessionsDir string transport guestssh.Transport clock func() time.Time + clockMu sync.Mutex + lastNow time.Time generateSessionID func() (domain.SessionID, error) publishOpenHook func() error syncSessionDir func(string) error @@ -100,7 +102,16 @@ func NewManager(sessionsDir string, transport guestssh.Transport, clock func() t } func (m *Manager) now() time.Time { - return m.clock().UTC() + now := m.clock().UTC() + m.clockMu.Lock() + defer m.clockMu.Unlock() + // Lifecycle observations must remain causal when the wall clock steps back. + // Authorization and execution deadlines use their own clocks and contexts. + if now.Before(m.lastNow) { + return m.lastNow + } + m.lastNow = now + return now } // MutationJournal returns the durable journal owned by this session manager. diff --git a/internal/sessions/reconcile.go b/internal/sessions/reconcile.go index 91542a8..49b58f9 100644 --- a/internal/sessions/reconcile.go +++ b/internal/sessions/reconcile.go @@ -34,6 +34,9 @@ func reconcileSessionFileWithSync( } obs.State = domain.SessionStateCrashed + if now.Before(obs.LastActivityAt) { + now = obs.LastActivityAt + } obs.ClosedAt = &now obs.ErrorMessage = "daemon_crash_recovered"