From 67e0c42c65d63ffa1cf9d10e2a5c16e881f31ad9 Mon Sep 17 00:00:00 2001 From: Lebedev Nikita Date: Wed, 21 Oct 2026 05:18:59 +0400 Subject: [PATCH 1/4] fix(lab): persist VM authority and report guest failures --- docs/guest-desktop.md | 26 +++ docs/guest-operations.md | 15 ++ docs/ssh-sessions.md | 2 +- docs/threat-model.md | 9 + internal/app/console_lab.go | 66 +++++-- internal/app/console_lab_active.go | 41 ++-- internal/app/console_lab_active_test.go | 6 +- internal/app/console_lab_coordination.go | 101 ++++++++++ internal/app/console_lab_guest_test.go | 80 ++++++++ internal/app/console_lab_lifecycle.go | 4 +- internal/app/console_lab_mutation.go | 37 ++-- internal/app/console_lab_persistent_test.go | 129 +++++++++++++ internal/app/console_lab_store.go | 15 +- internal/app/console_lab_types.go | 4 + .../app/operation_approval_persistence.go | 3 +- internal/app/recovery.go | 1 + internal/app/recovery_admission.go | 28 +++ internal/app/recovery_mutation.go | 37 +--- internal/app/session.go | 1 + internal/app/session_approval_resolution.go | 3 +- internal/app/session_coordination.go | 34 +++- internal/cli/app.go | 8 +- internal/cli/checkpoint_cmd.go | 51 ++--- internal/cli/checkpoint_restore_cmd.go | 40 ++-- internal/cli/console_cmd.go | 2 +- internal/cli/desktop_cmd.go | 17 +- internal/cli/desktop_cmd_test.go | 6 +- internal/cli/guest_cmd.go | 9 + internal/cli/guest_cmd_test.go | 24 ++- internal/cli/guest_validation_test.go | 63 ++++++ internal/client/guest.go | 13 +- internal/client/guest_errors.go | 61 ++++++ internal/client/guest_errors_test.go | 75 ++++++++ internal/client/guest_test.go | 3 +- internal/daemon/guest_errors.go | 86 +++++++++ internal/daemon/guest_errors_test.go | 182 ++++++++++++++++++ internal/daemon/guest_protocol.go | 40 +++- internal/daemon/guest_service_http_test.go | 50 +++-- internal/daemon/handlers_desktop_test.go | 4 +- internal/daemon/server.go | 11 +- internal/domain/guest_operation.go | 22 ++- internal/mcpadapter/errors.go | 89 +++++---- internal/mcpadapter/guest.go | 75 +++++++- internal/mcpadapter/guest_test.go | 6 +- internal/mcpadapter/guest_validation_test.go | 109 +++++++++++ .../mcpadapter/testdata/schemas/tools.json | 124 +++++------- 46 files changed, 1509 insertions(+), 303 deletions(-) create mode 100644 internal/app/console_lab_coordination.go create mode 100644 internal/app/console_lab_guest_test.go create mode 100644 internal/app/console_lab_persistent_test.go create mode 100644 internal/cli/guest_validation_test.go create mode 100644 internal/client/guest_errors.go create mode 100644 internal/client/guest_errors_test.go create mode 100644 internal/daemon/guest_errors.go create mode 100644 internal/daemon/guest_errors_test.go create mode 100644 internal/mcpadapter/guest_validation_test.go diff --git a/docs/guest-desktop.md b/docs/guest-desktop.md index c3020ea..5a5d87c 100644 --- a/docs/guest-desktop.md +++ b/docs/guest-desktop.md @@ -38,6 +38,32 @@ Issuing a grant does not install the guest driver. Provision it using `desktop_a A driver update must remove the old verified installation with its matching build before provisioning the new build. Foreign or modified installations are refused. +## Persistent disposable VM authority + +For an owner-controlled disposable test VM, the operator can enable persistent VM authority: + +```sh +amc desktop enable --target lab-vm --for-mcp --persistent-vm \ + --acknowledge-external-effects \ + --reason 'authorize autonomous work on the disposable test VM' \ + --idempotency-key persistent-lab-example +``` + +This grant has no time-based expiry. It survives daemon restarts and authorizes guest file and +script operations, terminal sessions, console and desktop actions, VM start/stop, and checkpoint +creation/restoration on the exact enrolled VM. A separate grant without `--for-mcp` enables the +operator CLI. Agents do not need to request one-use approvals for those operations. The service +derives their exact approvals from the stored operator grant and preserves normal audit, receipts, +actor scopes, deadlines, and idempotency checks. Actual safety classification remains unchanged; +enabling this mode does not declare external effects contained or invent a rollback checkpoint. + +Use `amc desktop status` to discover the current grant for the caller and selected target, or +provide `--lab-grant-id` to inspect a specific grant. The existing `desktop disable` command +revokes persistent authority. Clearing or replacing the enrollment also invalidates it, including +when the same VM is enrolled again. Other VMs, host administration, enrollment changes, credential +configuration, and approval issuance receive no authority from this mode. Without `--persistent-vm`, +the existing bounded console/desktop grant behavior is unchanged. + ## Agent interaction loop 1. Call `desktop_observe`. It returns a PNG content block, frame identity, native and diff --git a/docs/guest-operations.md b/docs/guest-operations.md index dce8bf8..bed1a6a 100644 --- a/docs/guest-operations.md +++ b/docs/guest-operations.md @@ -21,6 +21,10 @@ Each operation carries a reason, idempotency key and exact deadline. On protecte operator issues a one-use approval for the exact operation and beneficiary. Issuance supports the current operator or the canonical local MCP actor; MCP cannot issue approvals. +An operator may instead enable [persistent disposable VM authority](guest-desktop.md#persistent-disposable-vm-authority) +once for the enrolled test VM and beneficiary. The daemon then supplies exact operation approvals +automatically until that authority is revoked or the enrollment changes. + ## Operation contracts | Operation | Result and boundary | @@ -31,6 +35,13 @@ current operator or the canonical local MCP actor; MCP cannot issue approvals. | `exec` | Runs a bounded UTF-8 script in the persistent runspace, with bounded output and a final receipt. | | `remove-owned` | Removes up to 128 referenced original files in one request; reports accepted deletion and observed absence separately. | +MCP tools advertise operation-specific input schemas. `prepare` requires `max_output: 0` and no +source, destination, or artifact IDs. `put` also requires zero output and no artifact IDs or +destination. `get` requires one artifact ID, a new local destination, and positive output limit. +`exec` requires a local script, a new destination, and a positive output limit up to 16 MiB, with +no artifact IDs. `remove-owned` requires one or more artifact IDs and zero output, without local +source or destination paths. Invalid shapes are rejected before dispatch with an actionable error. + Transfers use bounded binary buffers. File content is not encoded into terminal commands, clipboard messages or control JSON. Script and command output limits are 16 MiB each. Download and command output are quarantined in private host files and released only after integrity checks and a durable @@ -48,6 +59,10 @@ result closes the affected worker and preserves durable uncertainty. Retrying an returns receipt metadata; it does not repeat effects or replay output bytes. Download publication requires verified bytes and the final result, and never replaces an existing local destination. +Known validation and authorization failures retain their typed categories across daemon, CLI and +MCP. Arbitrary provider messages are not exposed. A known rejection is distinct from an uncertain +transport outcome; incomplete responses still require inspecting the receipt before another action. + The low-level Go `Client.GuestOperation` method writes provisional output to its supplied sink before validating the final trailer. Callers must keep that sink unpublished and discard its contents on any error. CLI and MCP use `GuestOperationToFile`, which quarantines output and diff --git a/docs/ssh-sessions.md b/docs/ssh-sessions.md index cfa799a..c671c94 100644 --- a/docs/ssh-sessions.md +++ b/docs/ssh-sessions.md @@ -96,7 +96,7 @@ All session mutations (`session.open`, `session.write`, `session.control`, `sess 1. **Dynamic Safety Resolution**: - The safety resolver inspects the target machine's server-owned `config.json` (`external_effects_contained`, `rollback_checkpoint_id`) and queries the Hyper-V backend (`ListCheckpoints`). - If external effects are contained and the rollback checkpoint exists and is verified in Hyper-V, the operation is classified as `ClassReversibleMutation` with the checkpoint GUID as `rollbackRef`. - - If external effects are not contained or the rollback checkpoint is missing/invalid, the operation is classified as `ClassDestructivePrivileged`, requiring an explicit, unconsumed operator approval record. + - If external effects are not contained or the rollback checkpoint is missing/invalid, the operation is classified as `ClassDestructivePrivileged`, requiring an unconsumed operator approval record. An operator-enabled [persistent VM grant](guest-desktop.md#persistent-disposable-vm-authority) supplies exact approvals automatically for its enrolled VM and beneficiary, without another human prompt. 2. **Host Mutation Lease**: - Every session mutation acquires a host lease before reading containment configuration or querying the configured checkpoint. The same lease remains held through guest effect and diff --git a/docs/threat-model.md b/docs/threat-model.md index c038a93..0dda7dc 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -198,6 +198,15 @@ logical principal identity of the caller: untrusted agent from implicitly inheriting the operator's OS-level rights simply by communicating through a local adapter. +An operator can explicitly enable persistent authority for an enrolled disposable VM and a +specific beneficiary. This uses the protected lab-grant store and derives exact server-owned +operation approvals; it does not change the caller identity or declare external effects contained. +The opt-in `persistent-vm` mode covers guest operations, terminal sessions, VM console/desktop, +start/stop and checkpoint create/restore. It has no time-based expiry, is revocable, and is bound to +the current enrollment epoch. It grants no host administration, enrollment/configuration changes +or approval-issuance scope. Default and legacy bounded-grant behavior remain unchanged. See +[persistent disposable VM authority](guest-desktop.md#persistent-disposable-vm-authority). + ### Authenticated Caller versus Effective Actor - **Authenticated Caller**: The direct transport entity communicating with `amcd` (e.g., the diff --git a/internal/app/console_lab.go b/internal/app/console_lab.go index fd9ec25..e08c208 100644 --- a/internal/app/console_lab.go +++ b/internal/app/console_lab.go @@ -30,30 +30,25 @@ func (s *ConsoleService) IssueLabGrant(ctx context.Context, actor domain.ActorCo if err != nil { return grant, result, err } - if err := s.requireLabSafety(ctx, resolution, req.AcknowledgeExternalEffects); err != nil { + if err := s.requireGrantSafety(ctx, resolution, req.Mode, req.AcknowledgeExternalEffects); err != nil { return grant, result, err } existing, err := s.loadLabGrant(ctx, id) if err != nil && !errors.Is(err, os.ErrNotExist) { return grant, result, err } - now := s.recovery.now() - grant = ConsoleLabGrant{AcknowledgeExternalEffects: req.AcknowledgeExternalEffects, SchemaVersion: 1, GrantID: id, Target: domain.MachineRef(resolution.Locator.String()), EnrollmentIdentity: identity, - Issuer: actor.EffectiveActor, Beneficiary: beneficiary, Reason: req.Reason, IdempotencyKey: req.IdempotencyKey, - IssuedAt: now, ExpiresAt: now.Add(time.Duration(req.ValidForMillis) * time.Millisecond)} - if err == nil { - grant.IssuedAt, grant.ExpiresAt = existing.IssuedAt, existing.ExpiresAt - if grant != existing || existing.ExpiresAt.Sub(existing.IssuedAt).Milliseconds() != req.ValidForMillis { - return ConsoleLabGrant{}, result, receipt.ErrIdempotencyCollision - } - if err := s.validateLabBinding(ctx, existing); err != nil { - return ConsoleLabGrant{}, result, err - } + grant, err = s.prepareLabGrant(ctx, actor, req, beneficiary, resolution, identity, id, existing, err == nil) + if err != nil { + return ConsoleLabGrant{}, result, err } - op := labGrantOperation("console.lab.grant.issue", actor, grant, req.Reason, req.IdempotencyKey, grant.ExpiresAt) + issuanceDeadline := grant.ExpiresAt + if grant.Mode == ConsoleLabModePersistentVM { + issuanceDeadline = grant.IssuedAt.Add(5 * time.Minute) + } + op := labGrantOperation("console.lab.grant.issue", actor, grant, req.Reason, req.IdempotencyKey, issuanceDeadline) op.Parameters = map[string]any{"grant_id": id, "beneficiary": string(beneficiary), "enrollment_identity": identity, "expires_at": grant.ExpiresAt.UTC().Format(time.RFC3339Nano), "acknowledge_external_effects": grant.AcknowledgeExternalEffects} result, resultErr = s.persistLabAuthority(ctx, op, grant.IssuedAt, id, func() error { - if err == nil { + if existing.GrantID != "" { return nil } return s.writeLabDocument(ctx, id, ".json", grant) @@ -91,7 +86,7 @@ func labGrantID(actor domain.ActorID, key string) string { } func (s *ConsoleService) labIdentity(ctx context.Context, reference string) (TargetResolution, string, error) { - if s.labEnrollment == nil || s.labSafety == nil { + if s.labEnrollment == nil { return TargetResolution{}, "", ErrInvalidConsoleLabGrant } resolution, err := s.target.ResolveTarget(ctx, reference) @@ -137,7 +132,7 @@ func (s *ConsoleService) resolveLabBinding(ctx context.Context, grant ConsoleLab func (s *ConsoleService) resolveLabBindingWithResolution(ctx context.Context, grant ConsoleLabGrant, observed *TargetResolution) (TargetResolution, error) { now := s.recovery.now() - if now.Before(grant.IssuedAt) || !now.Before(grant.ExpiresAt) { + if now.Before(grant.IssuedAt) || (grant.Mode == "" && !now.Before(grant.ExpiresAt)) { return TargetResolution{}, ErrInvalidConsoleLabGrant } revoked, err := s.labRevoked(ctx, grant.GrantID) @@ -150,7 +145,7 @@ func (s *ConsoleService) resolveLabBindingWithResolution(ctx context.Context, gr resolution, identity, err = s.labIdentity(ctx, string(grant.Target)) } else { resolution = *observed - if s.labEnrollment == nil || s.labSafety == nil || resolution.Validate() != nil { + if s.labEnrollment == nil || resolution.Validate() != nil { return TargetResolution{}, ErrInvalidConsoleLabGrant } identity, err = s.labEnrollment(ctx, domain.MachineRef(resolution.Locator.String())) @@ -161,7 +156,7 @@ func (s *ConsoleService) resolveLabBindingWithResolution(ctx context.Context, gr if err != nil || resolution.Locator.String() != string(grant.Target) || identity != grant.EnrollmentIdentity { return TargetResolution{}, ErrInvalidConsoleLabGrant } - return resolution, s.requireLabSafety(ctx, resolution, grant.AcknowledgeExternalEffects) + return resolution, s.requireGrantSafety(ctx, resolution, grant.Mode, grant.AcknowledgeExternalEffects) } func labGrantOperation(kind domain.OperationKind, actor domain.ActorContext, grant ConsoleLabGrant, reason, key string, deadline time.Time) domain.Operation { @@ -198,8 +193,39 @@ func validateLabIssueRequest(actor domain.ActorContext, req ConsoleLabGrantIssue if err := labOperator(actor); err != nil { return "", err } - if domain.ValidateReason(req.Reason) != nil || domain.ValidateIdempotencyKey(req.IdempotencyKey) != nil || req.ValidForMillis < 1000 || req.ValidForMillis > MaxConsoleLabGrantValidity.Milliseconds() { + if domain.ValidateReason(req.Reason) != nil || domain.ValidateIdempotencyKey(req.IdempotencyKey) != nil || (req.Mode == "" && (req.ValidForMillis < 1000 || req.ValidForMillis > MaxConsoleLabGrantValidity.Milliseconds())) || (req.Mode != "" && (req.Mode != ConsoleLabModePersistentVM || !req.AcknowledgeExternalEffects)) { return "", ErrInvalidConsoleLabGrant } return labBeneficiary(actor, req.Beneficiary) } + +func (s *ConsoleService) requireGrantSafety(ctx context.Context, resolution TargetResolution, mode string, acknowledge bool) error { + if mode == ConsoleLabModePersistentVM { + return nil + } + if s.labSafety == nil { + return ErrInvalidConsoleLabGrant + } + return s.requireLabSafety(ctx, resolution, acknowledge) +} + +func (s *ConsoleService) prepareLabGrant(ctx context.Context, actor domain.ActorContext, req ConsoleLabGrantIssueRequest, beneficiary domain.ActorID, resolution TargetResolution, identity, id string, existing ConsoleLabGrant, exists bool) (ConsoleLabGrant, error) { + now := s.recovery.now() + grant := ConsoleLabGrant{Mode: req.Mode, AcknowledgeExternalEffects: req.AcknowledgeExternalEffects, SchemaVersion: 1, GrantID: id, Target: domain.MachineRef(resolution.Locator.String()), EnrollmentIdentity: identity, + Issuer: actor.EffectiveActor, Beneficiary: beneficiary, Reason: req.Reason, IdempotencyKey: req.IdempotencyKey, + IssuedAt: now, ExpiresAt: now.Add(time.Duration(req.ValidForMillis) * time.Millisecond)} + if req.Mode == ConsoleLabModePersistentVM { + grant.ExpiresAt = time.Time{} + } + if exists { + grant.IssuedAt, grant.ExpiresAt = existing.IssuedAt, existing.ExpiresAt + if grant != existing || (req.Mode == "" && existing.ExpiresAt.Sub(existing.IssuedAt).Milliseconds() != req.ValidForMillis) { + return ConsoleLabGrant{}, receipt.ErrIdempotencyCollision + } + if err := s.validateLabBinding(ctx, existing); err != nil { + return ConsoleLabGrant{}, err + } + } + + return grant, nil +} diff --git a/internal/app/console_lab_active.go b/internal/app/console_lab_active.go index 7f22430..7f6be05 100644 --- a/internal/app/console_lab_active.go +++ b/internal/app/console_lab_active.go @@ -13,11 +13,15 @@ import ( // ActiveLabGrant discovers only the caller's currently usable authority for the enrolled VM. func (s *ConsoleService) ActiveLabGrant(ctx context.Context, actor domain.ActorContext, reference string) (ConsoleLabGrantStatus, error) { + return s.activeLabGrant(ctx, actor, reference, false) +} + +func (s *ConsoleService) activeLabGrant(ctx context.Context, actor domain.ActorContext, reference string, persistentOnly bool) (ConsoleLabGrantStatus, error) { disabled := ConsoleLabGrantStatus{State: "disabled"} if actor.Validate() != nil || actor.IsDelegated() { return disabled, ErrInvalidConsoleLabGrant } - if err := s.validateDependencies(); err != nil { + if err := s.recovery.validateDependencies(); err != nil { return disabled, err } resolution, err := s.target.ResolveTarget(ctx, reference) @@ -43,14 +47,7 @@ func (s *ConsoleService) ActiveLabGrant(ctx context.Context, actor domain.ActorC return disabled, err } defer file.Close() - entries, err := file.ReadDir(129) - if err != nil && !errors.Is(err, io.EOF) { - return disabled, err - } - if len(entries) > 128 { - return disabled, ErrInvalidConsoleLabGrant - } - selected, err := s.selectActiveLabGrant(ctx, actor, domain.MachineRef(resolution.Locator.String()), entries) + selected, err := s.scanActiveLabGrants(ctx, file, actor, domain.MachineRef(resolution.Locator.String()), persistentOnly) if err != nil { return disabled, err } @@ -60,7 +57,7 @@ func (s *ConsoleService) ActiveLabGrant(ctx context.Context, actor domain.ActorC return ConsoleLabGrantStatus{Grant: selected, State: "active"}, nil } -func (s *ConsoleService) selectActiveLabGrant(ctx context.Context, actor domain.ActorContext, canonical domain.MachineRef, entries []os.DirEntry) (ConsoleLabGrant, error) { +func (s *ConsoleService) selectActiveLabGrant(ctx context.Context, actor domain.ActorContext, canonical domain.MachineRef, entries []os.DirEntry, persistentOnly bool) (ConsoleLabGrant, error) { var selected ConsoleLabGrant for _, entry := range entries { if err := ctx.Err(); err != nil { @@ -71,7 +68,7 @@ func (s *ConsoleService) selectActiveLabGrant(ctx context.Context, actor domain. continue } grant, err := s.loadLabGrant(ctx, id) - if err != nil || grant.Beneficiary != actor.EffectiveActor || grant.Target != canonical || s.requireActiveLabGrant(ctx, grant) != nil { + if err != nil || (persistentOnly && grant.Mode != ConsoleLabModePersistentVM) || grant.Beneficiary != actor.EffectiveActor || grant.Target != canonical || s.requireActiveLabGrant(ctx, grant) != nil { continue } if selected.GrantID == "" || grant.IssuedAt.After(selected.IssuedAt) || (grant.IssuedAt.Equal(selected.IssuedAt) && grant.GrantID > selected.GrantID) { @@ -80,3 +77,25 @@ func (s *ConsoleService) selectActiveLabGrant(ctx context.Context, actor domain. } return selected, nil } + +func (s *ConsoleService) scanActiveLabGrants(ctx context.Context, file *os.File, actor domain.ActorContext, canonical domain.MachineRef, persistentOnly bool) (ConsoleLabGrant, error) { + var selected ConsoleLabGrant + for { + entries, readErr := file.ReadDir(128) + if readErr != nil && !errors.Is(readErr, io.EOF) { + return ConsoleLabGrant{}, readErr + } + candidate, err := s.selectActiveLabGrant(ctx, actor, canonical, entries, persistentOnly) + if err != nil { + return ConsoleLabGrant{}, err + } + if candidate.GrantID != "" && (selected.GrantID == "" || candidate.IssuedAt.After(selected.IssuedAt) || (candidate.IssuedAt.Equal(selected.IssuedAt) && candidate.GrantID > selected.GrantID)) { + selected = candidate + } + if errors.Is(readErr, io.EOF) { + break + } + } + + return selected, nil +} diff --git a/internal/app/console_lab_active_test.go b/internal/app/console_lab_active_test.go index 06f3f38..ce4476b 100644 --- a/internal/app/console_lab_active_test.go +++ b/internal/app/console_lab_active_test.go @@ -43,7 +43,7 @@ func TestConsoleLabActiveDiscoverySelectsOwnNewestAuthority(t *testing.T) { } } -func TestConsoleLabActiveDiscoveryRejectsStaleAndOversizedDirectory(t *testing.T) { +func TestConsoleLabActiveDiscoveryRejectsStaleAndStreamsHistoricalDirectory(t *testing.T) { f := newConsoleFixture(t) _, epoch := configureLab(f) issueLab(t, f) @@ -62,7 +62,7 @@ func TestConsoleLabActiveDiscoveryRejectsStaleAndOversizedDirectory(t *testing.T t.Fatal(err) } } - if _, err := f.service.ActiveLabGrant(context.Background(), labActor(t), "default"); err == nil { - t.Fatal("unbounded directory discovery accepted") + if _, err := f.service.ActiveLabGrant(context.Background(), labActor(t), "default"); err != nil { + t.Fatalf("historical directory blocked discovery: %v", err) } } diff --git a/internal/app/console_lab_coordination.go b/internal/app/console_lab_coordination.go new file mode 100644 index 0000000..dc9bd17 --- /dev/null +++ b/internal/app/console_lab_coordination.go @@ -0,0 +1,101 @@ +package app + +import ( + "context" + "errors" + + "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/target" +) + +// WithSessionLabAuthority installs the shared enrolled-VM authority owner. +func WithSessionLabAuthority(authority *ConsoleService) SessionOption { + return func(s *SessionService) { s.labAuthority = authority } +} + +// WithRecoveryLabAuthority installs the same authority for direct and daemon mutations. +func WithRecoveryLabAuthority(authority *ConsoleService) Option { + return func(s *RecoveryService) { s.labAuthority = authority } +} + +func persistentLabOperation(kind domain.OperationKind) bool { + switch kind { + case "session.open", "session.write", "session.control", "session.close", "console.input", "desktop.action", "machine.start", "machine.stop", "checkpoint.create", "checkpoint.restore": + return true + default: + return domain.IsGuestOperation(kind) + } +} + +// Caller approvals are resolved before this method; only absent approval can derive authority. +func (s *ConsoleService) admitPersistentLab(ctx context.Context, op domain.Operation) (*ConsoleLabGrant, func() error, error) { + noop := func() error { return nil } + if s == nil || !persistentLabOperation(op.Kind) || op.Actor.IsDelegated() { + return nil, noop, nil + } + status, err := s.activeLabGrant(ctx, op.Actor, string(op.Target), true) + if errors.Is(err, target.ErrNoDefault) || errors.Is(err, target.ErrDifferentTarget) { + return nil, noop, nil + } + if err != nil { + return nil, noop, err + } + if status.State != "active" || status.Grant.Mode != ConsoleLabModePersistentVM { + return nil, noop, nil + } + grant := status.Grant + release, err := s.labLock(ctx, grant.GrantID) + if err != nil { + return nil, noop, err + } + if err := s.requireActiveLabGrant(ctx, grant); err != nil { + return nil, noop, errors.Join(err, release()) + } + if op.Target != grant.Target || !op.Deadline.After(s.recovery.now()) { + return nil, noop, errors.Join(ErrInvalidConsoleLabGrant, release()) + } + return &grant, release, nil +} + +func (s *ConsoleService) derivePersistentLab(ctx context.Context, op domain.Operation) (*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) + if err != nil { + return nil, nil, func() error { return nil }, errors.Join(err, release()) + } + return approval, grant, release, nil +} + +func (s *ConsoleService) withPersistentLabEffect(ctx context.Context, grant *ConsoleLabGrant, execute func(context.Context) error) error { + if grant == nil { + return execute(ctx) + } + return s.target.WithEnrollmentFence(ctx, func() error { + if err := s.requireActiveLabGrant(ctx, *grant); err != nil { + return err + } + return execute(ctx) + }) +} + +func (s *RecoveryService) coordinatePersistentRecovery(ctx context.Context, op domain.Operation, req MutationRequest, execute func(context.Context) error) (MutationRequest, func(context.Context) error, func() error, error) { + release := func() error { return nil } + if req.Approval != nil || req.ApprovalID != "" || req.ApprovalError != nil { + return req, execute, release, nil + } + derived, grant, release, err := s.labAuthority.derivePersistentLab(ctx, op) + if err != nil { + return req, execute, release, err + } + if derived == nil { + return req, execute, release, nil + } + req.Approval, req.ApprovalID = derived, string(derived.ID) + fenced := func(effectCtx context.Context) error { + return s.labAuthority.withPersistentLabEffect(effectCtx, grant, execute) + } + return req, fenced, release, nil +} diff --git a/internal/app/console_lab_guest_test.go b/internal/app/console_lab_guest_test.go new file mode 100644 index 0000000..4737751 --- /dev/null +++ b/internal/app/console_lab_guest_test.go @@ -0,0 +1,80 @@ +package app + +import ( + "context" + "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/target" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestPersistentVMGrantCoordinatesUncontainedGuestAndSurvivesRestart(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) + grant, _, err := authority.IssueLabGrant(t.Context(), operator, ConsoleLabGrantIssueRequest{Mode: ConsoleLabModePersistentVM, Target: "default", Reason: "operate disposable VM", IdempotencyKey: "persistent-guest", Beneficiary: "agent:mcp-local", AcknowledgeExternalEffects: true}) + if err != nil { + t.Fatal(err) + } + // A new service must discover protected on-disk authority without a console backend. + coordinator.labAuthority = NewConsoleService(nil, authority.recovery, authority.target, authority.framesDir, WithConsoleLabEnrollmentIdentity(authority.labEnrollment)) + if result, err := h.service.Execute(t.Context(), h.params("prepare", "persistent-prepare"), nil, nil); err != nil || result.Receipt == nil || h.transport.executed != 1 { + t.Fatalf("persistent guest: %+v %v effects=%d", result, err, h.transport.executed) + } + if _, err := authority.RevokeLabGrant(t.Context(), operator, ConsoleLabGrantRevokeRequest{GrantID: grant.GrantID, Reason: "end guest lab", IdempotencyKey: "revoke-guest", Deadline: time.Now().Add(time.Minute).Format(time.RFC3339Nano)}); err != nil { + t.Fatal(err) + } + if _, err := h.service.Execute(t.Context(), h.params("prepare", "revoked-prepare"), nil, nil); err == nil || h.transport.executed != 1 { + t.Fatalf("revoked guest dispatched: %v effects=%d", err, h.transport.executed) + } +} + +func persistentGuestAuthority(t *testing.T, h *guestHarness) (*ConsoleService, domain.ActorContext) { + t.Helper() + coordinator := h.service.session + resolution := h.service.resolver.(guestTestResolver).resolution + now := time.Now().UTC() + inventory, err := NewTrustedInventory(nil) + if err != nil { + t.Fatal(err) + } + observed := domain.MachineObservation{HostID: domain.LocalHostID, Locator: resolution.Locator, ID: resolution.ProviderVMID, Name: "synthetic-lab", State: domain.MachineStateOff, RawState: "Off", Generation: 2, Version: "10.0", MemoryAssignedBytes: 1024, Capabilities: domain.ReadOnlyMachineCapabilities(), ObservedAt: now, ObservationType: domain.ObservationObserved} + if err := inventory.ApplySnapshot(HostSnapshot{HostID: domain.LocalHostID, Health: HostHealthObserved, Machines: []domain.MachineObservation{observed}}); err != nil { + t.Fatal(err) + } + state := t.TempDir() + if err := os.Mkdir(filepath.Join(state, "targets"), 0700); err != nil { + t.Fatal(err) + } + store, err := target.NewStore(filepath.Join(state, "targets")) + if err != nil { + t.Fatal(err) + } + enrolled, err := target.NewDefault(resolution.Locator, nil) + if err != nil { + t.Fatal(err) + } + if _, err := store.Save(t.Context(), enrolled); err != nil { + t.Fatal(err) + } + targets, err := NewTargetService(inventory, store) + if err != nil { + t.Fatal(err) + } + recovery := &RecoveryService{backend: &guestApprovalBackend{}, leaseManager: coordinator.leaseMgr, auditStore: coordinator.auditStore, receiptStore: coordinator.receiptStore, approvalStore: coordinator.approvalStore} + epoch := strings.Repeat("a", 64) + options := []ConsoleOption{WithConsoleLabEnrollmentIdentity(func(_ context.Context, _ domain.MachineRef) (string, error) { return epoch, nil })} + authority := NewConsoleService(nil, recovery, targets, filepath.Join(state, "console-frames"), options...) + scopes := domain.NewScopeSet(domain.ScopeOperationAdmin) + operator, err := domain.NewActorContext("operator:synthetic", "operator:synthetic", scopes, scopes) + if err != nil { + t.Fatal(err) + } + + return authority, operator +} diff --git a/internal/app/console_lab_lifecycle.go b/internal/app/console_lab_lifecycle.go index 26961c4..5c75c46 100644 --- a/internal/app/console_lab_lifecycle.go +++ b/internal/app/console_lab_lifecycle.go @@ -14,7 +14,7 @@ func (s *ConsoleService) LabGrantStatus(ctx context.Context, actor domain.ActorC if actor.Validate() != nil || actor.IsDelegated() { return ConsoleLabGrantStatus{}, ErrInvalidConsoleLabGrant } - if err := s.validateDependencies(); err != nil { + if err := s.recovery.validateDependencies(); err != nil { return ConsoleLabGrantStatus{}, err } grant, err := s.loadLabGrant(ctx, id) @@ -32,7 +32,7 @@ func (s *ConsoleService) LabGrantStatus(ctx context.Context, actor domain.ActorC switch { case revoked: status.State = "revoked" - case !s.recovery.now().Before(grant.ExpiresAt): + case grant.Mode == "" && !s.recovery.now().Before(grant.ExpiresAt): status.State = "expired" case s.requireActiveLabGrant(ctx, grant) != nil: status.State = "stale" diff --git a/internal/app/console_lab_mutation.go b/internal/app/console_lab_mutation.go index 0c9be17..f0c207e 100644 --- a/internal/app/console_lab_mutation.go +++ b/internal/app/console_lab_mutation.go @@ -32,23 +32,10 @@ func (s *ConsoleService) executeLabMutation(ctx context.Context, actor domain.Ac return result, err } defer func() { resultErr = errors.Join(resultErr, release()) }() - grant, err := s.loadLabGrant(ctx, id) - if err != nil || grant.Beneficiary != actor.EffectiveActor || op.Target != grant.Target { - return result, ErrInvalidConsoleLabGrant - } - binding, err := s.resolveLabBindingWithResolution(ctx, grant, resolution) - if err == nil { - err = s.labActivation(ctx, grant.GrantID) - } + grant, err := s.admitLabMutation(ctx, actor, id, op, providerID, resolution) if err != nil { return result, err } - if !op.Deadline.After(s.recovery.now()) || op.Deadline.After(grant.ExpiresAt) { - return result, ErrInvalidConsoleLabGrant - } - if binding.ProviderVMID != providerID { - return result, ErrInvalidConsoleLabGrant - } issued, err := s.deriveLabApproval(ctx, grant, op) if err != nil { return result, err @@ -129,3 +116,25 @@ func labMutationIdentityMatches(actor domain.ActorContext, op domain.Operation, op.Target == domain.MachineRef(req.TargetID) && op.Reason == req.Reason && op.IdempotencyKey == req.IdempotencyKey && op.Deadline.Equal(req.Deadline) && req.Actor.AuthenticatedCaller == actor.AuthenticatedCaller && req.Actor.EffectiveActor == actor.EffectiveActor } + +func (s *ConsoleService) admitLabMutation(ctx context.Context, actor domain.ActorContext, id string, op domain.Operation, providerID string, resolution *TargetResolution) (ConsoleLabGrant, error) { + grant, err := s.loadLabGrant(ctx, id) + if err != nil || grant.Beneficiary != actor.EffectiveActor || op.Target != grant.Target { + return ConsoleLabGrant{}, ErrInvalidConsoleLabGrant + } + binding, err := s.resolveLabBindingWithResolution(ctx, grant, resolution) + if err == nil { + err = s.labActivation(ctx, grant.GrantID) + } + if err != nil { + return ConsoleLabGrant{}, err + } + if !op.Deadline.After(s.recovery.now()) || (grant.Mode == "" && op.Deadline.After(grant.ExpiresAt)) { + return ConsoleLabGrant{}, ErrInvalidConsoleLabGrant + } + if binding.ProviderVMID != providerID { + return ConsoleLabGrant{}, ErrInvalidConsoleLabGrant + } + + return grant, nil +} diff --git a/internal/app/console_lab_persistent_test.go b/internal/app/console_lab_persistent_test.go new file mode 100644 index 0000000..1063e9f --- /dev/null +++ b/internal/app/console_lab_persistent_test.go @@ -0,0 +1,129 @@ +package app_test + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "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/domain" + "github.com/Horcag/agent-machine-control/internal/lease" + "github.com/Horcag/agent-machine-control/internal/receipt" + "github.com/Horcag/agent-machine-control/internal/sessions" + "path/filepath" + "sync/atomic" + "testing" + "time" +) + +func TestPersistentVMGrantSurvivesElapsedTimeAndSafetyChanges(t *testing.T) { + f := newConsoleFixture(t) + safety, epoch := configureLab(f) + grant, _, err := f.service.IssueLabGrant(context.Background(), f.actor, app.ConsoleLabGrantIssueRequest{Mode: app.ConsoleLabModePersistentVM, Target: "default", Reason: "operate enrolled test VM", IdempotencyKey: "persistent-vm", Beneficiary: "agent:mcp-local", AcknowledgeExternalEffects: true}) + if err != nil { + t.Fatal(err) + } + if !grant.ExpiresAt.IsZero() { + t.Fatal("persistent grant expires") + } + *f.now = f.now.Add(48 * time.Hour) + safety.contained, safety.unverified = false, true + req := labRequest(grant) + req.Deadline = f.now.Add(time.Minute).Format(time.RFC3339Nano) + if _, err := f.service.Input(context.Background(), labActor(t), req); err != nil { + t.Fatal(err) + } + *epoch = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + req.IdempotencyKey = "after-reenrollment" + if _, err := f.service.Input(context.Background(), labActor(t), req); err == nil || len(f.provider.inputs) != 1 { + t.Fatalf("stale authority dispatched: %v", err) + } +} + +func TestPersistentVMGrantCoordinatesSessionsAndRejectsRevokedAuthority(t *testing.T) { + f := newConsoleFixture(t) + configureLab(f) + grant, _, err := f.service.IssueLabGrant(t.Context(), f.actor, app.ConsoleLabGrantIssueRequest{Mode: app.ConsoleLabModePersistentVM, Target: "default", Reason: "operate enrolled test VM", IdempotencyKey: "persistent-session", Beneficiary: "agent:mcp-local", AcknowledgeExternalEffects: true}) + if err != nil { + t.Fatal(err) + } + // A later bounded desktop grant cannot shadow VM authority for sessions. + *f.now = f.now.Add(time.Millisecond) + issueLab(t, f) + scopes := domain.NewScopeSet(domain.ScopeSessionOpen, domain.ScopeSessionWrite, domain.ScopeSessionRead, domain.ScopeSessionClose) + actor, err := domain.NewActorContext("agent:mcp-local", "agent:mcp-local", scopes, scopes) + if err != nil { + t.Fatal(err) + } + transport := &trackingTransport{} + manager := sessions.NewManager(filepath.Join(f.root, "sessions"), transport, time.Now) + coordinator := app.NewSessionService(manager, &dynamicClassSafetyResolver{resolution: destructiveSafetyResolution()}, nil, audit.NewStore(filepath.Join(f.root, "audit")), receipt.NewStore(filepath.Join(f.root, "receipts")), approval.NewStore(filepath.Join(f.root, "approvals")), app.WithSessionClock(func() time.Time { return *f.now }), app.WithSessionLabAuthority(f.service)) + params := app.SessionOpenParams{Target: string(grant.Target), Caller: actor, Reason: "open enrolled VM session", IdempotencyKey: "persistent-session-open", Timeout: time.Minute, Deadline: f.now.Add(time.Minute), Cols: 80, Rows: 24} + obs, rcpt, err := coordinator.OpenSession(t.Context(), params) + if err != nil || obs == nil || rcpt == nil || rcpt.Outcome.Status != domain.OutcomeSuccess { + t.Fatalf("persistent session: %+v %+v %v", obs, rcpt, err) + } + t.Cleanup(func() { + _, _, _ = coordinator.CloseSession(context.Background(), app.SessionCloseParams{SessionID: obs.ID, Caller: actor, Reason: "cleanup test session", IdempotencyKey: "cleanup-session", Timeout: time.Second}) + }) + if n, _, err := coordinator.WriteSession(t.Context(), app.SessionWriteParams{SessionID: obs.ID, Caller: actor, Data: "synthetic command", Reason: "exercise persistent write", IdempotencyKey: "persistent-write", Timeout: time.Minute}); err != nil || n == 0 { + t.Fatalf("persistent write: %v", err) + } + if _, err := coordinator.ControlSession(t.Context(), app.SessionControlParams{SessionID: obs.ID, Caller: actor, Key: domain.ControlKeyCtrlC, Reason: "exercise persistent control", IdempotencyKey: "persistent-control", Timeout: time.Minute}); err != nil { + t.Fatalf("persistent control: %v", err) + } + if _, _, err := coordinator.CloseSession(t.Context(), app.SessionCloseParams{SessionID: obs.ID, Caller: actor, Reason: "exercise persistent close", IdempotencyKey: "persistent-close", Timeout: time.Minute}); err != nil { + t.Fatalf("persistent close: %v", err) + } + params.IdempotencyKey = "invalid-explicit" + params.ApprovalID = "app-00000000000000000000000000000000" + if _, _, err := coordinator.OpenSession(t.Context(), params); err == nil { + t.Fatal("explicit bad approval fell back to grant") + } + params.ApprovalID = "" + _, err = f.service.RevokeLabGrant(t.Context(), f.actor, app.ConsoleLabGrantRevokeRequest{GrantID: grant.GrantID, Reason: "end VM authority", IdempotencyKey: "revoke-session", Deadline: f.now.Add(time.Minute).Format(time.RFC3339Nano)}) + if err != nil { + t.Fatal(err) + } + params.IdempotencyKey = "revoked-open" + if _, _, err := coordinator.OpenSession(t.Context(), params); err == nil || atomic.LoadInt32(&transport.dialCalls) != 1 { + t.Fatal("revoked session dispatched") + } +} + +func TestLabDerivedApprovalCannotEscapeRevocationAfterLeaseConflict(t *testing.T) { + f := newConsoleFixture(t) + configureLab(f) + grant := issueLab(t, f) + op, req, providerID := labOperation(t, grant) + leases := lease.NewManager(filepath.Join(f.root, "leases")) + held, err := leases.Acquire(t.Context(), providerID, "synthetic.blocker", "synthetic-owner", time.Minute) + if err != nil { + t.Fatal(err) + } + if _, err := f.service.ExecuteLabMutation(t.Context(), req.Actor, grant.GrantID, op, req, providerID, func(context.Context) error { t.Error("busy provider dispatched"); return nil }); !errors.Is(err, lease.ErrLeaseConflict) { + t.Fatalf("busy lease: %v", err) + } + if err := leases.Release(t.Context(), held); err != nil { + t.Fatal(err) + } + _, err = f.service.RevokeLabGrant(t.Context(), f.actor, app.ConsoleLabGrantRevokeRequest{GrantID: grant.GrantID, Reason: "revoke orphaned authority", IdempotencyKey: "revoke-orphan", Deadline: f.now.Add(time.Minute).Format(time.RFC3339Nano)}) + if err != nil { + t.Fatal(err) + } + digest := sha256.Sum256([]byte(grant.GrantID + "\x00" + string(op.Actor.EffectiveActor) + "\x00" + op.IdempotencyKey)) + id := app.ConsoleLabApprovalPrefix + hex.EncodeToString(digest[:16]) + // The exact issued record remains, but it is never an externally usable bearer reference. + store := approval.NewStore(filepath.Join(f.root, "approvals")) + if issued, err := store.LoadIssuedContext(t.Context(), id); err != nil || issued == nil { + t.Fatalf("missing orphan approval: %v", err) + } + if _, err := f.recovery.LoadOperationApprovalReference(t.Context(), op, id); !errors.Is(err, app.ErrInvalidOperationApprovalReference) { + t.Fatalf("derived reference escaped: %v", err) + } + if len(f.provider.inputs) != 0 { + t.Fatal("denied authority dispatched") + } +} diff --git a/internal/app/console_lab_store.go b/internal/app/console_lab_store.go index 83cb564..b7e7497 100644 --- a/internal/app/console_lab_store.go +++ b/internal/app/console_lab_store.go @@ -23,7 +23,7 @@ func (s *ConsoleService) labLock(ctx context.Context, id string) (func() error, if !validFrameID(id) { return nil, ErrInvalidConsoleLabGrant } - if err := s.validateDependencies(); err != nil { + if err := s.recovery.validateDependencies(); err != nil { return nil, err } lock, err := s.recovery.leaseManager.Acquire(ctx, "console-lab-"+id, "console.lab", id, 6*time.Minute) @@ -158,7 +158,7 @@ func (s *ConsoleService) loadLabGrant(ctx context.Context, id string) (ConsoleLa } if grant.SchemaVersion != 1 || grant.GrantID != id || !validLabDigest(grant.EnrollmentIdentity) || !validLabGrantAuthority(grant) || - grant.IssuedAt.IsZero() || !grant.ExpiresAt.After(grant.IssuedAt) || grant.ExpiresAt.Sub(grant.IssuedAt) > MaxConsoleLabGrantValidity { + grant.IssuedAt.IsZero() || !validLabGrantLifetime(grant) { return ConsoleLabGrant{}, ErrInvalidConsoleLabGrant } return grant, nil @@ -254,3 +254,14 @@ func reserveProtectedLabFile(ctx context.Context, root *os.Root, dir, name strin } return file, info, nil } + +func validLabGrantLifetime(grant ConsoleLabGrant) bool { + switch grant.Mode { + case "": + return grant.ExpiresAt.After(grant.IssuedAt) && grant.ExpiresAt.Sub(grant.IssuedAt) <= MaxConsoleLabGrantValidity + case ConsoleLabModePersistentVM: + return grant.ExpiresAt.IsZero() && grant.AcknowledgeExternalEffects + default: + return false + } +} diff --git a/internal/app/console_lab_types.go b/internal/app/console_lab_types.go index 5cf3356..044aead 100644 --- a/internal/app/console_lab_types.go +++ b/internal/app/console_lab_types.go @@ -10,6 +10,8 @@ import ( const MaxConsoleLabGrantValidity = 8 * time.Hour +const ConsoleLabModePersistentVM = "persistent-vm" + const ConsoleLabApprovalPrefix = "app-lab-operation-" var ErrInvalidConsoleLabGrant = errors.New("app: console lab grant is unavailable or invalid") @@ -30,6 +32,7 @@ func WithConsoleLabEnrollmentIdentity(identity ConsoleLabEnrollmentIdentity) Con // ConsoleLabGrantIssueRequest requests only guest console authority. type ConsoleLabGrantIssueRequest struct { + Mode string `json:"mode,omitempty"` AcknowledgeExternalEffects bool `json:"acknowledge_external_effects"` Target string `json:"target"` Reason string `json:"reason"` @@ -40,6 +43,7 @@ type ConsoleLabGrantIssueRequest struct { // ConsoleLabGrant is immutable server-owned authority, never a bearer credential. type ConsoleLabGrant struct { + Mode string `json:"mode,omitempty"` AcknowledgeExternalEffects bool `json:"acknowledge_external_effects"` SchemaVersion int `json:"schema_version"` GrantID string `json:"grant_id"` diff --git a/internal/app/operation_approval_persistence.go b/internal/app/operation_approval_persistence.go index 9956b96..307b17c 100644 --- a/internal/app/operation_approval_persistence.go +++ b/internal/app/operation_approval_persistence.go @@ -2,6 +2,7 @@ package app import ( "context" + "strings" "time" "github.com/Horcag/agent-machine-control/internal/domain" @@ -60,7 +61,7 @@ func operationApprovalGrant(issued domain.Approval, approved domain.Operation) * // LoadOperationApprovalReference resolves immutable authority after the exact operation is canonical. func (s *RecoveryService) LoadOperationApprovalReference(ctx context.Context, op domain.Operation, approvalID string) (*domain.Approval, error) { - if s == nil || s.approvalStore == nil || approvalID == "" { + if s == nil || s.approvalStore == nil || approvalID == "" || strings.HasPrefix(approvalID, ConsoleLabApprovalPrefix) { return nil, ErrInvalidOperationApprovalReference } if err := domain.ValidateApprovalID(approvalID); err != nil { diff --git a/internal/app/recovery.go b/internal/app/recovery.go index fc60420..11ce748 100644 --- a/internal/app/recovery.go +++ b/internal/app/recovery.go @@ -64,6 +64,7 @@ type MutationRequest struct { // RecoveryService orchestrates in-process direct recovery operations, policy, leases, and receipts. type RecoveryService struct { + labAuthority *ConsoleService backend Backend targetResolver interface { ResolveTarget(context.Context, string) (TargetResolution, error) diff --git a/internal/app/recovery_admission.go b/internal/app/recovery_admission.go index e5d65c8..0f3d06a 100644 --- a/internal/app/recovery_admission.go +++ b/internal/app/recovery_admission.go @@ -3,6 +3,7 @@ package app import ( "context" "errors" + "fmt" "time" "github.com/Horcag/agent-machine-control/internal/domain" @@ -90,3 +91,30 @@ func runLifecycleHooks(ctx context.Context, req MutationRequest) error { } return nil } + +func (s *RecoveryService) checkPreconditions(ctx context.Context, op domain.Operation, req MutationRequest) (*domain.Receipt, error) { + if s.receiptStore != nil { + // Durable terminal truth wins over caller cancellation for an exact retry. + lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + cached, err := s.receiptStore.LookupIdempotencyContext(lookupCtx, op) + cancel() + if err != nil { + return nil, err + } + if cached != nil { + if req.cachedReceipt != nil { + *req.cachedReceipt = true + } + return cached, nil + } + } + if err := ctx.Err(); err != nil { + return nil, err + } + if s.auditStore != nil { + if err := s.auditStore.CheckWritableContext(ctx); err != nil { + return nil, fmt.Errorf("%w: %w", ErrAuditUnavailable, err) + } + } + return nil, nil +} diff --git a/internal/app/recovery_mutation.go b/internal/app/recovery_mutation.go index 9d60e3f..5d7d49d 100644 --- a/internal/app/recovery_mutation.go +++ b/internal/app/recovery_mutation.go @@ -102,7 +102,7 @@ func (s *RecoveryService) executeMutation( req MutationRequest, providerTargetID string, execFn func(context.Context) error, -) (domain.Receipt, error) { +) (result domain.Receipt, resultErr error) { execCtx, cancelExecution := s.mutationExecutionContext(ctx, op, req) defer cancelExecution() ctx = execCtx @@ -117,16 +117,19 @@ func (s *RecoveryService) executeMutation( } // 1. Idempotency Check & 2. Audit Writability Check - if cached, err := s.checkPreconditions(ctx, op); err != nil || cached != nil { + if cached, err := s.checkPreconditions(ctx, op, req); err != nil || cached != nil { if cached != nil { - if req.cachedReceipt != nil { - *req.cachedReceipt = true - } return *cached, cachedRecoveryOutcomeError(cached.Outcome) } return s.preProviderFailure(ctx, op, fp, policy.Decision{}, s.now(), err, "", req.ApprovalID) } + req, execFn, releaseGrant, err := s.coordinatePersistentRecovery(ctx, op, req, execFn) + if err != nil { + return domain.Receipt{}, err + } + defer func() { resultErr = errors.Join(resultErr, releaseGrant()) }() + now := s.now() // 3. Rollback discovery & 4. Policy evaluation & 5. Approval check @@ -183,30 +186,6 @@ func (s *RecoveryService) executeMutation( return s.finalizeMutation(receiptRecord, runErr, persistErr, releaseErr) } -func (s *RecoveryService) checkPreconditions(ctx context.Context, op domain.Operation) (*domain.Receipt, error) { - if s.receiptStore != nil { - // Durable terminal truth wins over caller cancellation for an exact retry. - lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) - cached, err := s.receiptStore.LookupIdempotencyContext(lookupCtx, op) - cancel() - if err != nil { - return nil, err - } - if cached != nil { - return cached, nil - } - } - if err := ctx.Err(); err != nil { - return nil, err - } - if s.auditStore != nil { - if err := s.auditStore.CheckWritableContext(ctx); err != nil { - return nil, fmt.Errorf("%w: %w", ErrAuditUnavailable, err) - } - } - return nil, nil -} - func (s *RecoveryService) acquireMutationLease( ctx context.Context, op domain.Operation, diff --git a/internal/app/session.go b/internal/app/session.go index cde1cd1..819973d 100644 --- a/internal/app/session.go +++ b/internal/app/session.go @@ -16,6 +16,7 @@ import ( // SessionService coordinates session mutation admissions, policy, idempotency, audit, and receipts. type SessionService struct { + labAuthority *ConsoleService sessionMgr *sessions.Manager safetyResolver SafetyResolver targetResolver SessionTargetResolver diff --git a/internal/app/session_approval_resolution.go b/internal/app/session_approval_resolution.go index fd2d23f..eeadcef 100644 --- a/internal/app/session_approval_resolution.go +++ b/internal/app/session_approval_resolution.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "strings" "github.com/Horcag/agent-machine-control/internal/domain" "github.com/Horcag/agent-machine-control/internal/policy" @@ -23,7 +24,7 @@ func (s *SessionService) loadSessionApprovalReference(ctx context.Context, appro if approvalID == "" { return nil, nil } - if s.approvalStore == nil { + if s.approvalStore == nil || strings.HasPrefix(approvalID, ConsoleLabApprovalPrefix) { return nil, invalidSessionApprovalReference() } loaded, err := s.approvalStore.LoadIssuedContext(ctx, approvalID) diff --git a/internal/app/session_coordination.go b/internal/app/session_coordination.go index 9701469..61d0f86 100644 --- a/internal/app/session_coordination.go +++ b/internal/app/session_coordination.go @@ -290,6 +290,8 @@ func (s *SessionService) executeMutation( } type admittedSessionMutation struct { + approval *domain.Approval + labGrant *ConsoleLabGrant op domain.Operation fp domain.Fingerprint idFp domain.Fingerprint @@ -305,11 +307,21 @@ func (s *SessionService) admitSessionMutation( timeout time.Duration, initialFP domain.Fingerprint, ) (*admittedSessionMutation, *domain.Receipt, error) { + var labGrant *ConsoleLabGrant + releaseGrant := func() error { return nil } + if approval == nil { + grant, release, err := s.labAuthority.admitPersistentLab(ctx, op) + if err != nil { + return nil, nil, err + } + labGrant, releaseGrant = grant, release + } releaseLease, err := s.acquireMutationLease(ctx, op, timeout, initialFP) if err != nil { - return nil, nil, err + return nil, nil, errors.Join(err, releaseGrant()) } - now := s.now() + releaseMachine := releaseLease + releaseLease = func() error { return errors.Join(releaseGrant(), releaseMachine()) } safety := s.resolveSafety(ctx, op.Target) op.Classification = safety.Classification if domain.IsGuestOperation(op.Kind) && op.Classification != domain.ClassReversibleMutation && op.Classification != domain.ClassDestructivePrivileged { @@ -327,12 +339,19 @@ func (s *SessionService) admitSessionMutation( releaseLease: releaseLease, }, nil, nil } + if labGrant != nil && op.Classification.RequiresApproval() { + approval, err = s.labAuthority.deriveLabApproval(ctx, *labGrant, op) + if err != nil { + return nil, nil, errors.Join(err, releaseLease()) + } + } + now := s.now() 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, + op: op, fp: fp, idFp: idFp, decision: decision, safety: safety, releaseLease: releaseLease, approval: approval, labGrant: labGrant, }, nil, nil } @@ -432,13 +451,16 @@ func (s *SessionService) coordinateSessionMutation( } return sessionMutationResult{}, denialRcpt, err } - if err := s.reserveAndPrepareMutation(ctx, admitted, approval); err != nil { + if err := s.reserveAndPrepareMutation(ctx, admitted, admitted.approval); err != nil { entry.err = err return sessionMutationResult{}, nil, err } - result, rcpt, mutErr := s.executeMutation(withGuestAdmission(ctx, admitted), admitted.op, admitted.fp, admitted.idFp, admitted.safety, execute) - mutErr = errors.Join(mutErr, s.releaseUnexecutedApproval(ctx, admitted, approval, result)) + result, rcpt, mutErr := s.executeMutation(withGuestAdmission(ctx, admitted), admitted.op, admitted.fp, admitted.idFp, admitted.safety, func(execCtx context.Context) (result sessionMutationResult, err error) { + err = s.labAuthority.withPersistentLabEffect(execCtx, admitted.labGrant, func(fenced context.Context) error { result, err = execute(fenced); return err }) + return result, err + }) + mutErr = errors.Join(mutErr, s.releaseUnexecutedApproval(ctx, admitted, admitted.approval, result)) releaseErr := admitted.releaseLease() entry.result = result diff --git a/internal/cli/app.go b/internal/cli/app.go index 9140b5c..de1b070 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -196,6 +196,11 @@ func Run(args []string, stdout, stderr io.Writer) int { approvalStore, app.WithRecoveryTargetResolver(targetService), ) + consoleAuthority := app.NewConsoleService(adapter, recoveryService, targetService, filepath.Join(sd.Root(), "console-frames"), + app.WithConsoleLabEnrollmentIdentity(func(ctx context.Context, ref domain.MachineRef) (string, error) { + return targetService.EnrollmentIdentity(ctx, string(ref)) + })) + app.WithRecoveryLabAuthority(consoleAuthority)(recoveryService) actorResolver := &actor.DefaultResolver{} actCtx, err := actorResolver.Resolve() @@ -207,7 +212,7 @@ func Run(args []string, stdout, stderr io.Writer) int { appInstance := NewApp( discoveryService, WithRecoveryService(recoveryService), - WithConsoleService(app.NewConsoleService(adapter, recoveryService, targetService, filepath.Join(sd.Root(), "console-frames"))), + WithConsoleService(consoleAuthority), WithTargetService(targetService), WithTargetCoordinator(targetCoordinator), WithActor(actCtx), @@ -369,6 +374,7 @@ func printUsage(w io.Writer) { fmt.Fprintln(w, "Commands:") fmt.Fprintln(w, " console screenshot|key|type|move|click|drag Capture or control the enrolled VM console") fmt.Fprintln(w, " desktop observe|action|enable|status|disable Guest windows/UIA and bounded autonomous control") + fmt.Fprintln(w, " guest prepare|put|get|exec|remove-owned|approve Stream owned guest artifacts and bounded scripts") fmt.Fprintln(w, " doctor Check Hyper-V and host readiness") fmt.Fprintln(w, " machine list List discovered virtual machines") fmt.Fprintln(w, " machine inspect Inspect virtual machine configuration and state") diff --git a/internal/cli/checkpoint_cmd.go b/internal/cli/checkpoint_cmd.go index 0247d3e..b5b015c 100644 --- a/internal/cli/checkpoint_cmd.go +++ b/internal/cli/checkpoint_cmd.go @@ -2,6 +2,7 @@ package cli import ( "context" + "errors" "flag" "fmt" "io" @@ -13,6 +14,7 @@ import ( "github.com/Horcag/agent-machine-control/internal/app" "github.com/Horcag/agent-machine-control/internal/daemon" "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/policy" "github.com/Horcag/agent-machine-control/internal/receipt" ) @@ -174,6 +176,19 @@ func runCheckpointCreate( if !directMode { return executeDaemonCheckpointCreate(ctx, stateDir, targetID, *name, common, stdout, stderr) } + return executeDirectCheckpointCreate(ctx, recoverySvc, actor, prompter, nowFn, targetID, *name, common, stdout, stderr) +} + +func executeDirectCheckpointCreate( + ctx context.Context, + recoverySvc *app.RecoveryService, + actor domain.ActorContext, + prompter Prompter, + nowFn func() time.Time, + targetID, name string, + common *CommonFlags, + stdout, stderr io.Writer, +) int { if rejectDirectApprovalReference(common, stderr, "checkpoint create") { return ExitUsage } @@ -182,35 +197,27 @@ func runCheckpointCreate( return mapMutationError(err, stderr, "checkpoint create") } - appr := common.Approval - var reqDeadline time.Time - if appr == nil && prompter != nil { + req := app.MutationRequest{ + TargetID: string(canonicalTarget), Actor: actor, Reason: common.Reason, + IdempotencyKey: common.IdempotencyKey, Timeout: common.Timeout, Approval: common.Approval, + } + rcpt, snap, err := recoverySvc.CreateCheckpoint(ctx, req, name) + var denied *app.PolicyDeniedError + if errors.As(err, &denied) && denied.Reason == policy.DenialApprovalRequired && common.Approval == nil && prompter != nil { promptMsg := fmt.Sprintf("Destructive operation checkpoint.create on %s requires confirmation", canonicalTarget) - params := map[string]any{"name": *name} - promptedAppr, dl, ok := promptForApproval(prompter, nowFn, actor, string(canonicalTarget), "checkpoint.create", domain.CapabilityCheckpointCreate, domain.ClassDestructivePrivileged, common.Reason, common.IdempotencyKey, common.Timeout, params, promptMsg) + params := map[string]any{"name": name} + req.IdempotencyKey = domain.DeriveApprovalIdempotencyKey(common.IdempotencyKey) + approval, deadline, ok := promptForApproval(prompter, nowFn, actor, string(canonicalTarget), "checkpoint.create", domain.CapabilityCheckpointCreate, domain.ClassDestructivePrivileged, common.Reason, req.IdempotencyKey, common.Timeout, params, promptMsg) if !ok { fmt.Fprintln(stderr, "amc checkpoint create: operation aborted by operator") return ExitDenied } - appr = promptedAppr - if err := recoverySvc.IssueApproval(ctx, *appr); err != nil { - fmt.Fprintln(stderr, "amc checkpoint create: failed to issue server approval") - return ExitBackendUnavailable + if err := recoverySvc.IssueApproval(ctx, *approval); err != nil { + return mapMutationError(err, stderr, "checkpoint create") } - reqDeadline = dl + req.Approval, req.Deadline = approval, deadline + rcpt, snap, err = recoverySvc.CreateCheckpoint(ctx, req, name) } - - req := app.MutationRequest{ - TargetID: string(canonicalTarget), - Actor: actor, - Reason: common.Reason, - IdempotencyKey: common.IdempotencyKey, - Timeout: common.Timeout, - Deadline: reqDeadline, - Approval: appr, - } - - rcpt, snap, err := recoverySvc.CreateCheckpoint(ctx, req, *name) if err != nil { return mapMutationError(err, stderr, "checkpoint create") } diff --git a/internal/cli/checkpoint_restore_cmd.go b/internal/cli/checkpoint_restore_cmd.go index 18a0544..8a32f7a 100644 --- a/internal/cli/checkpoint_restore_cmd.go +++ b/internal/cli/checkpoint_restore_cmd.go @@ -12,6 +12,7 @@ import ( "github.com/Horcag/agent-machine-control/internal/daemon" "github.com/Horcag/agent-machine-control/internal/domain" "github.com/Horcag/agent-machine-control/internal/lease" + "github.com/Horcag/agent-machine-control/internal/policy" "github.com/Horcag/agent-machine-control/internal/receipt" ) @@ -94,6 +95,19 @@ func runCheckpointRestore( }, ) } + return executeDirectCheckpointRestore(ctx, recoverySvc, actor, prompter, nowFn, targetID, checkpointID, common, stdout, stderr) +} + +func executeDirectCheckpointRestore( + ctx context.Context, + recoverySvc *app.RecoveryService, + actor domain.ActorContext, + prompter Prompter, + nowFn func() time.Time, + targetID, checkpointID string, + common *CommonFlags, + stdout, stderr io.Writer, +) int { if rejectDirectApprovalReference(common, stderr, "checkpoint restore") { return ExitUsage } @@ -102,22 +116,22 @@ func runCheckpointRestore( return mapMutationError(err, stderr, "checkpoint restore") } - appr, reqDeadline, approvalExit := prepareCheckpointRestoreApproval(ctx, recoverySvc, actor, prompter, nowFn, string(canonicalTarget), checkpointID, common, stderr) - if approvalExit != ExitSuccess { - return approvalExit - } - req := app.MutationRequest{ - TargetID: string(canonicalTarget), - Actor: actor, - Reason: common.Reason, - IdempotencyKey: common.IdempotencyKey, - Timeout: common.Timeout, - Deadline: reqDeadline, - Approval: appr, + TargetID: string(canonicalTarget), Actor: actor, Reason: common.Reason, + IdempotencyKey: common.IdempotencyKey, Timeout: common.Timeout, Approval: common.Approval, } - rcpt, obs, err := recoverySvc.RestoreCheckpoint(ctx, req, checkpointID) + var denied *app.PolicyDeniedError + if errors.As(err, &denied) && denied.Reason == policy.DenialApprovalRequired && common.Approval == nil && prompter != nil { + promptFlags := *common + promptFlags.IdempotencyKey = domain.DeriveApprovalIdempotencyKey(common.IdempotencyKey) + approval, deadline, code := prepareCheckpointRestoreApproval(ctx, recoverySvc, actor, prompter, nowFn, string(canonicalTarget), checkpointID, &promptFlags, stderr) + if code != ExitSuccess { + return code + } + req.Approval, req.Deadline, req.IdempotencyKey = approval, deadline, promptFlags.IdempotencyKey + rcpt, obs, err = recoverySvc.RestoreCheckpoint(ctx, req, checkpointID) + } if err != nil { return mapMutationError(err, stderr, "checkpoint restore") } diff --git a/internal/cli/console_cmd.go b/internal/cli/console_cmd.go index a1f3186..b2b4c05 100644 --- a/internal/cli/console_cmd.go +++ b/internal/cli/console_cmd.go @@ -34,7 +34,7 @@ func consoleArgs(args []string) ([]string, []string) { } flags = append(flags, arg) name := strings.TrimLeft(arg, "-") - if !strings.Contains(name, "=") && name != "json" && name != "async" && name != "for-mcp" && name != "acknowledge-external-effects" && i+1 < len(args) { + if !strings.Contains(name, "=") && name != "json" && name != "async" && name != "persistent-vm" && name != "for-mcp" && name != "acknowledge-external-effects" && i+1 < len(args) { flags = append(flags, args[i+1]) i++ } diff --git a/internal/cli/desktop_cmd.go b/internal/cli/desktop_cmd.go index c540dba..a58f355 100644 --- a/internal/cli/desktop_cmd.go +++ b/internal/cli/desktop_cmd.go @@ -61,7 +61,7 @@ func readDesktopRequestFile(path string, out *domain.DesktopRequest) error { type desktopFlags struct { pos []string target, reason, key, grant, requestFile, deadline string - forMCP, ack bool + forMCP, ack, persistent bool validFor time.Duration } @@ -75,6 +75,7 @@ func parseDesktopFlags(args []string, stderr io.Writer) (desktopFlags, bool) { grant := fs.String("lab-grant-id", "", "active operator-issued grant") requestFile := fs.String("request-file", "", "JSON DesktopRequest file") forMCP := fs.Bool("for-mcp", false, "grant agent:mcp-local instead of self") + persistent := fs.Bool("persistent-vm", false, "authorize this enrolled VM until revoked") ack := fs.Bool("acknowledge-external-effects", false, "acknowledge guest external effects are not rolled back") validFor := fs.Duration("valid-for", time.Hour, "grant lifetime (up to 8h)") deadline := fs.String("deadline", "", "exact operation deadline") @@ -82,7 +83,7 @@ func parseDesktopFlags(args []string, stderr io.Writer) (desktopFlags, bool) { if fs.Parse(flags) != nil || len(pos) > 1 { return desktopFlags{}, false } - return desktopFlags{pos: pos, target: *target, reason: *reason, key: *key, grant: *grant, requestFile: *requestFile, forMCP: *forMCP, ack: *ack, validFor: *validFor, deadline: *deadline}, true + return desktopFlags{pos: pos, target: *target, reason: *reason, key: *key, grant: *grant, requestFile: *requestFile, forMCP: *forMCP, ack: *ack, persistent: *persistent, validFor: *validFor, deadline: *deadline}, true } func (a *App) observeDesktop(ctx context.Context, cl *client.Client, target string, pos []string) (app.DesktopActionResult, error) { @@ -123,12 +124,20 @@ func (a *App) dispatchDesktopCommand(ctx context.Context, cl *client.Client, com if *forMCP { beneficiary = "agent:mcp-local" } - out, err = cl.IssueConsoleLabGrant(ctx, app.ConsoleLabGrantIssueRequest{Target: *target, Reason: *reason, IdempotencyKey: *key, Beneficiary: beneficiary, ValidForMillis: validFor.Milliseconds(), AcknowledgeExternalEffects: *ack}) + mode := "" + if options.persistent { + mode = app.ConsoleLabModePersistentVM + } + out, err = cl.IssueConsoleLabGrant(ctx, app.ConsoleLabGrantIssueRequest{Mode: mode, Target: *target, Reason: *reason, IdempotencyKey: *key, Beneficiary: beneficiary, ValidForMillis: validFor.Milliseconds(), AcknowledgeExternalEffects: *ack}) case "status": if len(pos) == 1 { *grant = pos[0] } - out, err = cl.ConsoleLabGrantStatus(ctx, *grant) + if *grant == "" { + out, err = cl.ActiveConsoleLabGrant(ctx, *target) + } else { + out, err = cl.ConsoleLabGrantStatus(ctx, *grant) + } case "disable": if len(pos) == 1 { *grant = pos[0] diff --git a/internal/cli/desktop_cmd_test.go b/internal/cli/desktop_cmd_test.go index c17b475..278488f 100644 --- a/internal/cli/desktop_cmd_test.go +++ b/internal/cli/desktop_cmd_test.go @@ -72,12 +72,12 @@ func assertDesktopCLIRequest(t *testing.T, r *http.Request, route string, expect func desktopCLIResponse(name string) any { switch name { - case "enable": + case "enable", "persistent": return struct { Grant app.ConsoleLabGrant `json:"grant"` Receipt domain.Receipt `json:"receipt"` }{Grant: app.ConsoleLabGrant{GrantID: "synthetic-receipt"}} - case "status": + case "status", "active": return app.ConsoleLabGrantStatus{Grant: app.ConsoleLabGrant{GrantID: "synthetic-receipt"}, State: "active"} case "disable": return domain.Receipt{ReceiptID: "synthetic-receipt"} @@ -103,6 +103,8 @@ func TestDesktopCLIRequestsAndFlags(t *testing.T) { want any }{ {"enable", "/v1/desktop/lab/issue", []string{"enable", "--target", "default", "--reason", "synthetic grant", "--idempotency-key", "issue-key", "--for-mcp", "--valid-for", "2m", "--acknowledge-external-effects"}, app.ConsoleLabGrantIssueRequest{Target: "default", Reason: "synthetic grant", IdempotencyKey: "issue-key", Beneficiary: "agent:mcp-local", ValidForMillis: 120000, AcknowledgeExternalEffects: true}}, + {"persistent", "/v1/desktop/lab/issue", []string{"enable", "--persistent-vm", "--for-mcp", "--acknowledge-external-effects", "--reason", "persistent fixture", "--idempotency-key", "persistent-key"}, app.ConsoleLabGrantIssueRequest{Mode: app.ConsoleLabModePersistentVM, Reason: "persistent fixture", IdempotencyKey: "persistent-key", Beneficiary: "agent:mcp-local", ValidForMillis: 3600000, AcknowledgeExternalEffects: true}}, + {"active", "/v1/desktop/lab/active", []string{"status"}, map[string]string{}}, {"status", "/v1/desktop/lab/status", []string{"status", "own-grant"}, map[string]string{"grant_id": "own-grant"}}, {"disable", "/v1/desktop/lab/revoke", []string{"disable", "own-grant", "--reason", "synthetic revoke", "--idempotency-key", "revoke-key", "--deadline", deadline}, app.ConsoleLabGrantRevokeRequest{GrantID: "own-grant", Reason: "synthetic revoke", IdempotencyKey: "revoke-key", Deadline: deadline}}, {"action", "/v1/desktop/action", []string{"action", "--request-file", path, "--target", "default", "--reason", "synthetic action", "--idempotency-key", "action-key", "--lab-grant-id", "own-grant"}, app.DesktopActionRequest{Target: "default", Request: request, Reason: "synthetic action", IdempotencyKey: "action-key", LabGrantID: "own-grant"}}, diff --git a/internal/cli/guest_cmd.go b/internal/cli/guest_cmd.go index f5aed5f..c8167a3 100644 --- a/internal/cli/guest_cmd.go +++ b/internal/cli/guest_cmd.go @@ -13,6 +13,7 @@ import ( "github.com/Horcag/agent-machine-control/internal/app" "github.com/Horcag/agent-machine-control/internal/client" "github.com/Horcag/agent-machine-control/internal/daemon" + "github.com/Horcag/agent-machine-control/internal/domain" "github.com/Horcag/agent-machine-control/internal/guest/stream" ) @@ -117,6 +118,14 @@ func parseGuestCLI(operation string, args []string, approve bool, stderr io.Writ return guestCLIFlags{}, fmt.Errorf("invalid guest arguments") } } + if err := domain.ValidateGuestOperationShape(operation, 0, p.MaxOutput, p.ArtifactIDs); err != nil { + return guestCLIFlags{}, fmt.Errorf("invalid guest %s shape: use zero max-output for prepare, put and remove-owned; get requires one artifact, exec requires output from 1 to 16777216 bytes", operation) + } + payload := operation == "put" || operation == "exec" + output := operation == "get" || operation == "exec" + if (sourcePath != "") != payload || (!output && destination != "") || (!approve && output && destination == "") { + return guestCLIFlags{}, fmt.Errorf("invalid guest %s paths: source is required only for put/exec; new destination is required only for get/exec", operation) + } return guestCLIFlags{p, sourcePath, destination, validity, beneficiary}, nil } diff --git a/internal/cli/guest_cmd_test.go b/internal/cli/guest_cmd_test.go index 9fdc7af..0a14b83 100644 --- a/internal/cli/guest_cmd_test.go +++ b/internal/cli/guest_cmd_test.go @@ -69,14 +69,7 @@ func TestGuestCLIDiscoveryStreamsExactAuthorityAndMapsFailure(t *testing.T) { t.Fatal(err) } for _, operation := range []string{"prepare", "put", "get", "exec", "remove-owned"} { - deadline := time.Now().Add(time.Minute).Format(time.RFC3339Nano) - args := []string{operation, "--target", "synthetic-target", "--reason", "contract", "--approval-id", "synthetic-grant", "--idempotency-key", "request-" + operation, "--deadline", deadline, "--max-output", "64"} - if operation == "put" || operation == "exec" { - args = append(args, "--source", source) - } - if operation == "get" || operation == "exec" { - args = append(args, "--destination", filepath.Join(directory, operation+".bin")) - } + args := guestCLICaseArguments(operation, source, directory) var out, stderr bytes.Buffer if code := runGuest(t.Context(), nil, false, state, args, &out, &stderr); code == ExitSuccess || out.Len() != 0 { t.Fatalf("%s returned success or output after failure: %d %s", operation, code, out.String()) @@ -94,6 +87,21 @@ func TestGuestCLIDiscoveryStreamsExactAuthorityAndMapsFailure(t *testing.T) { t.Fatalf("failed downloads leaked outputs or stages: %v %v", entries, err) } } +func guestCLICaseArguments(operation, source, directory string) []string { + deadline := time.Now().Add(time.Minute).Format(time.RFC3339Nano) + args := []string{operation, "--target", "synthetic-target", "--reason", "contract", "--approval-id", "synthetic-grant", "--idempotency-key", "request-" + operation, "--deadline", deadline} + if operation == "put" || operation == "exec" { + args = append(args, "--source", source) + } + if operation == "get" || operation == "exec" { + args = append(args, "--destination", filepath.Join(directory, operation+".bin"), "--max-output", "64") + } + if operation == "get" || operation == "remove-owned" { + args = append(args, "--artifact-ids", strings.Repeat("a", 32)) + } + return args +} + func guestCLIFailureHandler(t *testing.T, captured *[]app.GuestOperationParams) http.HandlerFunc { t.Helper() return func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/cli/guest_validation_test.go b/internal/cli/guest_validation_test.go new file mode 100644 index 0000000..8c4c7b8 --- /dev/null +++ b/internal/cli/guest_validation_test.go @@ -0,0 +1,63 @@ +package cli + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/daemon" +) + +func TestGuestCLIInvalidShapesRejectBeforeDiscovery(t *testing.T) { + for _, args := range [][]string{ + {"prepare", "--max-output", "64"}, {"put", "--source", "private-missing-path", "--max-output", "64"}, + {"get", "--destination", "private-output", "--max-output", "64"}, + {"exec", "--source", "private-missing-path", "--destination", "private-output", "--max-output", "16777217"}, + {"remove-owned"}, {"prepare", "--source", "private-missing-path"}, + } { + args = append(args, "--deadline", time.Now().Add(time.Minute).Format(time.RFC3339Nano)) + var out, stderr bytes.Buffer + code := runGuest(t.Context(), nil, false, "missing-state", args, &out, &stderr) + if code != ExitUsage || !strings.Contains(stderr.String(), "invalid guest") || strings.Contains(stderr.String(), "private-") || out.Len() != 0 { + t.Fatalf("code=%d stderr=%s", code, stderr.String()) + } + } +} + +func TestGuestCLITypedFailureExitAndRedaction(t *testing.T) { + for _, tc := range []struct { + category string + exit int + }{ + {"invalid_argument", ExitUsage}, {"approval_required", ExitDenied}, {"guest_workspace_unprovisioned", ExitDenied}, + {"guest_authority", ExitDenied}, {"guest_not_prepared", ExitConflict}, {"guest_ownership", ExitConflict}, + {"guest_uncertain", ExitBackendUnavailable}, + } { + t.Run(tc.category, func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + if _, _, err := daemon.DecodeGuestMetadata(r.Body); err != nil { + t.Error(err) + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Trailer", daemon.GuestResultTrailer) + data, _ := json.Marshal(daemon.GuestFinal{Category: tc.category, Error: "private-secret-path-token"}) + w.Header().Set(daemon.GuestResultTrailer, base64.RawStdEncoding.EncodeToString(data)) + })) + defer server.Close() + state := guestCLIState(t, server.URL) + var out, stderr bytes.Buffer + args := []string{"prepare", "--deadline", time.Now().Add(time.Minute).Format(time.RFC3339Nano)} + code := runGuest(t.Context(), nil, false, state, args, &out, &stderr) + if code != tc.exit || calls != 1 || out.Len() != 0 || strings.Contains(stderr.String(), "private") { + t.Fatalf("code=%d calls=%d stderr=%s", code, calls, stderr.String()) + } + }) + } +} diff --git a/internal/client/guest.go b/internal/client/guest.go index 6324301..2acf68c 100644 --- a/internal/client/guest.go +++ b/internal/client/guest.go @@ -8,7 +8,7 @@ import ( "encoding/binary" "encoding/hex" "encoding/json" - "fmt" + "errors" "io" "net/http" @@ -42,9 +42,10 @@ func (c *Client) GuestOperation(ctx context.Context, p app.GuestOperationParams, req.ContentLength = int64(len(prefix)) + p.Size req.Header.Set("Authorization", "Bearer "+c.token) req.Header.Set("Content-Type", daemon.GuestContentType) + req.Header.Set(daemon.GuestErrorProtocolHeader, daemon.GuestErrorProtocolVersion) resp, err := c.guestHTTPClient().Do(req) if err != nil { - return zero, fmt.Errorf("%w: %v", app.ErrGuestUncertain, err) + return zero, app.ErrGuestUncertain } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -55,14 +56,14 @@ func (c *Client) GuestOperation(ctx context.Context, p app.GuestOperationParams, } total, digest, err := readGuestHTTPOutput(ctx, resp, cancel, p.MaxOutput, output) if err != nil { - return zero, err + return zero, errors.Join(app.ErrGuestUncertain, err) } final, err := decodeGuestFinal(resp) if err != nil { - return zero, err + return zero, errors.Join(app.ErrGuestUncertain, err) } - if final.Error != "" { - return final.Result, fmt.Errorf("%w: %s", app.ErrGuestUncertain, final.Error) + if final.Error != "" || final.Category != "" { + return final.Result, guestFinalError(final.Category) } if err = validateGuestFinal(p, final.Result, total, digest); err != nil { return final.Result, err diff --git a/internal/client/guest_errors.go b/internal/client/guest_errors.go new file mode 100644 index 0000000..6ce7db9 --- /dev/null +++ b/internal/client/guest_errors.go @@ -0,0 +1,61 @@ +package client + +import ( + "errors" + "net/http" + + "github.com/Horcag/agent-machine-control/internal/app" +) + +// Ignore trailer message text even from older servers. Categories are a bounded +// protocol vocabulary; unknown or legacy failures cannot prove a safe outcome. +func guestFinalError(category string) error { + status := http.StatusForbidden + var cause error + message := "guest operation denied" + switch category { + case "invalid_argument", "invalid_target", "target_mismatch": + status = http.StatusBadRequest + cause = ErrInvalidArgument + message = "invalid guest operation input" + case "approval_required", "approval_record_expired", "approval_record_consumed", "approval_record_mismatch", "approval_record_not_yet_valid", + "forbidden", "forbidden_operation", "missing_required_scope", "missing_sensitive_evidence_scope", "missing_required_capability", "missing_verified_rollback_point", "delegation_exceeds_authority", "access_denied": + cause = ErrDenied + case "guest_workspace_unprovisioned": + cause = errors.Join(app.ErrGuestWorkspaceUnprovisioned, ErrDenied) + message = "guest workspace requires explicit provisioning" + case "guest_authority": + cause = errors.Join(app.ErrGuestAuthority, ErrDenied) + message = "guest authority changed or unavailable" + case "guest_not_prepared": + status = http.StatusConflict + cause = errors.Join(app.ErrGuestNotPrepared, ErrConflict) + message = "guest worker requires explicit preparation" + case "guest_ownership": + status = http.StatusConflict + cause = errors.Join(app.ErrGuestOwnership, ErrConflict) + message = "guest artifact ownership or identity mismatch" + case "conflict", "target_not_enrolled": + status = http.StatusConflict + cause = ErrConflict + message = "guest operation conflicts with current state" + case "timeout": + status = http.StatusGatewayTimeout + cause = ErrTimeout + message = "guest operation deadline exceeded" + case "cancelled": + status = http.StatusRequestTimeout + message = "guest operation canceled" + case "target_unavailable", "host_unavailable", "module_missing", "backend_unavailable": + status = http.StatusServiceUnavailable + cause = ErrDaemonUnavailable + message = "guest target unavailable" + case "machine_not_found": + status = http.StatusNotFound + cause = ErrNotFound + message = "guest target not found" + default: + return app.ErrGuestUncertain + } + return errors.Join(cause, &APIError{StatusCode: status, Category: category, Message: message}) +} diff --git a/internal/client/guest_errors_test.go b/internal/client/guest_errors_test.go new file mode 100644 index 0000000..b688bc2 --- /dev/null +++ b/internal/client/guest_errors_test.go @@ -0,0 +1,75 @@ +package client + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/daemon" +) + +func TestGuestTrailerFailuresPreserveCategoriesWithoutReplayOrSecrets(t *testing.T) { + for _, tc := range []struct { + category string + cause error + }{ + {"invalid_argument", ErrInvalidArgument}, {"approval_required", ErrDenied}, + {"guest_workspace_unprovisioned", app.ErrGuestWorkspaceUnprovisioned}, + {"guest_authority", app.ErrGuestAuthority}, {"guest_not_prepared", app.ErrGuestNotPrepared}, + {"guest_ownership", app.ErrGuestOwnership}, {"conflict", ErrConflict}, + {"timeout", ErrTimeout}, {"", app.ErrGuestUncertain}, {"private-unknown-category", app.ErrGuestUncertain}, + } { + t.Run(tc.category, func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls++ + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Trailer", daemon.GuestResultTrailer) + final, _ := json.Marshal(daemon.GuestFinal{Category: tc.category, Error: "private-secret-path-token"}) + w.Header().Set(daemon.GuestResultTrailer, base64.RawStdEncoding.EncodeToString(final)) + })) + defer server.Close() + _, err := New(server.URL, "synthetic").GuestOperation(t.Context(), app.GuestOperationParams{Operation: "prepare", Deadline: time.Now().Add(time.Minute)}, nil, nil) + if !errors.Is(err, tc.cause) || calls != 1 || strings.Contains(err.Error(), "private") { + t.Fatalf("calls=%d err=%v", calls, err) + } + if tc.cause != app.ErrGuestUncertain && errors.Is(err, app.ErrGuestUncertain) { + t.Fatal("known failure became uncertain") + } + }) + } +} + +func TestGuestMissingTrailerRemainsUncertain(t *testing.T) { + cl, calls := guestFixture(t, nil, "missing") + _, err := cl.GuestOperation(t.Context(), app.GuestOperationParams{Operation: "prepare", Deadline: time.Now().Add(time.Minute)}, nil, nil) + if !errors.Is(err, app.ErrGuestUncertain) || !errors.Is(err, ErrMalformedResponse) || *calls != 1 { + t.Fatalf("calls=%d err=%v", *calls, err) + } +} + +func TestGuestLegacyHTTPEnvelopeUsesExistingErrorMapping(t *testing.T) { + for _, tc := range []struct { + status int + category string + cause error + }{ + {400, "invalid_argument", ErrInvalidArgument}, {403, "approval_required", ErrDenied}, + } { + payload, _ := json.Marshal(daemon.ErrorEnvelope{SchemaVersion: daemon.SchemaVersion, Error: daemon.ErrorField{Category: tc.category, Message: "guest operation rejected before dispatch; inspect its category"}}) + response := &http.Response{StatusCode: tc.status, Body: io.NopCloser(bytes.NewReader(payload))} + err := mapHTTPError(response) + api, ok := errors.AsType[*APIError](err) + if !errors.Is(err, tc.cause) || !ok || api.Category != tc.category || errors.Is(err, app.ErrGuestUncertain) { + t.Fatalf("legacy error=%v", err) + } + } +} diff --git a/internal/client/guest_test.go b/internal/client/guest_test.go index aaf9e8b..5bd9ae8 100644 --- a/internal/client/guest_test.go +++ b/internal/client/guest_test.go @@ -7,6 +7,7 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "errors" "io" "net/http" "net/http/httptest" @@ -196,7 +197,7 @@ func (w shortGuestWriter) WriteContext(_ context.Context, p []byte) (int, error) func TestGuestShortOutputRejected(t *testing.T) { cl, _ := guestFixture(t, []byte("output"), "valid") _, err := cl.GuestOperation(context.Background(), app.GuestOperationParams{Operation: "get", IdempotencyKey: "synthetic-request", MaxOutput: 20, Deadline: time.Now().Add(time.Second)}, nil, shortGuestWriter{}) - if err != io.ErrShortWrite { + if !errors.Is(err, io.ErrShortWrite) || !errors.Is(err, app.ErrGuestUncertain) { t.Fatalf("error=%v", err) } } diff --git a/internal/daemon/guest_errors.go b/internal/daemon/guest_errors.go new file mode 100644 index 0000000..0dcb8cb --- /dev/null +++ b/internal/daemon/guest_errors.go @@ -0,0 +1,86 @@ +package daemon + +import ( + "context" + "errors" + "net/http" + + "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/guest/stream" + "github.com/Horcag/agent-machine-control/internal/policy" + "github.com/Horcag/agent-machine-control/internal/receipt" +) + +// Guest failures carry allowlisted categories and fixed messages, never provider text. +// Uncertainty takes precedence over joined causes: a dispatched effect must not +// be presented as a safe pre-dispatch rejection. +func guestFailureCategory(err error) string { + if errors.Is(err, app.ErrGuestUncertain) { + return "guest_uncertain" + } + if denied, ok := errors.AsType[*app.PolicyDeniedError](err); ok { + switch denied.Reason { + case policy.DenialApprovalRequired, policy.DenialApprovalExpired, policy.DenialApprovalConsumed, + policy.DenialApprovalMismatch, policy.DenialApprovalNotYetValid, policy.DenialMissingScope, + policy.DenialMissingSensitiveEvidenceScope, policy.DenialRollbackMissing, policy.DenialForbidden, + policy.DenialDelegationExceeded, policy.DenialMissingCapability: + return string(denied.Reason) + default: + return "forbidden" + } + } + classes := []struct { + category string + causes []error + }{ + {"guest_workspace_unprovisioned", []error{app.ErrGuestWorkspaceUnprovisioned}}, + {"guest_authority", []error{app.ErrGuestAuthority}}, + {"guest_not_prepared", []error{app.ErrGuestNotPrepared}}, + {"guest_ownership", []error{app.ErrGuestOwnership}}, + {"invalid_argument", []error{domain.ErrNonCanonicalParameter, domain.ErrInvalidOperationKind, domain.ErrMissingDeadline, domain.ErrMissingReason, domain.ErrInvalidReason, domain.ErrMissingIdempotencyKey, domain.ErrInvalidIdempotencyKey, stream.ErrRequest}}, + {"forbidden", []error{domain.ErrSessionAccessDenied, domain.ErrDelegationExceedsAuthority}}, + {"conflict", []error{domain.ErrSessionConflict, receipt.ErrIdempotencyCollision}}, + {"timeout", []error{context.DeadlineExceeded}}, + {"cancelled", []error{context.Canceled}}, + } + for _, class := range classes { + for _, cause := range class.causes { + if errors.Is(err, cause) { + return class.category + } + } + } + if class, known := classifyTargetFailure(err); known { + return class.category + } + return "guest_uncertain" +} + +// Only legacy clients need the early HTTP error path. A started stream or an +// execution receipt cannot be rewritten as a rejection: its outcome stays in +// the final trailer, and the client must verify it before taking another action. +func writeGuestEarlyError(w http.ResponseWriter, category string, result app.GuestOperationResult, started bool) bool { + if started || category == "guest_uncertain" || (result.Receipt != nil && result.Receipt.Outcome.Status != domain.OutcomeDenied) { + return false + } + status := http.StatusForbidden + switch category { + case "invalid_argument", "invalid_target", "target_mismatch": + status = http.StatusBadRequest + case "guest_not_prepared", "guest_ownership", "conflict", "target_not_enrolled": + status = http.StatusConflict + case "timeout": + status = http.StatusGatewayTimeout + case "cancelled": + status = http.StatusRequestTimeout + case "target_unavailable", "host_unavailable", "module_missing", "backend_unavailable": + status = http.StatusServiceUnavailable + case "machine_not_found": + status = http.StatusNotFound + } + w.Header().Del("Trailer") + w.Header().Del(GuestResultTrailer) + writeError(w, status, category, "guest operation rejected before dispatch; inspect its category") + return true +} diff --git a/internal/daemon/guest_errors_test.go b/internal/daemon/guest_errors_test.go new file mode 100644 index 0000000..002675b --- /dev/null +++ b/internal/daemon/guest_errors_test.go @@ -0,0 +1,182 @@ +package daemon + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http/httptest" + "strings" + "testing" + + "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/policy" +) + +func TestGuestFailureClassificationRedactsAndPrioritizesUncertainty(t *testing.T) { + for _, tc := range []struct { + err error + category string + }{ + {fmt.Errorf("private-secret: %w", domain.ErrNonCanonicalParameter), "invalid_argument"}, + {&app.PolicyDeniedError{Reason: policy.DenialApprovalRequired, Message: "private-secret"}, "approval_required"}, + {app.ErrGuestWorkspaceUnprovisioned, "guest_workspace_unprovisioned"}, + {errors.Join(app.ErrGuestUncertain, domain.ErrNonCanonicalParameter), "guest_uncertain"}, + {errors.New("private-secret"), "guest_uncertain"}, + } { + if got := guestFailureCategory(tc.err); got != tc.category || strings.Contains(got, "private") { + t.Fatalf("category=%q want=%q", got, tc.category) + } + } +} + +func TestGuestHTTPMalformedShapesRejectedByRealServiceWithoutDispatch(t *testing.T) { + server, token, fixture := newGuestHTTPServiceFixture(t) + for _, operation := range []string{"prepare", "put", "get", "exec", "remove-owned"} { + t.Run(operation, func(t *testing.T) { + p, payload := guestHTTPCase(operation, strings.Repeat("a", 32)) + switch operation { + case "prepare", "put", "remove-owned": + p.MaxOutput = 64 + case "get": + p.ArtifactIDs = nil + case "exec": + p.MaxOutput = 16*1024*1024 + 1 + } + for range 2 { + final, body := invokeGuestHTTPFixture(t, server.URL, token, p, payload) + if final.Category != "invalid_argument" || final.Error == "" || len(body) != 0 || len(fixture.operations) != 0 { + t.Fatalf("final=%+v dispatch=%v", final, fixture.operations) + } + } + }) + } +} + +func TestGuestHTTPPreDispatchDenialsRemainTyped(t *testing.T) { + for _, tc := range []struct { + name, category string + configure func(*guestHTTPServiceFixture) + }{ + {"workspace", "guest_workspace_unprovisioned", func(f *guestHTTPServiceFixture) { + f.configErr = fmt.Errorf("private-secret: %w", app.ErrGuestWorkspaceUnprovisioned) + }}, + {"approval", "approval_required", func(f *guestHTTPServiceFixture) { f.privileged = true }}, + } { + t.Run(tc.name, func(t *testing.T) { + server, token, fixture := newGuestHTTPServiceFixture(t) + tc.configure(fixture) + p, payload := guestHTTPCase("prepare", "") + for range 2 { + final, body := invokeGuestHTTPFixture(t, server.URL, token, p, payload) + encoded, _ := json.Marshal(final) + if final.Category != tc.category || len(body) != 0 || len(fixture.operations) != 0 || strings.Contains(string(encoded), "private-secret") { + t.Fatalf("final=%s dispatch=%v", encoded, fixture.operations) + } + } + }) + } +} + +func TestGuestLegacyHTTPEarlyFailuresUseStandardEnvelope(t *testing.T) { + for _, tc := range []struct { + name, category string + status int + configure func(*guestHTTPServiceFixture, *app.GuestOperationParams) + }{ + {"invalid-prepare", "invalid_argument", 400, func(_ *guestHTTPServiceFixture, p *app.GuestOperationParams) { p.MaxOutput = 64 }}, + {"approval", "approval_required", 403, func(f *guestHTTPServiceFixture, _ *app.GuestOperationParams) { f.privileged = true }}, + {"workspace", "guest_workspace_unprovisioned", 403, func(f *guestHTTPServiceFixture, _ *app.GuestOperationParams) { + f.configErr = app.ErrGuestWorkspaceUnprovisioned + }}, + } { + t.Run(tc.name, func(t *testing.T) { + server, token, fixture := newGuestHTTPServiceFixture(t) + p, payload := guestHTTPCase("prepare", "") + tc.configure(fixture, &p) + response := guestHTTPFixtureResponse(t, server.URL, token, p, payload, false) + defer response.Body.Close() + var envelope ErrorEnvelope + if err := json.NewDecoder(response.Body).Decode(&envelope); err != nil { + t.Fatal(err) + } + if response.StatusCode != tc.status || envelope.Error.Category != tc.category || response.Header.Get("Trailer") != "" || len(fixture.operations) != 0 { + t.Fatalf("status=%d envelope=%+v operations=%v", response.StatusCode, envelope, fixture.operations) + } + }) + } +} + +func TestGuestLegacyHTTPDispatchedFailureRetainsStrictTrailer(t *testing.T) { + server, token, fixture := newGuestHTTPServiceFixture(t) + fixture.prepareErr = errors.New("private-secret-transport-error") + p, payload := guestHTTPCase("prepare", "") + response := guestHTTPFixtureResponse(t, server.URL, token, p, payload, false) + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + data, err := base64.RawStdEncoding.DecodeString(response.Trailer.Get(GuestResultTrailer)) + if err != nil { + t.Fatal(err) + } + // The installed legacy client has only these fields and rejects unknown fields. + var legacy struct { + Result app.GuestOperationResult `json:"result"` + Error string `json:"error,omitempty"` + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err = decoder.Decode(&legacy); err != nil { + t.Fatalf("legacy decoder: %v data=%s", err, data) + } + if response.StatusCode != 200 || len(body) != 0 || legacy.Error == "" || legacy.Result.Receipt == nil || legacy.Result.Receipt.Outcome.Status != domain.OutcomeFailed || strings.Contains(string(data), "private-secret") { + t.Fatalf("status=%d legacy=%+v body=%q", response.StatusCode, legacy, body) + } +} + +func TestGuestEarlyHTTPErrorNeverRewritesStreamedOrExecutedOutcome(t *testing.T) { + for _, tc := range []struct { + name, category string + started bool + receipt *domain.Receipt + }{ + {"stream-started", "invalid_argument", true, nil}, + {"uncertain", "guest_uncertain", false, nil}, + {"failed-receipt", "invalid_argument", false, &domain.Receipt{Outcome: domain.ExecutionOutcome{Status: domain.OutcomeFailed}}}, + {"success-receipt", "invalid_argument", false, &domain.Receipt{Outcome: domain.ExecutionOutcome{Status: domain.OutcomeSuccess}}}, + } { + t.Run(tc.name, func(t *testing.T) { + response := httptest.NewRecorder() + if writeGuestEarlyError(response, tc.category, app.GuestOperationResult{Receipt: tc.receipt}, tc.started) || response.Body.Len() != 0 { + t.Fatal("streamed/executed outcome rewritten as early rejection") + } + }) + } +} + +func TestGuestLegacyRejectionStatusContractClearsStreamHeaders(t *testing.T) { + for _, tc := range []struct { + category string + status int + }{ + {"invalid_argument", 400}, {"conflict", 409}, {"timeout", 504}, {"cancelled", 408}, + {"target_unavailable", 503}, {"machine_not_found", 404}, {"approval_required", 403}, + } { + response := httptest.NewRecorder() + response.Header().Set("Trailer", GuestResultTrailer) + response.Header().Set(GuestResultTrailer, "discard-stream-metadata") + denied := &domain.Receipt{Outcome: domain.ExecutionOutcome{Status: domain.OutcomeDenied}} + if !writeGuestEarlyError(response, tc.category, app.GuestOperationResult{Receipt: denied}, false) { + t.Fatal("denied receipt not recognized") + } + var envelope ErrorEnvelope + if json.Unmarshal(response.Body.Bytes(), &envelope) != nil || response.Code != tc.status || envelope.Error.Category != tc.category || response.Header().Get("Trailer") != "" || response.Header().Get(GuestResultTrailer) != "" { + t.Fatalf("response=%+v", response) + } + } +} diff --git a/internal/daemon/guest_protocol.go b/internal/daemon/guest_protocol.go index c7fc34c..d70f0b3 100644 --- a/internal/daemon/guest_protocol.go +++ b/internal/daemon/guest_protocol.go @@ -6,7 +6,6 @@ import ( "encoding/base64" "encoding/binary" "encoding/json" - "errors" "io" "net/http" "time" @@ -18,11 +17,17 @@ import ( const GuestMetadataLimit = 64 * 1024 const GuestResultTrailer = "X-Amc-Guest-Result" + +// GuestErrorProtocolHeader opts into typed trailer failures; older clients decode +// trailers strictly and receive ordinary HTTP errors for early rejections. +const GuestErrorProtocolHeader = "X-Amc-Guest-Errors" +const GuestErrorProtocolVersion = "categories-v1" const GuestContentType = "application/vnd.amc.guest-stream" type GuestFinal struct { - Result app.GuestOperationResult `json:"result"` - Error string `json:"error,omitempty"` + Result app.GuestOperationResult `json:"result"` + Error string `json:"error,omitempty"` + Category string `json:"category,omitempty"` } type GuestApprovalRequest struct { Params app.GuestOperationParams `json:"params"` @@ -95,9 +100,17 @@ func (r guestHTTPInput) ReadContext(ctx context.Context, p []byte) (int, error) return r.Read(p) } -type guestHTTPOutput struct{ http.ResponseWriter } +type guestHTTPOutput struct { + http.ResponseWriter + started bool +} + +func (w *guestHTTPOutput) Write(p []byte) (int, error) { + w.started = true + return w.ResponseWriter.Write(p) +} -func (w guestHTTPOutput) WriteContext(ctx context.Context, p []byte) (int, error) { +func (w *guestHTTPOutput) WriteContext(ctx context.Context, p []byte) (int, error) { if err := ctx.Err(); err != nil { return 0, err } @@ -140,17 +153,28 @@ func (s *Server) handleGuestOperation(w http.ResponseWriter, r *http.Request) { w.Header().Set("Trailer", GuestResultTrailer) var input io.Reader var output io.Writer + streamOutput := &guestHTTPOutput{ResponseWriter: w} if p.Operation == "put" || p.Operation == "exec" { input = guestHTTPInput{r.Body} } if p.Operation == "get" || p.Operation == "exec" { - output = guestHTTPOutput{w} + output = streamOutput } result, opErr := s.guestService.Execute(ctx, p, input, output) + writeGuestHTTPFinal(w, r.Header.Get(GuestErrorProtocolHeader), result, opErr, streamOutput.started) +} + +func writeGuestHTTPFinal(w http.ResponseWriter, errorProtocol string, result app.GuestOperationResult, opErr error, started bool) { final := GuestFinal{Result: result} if opErr != nil { - final.Error = "guest operation failed; verify the receipt before taking another action" - if errors.Is(opErr, app.ErrGuestWorkspaceUnprovisioned) { + category := guestFailureCategory(opErr) + if errorProtocol == GuestErrorProtocolVersion { + final.Category = category + } else if writeGuestEarlyError(w, category, result, started) { + return + } + final.Error = "guest operation failed; inspect its category and receipt before taking another action" + if category == "guest_workspace_unprovisioned" { final.Error = "guest workspace is not provisioned; an operator must install original authorized workspace identity metadata" } } diff --git a/internal/daemon/guest_service_http_test.go b/internal/daemon/guest_service_http_test.go index de485c8..dc63a6f 100644 --- a/internal/daemon/guest_service_http_test.go +++ b/internal/daemon/guest_service_http_test.go @@ -35,6 +35,9 @@ type guestHTTPServiceFixture struct { files map[string]stream.FileIdentity data map[string][]byte operations []string + configErr error + privileged bool + prepareErr error } func (f *guestHTTPServiceFixture) ResolveTarget(context.Context, string) (app.TargetResolution, error) { @@ -42,13 +45,17 @@ func (f *guestHTTPServiceFixture) ResolveTarget(context.Context, string) (app.Ta return app.TargetResolution{Locator: domain.MachineLocator{HostID: domain.LocalHostID, VMID: guid}, ProviderVMID: guid}, nil } func (f *guestHTTPServiceFixture) Current(_ context.Context, _ domain.MachineRef, caller domain.ActorContext) (app.GuestConfiguration, error) { - return app.GuestConfiguration{Generation: "synthetic-generation", Caller: caller, WorkspaceIdentity: f.root}, nil + return app.GuestConfiguration{Generation: "synthetic-generation", Caller: caller, WorkspaceIdentity: f.root}, f.configErr } func (f *guestHTTPServiceFixture) ResolveSafety(context.Context, domain.MachineRef) (app.SafetyResolution, error) { - return app.SafetyResolution{Classification: domain.ClassReversibleMutation, Contained: true, RollbackRef: "synthetic-checkpoint", RollbackState: policy.RollbackState{Available: true, Verified: true, CheckpointID: "synthetic-checkpoint"}}, nil + classification := domain.ClassReversibleMutation + if f.privileged { + classification = domain.ClassDestructivePrivileged + } + return app.SafetyResolution{Classification: classification, Contained: true, RollbackRef: "synthetic-checkpoint", RollbackState: policy.RollbackState{Available: true, Verified: true, CheckpointID: "synthetic-checkpoint"}}, nil } func (f *guestHTTPServiceFixture) Prepare(context.Context, domain.MachineRef, string, string) (stream.WorkerIdentity, error) { - return f.worker, nil + return f.worker, f.prepareErr } func (f *guestHTTPServiceFixture) Retire(domain.MachineRef, string, string) error { return nil } func (f *guestHTTPServiceFixture) Execute(_ context.Context, _ domain.MachineRef, _ string, _ string, p stream.Request, input io.Reader, output io.Writer) (stream.Result, error) { @@ -121,6 +128,25 @@ func TestGuestHTTPAllOperationsReachRealSharedService(t *testing.T) { } } func invokeGuestHTTPFixture(t *testing.T, endpoint, token string, p app.GuestOperationParams, payload []byte) (GuestFinal, []byte) { + t.Helper() + response := guestHTTPFixtureResponse(t, endpoint, token, p, payload, true) + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + trailer, err := base64.RawStdEncoding.DecodeString(response.Trailer.Get(GuestResultTrailer)) + if err != nil { + t.Fatal(err) + } + var final GuestFinal + if err = json.Unmarshal(trailer, &final); err != nil { + t.Fatalf("final trailer: %v status=%d body=%q", err, response.StatusCode, body) + } + return final, body +} + +func guestHTTPFixtureResponse(t *testing.T, endpoint, token string, p app.GuestOperationParams, payload []byte, typed bool) *http.Response { t.Helper() metadata, err := json.Marshal(p) if err != nil { @@ -139,24 +165,14 @@ func invokeGuestHTTPFixture(t *testing.T, endpoint, token string, p app.GuestOpe } request.Header.Set("Authorization", "Bearer "+token) request.Header.Set("Content-Type", GuestContentType) - response, err := http.DefaultClient.Do(request) - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - body, err := io.ReadAll(response.Body) - if err != nil { - t.Fatal(err) + if typed { + request.Header.Set(GuestErrorProtocolHeader, GuestErrorProtocolVersion) } - trailer, err := base64.RawStdEncoding.DecodeString(response.Trailer.Get(GuestResultTrailer)) + response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } - var final GuestFinal - if err = json.Unmarshal(trailer, &final); err != nil { - t.Fatalf("final trailer: %v status=%d body=%q", err, response.StatusCode, body) - } - return final, body + return response } func guestHTTPCase(operation, artifactID string) (app.GuestOperationParams, []byte) { diff --git a/internal/daemon/handlers_desktop_test.go b/internal/daemon/handlers_desktop_test.go index 8b0c892..add907f 100644 --- a/internal/daemon/handlers_desktop_test.go +++ b/internal/daemon/handlers_desktop_test.go @@ -38,7 +38,7 @@ func assertDesktopDaemonInvalidEnvelope(t *testing.T, url, token, body string) { func TestDesktopDaemonStrictRequestBoundary(t *testing.T) { backend := &consoleDaemonBackend{mockDaemonBackend: &mockDaemonBackend{}} endpoint, _, agent := setupConsoleDaemon(t, backend) - for _, path := range []string{"desktop/action", "desktop/lab/issue", "desktop/lab/status", "desktop/lab/active", "desktop/lab/revoke", "console/record"} { + for _, path := range []string{"desktop/action", "console/record"} { for _, body := range []string{`{"actor":"operator:forged"}`, `{"unknown":true}`, `{} {}`, `null`, `[]`, `{`, `{"target":"` + strings.Repeat("x", 128*1024) + `"}`} { t.Run(path+"/"+body[:min(len(body), 24)], func(t *testing.T) { assertDesktopDaemonInvalidEnvelope(t, endpoint+"/v1/"+path, agent, body) @@ -67,7 +67,7 @@ func TestDesktopDaemonStrictRequestBoundary(t *testing.T) { func TestDesktopDaemonUnavailableRoutes(t *testing.T) { srv, endpoint, _, agent := setupTestServer(t) defer func() { _ = srv.Shutdown(context.Background()) }() - for _, path := range []string{"desktop/action", "desktop/lab/issue", "desktop/lab/status", "desktop/lab/active", "desktop/lab/revoke", "console/record"} { + for _, path := range []string{"desktop/action", "console/record"} { status, body := doJSONReq(t, http.MethodPost, endpoint+"/v1/"+path, agent, map[string]any{}) if status != http.StatusNotImplemented || !bytes.Contains(body, []byte("capability_unavailable")) { t.Fatalf("%s status=%d body=%s", path, status, body) diff --git a/internal/daemon/server.go b/internal/daemon/server.go index 247401a..1452c41 100644 --- a/internal/daemon/server.go +++ b/internal/daemon/server.go @@ -197,10 +197,13 @@ func NewServer(cfg Config) (*Server, error) { identityProvider: ident, } - if provider, ok := backend.(app.ConsoleProvider); ok { - srv.consoleService = app.NewConsoleService(provider, recoverySvc, targetService, filepath.Join(sd.Root(), "console-frames"), app.WithConsoleLabSafetyResolver(safetyResolver), app.WithConsoleLabEnrollmentIdentity(func(ctx context.Context, ref domain.MachineRef) (string, error) { - return targetService.EnrollmentIdentity(ctx, string(ref)) - })) + provider, _ := backend.(app.ConsoleProvider) + srv.consoleService = app.NewConsoleService(provider, recoverySvc, targetService, filepath.Join(sd.Root(), "console-frames"), app.WithConsoleLabSafetyResolver(safetyResolver), app.WithConsoleLabEnrollmentIdentity(func(ctx context.Context, ref domain.MachineRef) (string, error) { + return targetService.EnrollmentIdentity(ctx, string(ref)) + })) + app.WithSessionLabAuthority(srv.consoleService)(sessionSvc) + app.WithRecoveryLabAuthority(srv.consoleService)(recoverySvc) + if provider != nil { srv.desktopService = app.NewDesktopService(guestdesktop.New(guestssh.NewTransport(keyProvider)), srv.consoleService) } srv.initializeGuestService(sessionSvc, targetService, keyProvider) diff --git a/internal/domain/guest_operation.go b/internal/domain/guest_operation.go index 38d8425..80d4408 100644 --- a/internal/domain/guest_operation.go +++ b/internal/domain/guest_operation.go @@ -31,25 +31,22 @@ func validateGuestOperationParams(params map[string]any) error { return ErrNonCanonicalParameter } size, err := guestParameterInt(params["size"]) - if err != nil || size < 0 || int64(size) > 1<<40 { + if err != nil { return ErrNonCanonicalParameter } limit, err := guestParameterInt(params["max_output"]) - if err != nil || limit < 0 || int64(limit) > 1<<40 { + if err != nil { return ErrNonCanonicalParameter } ids, ok := params["artifact_ids"].([]string) - if !ok || len(ids) > 128 { + if !ok { return ErrNonCanonicalParameter } - if err := validateGuestArtifactIDs(ids); err != nil { - return err - } op, ok := params["operation"].(string) if !ok || !IsGuestOperation(OperationKind("guest."+op)) { return ErrNonCanonicalParameter } - return validateGuestShape(op, size, limit, len(ids)) + return ValidateGuestOperationShape(op, size, limit, ids) } func validateGuestArtifactIDs(ids []string) error { @@ -63,6 +60,17 @@ func validateGuestArtifactIDs(ids []string) error { return nil } +// ValidateGuestOperationShape applies the shared bounds and artifact contract before I/O. +func ValidateGuestOperationShape(op string, size, limit int64, ids []string) error { + if size < 0 || size > 1<<40 || limit < 0 || limit > 1<<40 || len(ids) > 128 { + return ErrNonCanonicalParameter + } + if err := validateGuestArtifactIDs(ids); err != nil { + return err + } + return validateGuestShape(op, size, limit, len(ids)) +} + func validateGuestShape(op string, size, limit int64, number int) error { valid := false switch op { diff --git a/internal/mcpadapter/errors.go b/internal/mcpadapter/errors.go index 9be040b..2f6f2a0 100644 --- a/internal/mcpadapter/errors.go +++ b/internal/mcpadapter/errors.go @@ -3,6 +3,7 @@ package mcpadapter import ( "context" "errors" + "github.com/Horcag/agent-machine-control/internal/app" "net/http" "github.com/Horcag/agent-machine-control/internal/backends/hyperv" @@ -60,45 +61,52 @@ func operationToolError(err error, operationID, receiptID string) *mcp.CallToolR // Category keys are allowlisted protocol metadata, never provider message text. func categoryToolError(category string) string { messages := map[string]string{ - "recording_status_inconclusive": "recording_status_inconclusive: recording status is inconclusive", - "approval_required": "approval_required: operator approval required for this operation", - "target_not_enrolled": "target is not enrolled", - "target_mismatch": "target is not enrolled", - "target_unavailable": "protected target is unavailable", - "host_unavailable": "backend_host_unavailable: backend management host is unavailable", - "module_missing": "backend_module_missing: Hyper-V PowerShell module is unavailable", - "backend_error": "backend_error: backend operation failed", - "backend_unavailable": "backend_unavailable: machine backend is unavailable", - "access_denied": "backend_access_denied: machine backend access denied", - "malformed_response": "backend_malformed_response: machine backend returned an invalid response", - "output_limit": "backend_output_limit: machine backend output exceeded its size limit", - "machine_not_found": "requested resource not found", - "checkpoint_not_found": "requested resource not found", - "not_found": "requested resource not found", - "invalid_argument": "invalid_argument: invalid operation input", - "invalid_state": "operation_conflict: operation conflicts with current state", - "conflict": "operation_conflict: operation conflicts with current state", - "unauthorized": "authentication failed", - "unauthenticated_caller": "authentication failed", - "forbidden": "access_denied: operation denied by policy", - "policy": "access_denied: operation denied by policy", - "policy_denial": "access_denied: operation denied by policy", - "forbidden_operation": "access_denied: operation denied by policy", - "missing_required_scope": "access_denied: operation denied by policy", - "delegation_exceeds_authority": "access_denied: operation denied by policy", - "approval_record_expired": "approval_expired: operator approval has expired", - "approval_record_consumed": "approval_consumed: operator approval has already been consumed", - "approval_record_not_yet_valid": "approval_invalid: operator approval is not yet valid", - "approval_record_mismatch": "approval_invalid: operator approval does not match this operation", - "missing_verified_rollback_point": "rollback_required: operation requires a verified rollback point", - "timeout": "operation_timeout: operation timeout exceeded", - "deadline_exceeded": "operation_timeout: operation timeout exceeded", - "deadline_passed": "operation_timeout: operation timeout exceeded", - "cancelled": "operation_canceled: operation was canceled", - "caller_canceled": "operation_canceled: operation was canceled", - "persistence_failure": "operation_persistence_failure: operation record could not be saved", - "finalization_error": "operation_finalization_error: operation could not be finalized", - "daemon_crash_recovered": "operation_interrupted: operation was interrupted by daemon restart", + "guest_workspace_unprovisioned": "guest_workspace_unprovisioned: an operator must provision authorized workspace identity metadata", + "guest_authority": "guest_authority: guest authority changed or unavailable", + "guest_not_prepared": "guest_not_prepared: prepare the guest worker explicitly", + "guest_ownership": "guest_ownership: guest artifact ownership or identity mismatch", + "guest_uncertain": "guest_uncertain: guest operation outcome is uncertain; do not replay", + "missing_sensitive_evidence_scope": "access_denied: sensitive evidence scope required", + "missing_required_capability": "access_denied: required capability unavailable", + "recording_status_inconclusive": "recording_status_inconclusive: recording status is inconclusive", + "approval_required": "approval_required: operator approval required for this operation", + "target_not_enrolled": "target is not enrolled", + "target_mismatch": "target is not enrolled", + "target_unavailable": "protected target is unavailable", + "host_unavailable": "backend_host_unavailable: backend management host is unavailable", + "module_missing": "backend_module_missing: Hyper-V PowerShell module is unavailable", + "backend_error": "backend_error: backend operation failed", + "backend_unavailable": "backend_unavailable: machine backend is unavailable", + "access_denied": "backend_access_denied: machine backend access denied", + "malformed_response": "backend_malformed_response: machine backend returned an invalid response", + "output_limit": "backend_output_limit: machine backend output exceeded its size limit", + "machine_not_found": "requested resource not found", + "checkpoint_not_found": "requested resource not found", + "not_found": "requested resource not found", + "invalid_argument": "invalid_argument: invalid operation input", + "invalid_state": "operation_conflict: operation conflicts with current state", + "conflict": "operation_conflict: operation conflicts with current state", + "unauthorized": "authentication failed", + "unauthenticated_caller": "authentication failed", + "forbidden": "access_denied: operation denied by policy", + "policy": "access_denied: operation denied by policy", + "policy_denial": "access_denied: operation denied by policy", + "forbidden_operation": "access_denied: operation denied by policy", + "missing_required_scope": "access_denied: operation denied by policy", + "delegation_exceeds_authority": "access_denied: operation denied by policy", + "approval_record_expired": "approval_expired: operator approval has expired", + "approval_record_consumed": "approval_consumed: operator approval has already been consumed", + "approval_record_not_yet_valid": "approval_invalid: operator approval is not yet valid", + "approval_record_mismatch": "approval_invalid: operator approval does not match this operation", + "missing_verified_rollback_point": "rollback_required: operation requires a verified rollback point", + "timeout": "operation_timeout: operation timeout exceeded", + "deadline_exceeded": "operation_timeout: operation timeout exceeded", + "deadline_passed": "operation_timeout: operation timeout exceeded", + "cancelled": "operation_canceled: operation was canceled", + "caller_canceled": "operation_canceled: operation was canceled", + "persistence_failure": "operation_persistence_failure: operation record could not be saved", + "finalization_error": "operation_finalization_error: operation could not be finalized", + "daemon_crash_recovered": "operation_interrupted: operation was interrupted by daemon restart", } if message := messages[category]; message != "" { return message @@ -159,6 +167,9 @@ func classifiedToolError(err error) string { } func protectedToolError(err error) string { + if errors.Is(err, app.ErrGuestUncertain) { + return categoryToolError("guest_uncertain") + } if isApprovalRequired(err) { return "approval_required: operator approval required for this operation" } diff --git a/internal/mcpadapter/guest.go b/internal/mcpadapter/guest.go index f05459f..26c38a3 100644 --- a/internal/mcpadapter/guest.go +++ b/internal/mcpadapter/guest.go @@ -3,6 +3,7 @@ package mcpadapter import ( "context" "errors" + "github.com/Horcag/agent-machine-control/internal/domain" "time" "github.com/Horcag/agent-machine-control/internal/app" @@ -25,6 +26,9 @@ type GuestInput struct { func (a *Adapter) guestOperation(ctx context.Context, in GuestInput, operation string) (*mcp.CallToolResult, app.GuestOperationResult, error) { var zero app.GuestOperationResult + if err := validateGuestInput(in, operation); err != nil { + return mcpToolError(err), zero, nil + } deadline, err := time.Parse(time.RFC3339Nano, in.Deadline) if err != nil { return mcpToolError(NewInputError("invalid guest deadline")), zero, nil @@ -82,9 +86,70 @@ func (a *Adapter) GuestRemoveOwned(ctx context.Context, _ *mcp.CallToolRequest, return a.guestOperation(ctx, in, "remove-owned") } func (a *Adapter) addGuestTools(server *mcp.Server) { - mcp.AddTool(server, &mcp.Tool{Name: "guest_prepare", Description: "Explicitly prepare the enrolled guest worker using server-provisioned workspace identity"}, a.GuestPrepare) - mcp.AddTool(server, &mcp.Tool{Name: "guest_put", Description: "Stream an explicit local source file and return an opaque guest ownership reference"}, a.GuestPut) - mcp.AddTool(server, &mcp.Tool{Name: "guest_get", Description: "Download an opaque owned artifact to a new local destination after verification"}, a.GuestGet) - mcp.AddTool(server, &mcp.Tool{Name: "guest_exec", Description: "Execute an explicit local UTF-8 script and publish verified output to a new local destination"}, a.GuestExec) - mcp.AddTool(server, &mcp.Tool{Name: "guest_remove_owned", Description: "Remove only artifacts identified by immutable opaque ownership references"}, a.GuestRemoveOwned) + mcp.AddTool(server, &mcp.Tool{Name: "guest_prepare", InputSchema: guestInputSchema("prepare"), Description: "Explicitly prepare the enrolled guest worker using server-provisioned workspace identity"}, a.GuestPrepare) + mcp.AddTool(server, &mcp.Tool{Name: "guest_put", InputSchema: guestInputSchema("put"), Description: "Stream an explicit local source file and return an opaque guest ownership reference"}, a.GuestPut) + mcp.AddTool(server, &mcp.Tool{Name: "guest_get", InputSchema: guestInputSchema("get"), Description: "Download an opaque owned artifact to a new local destination after verification"}, a.GuestGet) + mcp.AddTool(server, &mcp.Tool{Name: "guest_exec", InputSchema: guestInputSchema("exec"), Description: "Execute an explicit local UTF-8 script and publish verified output to a new local destination"}, a.GuestExec) + mcp.AddTool(server, &mcp.Tool{Name: "guest_remove_owned", InputSchema: guestInputSchema("remove-owned"), Description: "Remove only artifacts identified by immutable opaque ownership references"}, a.GuestRemoveOwned) +} + +func validateGuestInput(in GuestInput, operation string) error { + if err := domain.ValidateGuestOperationShape(operation, 0, in.MaxOutput, in.ArtifactIDs); err != nil { + return NewInputError("invalid_argument: " + guestInputDescription(operation)) + } + payload := operation == "put" || operation == "exec" + output := operation == "get" || operation == "exec" + if (in.Source != "") != payload || (in.Destination != "") != output { + return NewInputError("invalid_argument: " + guestInputDescription(operation)) + } + return nil +} + +func guestInputDescription(operation string) string { + switch operation { + case "prepare": + return "guest_prepare requires max_output=0 and no source, destination or artifact_ids" + case "put": + return "guest_put requires source, max_output=0 and no destination or artifact_ids" + case "get": + return "guest_get requires one artifact_id, positive max_output, destination and no source" + case "exec": + return "guest_exec requires source, destination, max_output between 1 and 16777216 and no artifact_ids" + default: + return "guest_remove_owned requires 1 to 128 unique artifact_ids, max_output=0 and no source or destination" + } +} + +func guestInputSchema(operation string) map[string]any { + properties := map[string]any{ + "target": map[string]any{"type": "string"}, + "reason": map[string]any{"type": "string"}, + "idempotency_key": map[string]any{"type": "string"}, + "deadline": map[string]any{"type": "string", "description": "Exact canonical RFC3339Nano operation deadline"}, + "approval_id": map[string]any{"type": "string"}, + "max_output": map[string]any{"type": "integer", "minimum": 0, "maximum": 0, "description": "Must be zero; this operation produces no output stream"}, + } + required := []string{"reason", "idempotency_key", "deadline"} + if operation == "put" || operation == "exec" { + properties["source"] = map[string]any{"type": "string", "minLength": 1, "description": "Explicit local payload path, never sent to the guest; exec accepts UTF-8 scripts up to 16 MiB"} + required = append(required, "source") + } + if operation == "get" || operation == "exec" { + maximum := int64(1 << 40) + if operation == "exec" { + maximum = 16 * 1024 * 1024 + } + properties["max_output"] = map[string]any{"type": "integer", "minimum": 1, "maximum": maximum, "description": "Positive maximum output bytes; output exceeding this limit is rejected"} + properties["destination"] = map[string]any{"type": "string", "minLength": 1, "description": "Explicit new local output path; existing files are never replaced"} + required = append(required, "max_output", "destination") + } + if operation == "get" || operation == "remove-owned" { + maximum := 128 + if operation == "get" { + maximum = 1 + } + properties["artifact_ids"] = map[string]any{"type": "array", "minItems": 1, "maxItems": maximum, "uniqueItems": true, "items": map[string]any{"type": "string", "pattern": "^[0-9a-f]{32}$"}, "description": "Opaque ownership references returned by guest_put"} + required = append(required, "artifact_ids") + } + return map[string]any{"type": "object", "description": guestInputDescription(operation), "properties": properties, "required": required, "additionalProperties": false} } diff --git a/internal/mcpadapter/guest_test.go b/internal/mcpadapter/guest_test.go index e7e20a7..41be816 100644 --- a/internal/mcpadapter/guest_test.go +++ b/internal/mcpadapter/guest_test.go @@ -110,12 +110,16 @@ func assertGuestMCPUploadBinding(t *testing.T, p app.GuestOperationParams, input } func guestMCPCaseInput(operation, source, directory string) GuestInput { - in := GuestInput{Target: "synthetic-target", Reason: "contract", ApprovalID: "synthetic-grant", IdempotencyKey: "request-" + operation, Deadline: time.Now().Add(time.Minute).Format(time.RFC3339Nano), MaxOutput: 64} + in := GuestInput{Target: "synthetic-target", Reason: "contract", ApprovalID: "synthetic-grant", IdempotencyKey: "request-" + operation, Deadline: time.Now().Add(time.Minute).Format(time.RFC3339Nano)} if operation == "put" || operation == "exec" { in.Source = source } if operation == "get" || operation == "exec" { in.Destination = filepath.Join(directory, operation+".bin") + in.MaxOutput = 64 + } + if operation == "get" || operation == "remove-owned" { + in.ArtifactIDs = []string{strings.Repeat("a", 32)} } return in } diff --git a/internal/mcpadapter/guest_validation_test.go b/internal/mcpadapter/guest_validation_test.go new file mode 100644 index 0000000..444b942 --- /dev/null +++ b/internal/mcpadapter/guest_validation_test.go @@ -0,0 +1,109 @@ +package mcpadapter + +import ( + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Horcag/agent-machine-control/internal/client" + "github.com/Horcag/agent-machine-control/internal/daemon" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestGuestMCPMalformedShapesNeverDispatch(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ })) + defer server.Close() + a := &Adapter{client: client.New(server.URL, "synthetic")} + for _, tc := range []struct { + operation string + mutate func(*GuestInput) + }{ + {"prepare", func(in *GuestInput) { in.MaxOutput = 64 }}, + {"prepare", func(in *GuestInput) { in.ArtifactIDs = []string{strings.Repeat("a", 32)} }}, + {"put", func(in *GuestInput) { in.MaxOutput = 1 }}, + {"put", func(in *GuestInput) { in.ArtifactIDs = []string{strings.Repeat("a", 32)} }}, + {"get", func(in *GuestInput) { in.ArtifactIDs = nil }}, + {"get", func(in *GuestInput) { in.Source = "private-secret-path" }}, + {"exec", func(in *GuestInput) { in.MaxOutput = 16*1024*1024 + 1 }}, + {"exec", func(in *GuestInput) { in.ArtifactIDs = []string{strings.Repeat("a", 32)} }}, + {"remove-owned", func(in *GuestInput) { in.ArtifactIDs = nil }}, + {"remove-owned", func(in *GuestInput) { in.MaxOutput = 1 }}, + } { + in := guestMCPCaseInput(tc.operation, "private-secret-path", t.TempDir()) + tc.mutate(&in) + result, _, err := callGuestMCP(a, t, in, tc.operation) + if err != nil || result == nil || !result.IsError { + t.Fatalf("%s: %+v %v", tc.operation, result, err) + } + text := result.Content[0].(*mcp.TextContent).Text + if !strings.Contains(text, "invalid_argument") || !strings.Contains(text, "guest_") || strings.Contains(text, "private-secret") { + t.Fatalf("unsafe or unhelpful error: %q", text) + } + } + if calls != 0 { + t.Fatalf("invalid requests dispatched %d times", calls) + } +} + +func TestGuestMCPTypedDenialAcrossTransports(t *testing.T) { + for _, category := range []string{"approval_required", "guest_workspace_unprovisioned", "invalid_argument", "guest_uncertain"} { + t.Run(category, func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + if _, _, err := daemon.DecodeGuestMetadata(r.Body); err != nil { + t.Error(err) + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Trailer", daemon.GuestResultTrailer) + data, _ := json.Marshal(daemon.GuestFinal{Category: category, Error: "private-secret-path-token"}) + w.Header().Set(daemon.GuestResultTrailer, base64.RawStdEncoding.EncodeToString(data)) + })) + defer server.Close() + a := &Adapter{client: client.New(server.URL, "synthetic")} + cs := recordingMCPClient(t, a) + result, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "guest_prepare", Arguments: guestMCPCaseInput("prepare", "", t.TempDir())}) + if err != nil || result == nil || !result.IsError || calls != 1 { + t.Fatalf("result=%+v calls=%d err=%v", result, calls, err) + } + text := result.Content[0].(*mcp.TextContent).Text + if !strings.Contains(text, category) || strings.Contains(text, "private") { + t.Fatalf("category lost or secret exposed: %q", text) + } + }) + } +} + +func TestGuestMCPSchemasRejectIrrelevantFieldsBeforeHTTP(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ })) + defer server.Close() + cs := recordingMCPClient(t, &Adapter{client: client.New(server.URL, "synthetic")}) + for _, tc := range []struct { + operation, field string + value any + }{ + {"prepare", "source", "private-secret-path"}, {"prepare", "max_output", 64}, + {"put", "destination", "private-secret-path"}, {"get", "source", "private-secret-path"}, + {"exec", "artifact_ids", []string{strings.Repeat("a", 32)}}, {"remove-owned", "destination", "private-secret-path"}, + } { + in := guestMCPCaseInput(tc.operation, "private-secret-path", t.TempDir()) + encoded, _ := json.Marshal(in) + var arguments map[string]any + if err := json.Unmarshal(encoded, &arguments); err != nil { + t.Fatal(err) + } + arguments[tc.field] = tc.value + result, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "guest_" + strings.ReplaceAll(tc.operation, "-", "_"), Arguments: arguments}) + if err == nil && (result == nil || !result.IsError) { + t.Fatalf("schema admitted %s %s: %+v", tc.operation, tc.field, result) + } + } + if calls != 0 { + t.Fatalf("malformed schema input reached HTTP %d times", calls) + } +} diff --git a/internal/mcpadapter/testdata/schemas/tools.json b/internal/mcpadapter/testdata/schemas/tools.json index 0a7628c..77cced8 100644 --- a/internal/mcpadapter/testdata/schemas/tools.json +++ b/internal/mcpadapter/testdata/schemas/tools.json @@ -2356,38 +2356,35 @@ "description": "Execute an explicit local UTF-8 script and publish verified output to a new local destination", "inputSchema": { "additionalProperties": false, + "description": "guest_exec requires source, destination, max_output between 1 and 16777216 and no artifact_ids", "properties": { "approval_id": { "type": "string" }, - "artifact_ids": { - "items": { - "type": "string" - }, - "type": [ - "null", - "array" - ] - }, "deadline": { "description": "Exact canonical RFC3339Nano operation deadline", "type": "string" }, "destination": { - "description": "Explicit new local output path", + "description": "Explicit new local output path; existing files are never replaced", + "minLength": 1, "type": "string" }, "idempotency_key": { "type": "string" }, "max_output": { + "description": "Positive maximum output bytes; output exceeding this limit is rejected", + "maximum": 16777216, + "minimum": 1, "type": "integer" }, "reason": { "type": "string" }, "source": { - "description": "Explicit local payload path, never sent to the guest", + "description": "Explicit local payload path, never sent to the guest; exec accepts UTF-8 scripts up to 16 MiB", + "minLength": 1, "type": "string" }, "target": { @@ -2395,10 +2392,12 @@ } }, "required": [ - "max_output", "reason", "idempotency_key", - "deadline" + "deadline", + "source", + "max_output", + "destination" ], "type": "object" }, @@ -2622,49 +2621,54 @@ "description": "Download an opaque owned artifact to a new local destination after verification", "inputSchema": { "additionalProperties": false, + "description": "guest_get requires one artifact_id, positive max_output, destination and no source", "properties": { "approval_id": { "type": "string" }, "artifact_ids": { + "description": "Opaque ownership references returned by guest_put", "items": { + "pattern": "^[0-9a-f]{32}$", "type": "string" }, - "type": [ - "null", - "array" - ] + "maxItems": 1, + "minItems": 1, + "type": "array", + "uniqueItems": true }, "deadline": { "description": "Exact canonical RFC3339Nano operation deadline", "type": "string" }, "destination": { - "description": "Explicit new local output path", + "description": "Explicit new local output path; existing files are never replaced", + "minLength": 1, "type": "string" }, "idempotency_key": { "type": "string" }, "max_output": { + "description": "Positive maximum output bytes; output exceeding this limit is rejected", + "maximum": 1099511627776, + "minimum": 1, "type": "integer" }, "reason": { "type": "string" }, - "source": { - "description": "Explicit local payload path, never sent to the guest", - "type": "string" - }, "target": { "type": "string" } }, "required": [ - "max_output", "reason", "idempotency_key", - "deadline" + "deadline", + "max_output", + "destination", + "artifact_ids" ], "type": "object" }, @@ -2888,46 +2892,32 @@ "description": "Explicitly prepare the enrolled guest worker using server-provisioned workspace identity", "inputSchema": { "additionalProperties": false, + "description": "guest_prepare requires max_output=0 and no source, destination or artifact_ids", "properties": { "approval_id": { "type": "string" }, - "artifact_ids": { - "items": { - "type": "string" - }, - "type": [ - "null", - "array" - ] - }, "deadline": { "description": "Exact canonical RFC3339Nano operation deadline", "type": "string" }, - "destination": { - "description": "Explicit new local output path", - "type": "string" - }, "idempotency_key": { "type": "string" }, "max_output": { + "description": "Must be zero; this operation produces no output stream", + "maximum": 0, + "minimum": 0, "type": "integer" }, "reason": { "type": "string" }, - "source": { - "description": "Explicit local payload path, never sent to the guest", - "type": "string" - }, "target": { "type": "string" } }, "required": [ - "max_output", "reason", "idempotency_key", "deadline" @@ -3154,38 +3144,30 @@ "description": "Stream an explicit local source file and return an opaque guest ownership reference", "inputSchema": { "additionalProperties": false, + "description": "guest_put requires source, max_output=0 and no destination or artifact_ids", "properties": { "approval_id": { "type": "string" }, - "artifact_ids": { - "items": { - "type": "string" - }, - "type": [ - "null", - "array" - ] - }, "deadline": { "description": "Exact canonical RFC3339Nano operation deadline", "type": "string" }, - "destination": { - "description": "Explicit new local output path", - "type": "string" - }, "idempotency_key": { "type": "string" }, "max_output": { + "description": "Must be zero; this operation produces no output stream", + "maximum": 0, + "minimum": 0, "type": "integer" }, "reason": { "type": "string" }, "source": { - "description": "Explicit local payload path, never sent to the guest", + "description": "Explicit local payload path, never sent to the guest; exec accepts UTF-8 scripts up to 16 MiB", + "minLength": 1, "type": "string" }, "target": { @@ -3193,10 +3175,10 @@ } }, "required": [ - "max_output", "reason", "idempotency_key", - "deadline" + "deadline", + "source" ], "type": "object" }, @@ -3420,49 +3402,47 @@ "description": "Remove only artifacts identified by immutable opaque ownership references", "inputSchema": { "additionalProperties": false, + "description": "guest_remove_owned requires 1 to 128 unique artifact_ids, max_output=0 and no source or destination", "properties": { "approval_id": { "type": "string" }, "artifact_ids": { + "description": "Opaque ownership references returned by guest_put", "items": { + "pattern": "^[0-9a-f]{32}$", "type": "string" }, - "type": [ - "null", - "array" - ] + "maxItems": 128, + "minItems": 1, + "type": "array", + "uniqueItems": true }, "deadline": { "description": "Exact canonical RFC3339Nano operation deadline", "type": "string" }, - "destination": { - "description": "Explicit new local output path", - "type": "string" - }, "idempotency_key": { "type": "string" }, "max_output": { + "description": "Must be zero; this operation produces no output stream", + "maximum": 0, + "minimum": 0, "type": "integer" }, "reason": { "type": "string" }, - "source": { - "description": "Explicit local payload path, never sent to the guest", - "type": "string" - }, "target": { "type": "string" } }, "required": [ - "max_output", "reason", "idempotency_key", - "deadline" + "deadline", + "artifact_ids" ], "type": "object" }, From cdbfeaba5219e67de75dd1d1386235e28a68b91d Mon Sep 17 00:00:00 2001 From: Lebedev Nikita Date: Wed, 21 Oct 2026 05:30:31 +0400 Subject: [PATCH 2/4] fix(protocol): negotiate persistent lab grant responses --- internal/client/client.go | 4 ++ internal/client/desktop_test.go | 6 ++ internal/daemon/handlers_console.go | 2 +- internal/daemon/handlers_desktop.go | 15 +++- internal/daemon/handlers_lab_compat_test.go | 79 +++++++++++++++++++++ 5 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 internal/daemon/handlers_lab_compat_test.go diff --git a/internal/client/client.go b/internal/client/client.go index c239479..a5984d6 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -112,6 +112,10 @@ func (c *Client) doRequest(ctx context.Context, method, path string, body any, o } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token)) + switch path { + case "/v1/desktop/lab/issue", "/v1/desktop/lab/status", "/v1/desktop/lab/active": + req.Header.Set(daemon.LabGrantModeHeader, "1") + } if body != nil { req.Header.Set("Content-Type", "application/json") } diff --git a/internal/client/desktop_test.go b/internal/client/desktop_test.go index 30ab1b3..cde19df 100644 --- a/internal/client/desktop_test.go +++ b/internal/client/desktop_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/daemon" "github.com/Horcag/agent-machine-control/internal/domain" ) @@ -56,6 +57,11 @@ func TestDesktopClientAuthenticatedContracts(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ assertDesktopClientRequest(t, r, tc.path, tc.request) + if tc.name == "issue" || tc.name == "status" || tc.name == "active" { + if r.Header.Get(daemon.LabGrantModeHeader) != "1" { + t.Error("lab response extension was not negotiated") + } + } if err := json.NewEncoder(w).Encode(tc.response); err != nil { t.Error(err) } diff --git a/internal/daemon/handlers_console.go b/internal/daemon/handlers_console.go index 8de5556..95e0c0f 100644 --- a/internal/daemon/handlers_console.go +++ b/internal/daemon/handlers_console.go @@ -18,7 +18,7 @@ func (s *Server) dispatchConsole(w http.ResponseWriter, r *http.Request, path st writeError(w, http.StatusUnauthorized, "unauthorized", "unauthenticated caller") return } - if s.consoleService == nil { + if s.consoleService == nil || s.desktopService == nil { writeError(w, http.StatusNotImplemented, "capability_unavailable", "console provider unavailable") return } diff --git a/internal/daemon/handlers_desktop.go b/internal/daemon/handlers_desktop.go index 4554ca3..1a4b419 100644 --- a/internal/daemon/handlers_desktop.go +++ b/internal/daemon/handlers_desktop.go @@ -128,6 +128,9 @@ func (s *Server) dispatchDesktop(w http.ResponseWriter, r *http.Request, path st } } +// LabGrantModeHeader opts into the persistent grant mode response field. +const LabGrantModeHeader = "X-AMC-Lab-Grant-Mode" + func (s *Server) dispatchDesktopLab(w http.ResponseWriter, r *http.Request, path string) { actor, _ := getCallerContext(r.Context()) switch path { @@ -145,7 +148,7 @@ func (s *Server) dispatchDesktopLab(w http.ResponseWriter, r *http.Request, path writeJSON(w, http.StatusOK, struct { Grant app.ConsoleLabGrant `json:"grant"` Receipt any `json:"receipt"` - }{grant, rcpt}) + }{labGrantResponse(r, grant), rcpt}) case "desktop/lab/status": var req struct { GrantID string `json:"grant_id"` @@ -159,6 +162,7 @@ func (s *Server) dispatchDesktopLab(w http.ResponseWriter, r *http.Request, path writeConsoleError(w, err) return } + out.Grant = labGrantResponse(r, out.Grant) writeJSON(w, http.StatusOK, out) case "desktop/lab/active": var req struct { @@ -173,6 +177,7 @@ func (s *Server) dispatchDesktopLab(w http.ResponseWriter, r *http.Request, path writeConsoleError(w, err) return } + out.Grant = labGrantResponse(r, out.Grant) writeJSON(w, http.StatusOK, out) case "desktop/lab/revoke": var req app.ConsoleLabGrantRevokeRequest @@ -190,3 +195,11 @@ func (s *Server) dispatchDesktopLab(w http.ResponseWriter, r *http.Request, path writeError(w, http.StatusNotFound, "not_found", "endpoint not found") } } + +// The protected grant retains its mode; only the legacy wire projection omits it. +func labGrantResponse(r *http.Request, grant app.ConsoleLabGrant) app.ConsoleLabGrant { + if r.Header.Get(LabGrantModeHeader) != "1" { + grant.Mode = "" + } + return grant +} diff --git a/internal/daemon/handlers_lab_compat_test.go b/internal/daemon/handlers_lab_compat_test.go new file mode 100644 index 0000000..63c77aa --- /dev/null +++ b/internal/daemon/handlers_lab_compat_test.go @@ -0,0 +1,79 @@ +package daemon_test + +import ( + "bytes" + "encoding/json" + "net/http" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/app" + "github.com/Horcag/agent-machine-control/internal/client" + "github.com/Horcag/agent-machine-control/internal/domain" +) + +// Matches the installed client's strict schema before persistent authority. +type legacyLabGrant struct { + AcknowledgeExternalEffects bool `json:"acknowledge_external_effects"` + SchemaVersion int `json:"schema_version"` + GrantID string `json:"grant_id"` + Target domain.MachineRef `json:"target"` + EnrollmentIdentity string `json:"enrollment_identity"` + Issuer domain.ActorID `json:"issuer"` + Beneficiary domain.ActorID `json:"beneficiary"` + Reason string `json:"reason"` + IdempotencyKey string `json:"idempotency_key"` + IssuedAt time.Time `json:"issued_at"` + ExpiresAt time.Time `json:"expires_at"` +} + +func TestLabGrantModeWireNegotiationPreservesLegacyStrictClients(t *testing.T) { + endpoint, operator, agent := setupConsoleDaemon(t, &consoleDaemonBackend{mockDaemonBackend: &mockDaemonBackend{}}) + request := app.ConsoleLabGrantIssueRequest{Mode: app.ConsoleLabModePersistentVM, Target: "default", Reason: "persistent compatibility fixture", IdempotencyKey: "wire-compatibility", Beneficiary: "agent:mcp-local", AcknowledgeExternalEffects: true} + status, body := doJSONReq(t, http.MethodPost, endpoint+"/v1/desktop/lab/issue", operator, request) + var issued struct { + Grant legacyLabGrant `json:"grant"` + Receipt domain.Receipt `json:"receipt"` + } + strictLabDecode(t, status, body, &issued) + if issued.Grant.GrantID == "" || !issued.Grant.ExpiresAt.IsZero() { + t.Fatalf("legacy issue: %+v", issued.Grant) + } + for _, route := range []string{"status", "active"} { + payload := map[string]string{"grant_id": issued.Grant.GrantID} + if route == "active" { + payload = map[string]string{"target": "default"} + } + status, body = doJSONReq(t, http.MethodPost, endpoint+"/v1/desktop/lab/"+route, agent, payload) + var legacy struct { + Grant legacyLabGrant `json:"grant"` + State string `json:"state"` + } + strictLabDecode(t, status, body, &legacy) + if legacy.State != "active" || legacy.Grant.GrantID != issued.Grant.GrantID { + t.Fatalf("legacy %s: %+v", route, legacy) + } + } + modern := client.New(endpoint, agent) + active, err := modern.ActiveConsoleLabGrant(t.Context(), "default") + if err != nil || active.Grant.Mode != app.ConsoleLabModePersistentVM || active.Grant.GrantID != issued.Grant.GrantID { + t.Fatalf("modern active: %+v %v", active, err) + } + grant, err := modern.ConsoleLabGrantStatus(t.Context(), issued.Grant.GrantID) + if err != nil || grant.Grant.Mode != app.ConsoleLabModePersistentVM { + t.Fatalf("modern status: %+v %v", grant, err) + } + replay, err := client.New(endpoint, operator).IssueConsoleLabGrant(t.Context(), request) + if err != nil || replay.Grant.Mode != app.ConsoleLabModePersistentVM || replay.Grant.GrantID != issued.Grant.GrantID { + t.Fatalf("modern issue replay: %+v %v", replay, err) + } +} + +func strictLabDecode(t *testing.T, status int, body []byte, out any) { + t.Helper() + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(out); err != nil || status != http.StatusOK { + t.Fatalf("strict legacy status=%d body=%s error=%v", status, body, err) + } +} From 7f559f16997332f7a76262f70616fac8d767fecb Mon Sep 17 00:00:00 2001 From: Lebedev Nikita Date: Wed, 21 Oct 2026 05:36:52 +0400 Subject: [PATCH 3/4] test(lab): cover authority coordination failures Raise the Go minimum to1.26.10 to address GO-2026-6809 in the standard library. --- README.md | 2 +- docs/development.md | 2 +- go.mod | 2 +- internal/app/console_lab_coordination_test.go | 102 ++++++++++++++++++ 4 files changed, 105 insertions(+), 3 deletions(-) create mode 100644 internal/app/console_lab_coordination_test.go diff --git a/README.md b/README.md index a217888..58c4348 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,7 @@ The repository does not claim live Windows acceptance for these capabilities. ## Build the bootstrap -Go 1.26.9 or newer is required. +Go 1.26.10 or newer is required. ```sh go test ./... diff --git a/docs/development.md b/docs/development.md index e8c3f20..8b949d2 100644 --- a/docs/development.md +++ b/docs/development.md @@ -2,7 +2,7 @@ ## Toolchain -- Go 1.26.9 or newer. +- Go 1.26.10 or newer. - `golangci-lint` v2.13.2 for the full lint target. Keep the local and CI versions aligned. - ShellCheck for the small repository shell-tooling surface. - GoReleaser v2 for packaging checks. diff --git a/go.mod b/go.mod index 867325c..46c652f 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/Horcag/agent-machine-control -go 1.26.9 +go 1.26.10 require ( github.com/modelcontextprotocol/go-sdk v1.8.0 diff --git a/internal/app/console_lab_coordination_test.go b/internal/app/console_lab_coordination_test.go new file mode 100644 index 0000000..bb84a39 --- /dev/null +++ b/internal/app/console_lab_coordination_test.go @@ -0,0 +1,102 @@ +package app + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/Horcag/agent-machine-control/internal/approval" + "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/lease" +) + +func coordinationGrantFixture(t *testing.T) (*ConsoleService, ConsoleLabGrant, domain.Operation, domain.ActorContext) { + t.Helper() + h := newGuestHarness(t) + h.actor.AuthenticatedCaller, h.actor.EffectiveActor = "agent:mcp-local", "agent:mcp-local" + h.actor.CallerPermissions[domain.ScopeMachineWrite] = struct{}{} + h.actor.EffectivePermissions[domain.ScopeMachineWrite] = struct{}{} + authority, operator := persistentGuestAuthority(t, h) + grant, _, err := authority.IssueLabGrant(t.Context(), operator, ConsoleLabGrantIssueRequest{Mode: ConsoleLabModePersistentVM, Target: "default", Reason: "exercise VM coordination", IdempotencyKey: "coordination-grant", Beneficiary: "agent:mcp-local", AcknowledgeExternalEffects: true}) + if err != nil { + t.Fatal(err) + } + op := domain.Operation{Kind: "console.input", Target: grant.Target, Actor: h.actor, Reason: "exercise coordinated input", IdempotencyKey: "coordinated-input", Deadline: time.Now().Add(time.Minute), Classification: domain.ClassDestructivePrivileged, RequiredCapability: string(domain.CapabilityConsoleInput), RequiredScopes: []string{domain.ScopeMachineWrite}, EvidenceSensitivity: domain.EvidenceSensitivityStandard, Parameters: domain.ConsoleInputParameters(domain.ConsoleInput{Kind: "key", Key: "enter"})} + return authority, grant, op, operator +} + +func TestPersistentRecoveryCoordinationBindsApprovalAndFencesRevocation(t *testing.T) { + authority, grant, op, operator := coordinationGrantFixture(t) + recovery := authority.recovery + WithRecoveryLabAuthority(authority)(recovery) + req := MutationRequest{TargetID: string(op.Target), Actor: op.Actor, Reason: op.Reason, IdempotencyKey: op.IdempotencyKey, Deadline: op.Deadline} + dispatched := false + admitted, execute, release, err := recovery.coordinatePersistentRecovery(t.Context(), op, req, func(context.Context) error { dispatched = true; return nil }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = release() }) + if admitted.Approval == nil || admitted.ApprovalID != string(admitted.Approval.ID) { + t.Fatal("missing exact derived approval") + } + if err := admitted.Approval.Matches(op); err != nil { + t.Fatalf("derived approval binding: %v", err) + } + revoke := ConsoleLabGrantRevokeRequest{GrantID: grant.GrantID, Reason: "end coordinated authority", IdempotencyKey: "revoke-coordination", Deadline: time.Now().Add(time.Minute).Format(time.RFC3339Nano)} + if _, err := authority.RevokeLabGrant(t.Context(), operator, revoke); !errors.Is(err, lease.ErrLeaseConflict) { + t.Fatalf("revocation crossed active grant lock: %v", err) + } + if err := release(); err != nil { + t.Fatal(err) + } + if _, err := authority.RevokeLabGrant(t.Context(), operator, revoke); err != nil { + t.Fatal(err) + } + if err := execute(t.Context()); !errors.Is(err, ErrInvalidConsoleLabGrant) || dispatched { + t.Fatalf("revoked fenced callback dispatched=%v error=%v", dispatched, err) + } +} + +func TestPersistentRecoveryCoordinationRejectsBusyGrant(t *testing.T) { + authority, grant, op, _ := coordinationGrantFixture(t) + WithRecoveryLabAuthority(authority)(authority.recovery) + held, err := authority.labLock(t.Context(), grant.GrantID) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = held() }) + _, _, release, err := authority.recovery.coordinatePersistentRecovery(t.Context(), op, MutationRequest{}, func(context.Context) error { t.Error("busy grant dispatched"); return nil }) + if !errors.Is(err, lease.ErrLeaseConflict) { + t.Fatalf("busy grant admission: %v", err) + } + if err := release(); err != nil { + t.Fatal(err) + } +} + +func TestPersistentRecoveryCoordinationStorageFailureReleasesGrant(t *testing.T) { + authority, grant, op, _ := coordinationGrantFixture(t) + WithRecoveryLabAuthority(authority)(authority.recovery) + blocked := filepath.Join(t.TempDir(), "blocked-approval-store") + if err := os.WriteFile(blocked, []byte("synthetic storage conflict"), 0600); err != nil { + t.Fatal(err) + } + authority.recovery.approvalStore = approval.NewStore(blocked) + _, _, release, err := authority.recovery.coordinatePersistentRecovery(t.Context(), op, MutationRequest{}, func(context.Context) error { t.Error("failed storage admission dispatched"); return nil }) + if err == nil { + t.Fatal("unwritable approval store admitted mutation") + } + if err := release(); err != nil { + t.Fatal(err) + } + release, err = authority.labLock(t.Context(), grant.GrantID) + if err != nil { + t.Fatalf("failed approval retained grant lock: %v", err) + } + if err := release(); err != nil { + t.Fatal(err) + } +} From 7204ce429c45499be93fba630a71fc99239f36b3 Mon Sep 17 00:00:00 2001 From: Lebedev Nikita Date: Wed, 21 Oct 2026 05:48:52 +0400 Subject: [PATCH 4/4] test(lab): initialize protected state portably --- internal/app/console_lab_guest_test.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/internal/app/console_lab_guest_test.go b/internal/app/console_lab_guest_test.go index 4737751..c3a8d83 100644 --- a/internal/app/console_lab_guest_test.go +++ b/internal/app/console_lab_guest_test.go @@ -3,8 +3,8 @@ package app import ( "context" "github.com/Horcag/agent-machine-control/internal/domain" + "github.com/Horcag/agent-machine-control/internal/statedir" "github.com/Horcag/agent-machine-control/internal/target" - "os" "path/filepath" "strings" "testing" @@ -47,11 +47,16 @@ func persistentGuestAuthority(t *testing.T, h *guestHarness) (*ConsoleService, d if err := inventory.ApplySnapshot(HostSnapshot{HostID: domain.LocalHostID, Health: HostHealthObserved, Machines: []domain.MachineObservation{observed}}); err != nil { t.Fatal(err) } - state := t.TempDir() - if err := os.Mkdir(filepath.Join(state, "targets"), 0700); err != nil { + state, err := statedir.Resolve(filepath.Join(t.TempDir(), "state")) + if err != nil { + t.Fatal(err) + } + // Use the canonical state initializer so Windows creates the directory with + // the current user owner and protected DACL from the start. + if err := state.EnsureDirs(); err != nil { t.Fatal(err) } - store, err := target.NewStore(filepath.Join(state, "targets")) + store, err := target.NewStore(state.TargetsDir()) if err != nil { t.Fatal(err) } @@ -69,7 +74,7 @@ func persistentGuestAuthority(t *testing.T, h *guestHarness) (*ConsoleService, d recovery := &RecoveryService{backend: &guestApprovalBackend{}, leaseManager: coordinator.leaseMgr, auditStore: coordinator.auditStore, receiptStore: coordinator.receiptStore, approvalStore: coordinator.approvalStore} epoch := strings.Repeat("a", 64) options := []ConsoleOption{WithConsoleLabEnrollmentIdentity(func(_ context.Context, _ domain.MachineRef) (string, error) { return epoch, nil })} - authority := NewConsoleService(nil, recovery, targets, filepath.Join(state, "console-frames"), options...) + authority := NewConsoleService(nil, recovery, targets, filepath.Join(state.Root(), "console-frames"), options...) scopes := domain.NewScopeSet(domain.ScopeOperationAdmin) operator, err := domain.NewActorContext("operator:synthetic", "operator:synthetic", scopes, scopes) if err != nil {