diff --git a/README.ja.md b/README.ja.md index 09ce037..8fa0e1b 100644 --- a/README.ja.md +++ b/README.ja.md @@ -2,6 +2,8 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-TW.md) · [日本語](README.ja.md) +> **R12 開発更新:** `feat/r12-dual-mode` にはペアリング済み Agent、暗号化 Relay、操作ごとのローカル承認を必要とする Windows バックエンドが含まれます。既存 GUI/Web の高度な操作画面への接続は未完了です。既定の文書は英語です。[英語 README](README.md)、[開発ガイド](docs/R12_DEVELOPMENT.md)、[GUI 引き継ぎ](docs/GUI_HANDOFF.md)をご覧ください。以下は R11.3 デスクトップの説明です。 + **明示的に許可したローカルワークスペースを探索・検索・読取するための、Windows デスクトップ管理 UI と MCP ツール。** > **R11.3 Desktop Preview。** 独自コードは [MIT](LICENSE)、第三者コードは各自のライセンスです。この時点で公開済み GitHub Release はありません。署名なしのプレビューであり、本番 supervisor やインストーラーではありません。`execution_available=false`、`release_ready=false` は維持されています。 diff --git a/README.md b/README.md index bf885a6..b477c39 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,33 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-TW.md) · [日本語](README.ja.md) -**Windows desktop management and MCP tools for discovering, searching and reading explicitly authorized local workspaces.** +**MCP tools and Windows desktop management for authorized workspace access, with an R12 backend for paired remote Agent operations.** -> **R11.3 Desktop Preview.** Source is available under [MIT](LICENSE), with separate third-party licenses. There is no published GitHub Release at this snapshot. This is an unsigned preview, not a production supervisor or installer; `execution_available=false` and `release_ready=false` remain in effect. +> **R12 backend development branch.** Get the current implementation from `feat/r12-dual-mode`; `main` remains the R11.3 Desktop Preview baseline until reviewed and merged. This is source for development, not a new Release. The existing desktop Developer page still reports `execution_available=false`; the separate paired target can opt into locally approved `trusted_host` operations. `release_ready=false` remains in effect. Project-owned source is [MIT](LICENSE); retain separate third-party licenses. + +## R12: start here + +```powershell +git clone --branch feat/r12-dual-mode git@github.com:LE-saber/Local-Probe.git +Set-Location .\Local-Probe +``` + +Read the [R12 developer guide](docs/R12_DEVELOPMENT.md), [GUI handoff](docs/GUI_HANDOFF.md), and [current status](docs/IMPLEMENTATION_STATUS.md). English is the default documentation language; detailed Chinese design and historical evidence remain available through the [documentation index](docs/README.md). + +| Capability | Current implementation | Remaining work | +| --- | --- | --- | +| Web access to local files | Existing scoped MCP, Cloudflare Access and official OpenAI Tunnel integration | R12 advanced operations are not wired into the Web/desktop ingress | +| Agent access to another environment | Native stdio bridge, persistent pairing/revocation, direct WSS or static self-hosted Relay, inner TLS 1.3 mutual authentication | Certificate automation and production lifecycle management | +| Explicit developer operations | Windows command/script/version/build/test, text writes and exact patches; local per-operation approval, durable jobs, cancellation and bounded output | Trusted GUI management and approval interfaces | +| Concurrency and rules | Two independent connections can each run a job; scoped reads/writes and offline rule management | Full host for at least three independent connections, online rules and selective authorization epochs | + +`trusted_host` runs with the current OS user's actual file and network permissions. It is **not a sandbox**. Existing read-only profiles are not upgraded; operations require an explicit writable v2 profile, `agent_remote`, developer/tool permission, a local runner catalog and exact local approval. See [operation setup and limits](docs/R12_OPERATIONS.md). + +Local Windows operation tests and a public read-only Relay path have been exercised. The new operations have **not** been validated from the additional Linux computer through the real Relay, and Linux target execution/writes are unsupported. If an Agent already has authorized native access to the target workspace, use its native tools rather than this bridge. + +## Existing desktop Preview + +The sections below describe the existing R11.3 desktop behavior. Its saved connection controls and Developer page do not automatically use the new R12 target/Agent backend. ## What you can do @@ -22,7 +46,7 @@ The GUI manages **one selected connection**. Stored connection history is not si Requires Windows x64, WebView2 Runtime and PowerShell 7. Source builds require Go 1.25+ and Git; initial module resolution needs network access or a populated cache. Prepare the official `cloudflared` or `tunnel-client` separately for your chosen connection; neither is bundled. ```powershell -git clone --branch main https://github.com/LE-saber/Local-Probe.git +git clone --branch feat/r12-dual-mode git@github.com:LE-saber/Local-Probe.git Set-Location .\Local-Probe pwsh -NoLogo -NoProfile -File .\scripts\Build-LocalProbeDesktop.ps1 pwsh -NoLogo -NoProfile -File .\scripts\Start-LocalProbeDesktop.ps1 @@ -59,16 +83,21 @@ The older native Preview remains available through [Build-LocalProbePreview.ps1] ## Access and release boundaries -Available files and tools depend on profile roots, tools, deny/ignore rules and read-only policy. The preview does not expose arbitrary shell, arbitrary commands, writes, credential display or model-edited configuration. Backend modules and configuration intent are not proof that execution is enabled. +Available files and tools depend on profile roots, tools, deny/ignore rules and read-only policy. The existing desktop/Web Preview does not expose developer commands or writes. The separate R12 paired target supports explicitly configured and locally approved operations; merely saving a desktop command template does not enable them. Neither path exposes credential display or model-edited configuration. Production supervision/service, a real WFP/broker enforcement path, signing, an installer, automatic updates, Linux/macOS GUI, default large-scale indexing, million-file end-to-end evidence and independent security review are not claimed as delivered. Local checks and historical validation records do not establish those guarantees. The [R11.3 release note](docs/RELEASE_NOTES_R11.3.zh-CN.md) is a draft, not a published release. ## Guides and evidence -Most detailed implementation guides remain in Simplified Chinese; these links preserve the existing documentation. +Start with the English R12 guides. Detailed historical implementation plans remain in Simplified Chinese. | Guide | Contents | | --- | --- | +| [R12 development](docs/R12_DEVELOPMENT.md) | Source checkout, component map, verification and remaining backend work | +| [GUI handoff](docs/GUI_HANDOFF.md) | Approved design, existing/proposed interfaces and acceptance requirements | +| [Operations](docs/R12_OPERATIONS.md) | Explicit trusted-host setup, approvals, jobs and file semantics | +| [Pairing and transport](docs/R12_PAIRING_AND_TRANSPORT.md) | Endpoint pairing, Tunnel/Relay startup and trust boundaries | +| [Documentation index](docs/README.md) | English entry points and Chinese design/evidence references | | [Deployment](docs/DEPLOYMENT_PREVIEW.zh-CN.md) | Dependencies, configuration, workspaces and troubleshooting | | [Desktop GUI](docs/DESKTOP_PREVIEW.zh-CN.md) | Interface, backups, file rules and verification boundaries | | [Native Preview](docs/PREVIEW.zh-CN.md) | Older GUI, tray, workspaces and diagnostics | diff --git a/README.zh-CN.md b/README.zh-CN.md index f143692..fa1de8a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -2,6 +2,8 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-TW.md) · [日本語](README.ja.md) +> **R12 开发更新:** 当前分支 `feat/r12-dual-mode` 包含配对 Agent、加密 Relay 和逐次本地批准的 Windows 操作后端;尚未接入旧 GUI/Web 高级入口。仓库默认文档为英文,请先看[英文首页](README.md)、[开发指南](docs/R12_DEVELOPMENT.md)和[GUI交接](docs/GUI_HANDOFF.md)。下文保留 R11.3 桌面基线说明,不代表新独立后端的完整能力。 + Local-Probe 是面向 Windows 的本地 MCP 工具与桌面 GUI:让 ChatGPT 在明确授权的工作空间内发现、搜索和读取文件。当前版本为 **R11.3 Desktop Preview**,自有源码采用 [MIT](LICENSE);它不是生产级 supervisor、安装器或签名稳定版。 ## 桌面 GUI(推荐) diff --git a/README.zh-TW.md b/README.zh-TW.md index 1098b7f..866db0f 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -2,6 +2,8 @@ [English](README.md) · [简体中文](README.zh-CN.md) · [繁體中文](README.zh-TW.md) · [日本語](README.ja.md) +> **R12 開發更新:** `feat/r12-dual-mode` 已包含配對 Agent、加密 Relay 與逐次本機核准的 Windows 操作後端;舊 GUI/Web 進階入口尚未接入。英文為預設文件語言,請先閱讀[英文首頁](README.md)、[開發指南](docs/R12_DEVELOPMENT.md)及 [GUI 交接](docs/GUI_HANDOFF.md)。以下保留 R11.3 桌面基線說明。 + **Windows 桌面管理介面與 MCP 工具,讓 AI 探索、搜尋及讀取明確授權的本機工作區。** > **R11.3 Desktop Preview。** 自有原始碼採 [MIT](LICENSE),第三方授權另列。目前快照沒有已發布的 GitHub Release。這是未簽章預覽版,並非正式 supervisor 或安裝程式;`execution_available=false`、`release_ready=false` 維持不變。 diff --git a/cmd/local-probe-agent/main.go b/cmd/local-probe-agent/main.go new file mode 100644 index 0000000..f88198b --- /dev/null +++ b/cmd/local-probe-agent/main.go @@ -0,0 +1,90 @@ +// local-probe-agent is started by an Agent's native MCP stdio client. Stdout is +// reserved for the official SDK; credentials are read from local environment. +package main + +import ( + "context" + "crypto/tls" + "errors" + "flag" + "fmt" + "net/http" + "os" + "os/signal" + "syscall" + + "github.com/LE-saber/Local-Probe/internal/agentbridge" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func main() { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + if err := run(ctx, os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "local-probe-agent:", err) + os.Exit(1) + } +} +func run(ctx context.Context, args []string) error { + f := flag.NewFlagSet("local-probe-agent", flag.ContinueOnError) + f.SetOutput(os.Stderr) + path := f.String("store", "", "absolute paired Agent identity directory") + endpoint := f.String("endpoint", "", "explicit wss:// Tunnel or Relay data endpoint") + transport := f.String("transport", "tunnel", "tunnel or relay") + outerCA := f.String("outer-ca-file", "", "optional absolute public CA PEM for private Relay/edge TLS") + if err := f.Parse(args); err != nil { + return err + } + if f.NArg() != 0 { + return errors.New("unexpected positional argument") + } + store, err := deviceidentity.OpenStore(*path) + if err != nil { + return err + } + defer store.Close() + inner, err := store.ClientTLS() + if err != nil { + return err + } + headers := http.Header{} + if value := os.Getenv("LOCAL_PROBE_AGENT_ACCESS_TOKEN"); value != "" { + headers.Set("Authorization", "Bearer "+value) + } + id, secret := os.Getenv("LOCAL_PROBE_CF_CLIENT_ID"), os.Getenv("LOCAL_PROBE_CF_CLIENT_SECRET") + if (id == "") != (secret == "") { + return errors.New("both Cloudflare credential environment references are required") + } + if id != "" { + headers.Set("CF-Access-Client-Id", id) + headers.Set("CF-Access-Client-Secret", secret) + } + if *transport != "tunnel" && *transport != "relay" { + return errors.New("transport must be tunnel or relay") + } + roots, err := peertransport.LoadPublicRoots(*outerCA) + if err != nil { + return err + } + newClient := func(endpoint string, inner *tls.Config, headers http.Header) (*http.Client, func(), error) { + return peertransport.HTTPClientWithRoots(endpoint, inner, headers, roots) + } + if *transport == "relay" { + newClient = func(endpoint string, inner *tls.Config, headers http.Header) (*http.Client, func(), error) { + return peertransport.RelayHTTPClient(endpoint, inner, headers, roots) + } + } + client, closeTransport, err := newClient(*endpoint, inner, headers) + if err != nil { + return err + } + defer closeTransport() + server, remote, err := agentbridge.New(ctx, client) + if err != nil { + return err + } + defer remote.Close() + return server.Run(ctx, &mcp.StdioTransport{}) +} diff --git a/cmd/local-probe-operations/main.go b/cmd/local-probe-operations/main.go new file mode 100644 index 0000000..6c84fe9 --- /dev/null +++ b/cmd/local-probe-operations/main.go @@ -0,0 +1,74 @@ +// local-probe-operations is an owner-only approval/inspection CLI. It never +// runs commands and has no network listener or remote approval endpoint. +package main + +import ( + "encoding/json" + "errors" + "flag" + "fmt" + "github.com/LE-saber/Local-Probe/internal/operations" + "os" +) + +func main() { + if err := run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "local-probe-operations:", err) + os.Exit(1) + } +} +func run(args []string) error { + f := flag.NewFlagSet("local-probe-operations", flag.ContinueOnError) + root := f.String("journal", "", "absolute private operation journal, outside all workspaces") + action := f.String("action", "list", "init, list, inspect, approve, reject, cancel or before") + id := f.String("id", "", "operation ID") + expected := f.String("digest", "", "exact plan digest shown by inspect") + ack := f.Bool("ack-trusted-host", false, "acknowledge current-user file/network access; not a sandbox") + if err := f.Parse(args); err != nil { + return err + } + if f.NArg() != 0 { + return errors.New("unexpected arguments") + } + j, err := operations.OpenJournal(*root, *action == "init") + if err != nil { + return err + } + defer j.Close() + if *action == "init" { + return j.Initialize() + } + switch *action { + case "cancel": + return j.CancelLocal(*id, *expected) + case "before": + b, err := j.BeforeImage(*id, *expected) + if err != nil { + return err + } + return json.NewEncoder(os.Stdout).Encode(struct { + Data []byte `json:"data_base64"` + }{b}) + case "approve", "reject": + return j.Decide(*id, *expected, *action == "approve", *ack) + case "list", "inspect": + records, err := j.Records() + if err != nil { + return err + } + if *action == "inspect" { + r, ok := records[*id] + if !ok { + return operations.ErrDenied + } + return json.NewEncoder(os.Stdout).Encode(r) + } + out := []operations.Summary{} + for _, r := range records { + out = append(out, r.Summary) + } + return json.NewEncoder(os.Stdout).Encode(out) + default: + return errors.New("unsupported action") + } +} diff --git a/cmd/local-probe-pair/main.go b/cmd/local-probe-pair/main.go new file mode 100644 index 0000000..37e63ae --- /dev/null +++ b/cmd/local-probe-pair/main.go @@ -0,0 +1,181 @@ +// local-probe-pair is an OFFLINE owner-management tool. It has no listener and +// never prints private keys. Mutations require explicit local acknowledgements. +package main + +import ( + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "time" + + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/peertransport" +) + +func main() { + if err := run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr); err != nil { + fmt.Fprintln(os.Stderr, "local-probe-pair:", err) + os.Exit(1) + } +} +func run(args []string, in io.Reader, out, stderr io.Writer) error { + f := flag.NewFlagSet("local-probe-pair", flag.ContinueOnError) + f.SetOutput(stderr) + action := f.String("action", "show", "target-init, agent-init, request, issue, install, revoke, show") + path := f.String("store", "", "explicit absolute private identity directory") + expected := f.String("fingerprint", "", "independently reviewed public bundle/CSR fingerprint") + connection := f.String("connection-id", "", "locally selected existing target connection") + configPath := f.String("config", "", "absolute target config, mandatory for issue") + keyPin := f.String("key-pin", "", "public Agent key pin to revoke") + approve := f.Bool("approve", false, "local user approves the exact pairing/revocation") + offline := f.Bool("offline", false, "all runtimes using this identity store are stopped") + if err := f.Parse(args); err != nil { + return err + } + read := func(value any) error { + data, err := io.ReadAll(io.LimitReader(in, deviceidentity.MaxArtifactBytes+1)) + if err != nil { + return deviceidentity.ErrInvalid + } + return deviceidentity.DecodePublic(data, value) + } + if f.NArg() == 0 && (*action == "fingerprint-request" || *action == "fingerprint-bundle") { + var fingerprint string + var err error + if *action == "fingerprint-request" { + var r deviceidentity.Request + if err = read(&r); err == nil { + fingerprint, err = r.Fingerprint() + } + } else { + var b deviceidentity.Bundle + if err = read(&b); err == nil { + fingerprint, err = b.Fingerprint() + } + } + if err != nil { + return err + } + _, err = fmt.Fprintln(out, fingerprint) + return err + } + if f.NArg() != 0 || *path == "" { + return errors.New("provide explicit -store and no positional arguments") + } + if *action == "target-init" || *action == "agent-init" { + if !*approve || !*offline { + return errors.New("initialization requires -approve -offline") + } + s, err := deviceidentity.CreateStore(*path) + if err != nil { + return err + } + defer s.Close() + if *action == "target-init" { + a, err := deviceidentity.NewAuthority() + if err != nil { + return err + } + if err = s.SaveAuthority(a); err != nil { + return err + } + return json.NewEncoder(out).Encode(a.Bundle()) + } + a, r, err := deviceidentity.NewAgent() + if err != nil { + return err + } + if err = s.SaveAgent(a); err != nil { + return err + } + return json.NewEncoder(out).Encode(r) + } + s, err := deviceidentity.OpenStore(*path) + if err != nil { + return err + } + defer s.Close() + switch *action { + case "request": + a, err := s.LoadAgent() + if err != nil { + return err + } + r, err := a.Request() + if err != nil { + return err + } + return json.NewEncoder(out).Encode(r) + case "show": + a, err := s.LoadAuthority() + if err == nil { + return json.NewEncoder(out).Encode(a.Bundle()) + } + p, err := s.LoadPairing() + if err != nil { + return err + } + return json.NewEncoder(out).Encode(p) + case "issue": + if !*approve || !*offline || *expected == "" || *configPath == "" || *connection == "" { + return errors.New("issue requires -approve -offline -fingerprint -config -connection-id") + } + store, err := config.NewFileStore(*configPath) + if err != nil { + return errors.New("invalid target config") + } + snapshot, err := store.Load() + if err != nil { + return errors.New("target config unavailable") + } + c, ok := snapshot.Config().Connection(*connection) + if !ok || !c.Enabled() || c.Purpose() != config.PurposeAgentRemote { + return errors.New("select an enabled agent_remote connection") + } + var r deviceidentity.Request + if err := read(&r); err != nil { + return err + } + g, err := s.IssueGrant(r, *expected, *connection, 30*24*time.Hour) + if err != nil { + return err + } + a, err := s.LoadAuthority() + if err != nil { + return err + } + b := a.Bundle() + fingerprint, err := b.Fingerprint() + if err != nil { + return err + } + return json.NewEncoder(out).Encode(deviceidentity.Pairing{Version: deviceidentity.Version, Bundle: b, Grant: g, Fingerprint: fingerprint}) + case "install": + if !*approve || !*offline || *expected == "" { + return errors.New("install requires -approve -offline -fingerprint") + } + var p deviceidentity.Pairing + if err := read(&p); err != nil { + return err + } + return s.InstallPairing(p, *expected) + case "revoke": + if !*approve || !*offline { + return errors.New("offline revocation requires -approve -offline") + } + b, err := hex.DecodeString(*keyPin) + if err != nil || len(b) != 32 { + return deviceidentity.ErrInvalid + } + var pin peertransport.Pin + copy(pin[:], b) + return s.Revoke(pin) + default: + return errors.New("unsupported pairing action") + } +} diff --git a/cmd/local-probe-pair/main_test.go b/cmd/local-probe-pair/main_test.go new file mode 100644 index 0000000..dcf8884 --- /dev/null +++ b/cmd/local-probe-pair/main_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "bytes" + "encoding/json" + "path/filepath" + "strings" + "testing" + + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" +) + +func TestOfflinePairingWorkflowAndMandatoryAcknowledgements(t *testing.T) { + base := t.TempDir() + target, agent := filepath.Join(base, "target"), filepath.Join(base, "agent") + call := func(input []byte, args ...string) ([]byte, error) { + t.Helper() + var out, stderr bytes.Buffer + err := run(args, bytes.NewReader(input), &out, &stderr) + return out.Bytes(), err + } + if _, err := call(nil, "-store", target, "-action", "target-init"); err == nil { + t.Fatal("initialized without approval") + } + bundle, err := call(nil, "-store", target, "-action", "target-init", "-approve", "-offline") + if err != nil { + t.Fatal(err) + } + request, err := call(nil, "-store", agent, "-action", "agent-init", "-approve", "-offline") + if err != nil { + t.Fatal(err) + } + bfp, err := call(bundle, "-action", "fingerprint-bundle") + if err != nil { + t.Fatal(err) + } + rfp, err := call(request, "-action", "fingerprint-request") + if err != nil { + t.Fatal(err) + } + conn, err := config.NewConnection("remote-a", "remote", "profile-a", "credential-a", true).WithPurpose(config.PurposeAgentRemote) + if err != nil { + t.Fatal(err) + } + profile, err := config.NewProfile("profile-a", nil, []string{"server_info"}, nil) + if err != nil { + t.Fatal(err) + } + cfg, err := config.New(config.SchemaVersionV2, nil, []config.Profile{profile}, []config.Connection{conn}, []config.CredentialRef{config.NewCredentialRef("credential-a", "runtime")}) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(base, "config.json") + cs, err := config.NewFileStore(path) + if err != nil { + t.Fatal(err) + } + if _, err = cs.Save(cfg); err != nil { + t.Fatal(err) + } + args := []string{"-store", target, "-action", "issue", "-config", path, "-connection-id", "remote-a", "-fingerprint", strings.TrimSpace(string(rfp)), "-approve", "-offline"} + pairing, err := call(request, args...) + if err != nil { + t.Fatal(err) + } + if _, err = call(pairing, "-store", agent, "-action", "install", "-approve", "-offline", "-fingerprint", strings.TrimSpace(string(bfp))); err != nil { + t.Fatal(err) + } + shown, err := call(nil, "-store", agent, "-action", "show") + if err != nil { + t.Fatal(err) + } + var p deviceidentity.Pairing + if err = json.Unmarshal(shown, &p); err != nil { + t.Fatal(err) + } + if p.Grant.ConnectionID != "remote-a" { + t.Fatal("wrong scope") + } + if bytes.Contains(shown, []byte("PRIVATE KEY")) || bytes.Contains(pairing, []byte("ca_key")) { + t.Fatal("private output") + } + if _, err = call(nil, "-store", target, "-action", "revoke", "-key-pin", p.Grant.KeyPin, "-approve", "-offline"); err != nil { + t.Fatal(err) + } +} diff --git a/cmd/local-probe-relay-edge/listen_linux.go b/cmd/local-probe-relay-edge/listen_linux.go new file mode 100644 index 0000000..402b48f --- /dev/null +++ b/cmd/local-probe-relay-edge/listen_linux.go @@ -0,0 +1,28 @@ +package main + +import ( + "errors" + "net" + "syscall" +) + +// This option affects only this listener, never host routes or firewall rules. +func edgeListenConfig(mss int) (net.ListenConfig, error) { + var config net.ListenConfig + if mss == 0 { + return config, nil + } + if mss < 536 || mss > 1460 { + return config, errors.New("TCP MSS must be 0 or between 536 and 1460") + } + config.Control = func(_, _ string, raw syscall.RawConn) error { + var optionErr error + if err := raw.Control(func(fd uintptr) { + optionErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_MAXSEG, mss) + }); err != nil { + return err + } + return optionErr + } + return config, nil +} diff --git a/cmd/local-probe-relay-edge/listen_linux_test.go b/cmd/local-probe-relay-edge/listen_linux_test.go new file mode 100644 index 0000000..f5f34d6 --- /dev/null +++ b/cmd/local-probe-relay-edge/listen_linux_test.go @@ -0,0 +1,37 @@ +package main + +import ( + "context" + "net" + "syscall" + "testing" +) + +func TestListenerMSSAppliesOnlyToItsSocket(t *testing.T) { + for _, value := range []int{-1, 535, 1461} { + if _, err := edgeListenConfig(value); err == nil { + t.Fatal("invalid TCP MSS accepted") + } + } + config, err := edgeListenConfig(1100) + if err != nil { + t.Fatal(err) + } + listener, err := config.Listen(context.Background(), "tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + raw, err := listener.(*net.TCPListener).SyscallConn() + if err != nil { + t.Fatal(err) + } + var mss int + var optionErr error + err = raw.Control(func(fd uintptr) { + mss, optionErr = syscall.GetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_MAXSEG) + }) + if err != nil || optionErr != nil || mss != 1100 { + t.Fatalf("listener MSS=%d, control error=%v, option error=%v", mss, err, optionErr) + } +} diff --git a/cmd/local-probe-relay-edge/listen_other.go b/cmd/local-probe-relay-edge/listen_other.go new file mode 100644 index 0000000..2c5816f --- /dev/null +++ b/cmd/local-probe-relay-edge/listen_other.go @@ -0,0 +1,15 @@ +//go:build !linux + +package main + +import ( + "errors" + "net" +) + +func edgeListenConfig(mss int) (net.ListenConfig, error) { + if mss != 0 { + return net.ListenConfig{}, errors.New("explicit TCP MSS is supported only on Linux") + } + return net.ListenConfig{}, nil +} diff --git a/cmd/local-probe-relay-edge/main.go b/cmd/local-probe-relay-edge/main.go new file mode 100644 index 0000000..40ce4d6 --- /dev/null +++ b/cmd/local-probe-relay-edge/main.go @@ -0,0 +1,98 @@ +// local-probe-relay-edge is a narrow TLS front end for a loopback Relay. It +// forwards only the three Relay routes and never logs headers or payloads. +package main + +import ( + "context" + "crypto/tls" + "errors" + "flag" + "fmt" + "io" + "log" + "net" + "net/http" + "net/http/httputil" + "net/url" + "os" + "os/signal" + "syscall" + "time" +) + +func main() { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + if err := run(ctx, os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "local-probe-relay-edge:", err) + os.Exit(1) + } +} +func run(ctx context.Context, args []string) error { + f := flag.NewFlagSet("local-probe-relay-edge", flag.ContinueOnError) + f.SetOutput(os.Stderr) + listen := f.String("listen", ":8443", "explicit public TLS listener") + upstream := f.String("upstream", "http://127.0.0.1:8792", "fixed loopback Relay origin") + cert := f.String("cert-file", "", "TLS leaf certificate file") + key := f.String("key-file", "", "TLS private key file") + mss := f.Int("tcp-max-segment", 0, "optional Linux per-listener TCP MSS (0 uses network default)") + if err := f.Parse(args); err != nil { + return err + } + if f.NArg() != 0 || *cert == "" || *key == "" { + return errors.New("explicit certificate and key required") + } + handler, closeTransport, err := edgeHandler(*upstream) + if err != nil { + return err + } + defer closeTransport() + identity, err := tls.LoadX509KeyPair(*cert, *key) + if err != nil { + return errors.New("TLS identity unavailable") + } + server := &http.Server{Handler: handler, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{identity}, NextProtos: []string{"http/1.1"}}} + listenConfig, err := edgeListenConfig(*mss) + if err != nil { + return err + } + listener, err := listenConfig.Listen(ctx, "tcp", *listen) + if err != nil { + return errors.New("TLS listener unavailable") + } + defer listener.Close() + defer server.Close() + done := make(chan error, 1) + go func() { done <- server.ServeTLS(listener, "", "") }() + select { + case <-ctx.Done(): + return nil + case err := <-done: + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return errors.New("TLS front end stopped") + } +} + +func edgeHandler(upstream string) (http.Handler, func(), error) { + u, err := url.Parse(upstream) + if err != nil || u.Scheme != "http" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || net.ParseIP(u.Hostname()) == nil || !net.ParseIP(u.Hostname()).IsLoopback() { + return nil, nil, errors.New("fixed loopback HTTP upstream required") + } + transport := &http.Transport{Proxy: nil, MaxConnsPerHost: 128, MaxIdleConnsPerHost: 8, ResponseHeaderTimeout: 10 * time.Second, DialContext: (&net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}).DialContext} + proxy := &httputil.ReverseProxy{Rewrite: func(r *httputil.ProxyRequest) { r.SetURL(u); r.Out.Host = u.Host }, Transport: transport, ErrorLog: log.New(io.Discard, "", 0), ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { + http.Error(w, "Relay origin unavailable", http.StatusBadGateway) + }} + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.RawQuery != "" || (r.URL.Path != "/healthz" && r.URL.Path != "/v1/target" && r.URL.Path != "/v1/agent") { + http.NotFound(w, r) + return + } + if r.ContentLength != 0 || len(r.TransferEncoding) != 0 { + http.Error(w, "request body not supported", http.StatusBadRequest) + return + } + proxy.ServeHTTP(w, r) + }), transport.CloseIdleConnections, nil +} diff --git a/cmd/local-probe-relay-edge/main_test.go b/cmd/local-probe-relay-edge/main_test.go new file mode 100644 index 0000000..1dc147b --- /dev/null +++ b/cmd/local-probe-relay-edge/main_test.go @@ -0,0 +1,82 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/relay" + "github.com/gorilla/websocket" +) + +func TestEdgePreservesRelayWebSocketsAndRoleAuthentication(t *testing.T) { + service, err := relay.New([]relay.Route{{DeviceID: "edge-test", TargetToken: strings.Repeat("t", 40), AgentToken: strings.Repeat("a", 40)}}) + if err != nil { + t.Fatal(err) + } + defer service.Close() + backend := httptest.NewServer(service) + defer backend.Close() + handler, closeTransport, err := edgeHandler(backend.URL) + if err != nil { + t.Fatal(err) + } + defer closeTransport() + front := httptest.NewTLSServer(handler) + defer front.Close() + dialer := websocket.Dialer{TLSClientConfig: front.Client().Transport.(*http.Transport).TLSClientConfig.Clone()} + base := "wss" + strings.TrimPrefix(front.URL, "https") + target, _, err := dialer.Dial(base+"/v1/target", http.Header{"Authorization": []string{"Bearer " + strings.Repeat("t", 40)}}) + if err != nil { + t.Fatal(err) + } + defer target.Close() + agent, _, err := dialer.Dial(base+"/v1/agent", http.Header{"Authorization": []string{"Bearer " + strings.Repeat("a", 40)}}) + if err != nil { + t.Fatal(err) + } + defer agent.Close() + for _, conn := range []*websocket.Conn{target, agent} { + _ = conn.SetReadDeadline(time.Now().Add(time.Second)) + kind, b, err := conn.ReadMessage() + if err != nil || kind != websocket.TextMessage || string(b) != relay.ReadyMessage { + t.Fatal("rendezvous failed") + } + } + if err = agent.WriteMessage(websocket.BinaryMessage, []byte("ciphertext-fixture")); err != nil { + t.Fatal(err) + } + kind, b, err := target.ReadMessage() + if err != nil || kind != websocket.BinaryMessage || string(b) != "ciphertext-fixture" { + t.Fatal("WebSocket forwarding corrupted data") + } + request := httptest.NewRequest(http.MethodGet, "/v1/agent", nil) + request.Header.Set("Authorization", "Bearer wrong") + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != 401 { + t.Fatal("role authentication bypassed") + } +} + +func TestEdgeCannotProxyArbitraryDestinations(t *testing.T) { + for _, upstream := range []string{"https://127.0.0.1:8792", "http://example.com", "http://127.0.0.1:8792/private", "http://user@127.0.0.1:8792"} { + if _, _, err := edgeHandler(upstream); err == nil { + t.Fatal("unsafe upstream accepted") + } + } + handler, closeTransport, err := edgeHandler("http://127.0.0.1:8792") + if err != nil { + t.Fatal(err) + } + defer closeTransport() + for _, path := range []string{"/admin", "/v1/agent?url=http://internal"} { + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if w.Code != 404 { + t.Fatal("unexpected route exposed") + } + } +} diff --git a/cmd/local-probe-relay/main.go b/cmd/local-probe-relay/main.go new file mode 100644 index 0000000..bb351b2 --- /dev/null +++ b/cmd/local-probe-relay/main.go @@ -0,0 +1,108 @@ +// local-probe-relay runs behind an HTTPS/WSS reverse proxy. It binds loopback +// only and loads role-separated credentials from environment references. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "net" + "net/http" + "os" + "os/signal" + "path/filepath" + "syscall" + "time" + + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/relay" +) + +type settings struct { + Version string `json:"version"` + Routes []routeConfig `json:"routes"` +} +type routeConfig struct { + DeviceID string `json:"device_id"` + TargetTokenEnv string `json:"target_token_env"` + AgentTokenEnv string `json:"agent_token_env"` +} + +func main() { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + if err := run(ctx, os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "local-probe-relay:", err) + os.Exit(1) + } +} +func run(ctx context.Context, args []string) error { + f := flag.NewFlagSet("local-probe-relay", flag.ContinueOnError) + f.SetOutput(os.Stderr) + path := f.String("config", "", "absolute Relay route config with environment references") + listen := f.String("listen", "127.0.0.1:8792", "loopback HTTPS reverse-proxy origin") + if err := f.Parse(args); err != nil { + return err + } + if f.NArg() != 0 || !filepath.IsAbs(*path) { + return errors.New("explicit absolute Relay config required") + } + host, _, err := net.SplitHostPort(*listen) + ip := net.ParseIP(host) + if err != nil || ip == nil || !ip.IsLoopback() { + return errors.New("Relay must bind explicit loopback behind HTTPS") + } + file, err := os.Open(*path) + if err != nil { + return errors.New("Relay config unavailable") + } + data, err := io.ReadAll(io.LimitReader(file, deviceidentity.MaxArtifactBytes+1)) + _ = file.Close() + if err != nil { + return errors.New("Relay config unavailable") + } + var cfg settings + if deviceidentity.DecodePublic(data, &cfg) != nil || cfg.Version != "local-probe.relay.v1" { + return errors.New("invalid Relay configuration") + } + var routes []relay.Route + for _, r := range cfg.Routes { + if !validEnv(r.TargetTokenEnv) || !validEnv(r.AgentTokenEnv) { + return errors.New("invalid credential environment reference") + } + routes = append(routes, relay.Route{DeviceID: r.DeviceID, TargetToken: os.Getenv(r.TargetTokenEnv), AgentToken: os.Getenv(r.AgentTokenEnv)}) + } + service, err := relay.New(routes) + if err != nil { + return err + } + defer service.Close() + server := &http.Server{Handler: service, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} + defer server.Close() + listener, err := net.Listen("tcp", *listen) + if err != nil { + return errors.New("cannot bind Relay loopback origin") + } + defer listener.Close() + done := make(chan error, 1) + go func() { done <- server.Serve(listener) }() + select { + case <-ctx.Done(): + return nil + case <-done: + return errors.New("Relay stopped") + } +} +func validEnv(s string) bool { + if len(s) == 0 || len(s) > 128 { + return false + } + for i, c := range s { + if !(c >= 'A' && c <= 'Z' || c == '_' || i > 0 && c >= '0' && c <= '9') { + return false + } + } + return true +} diff --git a/cmd/local-probe-target/main.go b/cmd/local-probe-target/main.go new file mode 100644 index 0000000..d95b09f --- /dev/null +++ b/cmd/local-probe-target/main.go @@ -0,0 +1,196 @@ +// local-probe-target is a paired Agent ingress, read-only by default, with an +// optional explicitly configured trusted-host operation engine. +// A configured Tunnel supplies public WSS; inner mTLS terminates here. This is +// independent from the user's existing desktop/Tunnel process. +package main + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "errors" + "flag" + "fmt" + "net" + "net/http" + "os" + "os/signal" + "path/filepath" + "runtime" + "strings" + "syscall" + "time" + + "github.com/LE-saber/Local-Probe/internal/audit" + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/mcpserver" + "github.com/LE-saber/Local-Probe/internal/operations" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "github.com/LE-saber/Local-Probe/internal/policy" + "github.com/LE-saber/Local-Probe/internal/rootfs" +) + +func main() { + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + if err := run(ctx, os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, "local-probe-target:", err) + os.Exit(1) + } +} +func run(ctx context.Context, args []string) error { + f := flag.NewFlagSet("local-probe-target", flag.ContinueOnError) + f.SetOutput(os.Stderr) + identityPath := f.String("store", "", "absolute target identity directory") + configPath := f.String("config", "", "absolute target configuration") + listen := f.String("listen", "127.0.0.1:8791", "loopback Tunnel origin only") + relayEndpoint := f.String("relay-endpoint", "", "optional wss:// self-hosted Relay /v1/target endpoint; outbound only") + outerCA := f.String("outer-ca-file", "", "optional absolute public CA PEM for private Relay TLS") + auditPath := f.String("audit-dir", "", "explicit private audit directory") + operationJournal := f.String("operations-journal", "", "optional owner-private initialized journal outside all workspaces") + operationCatalog := f.String("operations-catalog", "", "optional absolute trusted runner catalog; requires operation journal") + if err := f.Parse(args); err != nil { + return err + } + if f.NArg() != 0 { + return errors.New("unexpected positional arguments") + } + host, _, err := net.SplitHostPort(*listen) + ip := net.ParseIP(host) + if err != nil || ip == nil || !ip.IsLoopback() { + return errors.New("explicit loopback listener required") + } + if !filepath.IsAbs(*auditPath) { + return errors.New("explicit absolute private audit directory required") + } + tokenEnv := "LOCAL_PROBE_TARGET_ACCESS_TOKEN" + if *relayEndpoint != "" { + tokenEnv = "LOCAL_PROBE_RELAY_TARGET_TOKEN" + } + token := os.Getenv(tokenEnv) + if len(token) < 32 || len(token) > 4096 || strings.ContainsAny(token, "\r\n") { + return errors.New("set the selected transport's strong admission credential locally") + } + expected := sha256.Sum256([]byte("Bearer " + token)) + identity, err := deviceidentity.OpenStore(*identityPath) + if err != nil { + return err + } + defer identity.Close() + registry, err := deviceidentity.NewRegistry(identity) + if err != nil { + return err + } + fileStore, err := config.NewFileStore(*configPath) + if err != nil { + return errors.New("invalid config path") + } + snapshot, err := fileStore.Load() + if err != nil { + return errors.New("config unavailable") + } + store, err := config.NewStore(snapshot.Config()) + if err != nil { + return err + } + manager, err := policy.NewManager(store) + if err != nil { + return err + } + source, err := rootfs.New(store) + if err != nil { + return errors.New("cannot safely open roots") + } + defer source.Close() + sink, err := audit.New(audit.Config{Directory: *auditPath}) + if err != nil { + return errors.New("private audit directory unavailable") + } + defer sink.Close() + var operationEngine *operations.Engine + if (*operationJournal == "") != (*operationCatalog == "") { + return errors.New("operation journal and catalog required together") + } + if *operationJournal != "" { + if runtime.GOOS != "windows" { + return errors.New("trusted-host operation target currently requires Windows; Linux Agent and Relay remain supported") + } + catalog, err := operations.LoadCatalog(*operationCatalog) + if err != nil { + return err + } + journal, err := operations.OpenJournal(*operationJournal, false) + if err != nil { + return err + } + defer journal.Close() + operationEngine, err = operations.New(ctx, operations.Options{Journal: journal, Config: store, Manager: manager, Workspace: source, Catalog: catalog, Acquire: func(parent context.Context, subject operations.Subject) (context.Context, func(), error) { + decoded, err := hex.DecodeString(subject.Principal) + if err != nil || len(decoded) != 32 { + return nil, nil, operations.ErrDenied + } + var pin peertransport.Pin + copy(pin[:], decoded) + lease, release, err := registry.Acquire(parent, pin) + if err != nil { + return nil, nil, err + } + g, ok := deviceidentity.GrantFromContext(lease) + if !ok || g.ConnectionID != subject.Connection { + release() + return nil, nil, operations.ErrDenied + } + return lease, release, nil + }}) + if err != nil { + return err + } + defer operationEngine.Close() + } + server, err := mcpserver.New(mcpserver.Options{Manager: manager, Source: source, PeerRegistry: registry, Audit: sink, Operations: operationEngine}) + if err != nil { + return err + } + inner, err := registry.ServerTLS() + if err != nil { + return err + } + endpoint, err := peertransport.NewEndpoint(inner, server.Handler(), func(r *http.Request) bool { + values := r.Header.Values("Authorization") + if len(values) != 1 || len(values[0]) > 4103 { + return false + } + actual := sha256.Sum256([]byte(values[0])) + return subtle.ConstantTimeCompare(actual[:], expected[:]) == 1 + }) + if err != nil { + return err + } + defer endpoint.Close() + if *relayEndpoint != "" { + roots, err := peertransport.LoadPublicRoots(*outerCA) + if err != nil { + return err + } + return endpoint.ServeRelay(ctx, *relayEndpoint, http.Header{"Authorization": []string{"Bearer " + token}}, roots) + } + mux := http.NewServeMux() + mux.Handle("/v1/peer", endpoint) + outer := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} + listener, err := net.Listen("tcp", *listen) + if err != nil { + return errors.New("cannot bind loopback origin") + } + defer listener.Close() + defer outer.Close() + done := make(chan error, 1) + go func() { done <- outer.Serve(listener) }() + select { + case <-ctx.Done(): + return nil + case <-done: + return errors.New("paired target stopped") + } +} diff --git a/deploy/operations/catalog.example.json b/deploy/operations/catalog.example.json new file mode 100644 index 0000000..e8f2016 --- /dev/null +++ b/deploy/operations/catalog.example.json @@ -0,0 +1,4 @@ +{ + "version": "local-probe.operations.v1", + "tools": [] +} diff --git a/deploy/relay/bootstrap-test-server.py b/deploy/relay/bootstrap-test-server.py new file mode 100644 index 0000000..60460f6 --- /dev/null +++ b/deploy/relay/bootstrap-test-server.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Deploy only Local-Probe's R12 test namespace; never print secret contents. + +Upload locally built Linux binaries beside this script before running as root. +Does not create accounts, install packages, or change firewall/other services. +""" +import argparse +import hashlib +import ipaddress +import json +import os +from pathlib import Path +import pwd +import re +import secrets +import socket +import subprocess + +ROOT = Path('/opt/local-probe-relay-r12') +CONFIG = Path('/etc/local-probe-relay-r12') +MARKER = 'Managed by Local-Probe R12 public relay test' + + +def command(args): + result = subprocess.run(args, text=True, capture_output=True) + if result.returncode: + raise RuntimeError('deployment command failed: ' + args[0]) + return result.stdout + + +def write_new(path, data, mode): + with open(path, 'x', encoding='utf-8') as stream: + os.chmod(path, mode) + stream.write(data) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--host', required=True) + parser.add_argument('--port', type=int, default=8443) + parser.add_argument('--bind-address', default='', help='specific local IP; avoid wildcard listeners on shared Docker hosts') + parser.add_argument('--tcp-max-segment', type=int, default=0, help='optional per-socket Linux TCP MSS; does not change routes/firewall') + parser.add_argument('--relay-sha256', required=True) + parser.add_argument('--edge-sha256', required=True) + parser.add_argument('--update-owned-units', action='store_true') + args = parser.parse_args() + if os.geteuid() != 0 or not re.fullmatch(r'[a-z0-9][a-z0-9.-]{0,251}', args.host): + raise RuntimeError('root and a constrained DNS hostname required') + if args.port < 1024 or args.port > 65535: + raise RuntimeError('unprivileged dedicated TLS port required') + bind = str(ipaddress.ip_address(args.bind_address)) if args.bind_address else '' + listen = ('[' + bind + ']' if ':' in bind else bind) + ':' + str(args.port) + if args.tcp_max_segment != 0 and not 536 <= args.tcp_max_segment <= 1460: + raise RuntimeError('TCP MSS must be 0 or between 536 and 1460') + pwd.getpwnam('nobody') + for name, expected in [('local-probe-relay', args.relay_sha256), ('local-probe-relay-edge', args.edge_sha256)]: + binary = ROOT / name + if not re.fullmatch(r'[0-9a-fA-F]{64}', expected) or hashlib.sha256(binary.read_bytes()).hexdigest() != expected.lower(): + raise RuntimeError('uploaded binary checksum mismatch') + os.chmod(binary, 0o755) + + if CONFIG.exists() and not (CONFIG / 'managed-marker').exists(): + raise RuntimeError('refusing to reuse an unowned configuration directory') + CONFIG.mkdir(mode=0o700, exist_ok=True) + if not (CONFIG / 'managed-marker').exists(): + write_new(CONFIG / 'managed-marker', MARKER + '\n', 0o600) + elif (CONFIG / 'managed-marker').read_text().strip() != MARKER: + raise RuntimeError('configuration namespace ownership mismatch') + + credentials = CONFIG / 'credentials.json' + if not credentials.exists(): + values = {'device_id': 'public-test-route', 'target_token': secrets.token_urlsafe(48), 'agent_token': secrets.token_urlsafe(48)} + write_new(credentials, json.dumps(values), 0o600) + values = json.loads(credentials.read_text()) + if not (CONFIG / 'relay.env').exists(): + write_new(CONFIG / 'relay.env', 'LOCAL_PROBE_RELAY_TARGET_TOKEN=' + values['target_token'] + '\nLOCAL_PROBE_RELAY_AGENT_TOKEN=' + values['agent_token'] + '\n', 0o600) + if not (CONFIG / 'relay.json').exists(): + config = {'version': 'local-probe.relay.v1', 'routes': [{'device_id': values['device_id'], 'target_token_env': 'LOCAL_PROBE_RELAY_TARGET_TOKEN', 'agent_token_env': 'LOCAL_PROBE_RELAY_AGENT_TOKEN'}]} + write_new(CONFIG / 'relay.json', json.dumps(config), 0o600) + + ca, ca_key = CONFIG / 'outer-ca.pem', CONFIG / 'outer-ca.key' + cert, key = CONFIG / 'edge-cert.pem', CONFIG / 'edge.key' + if not ca.exists(): + if ca_key.exists(): + raise RuntimeError('incomplete CA initialization; inspect before retrying') + command(['openssl', 'req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-sha256', '-days', '30', '-subj', '/CN=Local-Probe-R12-Private-Test-CA', '-keyout', str(ca_key), '-out', str(ca)]) + os.chmod(ca_key, 0o600) + if not cert.exists(): + if key.exists(): + raise RuntimeError('incomplete edge key initialization; inspect before retrying') + csr = CONFIG / 'edge.csr' + command(['openssl', 'req', '-new', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-subj', '/CN=' + args.host, '-keyout', str(key), '-out', str(csr)]) + extension = CONFIG / 'edge-extension.conf' + write_new(extension, 'basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:' + args.host + '\n', 0o600) + command(['openssl', 'x509', '-req', '-in', str(csr), '-CA', str(ca), '-CAkey', str(ca_key), '-CAcreateserial', '-out', str(cert), '-days', '14', '-sha256', '-extfile', str(extension)]) + os.chmod(key, 0o600) + + # PID 1 loads root-only credentials into each service's private credential + # directory. Reuse nobody; no useradd/DynamicUser/account provisioning. + changed_units = [] + for name in ['relay', 'relay-edge']: + unit = Path('/etc/systemd/system/local-probe-' + name + '-r12.service') + if unit.exists() and MARKER not in unit.read_text(): + raise RuntimeError('refusing to replace an unowned unit') + if name == 'relay': + specific = 'EnvironmentFile=' + str(CONFIG / 'relay.env') + '\nLoadCredential=relay.json:' + str(CONFIG / 'relay.json') + '\nExecStart=' + str(ROOT / 'local-probe-relay') + ' -config %d/relay.json -listen 127.0.0.1:8792\n' + else: + specific = 'LoadCredential=edge-cert.pem:' + str(cert) + '\nLoadCredential=edge.key:' + str(key) + '\nExecStart=' + str(ROOT / 'local-probe-relay-edge') + ' -listen ' + listen + ' -tcp-max-segment ' + str(args.tcp_max_segment) + ' -upstream http://127.0.0.1:8792 -cert-file %d/edge-cert.pem -key-file %d/edge.key\n' + content = '# ' + MARKER + '\n[Unit]\nDescription=Local-Probe R12 ' + name + ' test\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nUser=nobody\nGroup=nogroup\n' + specific + 'Restart=on-failure\nRestartSec=2\nNoNewPrivileges=yes\nProtectSystem=strict\nProtectHome=yes\nPrivateTmp=yes\nUMask=0077\nLimitNOFILE=1024\nMemoryMax=192M\nTasksMax=64\nLogRateLimitIntervalSec=30s\nLogRateLimitBurst=20\n\n[Install]\nWantedBy=multi-user.target\n' + if not unit.exists(): + write_new(unit, content, 0o644) + elif unit.read_text() != content: + if not args.update_owned_units: + raise RuntimeError('existing owned unit differs; review before changing') + backup = CONFIG / (unit.name + '.before-' + secrets.token_hex(4)) + write_new(backup, unit.read_text(), 0o600) + unit.write_text(content) + changed_units.append(unit.name) + command(['systemctl', 'daemon-reload']) + command(['systemctl', 'enable', '--now', 'local-probe-relay-r12.service', 'local-probe-relay-edge-r12.service']) + for unit in changed_units: + command(['systemctl', 'restart', unit]) + result = {'host': args.host, 'port': args.port, 'outer_ca_pem_sha256': hashlib.sha256(ca.read_bytes()).hexdigest()} + print(json.dumps(result)) + + +if __name__ == '__main__': + try: + main() + except Exception as error: + # Never include subprocess output, environment values or secret records. + print('deployment failed: ' + str(error), file=__import__('sys').stderr) + raise SystemExit(1) diff --git a/deploy/relay/relay.example.json b/deploy/relay/relay.example.json new file mode 100644 index 0000000..3db0324 --- /dev/null +++ b/deploy/relay/relay.example.json @@ -0,0 +1,10 @@ +{ + "version": "local-probe.relay.v1", + "routes": [ + { + "device_id": "replace-with-public-device-id", + "target_token_env": "LOCAL_PROBE_RELAY_TARGET_TOKEN", + "agent_token_env": "LOCAL_PROBE_RELAY_AGENT_TOKEN" + } + ] +} diff --git a/docs/GUI_HANDOFF.md b/docs/GUI_HANDOFF.md new file mode 100644 index 0000000..af6ad04 --- /dev/null +++ b/docs/GUI_HANDOFF.md @@ -0,0 +1,134 @@ +# GUI implementation handoff + +Updated: 2026-10-24. Audience: GUI designer/frontend/desktop engineer. This is the default English handoff; [detailed Chinese version](GUI_HANDOFF.zh-CN.md) remains available. Start with the complete `feat/r12-dual-mode` branch as described in the [developer guide](R12_DEVELOPMENT.md). + +## Objective and implementation boundary + +Extend the existing approved Windows GUI to manage two connection purposes, pairing, explicit developer authorization, local approvals and jobs. Preserve the current working interface; do not replace it with a disconnected demonstration website. + +The separate R12 backend supports real Windows operations, but **the backend is not frozen**. Trusted local management APIs, the full multi-connection host, online rules and selective authorization epochs remain incomplete. GUI code cannot fill these gaps with fake state or by removing permission gates. Coordinate these contracts with the backend owner, implement/test them in Go first, then integrate the interface. + +The current GUI is real HTML/CSS/JavaScript embedded in WebView2 at `https://localassets/index.html`. The implementation under `internal/desktopweb/assets` is the visual and behavioral baseline. Historical `prototypes/typography-review` contains simulated data and is only a design reference. + +Two purposes: + +| Purpose | Intended experience | +| --- | --- | +| Web access to local files | Standard MCP through the existing Web-facing ingress | +| Agent remote operations | A native Agent bridge accesses another authorized environment through direct WSS/Tunnel or self-hosted Relay | + +If the Agent already has lawful native access to the same target workspace, advise native tools. Client names, shared paths and IPs are not trusted host identity, and this advice must not bypass native permission boundaries. Same physical machine does not necessarily mean same environment. + +## Preserve the accepted design + +- Keep Overview, Connections, Access, Activity and Settings. Mix topology, trees, cards, timeline, prose and tables; avoid turning every page into a table. +- Use one collapsible sidebar with a top-right `< / >` control. Expanded items show icon and text in the same aligned button; collapsed items show labeled icons. Do not restore a separate LP rail or global inspector/details panel. +- Put active connection controls on Overview. Connections is primarily new connection configuration and reusable history; saving adds a history item. Viewing/selecting an entry must not implicitly stop other connections. +- Access uses a left tree and corresponding right list. Keep read-only, commands and advanced rule sections. Use collapsible branches rather than an expanding wall of cards. Pause/remove icon buttons require labels/tooltips and keyboard access. +- Activity combines workspace, connection, channel, device, category, result, time and keyword filters. Preserve the event's historical labels instead of retroactively rewriting them. +- Settings includes appearance, font size, About/update, program health and configuration backup. Diagnostic export belongs in health. Save uses a native location/base-name dialog with `.lpbackup` supplied by the app; restore uses native file selection, validation and preview. +- Remove global font specifications, “font loaded”, demo-data and preview badges. Keep meaningful offline, expired, unauthorized, pending approval and trust-change states. +- Preserve text selection/copy, native right-click, F5 and Ctrl+R. Polling must preserve drafts, selection, scrolling and focus. + +### Typography, color and clarity + +Current baseline: sidebar 232px, top bar 48px, body 14px. Body uses Geist / HarmonyOS Sans SC / system fallbacks; technical values use Geist Mono / Cascadia Code / Consolas. Chinese headings use locally installed STZhongsong with fallback. A CSS font name is not evidence that a distributable font asset is bundled. New fonts require licensing/offline fallback review; do not depend on a CDN. + +Dark theme: background `#181818`, cards `#222222`, borders `#3c3c3c`, text `#f2f0ec`, warm-gray emphasis `#d6cfc2`. Light background `#f5f5f1`, white cards. Keep the neutral charcoal/warm-gray palette; **no blue/purple dark theme**. Font sizes 12/14/16/18 must consistently affect navigation, controls, headings and dialogs. + +Use real table semantics and explicit column sizing; long names/IDs/paths cannot push action buttons under the wrong header. Test narrow windows and large fonts. + +The host already uses Per-Monitor V2 and `WM_DPICHANGED`. Do not use CSS zoom, whole-page transforms or bitmap scaling to repair clarity; do not apply DPI scaling twice. Validate actual WebView2 windows at 100/125/150/200% and across mixed-DPI monitors. Report unavailable hardware as untested rather than claiming all computers are clear. + +Synchronize page, native title bar/border and native context menu with light/dark mode. Preserve `window.ready`, acknowledged `window.theme`, retries and rapid-switch final-state consistency. CSS alone cannot theme native menus. + +## Required workflows + +### Connections and pairing + +Choose purpose separately from transport. Existing official OpenAI Secure MCP Tunnel remains standard MCP; the new opaque byte-stream `/v1/peer` is not a generic use of that official tunnel. Direct WSS/Tunnel and self-hosted Relay are supported by the native Agent bridge. + +Show target identity, connection/profile, transport readiness, endpoint authentication and MCP readiness as separate states. Saved configuration, a listening port and completed endpoint authentication are different facts. Do not show online solely because a record exists. + +Pairing imports/exports only public bundle/CSR/certificate material, displays independently checked fingerprints and binds the intended connection. Private keys and CA signing authority remain in the trusted host, never in JS. Revocation errors and certificate expiry must be visible. Do not request real server secrets to build mock interactions. + +### Explicit developer access and approvals + +Display the execution contract: `trusted_host` uses current-user file/network permissions and **is not a sandbox**. Commands may reach files outside a scoped root through OS permissions. Read-only remains the default; saving a runner/template cannot grant access. + +Require the backend's writable v2 profile, `agent_remote`, developer connection allowlist, tool permission, audited runner/hash and local approval. The old desktop `execution_available=false` projection is not the new engine. Do not relabel it as ready or delete `network_enforcement_required` to simulate integration. + +Approval details show operation ID/digest, authenticated Agent/connection, workspace, exact arguments/script, executable identity/hash, timeout, file before/after content, expected file version and expiry. Approve/reject are local-owner actions bound to that exact plan; remote MCP has no approval method. Changed/expired plans must be prepared and approved again. Do not accept a remote `confirmed=true`. + +### Jobs and output + +Use backend states and distinguish queued/pending approval/running/terminal failure/interrupted/unknown. Display rejection and cleanup failures accurately. Reconnection queries the original job, rather than generating a new nonce and repeating side effects. + +Output is currently available after completion, bounded and paged by stdout/stderr byte offset, with base64 raw bytes. Do not invent a live terminal or assume cmd output is UTF-8. + +Local viewing must not accidentally renew the Agent's 60-second status-poll lease. Remote cancellation waits for cleanup; local owner cancellation persists a request. Display “cancelling” until a real terminal state is observed. Unconfirmed process-tree cleanup remains unknown and disables admission. + +### Rules, health and backup + +Deny takes precedence; ignore affects discovery and is not secrecy. Show preview, affected scope and revision/CAS conflicts while retaining edits. Current rules RPC is offline; do not claim immediate global revocation until the backend implements it for active targets. + +Health distinguishes configuration, process, transport, identity, authorization, runner and certificate expiry. An absent update source means “not configured”, not “latest”. Restore validates `local-probe.backup.v1`, previews changes and preserves removal of developer grants; do not include keys/journals in ordinary config backups or resurrect revoked grants. + +## Existing interfaces versus proposed work + +Actual message envelope: + +```json +{"id":"gui-request-1","method":"snapshot","params":{}} +``` + +Response: `{id,ok,data,error}`; current data is a snapshot containing desktop, connection, workspace, view and optional rules/backup candidate. It is not JSON-RPC 2.0 and must not be exposed as a remote approval API. Keep the fixed origin/CSP; no arbitrary fetch, inline scripts or remote fonts/icons. + +| Existing method | Behavior | +| --- | --- | +| `snapshot` | Current desktop projection | +| `connections.save/select/remove` | History; old DTO lacks purpose/Relay fields | +| `connection.connect/reconnect/cancel/disconnect/setTransport` | One selected controller | +| `workspace.pick/add/update/remove` | Native directory selection and roots | +| `rules.read/preview/apply` | Offline rule administration | +| `developer.configure/saveProfile/removeProfile` | Old configuration, not the new operation engine | +| `settings.backup/pickBackup/restore` | Native save/select/validate/preview/restore | +| `logs.export`, `diagnostics.export` | Controlled redacted exports | +| `window.theme` | Separately handled host theme application/acknowledgement | + +**Proposed local contracts below do not yet exist as stable RPC methods:** + +| Contract | Backend responsibility | +| --- | --- | +| Purpose, target identity, capabilities and independent connection lifecycle | Versioned connection DTOs and full runtime host | +| Pair/import/issue/revoke and fingerprints | Trusted local deviceidentity management | +| Catalog and explicit execution policy | Native selection, hashing and config revision | +| Local approval queue/detail/decision | Owner context and exact journal ID/digest | +| Job projection/output/owner cancel | Read-only local status without Agent lease renewal | +| Online rules and health/certificate state | Affected connections, immediate revocation and truthful diagnostics | + +Prefer direct Go APIs or typed local IPC. Do not concatenate shell commands, accept arbitrary management executables or transfer host authority into remote JSON fields. Agree required/nullable fields, errors, paging, bounds and cancellation behavior with the backend owner before integrating. + +## Current limits that the interface must show + +- Windows execution target only; Linux Agent needs real-machine acceptance. +- Job limits: global two / one per connection, 32 processes, 1 GiB aggregate committed memory, cumulative user CPU and wall-time bounds, 64 KiB per output stream. These are not sandbox guarantees. +- Default timeout 60 seconds, maximum 30 minutes; approval window five minutes; Agent lease 60 seconds. +- UTF-8 files up to 128 KiB; at most 32 unique-context exact text edits. Existing-file updates are not atomic replacement; before images support manual recovery after unknown/partial results. +- cmd scripts reject extra arguments and journal paths with spaces/cmd metacharacters. +- Journal: 128 historical jobs and about 64 MiB; no automatic archive. Show admission/maintenance failure. +- Global config revision currently invalidates old plans; selective connection epochs and online reload are incomplete. +- Two concurrent jobs are not three independent production connection lifecycles. +- Prior public Relay checks were read-only, not the new cross-machine execution acceptance. + +## Delivery and acceptance + +Deliver the official assets and necessary typed host adapters, contract changes, independent builds, screenshots and actual evidence. New interactions may first use a separate operable HTML mock for owner review; the existing approved visual baseline does not need a wholesale redesign. + +Run frontend VM tests and Go test/race/vet. Add meaningful tests for changed behavior. Manually test long content, collapsed sidebar, filters, scope tree/list coordination, keyboard labels/focus, drafts, copy/right-click/refresh, native backup dialogs, fast theme switching, mixed DPI and disconnect/recovery. VM tests do not establish pixel/native-menu correctness. + +Verify default read-only, refusal without exact local approval, changed-plan expiry, cross-subject isolation, revocation, idempotent retry, owner cancellation and unknown cleanup. New runtime features must be tested in the backend first. + +Do not overwrite running binaries, alter real authorization, connect to the user's Linux computer or deploy on the real Relay as part of design work. Real Relay/Linux operation acceptance follows backend and GUI development with explicit test details from the owner. Uploading this branch is not merge/Release authorization. + +Next: [developer guide](R12_DEVELOPMENT.md), [operations](R12_OPERATIONS.md), [pairing](R12_PAIRING_AND_TRANSPORT.md), [latest status](IMPLEMENTATION_STATUS.md). diff --git a/docs/GUI_HANDOFF.zh-CN.md b/docs/GUI_HANDOFF.zh-CN.md new file mode 100644 index 0000000..25bcd3b --- /dev/null +++ b/docs/GUI_HANDOFF.zh-CN.md @@ -0,0 +1,275 @@ +# Local-Probe GUI 开发交接书 + +日期:2026-10-24。对象:接手 GUI 的设计/前端/桌面工程人员。 +项目云端地址:https://github.com/LE-saber/Local-Probe + +仓库默认交接入口为[英文版](GUI_HANDOFF.md),本文保留完整中文需求。 +## 0. 接手结论与源码版本 + +项目已有可用的 Windows GUI 和经过本机测试的新操作后端。此次工作是沿用已认可的页面风格,补齐双用途连接、设备配对、开发者授权、审批与作业的真实 GUI 接入,不是重新制作一套脱离宿主的展示站。 + +**后端尚未全部封板。** 操作引擎可运行,但桌面桥接、完整多连接宿主、在线规则和选择性授权版本还有缺口。不能通过前端模拟状态或删除权限门来补齐这些缺口。GUI 负责人负责交互、页面及本地桥接适配;涉及权限、运行宿主与撤权机制的新增契约,应与后端负责人协作落实。 + +当前 R12 源码交付分支为 `feat/r12-dual-mode`,最初开发基线为 `dd0a6b73981d8006403913e400d698c3b8fee291`,本次整合了 main 的四语言 README 更新。请直接克隆该分支,记录实际 `git rev-parse HEAD`;仅克隆旧 main/最初基线拿不到 R12。此前“尚未提交、需源码快照”的提示属于打包前状态,现以[仓库开发指南](R12_DEVELOPMENT.md)为准;不要 reset/clean 覆盖现有工作。 + +本文路径均相对仓库根目录。传递源码时应排除 `.tools/`、`.runtime/`、`.secrets/`、运行配置、令牌、私钥、SSH 主机信息、备份和日志;不要直接打包整个本机工作目录。本文不包含真实服务器地址或凭据,也不授权发布、推送、修改系统策略或操作用户真实连接。 + +## 1. 产品目标与本次范围 + +Local-Probe 让 AI 通过受控连接访问用户授权的电脑文件,并在用户明确授权时执行开发任务。 + +| 用途 | 面向谁 | 用户要完成的事情 | +|---|---|---| +| Web 访问本地 | Web AI 的标准 MCP 客户端 | 连接本机服务,访问获准文件;当前 GUI 主要覆盖此路径 | +| Agent 远程操作 | 另一执行环境中的原生 Agent | 运行轻量 stdio 桥接,经 Tunnel 或自建中转连接目标;配对、授权、请求本地批准并操作 | + +Agent 已能在自己的当前环境中合法直接操作同一工作区时,优先使用原生工具。不能仅凭客户端叫 Codex、路径相同或 IP 相同就认定同机,也不能借本项目绕过原生沙箱/审批。 + +首个 GUI/操作目标是 **Windows + WebView2**。Linux 已有 Agent/配对程序构建,用户另有一台 Linux 电脑供后续跨机测试;Linux 操作目标目前不支持执行/写入,此次不要求移植 Linux GUI。 + +本项目不是 IDE、AI 推理服务、远程桌面或任意端口代理。GUI 不应扩展成完整代码编辑器或通用终端。 + +## 2. 现状:哪些可复用,哪些还没接入 + +| 模块 | 实际状态 | GUI 工作 | +|---|---|---| +| 现有五页 GUI | 已有概览、连接、访问范围、活动、设置;真实桌面桥接 | 保留布局和已修复行为,增量扩展 | +| 旧连接管理 | 保存/选择历史连接、连接/重连/断开已接;桌面 Service 仍是单 controller | 增加用途和远程参数;完整多实例需后端控制面 | +| 文件授权/规则 | 根目录选择、增删/暂停、deny/ignore 读取/预览/离线提交已实现 | 保留树/列表;不得宣传为全局在线即时撤权 | +| 开发者旧设置 | 保存模式与旧命令模板;`execution_available` 仍关闭、门码为 `network_enforcement_required` | 不能把它直接当成新受信任操作界面 | +| 新设备配对 | 持久化身份、公开 bundle/CSR、指纹、签发、撤销及租约已实现 | 缺少 GUI 与可信本地管理适配 | +| 新操作引擎 | 命令/版本/脚本/build/test、文本写入/补丁、本地审批、作业账本、取消已运行 | 缺 GUI 宿主接线、审批队列与作业视图 | +| 双连接作业 | 两连接可并行各一个任务,取消一方不影响另一方 | 不等于 GUI 已有多个独立运行连接 | +| 自建 Relay | Linux 测试部署已完成,真实公网只读链路通过 | GUI 尚不能完整配置/管理;新操作链路未做真实中转验收 | +| 备份/诊断/主题/DPI | 已有原生对话框、备份校验、脱敏导出及主题/DPI修复 | 属于必须保持的回归基线 | + +截至交接:完整 Go test/race/vet、本机真实运行器/构建测试已通过;本次交接又运行 `node scripts/Test-LocalProbeDesktopFrontend.mjs`,24 个 VM 场景通过。VM 测试不等于像素、原生菜单或跨屏 DPI 实测。 + +## 3. 必读代码与文件地图 + +| 路径 | 作用 | +|---|---| +| `AGENTS.md` | 仓库约束、验证要求及权限边界 | +| `internal/desktopweb/assets/index.html` | 正式五页结构、弹窗、控件 | +| `internal/desktopweb/assets/app.css` | 已认可的视觉基线与响应式样式 | +| `internal/desktopweb/assets/app.js` | 页面状态、渲染、RPC、轮询、主题同步 | +| `internal/desktopweb/assets/icons.js` | 现有 SVG 图标体系 | +| `internal/desktopweb/desktopweb.go` | 内嵌资源、固定本地 origin | +| `internal/desktopbridge/service.go` | RPC envelope、dispatch、snapshot、单 controller 生命周期 | +| `internal/desktopbridge/desktop.go` | 历史连接和桌面状态投影、配置更新 | +| `internal/desktopbridge/developer.go` | 旧开发者配置与执行门,不能移除门以假装新后端可用 | +| `internal/desktopbridge/rules.go` | 现有离线规则管理、预览、CAS 与共享影响确认 | +| `internal/desktopbridge/backup.go` | `.lpbackup`、校验和、恢复候选与安全门 | +| `internal/desktophost/host_windows.go` | Win32/WebView2、消息桥接、原生对话框、托盘 | +| `internal/desktophost/theme_windows.go` | 原生窗口框架和 WebView2 的主题一致性 | +| `internal/desktophost/dpi_windows.go` | PMv2、初始尺寸和跨屏 DPI 处理 | +| `internal/operations/{types,engine,journal}.go` | 新操作模型、执行、持久化、本地审批/取消 | +| `internal/deviceidentity/` | 配对、身份保护、撤销和活动租约 | +| `internal/mcpserver/operations.go` | 八个新 MCP 工具与能力过滤 | +| `cmd/local-probe-{target,agent,pair,operations}/` | 当前可运行的后端 CLI | +| `prototypes/typography-review/index.html` | 历史交互样稿,仅作设计参考,数据是演示 | +| `scripts/Test-LocalProbeDesktopFrontend.mjs` | 正式前端 24 个 VM 回归场景 | + +**正式 `desktopweb/assets` 优先于历史 HTML 样稿。** 样稿中的演示连接、模拟健康/更新和浏览器目录选择器不能直接移植为真实功能。 + +## 4. 用户已经认可的视觉与行为约束 + +- 保留“概览 / 连接 / 访问范围 / 活动 / 设置”主结构,拓扑图、树、卡片、时间线、文字与表格配合;不能再做成整页纯文字表格。 +- 保留单一侧栏。不要恢复独立 LP 图标轨道、全局右侧检查器或全局“详情”按钮。侧栏右上角 `< / >` 收展,收起只留图标;每个图标和文字必须在同一按钮中对齐。 +- 概览展示连接拓扑,连接控制位于概览。连接页主要用于新建与历史复用,新增后进入历史;切换查看对象不能隐式断开其它运行连接。 +- 访问范围左侧树、右侧列表,保留只读、命令、高级自定义规则分区;分支可折叠,避免长期使用卡片堆积。暂停/恢复/移除可用图标,但需提示和可访问名称。 +- 活动支持空间、连接、通道、设备、类别、结果、时间和关键字组合筛选;事件保留发生时的名称/对象信息,不能随后改写历史。 +- 设置保留外观、字号、关于/更新、程序健康、配置备份。诊断导出在程序健康卡片;备份支持原生保存位置/名称,名称不要求用户填写后缀;恢复进入原生文件选择、格式校验和恢复预览。 +- 不恢复“字体规格”“字体已加载”“交互预览·示例数据”等全局提示。必要的离线、未授权、待审批、信任变更等状态必须保留,不能为了简洁隐藏。 +- 右键、文字选择/复制、F5、Ctrl+R 保持可用。轮询不能反复替换用户正在选中的文字、输入草稿或滚动位置。 + +### 字体、颜色和尺寸 + +当前 CSS 默认侧栏 232px、顶栏 48px、正文 14px;正文栈为 Geist / HarmonyOS Sans SC / 系统中文字体,技术值为 Geist Mono / Cascadia Code / Consolas。中文标题使用本机华文中宋(STZhongsong)并有回退。现有名字不代表字体已随包分发;新增字体需处理许可证、离线资源和回退,不能依赖 CDN。 + +暗色基线:背景 `#181818`、卡片 `#222222`、边线 `#3c3c3c`、正文 `#f2f0ec`、暖灰强调 `#d6cfc2`。不要改成蓝紫色主题。浅色背景为 `#f5f5f1`,卡片白色;具体层级沿用现有 CSS。 + +字号 12/14/16/18 的调整必须覆盖导航、标题、正文、控件和弹窗。表格表头与行列必须对应,长连接名/ID/路径不能挤乱操作列;用明确列定义、截断/展开、min-width/overflow 处理,不以破坏 table 语义补布局。 + +### DPI 与原生主题是独立验收项 + +宿主已有 Per-Monitor V2、WM_DPICHANGED、WebView2 自动缩放。不要用 CSS zoom、页面整体 transform 或位图拉伸修复清晰度,也不要重复叠加系统和页面缩放。 + +浅/深模式必须同步页面、标题栏/上边框与右键菜单;不能简单固定成某种颜色。已有 `window.ready`、`window.theme`、应用确认和失败重试逻辑,需保留快速深→浅→深切换的最终一致性。原生菜单颜色需宿主/WebView2 配合,不能只改 CSS。 + +## 5. 应完成的用户流程 + +### 5.1 新建与复用连接 + +第一步选择“Web 访问本地 / Agent 远程操作”,再选择支持的传输、目标和授权配置。保存配置不自动连接、配对、启用写权限或批准任务。 + +| 组合 | 当前实际支持 | GUI 表现 | +|---|---|---| +| Web + OpenAI Secure Tunnel | 既有标准 MCP/官方运行时路径 | 保留;账号实际支持单独验证 | +| Web + Cloudflare Named Tunnel | 既有标准 HTTPS MCP 路径 | 保留 | +| Agent + Cloudflare WSS | 新配对桥接/目标 CLI 已有 | 新增配置和配对流程 | +| Agent + 自建 Relay WSS | 新 CLI 已有,公网只读已验证 | 新增端点、可信 CA、凭据引用和状态 | +| Agent + 官方 Tunnel 标准 MCP | 不等于现有配对 WSS 操作链 | 不将 `/v1/peer` 当成通用官方 Tunnel;未接能力明确不可用 | + +GUI 的旧 `ConnectionTransport`/SavedConnection/RPC 还没有等价的 Relay 配置字段;不能只往旧 connections.save 填入新字符串。需后端先定义一致的保存契约。自建 Relay 外层 TLS 在中转终止,文件/操作内容由端点内层 mTLS 保护;普通 Web 客户端不能直接替代持有配对密钥的原生桥接。 + +历史列表至少区分名称、用途/目标、通道、授权、运行状态、操作。查看、设为默认、启动、停止是不同动作。离线不能显示在线,Tunnel 就绪不能显示为客户端已认证,更不能显示可执行。 + +### 5.2 配对与设备 + +提供目标/Agent 角色、公开 bundle/CSR 导入导出、完整指纹核对、连接范围、证书有效期和撤销入口。只展示公开材料和可安全复制的指纹;私钥不得进入 JS、DOM、剪贴板、日志或普通备份。 + +指纹需用户通过可信方式核对,不因服务器同时返回 bundle 和指纹就自动信任。信任变化/证书过期应阻断连接并明确说明,不能重试后自动接受新设备。 + +### 5.3 开发者模式与运行器 + +明确区分只读、受信任主机执行、尚不可用的严格隔离执行。`trusted_host` 使用当前用户文件/网络权限,不是沙箱;必须在授权和审批位置说明这一实际后果。 + +旧 developer.saveProfile 的 command_profiles 与新 operations.Catalog 是不同模型。新 UI 应管理明确的运行器路径、SHA-256、脚本类型和最少环境变量;通过原生浏览/受控宿主取值,不让远程 Agent任意配置可执行文件。 + +实际版本来自获批的 kind=version 作业;“已安装/启动时哈希已核对”不能显示为“版本验证成功”。开发者开关不等于可执行,后端 capability 和失败原因应独立显示。 + +### 5.4 本地审批中心 + +提供待审队列、详情、批准/拒绝和状态反馈。详情需绑定:请求主体、连接/设备、工作区、操作类别、运行器和映像哈希、argv、完整脚本、资源限制、文件新旧内容/补丁结果、摘要和审批期限。 + +新旧内容/脚本/输出均按不可信数据处理,使用纯文本/安全高亮,严禁未转义 innerHTML。不得截断关键参数后不提供查看完整内容。用户批准的摘要必须正是看到的那一份,配置或内容变更后原审批失效。 + +批准只能从可信本地 UI 进入宿主,不注册成远程 MCP 工具;不能把 JS 中一个 `confirmed=true` 视为权限。不要默认勾选信任声明、批量默许未知计划或在刷新后重放批准。 + +### 5.5 作业与输出 + +使用真实状态:prepared、awaiting_approval、queued、running、succeeded、failed、cancelled、interrupted、unknown、rejected、expired。unknown 必须与 failed 分开,提示可能已经产生副作用,提供检查/恢复材料,不能自动重跑。 + +输出在任务结束后按 stdout/stderr 分页读取;后端返回 base64 字节,不保证 UTF-8。需要明确解码/原始数据处理,不能以乱码证明命令失败。当前没有实时输出流,GUI 不应伪造逐行运行日志。 + +保留 Agent 的 60 秒轮询租约语义:**GUI 本地查看状态不能偷偷代替 Agent 心跳延长远程作业**。本地状态投影应读取只读快照,而不是无条件调用会续租的 Agent status 路径。 + +远程 cancel_operation 等待回收后返回;本地 CancelLocal 只是持久化请求,GUI 要等待真实终态再显示已停止。进程树清理无法确认时必须保持故障/unknown 并关闭准入,不能继续显示安全就绪。 + +### 5.6 文件规则、健康和备份 + +deny 优先;ignore 仅影响发现,不是保密机制。规则编辑需展示影响连接、预览与 revision/CAS 冲突,冲突时保留草稿并重新加载。现有 rules.apply 是离线管理,不证明外部 CLI 目标已停止;在线撤权与选择性 epoch 未完成前,不做“已立即全局生效”的提示。 + +健康报告区分配置校验、进程、传输、认证、权限、执行器、证书有效期。检查更新在没有真实更新源时明确未配置,不伪报最新版。 + +现有 `.lpbackup` schema 为 `local-probe.backup.v1`。恢复须校验并预览,不直接解析任意 JSON 成可执行权限。保留恢复时清空/撤销开发者授权的防护;不要把身份私钥或操作账本自动纳入普通配置备份。 + +## 6. 现有桌面接口与待补契约 + +正式页面通过 `window.chrome.webview.postMessage` 与宿主通信,固定 origin 为 `https://localassets/index.html`。CSP 禁止任意网络连接和内联脚本;不要为图标、字体或调试 fetch 放宽策略。 + +实际 envelope: + +```json +{"id":"gui-request-1","method":"snapshot","params":{}} +``` + +响应为 `{id,ok,data,error}`。data 目前是 Snapshot:desktop、connection、workspace、view 及可选规则/备份选择数据。不是通用 JSON-RPC 2.0,不应擅自改 envelope 或向远程公开它。window.theme 由宿主单独处理,确认实际主题后返回。 + +| 已存在方法 | 当前作用 | +|---|---| +| snapshot | 当前桌面快照 | +| connections.save/select/remove | 保存、选择、移除历史配置;旧参数无 purpose/Relay 等新字段 | +| connection.connect/reconnect/cancel/disconnect/setTransport | 当前单 controller 的生命周期 | +| workspace.pick/add/update/remove | 原生目录选择与授权管理 | +| rules.read/preview/apply | 读取/预览/离线规则提交 | +| developer.configure/saveProfile/removeProfile | 旧开发者配置,未绑定新操作引擎 | +| settings.backup/pickBackup/restore | 原生备份保存/选择/预览/恢复 | +| logs.export / diagnostics.export | 受控日志/诊断导出 | +| window.theme | 宿主主题应用与确认 | + +**以下只是待实现的 GUI 本地契约方向,不是已存在 RPC 名称:** + +| 契约方向 | 要求 | 可复用后端 | +|---|---|---| +| 连接详情/能力/多实例状态 | connection ID、用途、目标、传输、各层 readiness、受影响范围;支持独立启动/停止 | config、连接宿主;完整多实例控制面待补 | +| 配对申请/核对/签发/导入/撤销 | 公开材料、指纹、范围;私钥留宿主;本地认证与撤权 | deviceidentity | +| 运行器目录表/执行策略 | 原生选择、哈希核对、显式权限和 revision | operations.Catalog、config v2 | +| 审批列表/详情/批准/拒绝 | 本地所有者上下文、ID/digest、到期与确认;禁止从远程主体字段取得权限 | Journal.Records / Decide | +| 作业列表/详情/输出/本地取消 | 只读投影、不续 Agent 租约;取消后等待终态;输出有界 | Journal、Engine、CancelLocal | +| 健康/证书/诊断 | 真实状态、脱敏、明确未实现能力 | 现有诊断及后续宿主投影 | + +优先直接复用 Go API 或可信的类型化本地 IPC。不要拼接 shell 命令调用 CLI,不将私有路径/运行器由远程参数任意指定。若先用固定 CLI 适配,也须固定程序、结构化 argv、超时、权限校验与严格结果解析,并明确临时方案边界。 + +新快照/错误 DTO 和本地 RPC 必须先与后端对齐,再让页面依赖它们;这里不预设尚未存在的字段就是稳定 API。 + +## 7. 当前后端限制,设计时必须体现 + +- 操作目标 Windows;Linux Agent 尚未实机运行。此次测试方向是 Linux Agent → Windows 目标。 +- 运行器需要本地明确配置和哈希,默认不继承全部环境。每作业最多32进程、1 GiB汇总提交内存、累计用户态CPU/墙钟预算、每路64 KiB输出;不是网络/文件沙箱。 +- 默认作业超时60秒,上限30分钟;审批五分钟;Agent运行状态轮询租约60秒。 +- 文本文件上限128 KiB;精确补丁最多32个唯一上下文编辑。已有文件是保存 before image 后锁定句柄更新,**不是原子替换**;异常可能部分写入,必须保留 unknown/人工检查路径。 +- 当前 cmd 脚本不接额外 args,作业目录不得有空格/cmd元字符;准备阶段拒绝不支持组合。不能在 GUI 中悄悄改成 shell 拼接。 +- 历史作业最多128个,约64 MiB账本预算,尚无自动归档;需明确满额/维护状态。 +- 当前全局配置 revision 改动会使旧审批失效;连接级选择性 epoch 和在线规则尚未完成,不能承诺只影响一个连接的配置热更新。 +- 已验证两连接作业并发;完整多连接生产宿主仍待做,计划验收至少三条连接独立生命周期。 +- 之前的真实公网验证覆盖只读链路。新增命令/写入尚未经过真实 Relay 和另一电脑,不可在 GUI 宣称已跨机验收。 + +## 8. 工作拆分与责任 + +| 优先级 | GUI 负责人交付 | 后端依赖/协作 | +|---|---|---| +| P0 基线与设计 | 复用当前正式页面;补双用途、配对、审批/作业的可操作样稿与状态清单 | 核对真实字段,记录接口缺口;演示数据只能留在隔离样稿 | +| P0 类型契约 | 定义并评审本地 DTO、错误与异步状态;保留只读兼容 | 后端确认权限/生命周期,补缺失管理 API | +| P1 单连接真实闭环 | 用途→配置→配对→授权→待审→批准→真实结果/取消 | 目标运行器托管、审批/作业本地投影 | +| P1 多连接与规则 | 独立卡片/拓扑、筛选、影响范围、冲突草稿、明确待接能力 | 多实例宿主、在线撤权、选择性 epoch | +| P1 桌面一致性 | 原生主题、DPI、目录/备份对话框、右键/复制/刷新 | 必要时共同修改 desktophost/fork 并保留实际测试 | +| P2 验收与打包 | 截图、测试记录、独立开发包、文档、明确遗留项 | 后端封板后做 Linux/真实 Relay 联调 | + +新增关键交互可先交付独立可操作 HTML 样稿供人工确认;已认可的现有布局无需推倒重做。正式页面不得混入 demo ID、模拟在线、假版本、假健康或自动批准。 + +## 9. 验收清单 + +### 功能与权限 + +- 新建后能在历史找到并复用同一配置;查看/选择不误断其他连接;至少三条连接生命周期以真实宿主为准。 +- 只读默认不变。只有显式可写 profile + trusted_host + 开发者连接许可 + 工具许可 + 本地批准,才可执行对应操作。 +- 改变脚本/参数/文件版本/授权后,旧审批不能继续;失效/撤权/过期/存储故障可见且不自动放开。 +- 两个主体/连接之间看不到或取消不了对方任务;本地所有者可查看/取消自己的所有受管任务。 +- 相同 nonce 重试不重复执行;未知结果不自动重跑。规则/恢复冲突保留用户修改和输入草稿。 +- 令牌不写日志/URL/localStorage/普通备份;私钥不送到页面。秘密输入若暂经页面,及时移交可信宿主并清空,不回读明文。 + +### 视觉、桌面与可访问性 + +- 宽/窄窗均检查侧栏图文对齐、长连接名/路径、表头对应、树与列表联动、弹窗和键盘焦点。 +- 明暗切换覆盖页面、原生上边框与右键菜单,快速切换、失败重试和刷新后仍一致。 +- 实际 WebView2 检查100/125/150/200%缩放、窗口缩放及混合DPI跨屏;缺设备的项目标未验收,不能用浏览器样稿代替。 +- 正文、错误、脚本、输出可选择复制,右键/F5/Ctrl+R可用;轮询不吞掉草稿、选区或滚动。 +- 图标按钮有 tooltip/aria-label,收展状态、键盘操作与深色输入框对比清楚。必要状态不能仅靠颜色区分。 + +### 自动检查 + +```text +node scripts/Test-LocalProbeDesktopFrontend.mjs +go test ./... +go test -race ./... +go vet ./... +``` + +新增 UI/RPC 行为要补相应测试;涉及原生主题/DPI需运行有关宿主测试并做真实窗口人工检查。现有前端 VM 用例只验证逻辑与部分结构,不证明像素、原生对话框或所有电脑清晰度。 + +构建脚本是 `scripts/Build-LocalProbeDesktop.ps1`,启动脚本是 `scripts/Start-LocalProbeDesktop.ps1`,打包验证是 `scripts/Test-LocalProbeDesktopPackaging.ps1`。使用明确的 GoPath 与新的输出目录,先阅读脚本:Desktop 构建还会生成 `bin/local-probe-mcp.exe`,仅改 GUI OutputPath 不代表不会覆盖其它文件。不要覆盖用户正在运行的 EXE、改真实授权或启动真实 Tunnel 做设计验收。 + +仓库 go.mod 最低 Go1.25;本轮证据使用Go1.26.5。有本地 go-webview2 fork 和许可证要求;新增依赖/字体需审查许可、离线打包、CSP、包大小与原生兼容影响,默认复用现有技术栈。 + +## 10. 最终交付物 + +1. 修改后的正式页面/样式/图标及需要的受控宿主桥接代码,不能只交图片或独立 HTML。 +2. 新交互样稿(如使用)、关键页面/明暗模式截图、真实窗口与DPI验收结果。 +3. 稳定的本地 DTO/RPC 说明、后端缺口清单及已联调能力矩阵。 +4. 自动测试与人工步骤/结果,明确失败和未验收项目;禁止用配置意图替代运行证据。 +5. 独立可运行开发构建、操作手册和遗留项;未完成的按钮有真实禁用理由。 + +此次交接不包含提交/推送/合并/Release 授权。公开交付前另做敏感信息、许可证和包检查。真实 Relay 与用户 Linux 电脑的操作验收,放在后端与 GUI 开发完成后按用户安排进行。 + +## 11. 继续阅读 + +- [总体技术实现书](R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md):完整范围和阶段;历史未决项以最新执行决策/源码为准。 +- [实际实施状态](IMPLEMENTATION_STATUS.md)、[R12进展](R12_PROGRESS.zh-CN.md):按日期区分历史与最新实现。 +- [受信任执行决策](R12_EXECUTION_DECISION.zh-CN.md):用户已明确选择 trusted_host,无需重新询问同一产品选择。 +- [操作后端用法与限制](R12_OPERATIONS_BACKEND.zh-CN.md):作业、审批、文件及资源约束。 +- [配对与通道](R12_PAIRING_AND_TRANSPORT.zh-CN.md)、[Relay部署记录](R12_RELAY_DEPLOYMENT.zh-CN.md):连接方式与实际公网边界。 +- [本轮后端证据](evidence/r12/2026-10-24-operations.md):真实本机测试范围,不能替代GUI/跨机验收。 + +**给接手人的开始指令:** 克隆 `feat/r12-dual-mode` 并记录提交,核对正式GUI资源,复现24个前端VM基线;据本交接书列出页面/本地契约缺口,复用当前风格完成新增交互样稿和类型化适配。对尚未实现的后台控制面提出明确接口需求,逐个接入真实闭环,保持默认只读、逐次本地审批、主题/DPI/右键等既有行为,提交独立构建与验收记录。 diff --git a/docs/IMPLEMENTATION_STATUS.md b/docs/IMPLEMENTATION_STATUS.md index 44a8803..d503bc7 100644 --- a/docs/IMPLEMENTATION_STATUS.md +++ b/docs/IMPLEMENTATION_STATUS.md @@ -1,4 +1,51 @@ -# 实际实施状态与验证记录 +# Implementation status and verification history + +## 2026-10-24: R12 repository handoff + +The complete R12 development implementation is delivered on `feat/r12-dual-mode`, based on the R11.3 code plus the four-language README update from main. Earlier entries saying "uncommitted" or "not pushed" describe their historical development rounds; they do not supersede this source handoff. No new Release, deployment or main merge is part of this upload. + +English is the default entry language: [developer guide](R12_DEVELOPMENT.md), [GUI handoff](GUI_HANDOFF.md), [operations](R12_OPERATIONS.md), [pairing/transport](R12_PAIRING_AND_TRANSPORT.md) and [documentation index](README.md). The dated Chinese plans and evidence are retained. + +| Area | Implemented | Still pending | +| --- | --- | --- | +| Paired transport | Persistent identities, certificate grants, revocation/leases, stdio Agent, direct WSS and static Relay with endpoint mTLS | Automated rotation/renewal and production control plane | +| Windows operations | Explicit trusted-host commands/scripts/versions/build/test, text writes/patches, exact local approval, private durable jobs, bounded output and cancellation | GUI/Web advanced ingress and trusted local management adapters | +| Runtime/rules | Scoped reads/writes, offline rules, two independent concurrent jobs | Full three-connection host, online rules and selective authorization epochs | +| Testing | Local Windows operation evidence; previous public read-only Relay evidence; fresh Go test/race/vet and frontend checks for upload | Linux Agent to Windows operation acceptance over the real Relay, GUI integration and actual mixed-DPI acceptance | + +`trusted_host` uses current-user file/network permissions without sandbox guarantees. It does not enable old desktop execution gates or upgrade read-only profiles. Linux target execution/writes remain unsupported. File updates are not atomic replacement, and unknown results are not replayed. + +Fresh upload checks and their limits are recorded in [source handoff evidence](evidence/r12/2026-10-24-source-upload.md). The records below remain a historical timeline. + +--- + +## 2026-10-24:R12 本地审批与真实操作后端 + +- 新增私有持久化作业、本地批准 CLI 和配对 MCP 操作工具。真实命令/版本/脚本/build/test、文本写入/精确补丁已接线;需 v2 显式可写 profile、trusted_host、开发者连接许可、工具许可及精确计划本地批准,旧只读配置不升级。 +- 本机真实四类脚本、Go 编译/单元测试、加密 MCP 闭环、CLI批准、幂等、重启不重放、双连接作业隔离、取消、文件冲突及只读权限测试通过;Windows Job 限制经内核读取验证。 +- 独立后端开发构建,未接 GUI/Web 高级入口;Linux Agent 待实机验收,Linux 目标执行不支持。在线规则/选择性授权版本/完整多连接宿主仍待完成。本轮未测试或修改真实 Relay、未连接另一电脑、未提交或推送。 +- 细节见[操作后端说明](R12_OPERATIONS_BACKEND.zh-CN.md)。 +- 最终完整 test/race/vet、独立 Windows 构建、Linux 交叉编译及敏感信息扫描通过;跨机/真实中转操作未测试。证据见[本轮操作验证](evidence/r12/2026-10-24-operations.md)。 + +## 2026-10-24:R12 公网 Relay 测试部署 + +- 已按授权在既有云服务器部署 Relay/TLS 前端,仅开放 TCP 8080,复用 nobody,保留原有 443 服务。直接公网 WSS、端点 mTLS、实际合成文件读取与范围拒绝通过;修复等待目标断线槽残留后,公网 race 连续三次 PASS,临时 SSH 转发已关闭。 +- 前端限制公网 NAT 网卡监听、单元日志限流及自身 socket MSS=1100,解决 Docker 误连和本次公网 TLS 超时;未降低证书验证、未修改全局 MTU/路由。Linux 前端实际测试通过。测试叶证书 2026-11-07 到期,正式续期和完整远程操作仍未交付。 +- 详细故障、测试范围、部署哈希及维护约束见[公网 Relay 运维记录](R12_RELAY_DEPLOYMENT.zh-CN.md)。本轮没有提交或推送源码。 +- 最终源码完整 `go test ./...`、`go test -race ./...`、`go vet ./...` 均通过;相关源码/部署脚本/文档敏感信息扫描未命中。 + +## 2026-10-24:R12 配对、原生 Agent 与 Relay 只读后端闭环 + +- 新增持久化设备身份/配对/撤销、Windows DPAPI 与私有 DACL、独立叶密钥运行时;新 pair/agent/target/relay CLI 已可编译运行。配对主体进入现有 MCP policy,保留只读与目录范围,认证入口互斥。 +- 直接 WSS 和自建静态 Relay 均通过本机集成;真实目标/Agent EXE 经官方 SDK stdio 和 Relay 读取合成文件通过。修复 WSS 读取 deadline 被 Gorilla 永久缓存导致的 HTTP EOF 风险,增加恢复读取回归和 race 重复验证。 +- 本轮不等于完整远程操作交付;实际命令/写入/审批/作业、多连接控制面、GUI 和公网跨机验收仍未完成。完整范围、失败与测试记录见 [R12 进展](R12_PROGRESS.zh-CN.md),操作约定见 [配对与通道说明](R12_PAIRING_AND_TRANSPORT.zh-CN.md)。 +- 最终完整 test/race/vet 通过,配对解码 fuzz 237,185 次通过;还修复 Windows 配置替换的短暂错误 5,占用类错误有限重试且保留永久失败,暂停/恢复 race 300 次通过。开发产物位于忽略目录 `bin/r12/`,未提交/推送或部署。 + +## 2026-10-23:R12 双用途与远程操作第一后端增量 + +- 依据 [R12 技术实现书](R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md) 在 `feat/r12-dual-mode` 实施;用户已明确选择新增 `trusted_host`。旧配置仍默认隔离要求,不自动开放执行。 +- 已新增 v2 用途/执行策略配置、官方 MCP 的原生访问优先说明、TLS 1.3 双向认证与 WSS 字节流样机,以及 Windows 本地受信任进程启动基础。尚未接入生产 MCP/GUI,也未完成 Relay、持久化配对、作业审批、写入和多连接。 +- 正常主机环境全项目 test、完整 race 复测、vet 通过;首轮 race 的连接切换偶发失败仍保留,不能声称根因已修复。详细范围、失败与后续事项见 [R12 进展](R12_PROGRESS.zh-CN.md)。未提交/推送/部署,未新建账号或修改系统网络策略。 ## 2026-10-07 补充:源码整合与 MIT Preview 发布准备 diff --git a/docs/R12_DEVELOPER_START.zh-CN.md b/docs/R12_DEVELOPER_START.zh-CN.md new file mode 100644 index 0000000..cb59b90 --- /dev/null +++ b/docs/R12_DEVELOPER_START.zh-CN.md @@ -0,0 +1,148 @@ +# R12 开发材料与接手入口 + +交接日期:2026-10-24。适用对象:接手 GUI 的开发人员,以及协作补齐本地管理接口的后端人员。 + +仓库默认入口为[英文开发指南](R12_DEVELOPMENT.md)。最新 R12 从 `feat/r12-dual-mode` 获取;此前 ZIP 保留为独立时间点快照。 + +## 1. 先取得正确源码 + +R12 的持续开发入口是仓库 `feat/r12-dual-mode` 分支,包含原先未提交/未跟踪的完整实现。克隆时使用 `git clone --branch feat/r12-dual-mode git@github.com:LE-saber/Local-Probe.git`,并记录实际提交;只克隆旧 main 或最初基线会缺少 R12。本轮只上传开发源码,不代表已合并 main 或发布 Release。 + +此前已交付的 ZIP 是以 `dd0a6b73981d8006403913e400d698c3b8fee291` 为基线的工作树快照,没有 `.git`。下面包结构说明仅适用于该存档;仓库接手直接使用英文开发指南,不需要额外下载本机快照。 + +交付包目录: + +```text +README.zh-CN.md 交付包使用说明 +SNAPSHOT.json 基线、文件数、排除范围与验证范围 +SOURCE_SHA256SUMS.txt source 下每个文件的 SHA-256 +Verify-Snapshot.ps1 解压后核对完整性,不运行项目 +source/ 可独立构建的当前源码、测试、示例和文档 +``` + +在新目录解压并校验,保留原 ZIP 作为交接基准。不要覆盖已有工作树、执行 reset/clean,或把这个快照当作正式版本安装到用户环境。已有仓库需要整合时,在独立分支/工作目录中比对后导入;快照包含新增文件,不能仅应用 tracked diff。 + +本包不提供真实运行配置、配对身份、令牌、私钥、CA、SSH 信息、账本、用户备份、日志、编译缓存、现成 EXE 或 Go 工具链。示例配置并不授权任何真实连接;接手人应创建自己的临时工作区和测试身份。 + +## 2. 阅读顺序 + +1. [GUI 开发交接书](GUI_HANDOFF.zh-CN.md):视觉基准、交互、现有 RPC、拟议契约和验收要求。 +2. [R12 最新进展](R12_PROGRESS.zh-CN.md)、[实施状态](IMPLEMENTATION_STATUS.md):从上往下阅读,后面的旧记录属于历史。 +3. [操作后端](R12_OPERATIONS_BACKEND.zh-CN.md):本地审批、作业、运行器、文件写入及实际限制。 +4. [执行契约决策](R12_EXECUTION_DECISION.zh-CN.md):已经批准 `trusted_host`,不需要重新决定同一产品选择。 +5. [配对与通道](R12_PAIRING_AND_TRANSPORT.zh-CN.md)、[Relay 部署记录](R12_RELAY_DEPLOYMENT.zh-CN.md)。 +6. [R12 总体技术计划](R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md):后续任务与总体架构;计划中的接口不代表已实现。 +7. [本地操作验证证据](evidence/r12/2026-10-24-operations.md)、[通道证据](evidence/r12/2026-10-24-transport.md)。 + +以真实代码、最新证据和执行决策为准。历史计划中的严格网络隔离要求没有在新模式中实现;`trusted_host` 使用当前用户的文件和网络权限,**不是沙箱**。 + +## 3. 当前可以复用的成果 + +| 范围 | 已有实现 | 尚不能据此宣称 | +|---|---|---| +| GUI | 五页正式页面、桌面桥接、原生备份对话框、主题/DPI处理、24个前端VM场景 | R12 GUI 已接好、所有显示器均已人工验收 | +| 身份/通道 | 持久化配对、撤销、端点 mTLS、原生 stdio Agent、直接 WSS 与静态 Relay | 自动续期、动态路由/票据、身份灾备已完成 | +| 操作后端 | Windows 命令/脚本/版本/build/test、文本写入/精确补丁、逐次本地审批、作业与取消 | Web/GUI 高级入口或 Linux 目标执行已完成 | +| 并发 | 两连接各一个真实作业,互相隔离 | 至少三条独立生产连接宿主已交付 | +| 文件规则 | 只读边界、deny/ignore、离线读取/预览/提交、写前复核 | 在线规则立即撤权与选择性 epoch 已全部实现 | +| 验证 | 全项目 Go test/race/vet、实际运行器/构建测试、本机加密操作闭环已通过 | 新操作经 Linux 电脑和真实公网 Relay 已通过 | + +公网只读中转曾实际验证;当时 Agent 和目标仍在同一 Windows 电脑。新增操作后端尚未完成跨机中转验收,不能挪用旧证据。用户另有 Linux 电脑,要求开发完成后再测试;本材料不含其访问方式。 + +## 4. 工程入口与分工 + +| 路径 | 接手用途 | 责任边界 | +|---|---|---| +| `internal/desktopweb/assets/` | 正式 HTML/CSS/JS/SVG,现有风格的唯一正式基线 | GUI 主责 | +| `internal/desktopbridge/` | 本地 RPC、snapshot、备份、规则与旧开发者投影 | GUI 适配;权限契约与后端协作 | +| `internal/desktophost/`、`third_party/go-webview2/` | WebView2 宿主、原生对话框、主题与 DPI | 修改须保留真实 Windows 验证 | +| `internal/operations/` | 私有账本、审批、执行、状态和本地取消 | 后端核心,GUI 通过可信本地接口使用 | +| `internal/deviceidentity/` | 配对、授权主体、撤销与证书 | 后端核心;页面不接触私钥 | +| `internal/mcpserver/operations.go` | 配对 MCP 的八个操作工具 | 远程入口没有本地批准权限 | +| `internal/agentbridge/`、`internal/peertransport/`、`internal/relay/` | Agent 转发、加密流、静态中转 | 后端/后续集成 | +| `cmd/local-probe-target/` | 目标服务与可选操作引擎 | 独立后端入口 | +| `cmd/local-probe-agent/` | 原生 Agent 的 stdio MCP 桥接 | Linux/Windows Agent | +| `cmd/local-probe-pair/`、`cmd/local-probe-operations/` | 本地配对、检查、批准/拒绝/取消 | 可作为 GUI 管理契约的行为参照 | +| `deploy/operations/catalog.example.json` | 空的运行器目录表示例 | 按本机真实路径和哈希配置,不预授权 | +| `deploy/relay/` | 通用 Relay 示例和测试部署脚本 | 阅读材料,不自动部署或改真实服务器 | + +旧 `DesktopBridge.Service` 仍为单 controller;旧 `developer.go` 的 `network_enforcement_required` 不属于新操作引擎。不得仅改按钮状态或删旧门来假装新后端可用。 + +GUI 负责人优先完成页面和类型化适配;管理接口由后端协作补齐,不把安全核心搬进 JS,不另做一套执行器。接口正式落地前可用独立样稿评审,正式页面不得输出模拟健康、在线或批准状态。 + +## 5. 必须先对齐的本地接口 + +现有 envelope 为 `{id,method,params}` → `{id,ok,data,error}`,不是 JSON-RPC 2.0。完整已有方法和建议新增方法见 GUI 交接书;下表是**待设计/实现的接口范围,不是现有可调用方法**。 + +| 范围 | 必要数据和行为 | 实施注意 | +|---|---|---| +| 能力与连接 | 用途、通道、目标、单连接生命周期、可用能力与拒绝理由 | 配置选择、传输建立、内层认证和 MCP 就绪分别显示 | +| 配对 | 公开指纹、CSR/bundle 导入导出、连接绑定、撤销 | 可信本地操作;不把私钥或签发权限交给页面/模型 | +| 开发者配置 | trusted_host 明示、连接许可、可写 profile、运行器哈希 | 默认只读;改模式不自动批准任务 | +| 本地审批 | 精确计划、主体、目录、argv/脚本、文件前后内容、digest、失效原因 | 批准只走本地可信管理入口,绑定完整计划 | +| 作业 | 状态、分页输出、本地拒绝/取消、unknown/中断 | 本地查看不能误续 Agent 的运行租约 | +| 在线规则 | 预览、CAS、影响连接、撤权与活动任务处理 | 依赖后端;当前不能宣传在线即时生效 | +| 诊断/恢复 | 脱敏健康信息、配置备份恢复范围 | 恢复不能复活私钥、撤销授权或开发者批准 | + +新增 DTO 要标注必填/可空、版本、错误码、分页/大小限制和取消语义;先写契约/后端测试,再接正式 GUI。 + +## 6. 首次开发环境与检查 + +Windows amd64 为操作目标和 GUI 的验证环境。仓库 `go.mod` 最低 Go 1.25.0,已有完整证据使用 Go 1.26.5;建议先复用同一版本重现。模块初次获取需要网络或可信模块缓存;本包不是离线依赖包。保留 `go.mod/go.sum` 和本地 WebView2 replace。 + +GUI 需要 Windows WebView2 Runtime;前端逻辑测试需要 Node。race 需要该 Go 版本支持的 C 工具链。Python/Node/PowerShell/cmd 为可选真实脚本测试运行器;不因为缺少它们就伪造版本或自动安装软件。 + +从解压后的 `source` 目录执行: + +```powershell +go version +node --version +go mod verify +node scripts/Test-LocalProbeDesktopFrontend.mjs +go test ./... +go test -race ./... +go vet ./... +``` + +测试在开发人员正常用户环境执行,使用合成目录;已有 Windows 受限令牌/DACL 测试可能受自动化沙箱身份影响,失败需记录实际原因,不能删断言。TEMP/TMP 建议指向仓库隐藏的 `.tools` 子目录,避免 `./...` 枚举暂存构建目录;不要更改全局环境。 + +独立后端构建示例: + +```powershell +go build -trimpath -o bin/dev/local-probe-target.exe ./cmd/local-probe-target +go build -trimpath -o bin/dev/local-probe-agent.exe ./cmd/local-probe-agent +go build -trimpath -o bin/dev/local-probe-pair.exe ./cmd/local-probe-pair +go build -trimpath -o bin/dev/local-probe-operations.exe ./cmd/local-probe-operations +``` + +完整配对/启动顺序以通道说明为准。不要把示例中的省略号当作启动参数;命令行真实 flags 在相应 `main.go` 中。 + +GUI 构建:先阅读 `scripts/Build-LocalProbeDesktop.ps1`,再指定本机 `-GoPath`、独立输出目录。脚本还会写 `bin/local-probe-mcp.exe`;应在解压的新目录构建,不能覆盖用户正在运行的二进制。启动/打包的脚本见 GUI 交接书。 + +真实运行器 opt-in:设置进程级 `LOCAL_PROBE_OPERATIONS_REAL_TOOLS=1`,并提供 `LOCAL_PROBE_OPERATIONS_PYTHON`、`LOCAL_PROBE_OPERATIONS_NODE`、`LOCAL_PROBE_OPERATIONS_POWERSHELL`、`LOCAL_PROBE_OPERATIONS_CMD` 的本机绝对路径;定向运行 `TestInstalledPythonNodePowerShellScriptsAndVersions` 和 `TestRealGoBuildAndTestProject`。默认跳过不代表通过,Go build/test 还需本机可用的 Go。 + +## 7. 开发顺序和可验收成果 + +1. **基线重现**:校验包,运行前端与 Go 基线,列出环境差异;不得把历史 PASS 写成本机新结果。 +2. **契约评审**:确认能力/错误/状态,本地审批、身份与连接控制的接口先有后端实现和测试。 +3. **单连接闭环**:用途/配对/授权 → Agent 请求 → 本地查看精确计划 → 批准/拒绝 → 实际结果/取消;保持只读兼容。 +4. **生产控制面**:后端补在线配置、连接级选择性 epoch、至少三条独立连接宿主,再接 GUI;两并行作业不能代替验收。 +5. **桌面回归**:五页、树/拓扑/列表、主题与原生菜单一致、备份对话框、复制/右键/刷新、长文本和草稿保留;人工检查 100/125/150/200% 与跨屏。 +6. **跨机中转**:开发完成后,经用户提供 Linux 访问方式,测试 Linux Agent → 真实 Relay → Windows 目标;使用独立测试身份和合成文件,不使用用户工作目录。需要时由所有者安全提供短期凭据和有效 CA,不随源码交付。 + +每一步交付实际修改、接口说明、测试结果、失败/未测试项和独立构建。GUI 保留当前暖灰/中性暗色风格,不能重做为蓝紫主题或纯表格站;完整视觉要求见 GUI 交接书。 + +## 8. 当前限制与禁止误报 + +- Windows trusted_host 继承当前用户权限;进程 Job 限额不是文件/网络沙箱。不新增账号或修改系统网络策略来绕过既定边界。 +- 作业有全局 2/每连接 1 的并发限制、5 分钟批准窗口和 60 秒 Agent 状态轮询租约;输出结束后分页读取,不是交互式终端。 +- 账本有 128 个历史作业和约 64 MiB 的预算,满额拒绝,尚无自动归档。 +- 文本文件上限 128 KiB;精确补丁最多 32 项,非完整 unified diff。已有文件更新并非原子替换,异常可能 unknown,before image 用于人工恢复。 +- 当前配置整体 revision 变化会使旧计划失效;尚无完整连接级选择性热更新。 +- Linux Agent/Relay 与 Linux 目标执行是不同能力;当前不支持 Linux 目标执行/写入。 +- Relay 是静态角色路由开发版;动态凭据、自动证书生命周期和正式运维交付未完成。原测试叶证书将于 2026-11-07 到期,测试前需核对,不能关闭 TLS 验证。 +- 用户未授权本次交接执行 push/merge/Release、安装服务或改真实连接;源码材料不含部署凭据。 + +## 9. 对接后的反馈格式 + +请交回:修改基准/文件清单、已实现流程、接口新增/变更、自动检查及人工验收证据、待后端协作事项、失败和未测范围。GUI 专业人员可直接从 [GUI 开发交接书](GUI_HANDOFF.zh-CN.md) 的“给接手人的开始指令”继续,后端协作以本文件的接口和阶段边界为准。 diff --git a/docs/R12_DEVELOPMENT.md b/docs/R12_DEVELOPMENT.md new file mode 100644 index 0000000..0568e50 --- /dev/null +++ b/docs/R12_DEVELOPMENT.md @@ -0,0 +1,112 @@ +# R12 developer guide + +Updated: 2026-10-24. This is the English entry point for the current development implementation. Read [repository rules](../AGENTS.md), the [master plan](MASTER_PLAN.zh-CN.md) and [actual status](IMPLEMENTATION_STATUS.md) before editing. + +## Get the implementation + +```powershell +git clone --branch feat/r12-dual-mode git@github.com:LE-saber/Local-Probe.git +Set-Location .\Local-Probe +git status --short --branch +git rev-parse HEAD +``` + +The R12 code and handoff documents are on this branch, including files that were previously untracked. Cloning the older main baseline is insufficient. The earlier developer ZIP is a dated snapshot; this branch is the continuing source of development. No release/tag is created by uploading this source. + +If you already have local changes, fetch and compare in a separate checkout/branch. Do not overwrite a working tree, run reset/clean, or copy private runtime data into Git. Record the commit used for every test or build. + +## Product scope and actual status + +Two connection purposes are distinct from their transports: + +- `web_local`: standard MCP access from a Web AI to authorized local files, through the existing supported ingress. +- `agent_remote`: a native Agent bridge connecting to another execution environment through direct WSS/Tunnel or a self-hosted Relay. + +The Agent should use authorized native tools when it already has direct access to the same workspace. Client name, IP or matching paths do not establish locality and must not grant permission or bypass an Agent's own restrictions. WSL, containers and VMs may be different execution environments on the same computer. + +Implemented R12 backend: + +- Persistent device/Agent pairing, certificate-bound grants, revocation and active leases. +- Native stdio MCP bridge, scoped paired target, direct WSS and static role-separated Relay; endpoint TLS 1.3 mutual authentication keeps MCP payloads encrypted through the Relay. +- Explicit Windows `trusted_host` commands, scripts, actual version calls, build/test, bounded UTF-8 writes and exact patches. +- Private durable jobs, exact per-operation local approval, subject/connection isolation, idempotency, cancellation, output bounds and restart without automatic replay. +- Two connections each running one real job independently. This is not the full production multi-connection host. + +Not complete: GUI/Web advanced-operation ingress, trusted local management interfaces, at least three independently managed production connections, online rules/selective epochs, automatic certificate/credential lifecycle, archival/retention and final cross-machine operation acceptance. Linux Agent builds exist; Linux target execution/writes are unsupported. + +## Source map + +| Path | Responsibility | +| --- | --- | +| `cmd/local-probe-agent` | Official SDK stdio bridge for the native Agent | +| `cmd/local-probe-target` | Paired MCP target; optional operation engine | +| `cmd/local-probe-pair` | Local identity creation, fingerprints, issue/install/revoke | +| `cmd/local-probe-operations` | Local inspect/approve/reject/cancel and before-image access | +| `cmd/local-probe-relay` | Fixed-route encrypted stream forwarding on loopback | +| `cmd/local-probe-relay-edge` | Narrow TLS reverse proxy for the Relay | +| `internal/deviceidentity` | Private identity storage, grants, revocation and leases | +| `internal/peertransport`, `internal/agentbridge`, `internal/relay` | TLS/WSS transport and MCP forwarding | +| `internal/operations` | Runner catalog, immutable plans, private journal and execution | +| `internal/mcpserver/operations.go` | Eight paired MCP operation tools | +| `internal/config`, `internal/policy`, `internal/rootfs` | Configuration, authenticated scope, real file boundaries and controlled writes | +| `internal/desktopweb/assets` | Existing approved GUI HTML/CSS/JS/SVG baseline | +| `internal/desktopbridge`, `internal/desktophost` | Local RPC and Windows/WebView2 host | +| `deploy/operations`, `deploy/relay` | Empty catalog and generic Relay deployment examples | + +The official GUI is under `desktopweb/assets`; `prototypes/typography-review` is a historical mock with fake data. The old desktop bridge still owns one controller; its old `network_enforcement_required` gate is not the new operation engine. Do not remove a gate or fabricate state to simulate integration. + +## Environment and first checks + +Windows amd64 is the execution and GUI target. `go.mod` requires Go 1.25.0; CI and the recorded Windows verification use Go 1.26.5. Start with that toolchain to reproduce evidence. Initial dependency resolution requires network access or a trusted module cache. Keep `go.mod`, `go.sum`, the local WebView2 replace and third-party notices intact. + +Use Git, PowerShell and Node for development; WebView2 Runtime is required for the GUI. Race testing needs a supported C toolchain. Actual Python/Node/PowerShell/cmd runtime tests require explicitly selected local installations; do not auto-install them or invent version results. + +```powershell +go version +node --version +go mod verify +node scripts/Test-LocalProbeDesktopFrontend.mjs +go test ./... +go test -race ./... +go vet ./... +go build ./... +git diff --check +``` + +Run Windows account/ACL tests as the normal development user; an automation sandbox may change the identity being tested. Report such failures rather than weakening assertions. Keep process-local TEMP/TMP in an ignored `.tools` subdirectory so `./...` does not enumerate transient build files. Do not modify global environment settings. + +Build separate development binaries: + +```powershell +go build -trimpath -o bin/dev/local-probe-target.exe ./cmd/local-probe-target +go build -trimpath -o bin/dev/local-probe-agent.exe ./cmd/local-probe-agent +go build -trimpath -o bin/dev/local-probe-pair.exe ./cmd/local-probe-pair +go build -trimpath -o bin/dev/local-probe-operations.exe ./cmd/local-probe-operations +``` + +Read [pairing and transport](R12_PAIRING_AND_TRANSPORT.md) before starting a target. Use synthetic directories and new test identities. Samples are not complete live configurations and grant no access by themselves. + +For GUI builds, read `scripts/Build-LocalProbeDesktop.ps1` before selecting `-GoPath` and `-OutputPath`. It also writes `bin/local-probe-mcp.exe`; changing only the GUI output path does not protect an existing running MCP binary. Build and test in a separate directory. Preserve the existing user's processes, connections and authorizations. + +Real-runtime opt-in tests use `LOCAL_PROBE_OPERATIONS_REAL_TOOLS=1` and absolute paths in `LOCAL_PROBE_OPERATIONS_PYTHON`, `LOCAL_PROBE_OPERATIONS_NODE`, `LOCAL_PROBE_OPERATIONS_POWERSHELL` and `LOCAL_PROBE_OPERATIONS_CMD`. Run `TestInstalledPythonNodePowerShellScriptsAndVersions` and `TestRealGoBuildAndTestProject` separately with these prerequisites. Their default skip is not a pass. + +## Implementation sequence and ownership + +1. **Reproduce the baseline.** Record the commit, tool versions and actual checks. Previous PASS records are not new results on your computer. +2. **Agree local management contracts.** Backend first: capability/readiness, pairing, catalog, exact local approvals, job projections and owner cancellation. Define versioned DTOs, errors, paging and asynchronous state before the GUI depends on them. +3. **Complete one real connection.** Pair → explicitly authorize → request → locally inspect → approve/reject → observe actual result/cancel, preserving the read-only path. +4. **Finish the production control plane.** Backend first: online configuration/rule changes, affected-connection revocation/selective epochs and at least three independent connection lifecycles; then wire the GUI. +5. **Perform desktop regressions.** Existing five pages, topology/tree/list mix, native dialogs, theme synchronization, selection/copy/right-click/refresh, drafts, long content and real mixed-DPI windows. +6. **Validate cross-machine Relay operations.** After development, obtain the owner's Linux access details and short-lived test credentials. Test Linux Agent → real Relay → Windows target using synthetic data. Do not scan the LAN or assume authorization to an unknown machine. + +GUI ownership covers interaction, official assets and typed local adapters. Backend ownership covers authorization, identity, execution and runtime lifecycle. Prefer direct Go APIs or trusted typed local IPC. Remote MCP must never gain a local approval method; do not shell-concatenate a CLI wrapper or move security decisions into JavaScript. + +## Evidence and release boundary + +See the [upload verification](evidence/r12/2026-10-24-source-upload.md), [operation evidence](evidence/r12/2026-10-24-operations.md) and [transport evidence](evidence/r12/2026-10-24-transport.md). The prior public Relay test covered read-only behavior with both endpoint programs on the Windows computer; it does not establish Linux-to-Windows execution. + +No live configuration, token, endpoint identity, private key, SSH data, job journal, backup, binary or raw local log belongs in the source upload. Generic deployment examples do not authorize deployment. No new accounts or global network-policy changes are approved; the earlier Relay TCP 8080 exception is specific to that test deployment. `trusted_host` was explicitly approved and uses current-user OS permissions, without sandbox guarantees. + +Source upload is not authorization to merge main, publish a Release, install a service or change real connections. Return a file/commit list, interface changes, test and manual evidence, remaining gaps and independent development builds. Preserve MIT and all third-party licensing. + +Detailed supplementary materials: [Chinese handoff](R12_DEVELOPER_START.zh-CN.md), [R12 plan](R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md), [progress](R12_PROGRESS.zh-CN.md). diff --git a/docs/R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md b/docs/R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md new file mode 100644 index 0000000..bcdd7b1 --- /dev/null +++ b/docs/R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md @@ -0,0 +1,558 @@ +# Local-Probe 双用途与远程操作技术实现书 + +版本:1.0 · 2026-10-23 · 状态:待执行的开发方案,非功能交付声明。 + +2026-10-23 执行更新:用户已明确选择允许新增 `trusted_host` 受信任主机执行策略,不再需要等待该产品选择。默认/历史连接仍为 `isolated_required`。详见 [执行安全决策](R12_EXECUTION_DECISION.zh-CN.md) 和 [开发进展](R12_PROGRESS.zh-CN.md);正文中的待选择描述保留为决策背景,不用于再次请求同一授权。 + +本方案以当前仓库代码为起点,补齐“Web 访问本地”和“Agent 远程操作”。Agent 远程操作提供 Tunnel 与自建服务器转发两类通道。先交付并验证后端,再接入现有 GUI;不重新设计已经认可的界面。 + +本次仅新增计划文档。没有安装服务、部署公网服务器、创建账号、更改网络策略、启动命令执行或发布版本。本方案不把之前暂停的严格网络检查视为通过。 + +## 1. 结论与范围 + +### 1.1 推荐方案 + +采用“两个用途、一套权限核心、可替换的传输层”: + +1. **Web 访问本地**:Web AI 通过标准 MCP 访问用户授权的目标电脑;保留 OpenAI Secure MCP Tunnel 和 Cloudflare Named Tunnel 接入。 +2. **Agent 远程操作**:Agent 通过本机安装的轻量桥接程序访问另一执行环境;支持 Cloudflare Tunnel 与自建 Relay。支持官方 Tunnel 的 OpenAI 客户端还可走标准 MCP 通道。 +3. **自建 Relay**:公网服务器负责在线登记、路由、限流和密文字节转发。文件内容、命令、参数和结果在 Agent 桥接程序与目标电脑之间加密,Relay 不持有解密私钥。 +4. **权限与通道分离**:选择 Agent 用途不自动授予执行权限;选择 Web 用途也不永久限定只能读。实际能力由目标电脑上的授权配置和执行条件共同决定。 +5. **本地原生优先**:Agent 已能在当前环境中合法直接操作目标工作区时,提示使用原生工具;不通过本项目绕过 Agent 的沙箱、审批或文件权限。 + +### 1.2 本阶段必须交付 + +继承 [R11 后端优先计划](R11_BACKEND_FIRST_PLAN.zh-CN.md) 中尚未交付的七项能力,不因增加 Relay 而缩水: + +| 能力 | 本阶段交付边界 | +|---|---| +| 高级开发者命令运行 | 用户授权的运行器、命令、参数、工作目录与资源限制;真实运行、取消、返回退出状态 | +| 工具版本探查 | 真实探查选定工具,返回可执行文件身份、版本与失败原因;发现安装位置不等于版本已验证 | +| 多连接同时运行 | 多个连接有独立生命周期、权限和作业;一个连接停止不影响其他连接 | +| 高级文件规则 | 在线编辑、预览、版本控制及立即撤权;覆盖读取、搜索、写入、快照与写回 | +| 工作文件写入 | 授权目录内创建、更新及补丁写入;版本冲突和路径越界拒绝 | +| 构建与测试 | 真实执行用户批准的构建/测试流程,管理子进程及输出 | +| 自选脚本 | 用户选择脚本或批准脚本内容、运行器及输入;内容变更重新授权 | + +新增双用途、设备身份、Agent 桥接、两类远程通道、端点加密、配对撤销、远程部署与真实跨机验收。 + +这里的“远程操作”是文件、工具和开发任务操作。本阶段不包括屏幕投送、鼠标键盘控制、RDP、任意端口代理、完整 IDE 或自建 AI 推理服务。 + +### 1.3 默认假设 + +- 首个目标端是现有 Windows GUI;Agent 桥接支持 Windows/Linux;Relay 首先交付 Linux amd64,其他平台只在真实验证后声明支持。 +- 首版面向一个所有者管理少量可信设备,仍严格隔离不同连接;不承诺企业多租户 SaaS。 +- 公网服务器由用户持有或日后选择;当前不假定已经有域名、证书、管理员权限或可用账户套餐。 +- 默认只读。开启开发者功能必须指定连接、工作区与具体权限;旧配置不自动升级授权。 + +## 2. 实际代码基线 + +以下为本轮源码核对结果,历史测试说明见 [实施状态](IMPLEMENTATION_STATUS.md) 与 [R11 进展](R11_BACKEND_PROGRESS.zh-CN.md)。历史 PASS 不代表本方案已验证。 + +| 代码位置 | 已有基础 | 需要补建 | +|---|---|---| +| `internal/config/config.go` 的 `Connection` | connection/profile/credential、transport、Tunnel 与端口字段 | 用途、目标设备、授权主体、协议及加密配置引用 | +| `internal/config/transport.go` | `local`、`openai_runtime`、`cloudflare_named` | 新通道配置与合法组合校验;不能把 transport 元数据当身份 | +| `internal/mcpserver/server.go` | 官方 Go SDK;11 个只读工具;按 BoundScope 限制工具 | 设备信息、用途说明、作业及写入工具;按可信授权公开能力 | +| 同文件 `serverInfoOutput` / `handleServerInfo` | 版本、transport、connection/profile/root IDs;返回 `ReadOnly: true` | 目标身份、能力状态与原生访问提示;不能只改 readOnly 标志假装已可执行 | +| `internal/desktopbridge/developer.go` | 开发者配置投影 | 当前仍返回 `network_enforcement_required`,实际执行不可用 | +| `internal/networkguard/wfp/disabled.go` | 禁用实现 | 不提供实际网络 enforcement;不能当作通过的隔离能力 | +| `internal/desktopbridge/service.go` | 单一 `controller` 的桌面生命周期 | 多连接运行实例注册表、资源管理与故障隔离 | +| `readcore`、`rootfs`、`policy` | 读取、路径安全和规则基础 | 写入/快照/在线撤权的一致授权 | +| `config/FileStore`、`workspaceadmin` | 配置 CAS、锁与离线规则管理 | 在线管理事务、配置迁移及回滚 | +| `commandprofile`、`commandexec`、`confirmation`、`probe` | 执行计划、确认及固定探查基础 | 生产执行链、实际运行器与端到端验证 | +| `connectionmanager`、`supervisor`、`admission`、`runtimeowner`、`readiness` | 生命周期和准入组件 | 接入实际多连接宿主,避免并行另造一套协调器 | +| `cfaccess`、`previewconnect`、现有 GUI | 已有接入及操作界面 | 新用途、设备配对、Relay、真实作业状态 | + +尚无可交付的自建 Relay、原生 Agent 桥接、端到端配对 PKI。生产命令、写文件、脚本及多连接仍需完成。 + +当前 `go.mod` 为 Go 1.25.0,官方 MCP Go SDK 为 v1.7.0。执行阶段核对受支持的 Go 工具链及依赖版本后固定构建版本;不在本计划中顺手升级依赖,也不以模块语言版本代替构建工具链版本。 + +## 3. 产品模型与兼容性 + +### 3.1 三个独立维度 + +| 维度 | 值 | 职责 | +|---|---|---| +| 用途 `purpose` | `web_local` / `agent_remote` | 用户意图、引导、工具说明及原生访问提示 | +| 通道 `transport` | 现有官方/Cloudflare 通道;新增 Relay | 网络可达性和外层身份校验 | +| 权限 `grant` | 读、写、探查、命令、构建、脚本 | 在目标端限制实际操作,独立撤销 | + +加密配置另用 `security_profile` 表示。不能从用途推断是否加密,也不能从加密成功推断可以执行。 + +### 3.2 通道矩阵 + +| 用途与客户端 | 通道 | 是否需要 Agent 桥接 | 加密信任边界 | +|---|---|---|---| +| Web AI | OpenAI Secure MCP Tunnel | 否 | 标准 MCP,经平台处理;不声称对平台隐藏内容 | +| Web AI | Cloudflare Named Tunnel + 现有受控 HTTPS MCP | 否 | HTTPS 保护传输;Cloudflare 终止外层 TLS,不是中间方不可见的端到端加密 | +| 支持官方 Tunnel 的 OpenAI Agent | OpenAI Secure MCP Tunnel | 否 | 标准 MCP;按实际产品权限与能力验收 | +| 可启动本机桥接的 Agent | Cloudflare Named Tunnel 的 WSS 入口 | 是 | WSS 内再运行端点 TLS 1.3;边缘看到密文 | +| 可启动本机桥接的 Agent | 自建 Relay 的 WSS 转发 | 是 | Agent 桥接 ↔ 目标电脑双向 TLS 1.3;Relay 只转发密文 | +| 无法运行桥接的通用云 Agent | 任意自建盲转发 Relay | 不直接支持 | 不能要求普通 MCP 客户端理解项目自定义密文协议 | + +最后一种客户端可使用其支持的标准 MCP 服务路径;未来也可增加用户信任的网关,但网关会成为明文终点,必须另行设计,不能沿用“Relay 无法解密”的承诺。 + +官方 Secure MCP Tunnel 使用出站 HTTPS 拉取并转发 MCP,不是通用 TCP/WebSocket 隧道。其当前默认请求总期限为 120 秒、完整请求/响应封装上限为 10 MiB,且私有 Tunnel 不等于公开插件分发通道。因此长任务采用提交与查询方式,不能依赖一个长 RPC 持续等待。实际权限、关联和限制以接入时核验为准。[官方说明](https://developers.openai.com/api/docs/guides/secure-mcp-tunnels) + +### 3.3 同机 Agent 的处理 + +判定对象是“Agent 当前执行环境是否已具备目标工作区的原生访问能力”,不只是物理电脑是否相同。 + +- `native_preferred`:安装身份匹配、目标工作区可对应,且原生工具已有合法访问能力;桥接在本地给出原生访问建议,默认不建立不必要的远程数据连接。 +- `remote_required`:经配对确认目标是另一环境,或当前环境确实需要跨环境访问;按目标端授权连接。 +- `unknown`:无法证明;显示目标设备及工作区,让用户确认,不根据猜测自动运行。 + +实现使用随机安装 ID、执行环境 ID 和本地受控身份标记;安装 ID 不使用硬件序列号,也不单独作为授权凭据。WSL、容器、虚拟机、SSH/云执行环境分别处理。MCP `clientInfo`、机器名、相同路径和来源 IP 均不能证明同机。 + +MCP 初始化说明和工具描述统一加入:“目标已在当前环境可用且原生访问获准时,请使用原生工具;不要通过此服务绕过原生权限限制。”该提示是路由建议,不是可靠的客户端封锁机制。仅靠服务端无法识别所有本地 Codex 调用;确需禁止某客户端时,应撤销其连接授权或在客户端取消该插件。 + +## 4. 总体架构 + +```mermaid +flowchart LR + W[Web AI / 支持官方 Tunnel 的客户端] --> P[标准 MCP 平台通道] + P --> I[目标端受控 MCP 入口] + A[Agent 原生 MCP 客户端] --> B[local-probe-agent / stdio 桥接] + B --> T[Cloudflare WSS 或自建 Relay] + T --> E[目标端 TLS 1.3 双向认证入口] + E --> I + I --> G[可信主体 / 连接范围 / 授权版本] + G --> R[文件读取与规则核心] + G --> J[作业与写入管理] + J --> X[执行后端 / 快照 / 受控写回] + U[目标电脑上的用户管理界面] --> G + U --> J +``` + +图中的 B—E 之间建立内层 TLS。T 只承载加密流;标准 MCP 平台通道 P 不包含该自定义加密层。 + +### 4.1 三个程序的职责 + +| 程序 | 部署位置 | 职责 | 明确不做 | +|---|---|---|---| +| 现有 Local-Probe 宿主 | 被访问/操作的电脑 | 文件、规则、授权、执行、审批、多连接、审计 | 不把授权交给 Relay 决定 | +| 新 `local-probe-agent` | Agent 实际运行环境 | stdio MCP 入口、目标选择、身份验证、加密通道、断线恢复 | 不自行规划任务、不持有目标端所有者私钥 | +| 新 `local-probe-relay` | 用户公网服务器 | 设备登记、路由配对、连接配额、限流、密文转发 | 不执行命令、不存文件、不做开放代理 | + +GUI 不成为必需的网络转发节点;关闭窗口但保留托盘时维持既有宿主语义。真正退出宿主时明确处理连接和作业,不能遗留孤儿进程。首版后台常驻安装作为可选部署,不默认注册系统服务。 + +### 4.2 复用方式 + +传输适配器只产出经过验证的主体与字节通道,不直接访问磁盘或启动进程。所有工具共用现有 readcore/policy 及新增 operation 核心。Agent 桥接也用官方 MCP SDK,实现本地 stdio 服务和远端 MCP 客户端,保留取消、错误、能力和通知语义。 + +先做兼容性样机,验证官方 SDK 能在自定义 `net.Conn` 和 HTTP transport 上正常运行 Streamable HTTP;不自行实现另一套 JSON-RPC/MCP 协议。 + +## 5. 加密、配对与身份生命周期 + +### 5.1 两层加密 + +**外层**:双方通过 HTTPS/WSS 访问公开入口,验证域名证书。Relay 控制接口用独立的短期接入凭据;凭据不能放在 URL 查询串和日志中。 + +**内层**:Agent 桥接作为 TLS 客户端,目标端作为 TLS 服务端,使用 TLS 1.3 + 双向证书验证。Go 标准库 `crypto/tls` 包装有序的 WSS 字节流;使用标准链校验,再校验预配对的目标身份、证书用途及允许的 Agent 主体。不使用 `InsecureSkipVerify` 绕过正常验证,不设计自己的加密算法。[Go TLS 文档](https://pkg.go.dev/crypto/tls) + +TLS 建议固定最低版本 1.3,初版关闭会使撤销处理复杂化的会话恢复;后续启用恢复前必须证明重新执行主体撤销检查。不采用 0-RTT 写操作。 + +E2EE 保护的是桥接到目标之间的数据。Agent/模型仍会获得它请求的明文结果;不能宣传为模型提供方也不可见。两端被攻陷、用户批准恶意脚本等问题不由传输加密解决。 + +### 5.2 配对:信任不能由 Relay 自行建立 + +首版采用目标所有者控制的设备 CA + 显式配对: + +1. 目标端生成随机 device ID、独立 CA 密钥和目标 TLS 叶证书。CA 私钥仅供本地管理流程签发,不交给运行工具、远程调用或 Relay。 +2. 用户从目标 GUI 导出只含公开身份的配对包:协议版本、device ID、CA/公钥指纹、目标名称与入口信息。通过可信文件传输或当面核对指纹交给 Agent 侧用户。 +3. Agent 桥接本地生成私钥和 CSR,将待签发请求交给目标用户;可以由 Relay 中转,但必须核对 CSR 指纹。简单短码只用于定位请求,不能独立建立可信身份。 +4. 目标 GUI 展示 Agent 指纹、连接、工作区、权限和有效期。用户确认后签发 Agent 客户端证书,并创建目标端授权记录。 +5. Agent 验证收到的证书属于自己的公钥,保存证书和预先核对的目标信任根。Relay 替换包、CSR 或证书时应失败。 +6. 首次握手验证目标与 Agent 双方身份;目标再校验主体与 connection/profile 的绑定。 + +首版配对可用文件往返完成,避免依赖低熵口令自创协议;扫码和简化配对在安全流程稳定后增加。目标电脑重装或根证书改变必须重新核对,不能点一次“重试”就接受新身份。 + +### 5.3 存储、更新与撤销 + +- Windows 密钥使用系统凭据保护能力与严格文件 ACL;Linux 首版使用所属用户独占文件权限,明确不等同于硬件密钥库。 +- 配置保存 `credential_ref`、`key_ref` 等引用,不保存明文令牌/私钥。禁止将秘密写入插件配置示例、诊断包、审计和源码。 +- 叶证书建议 30 天有效期,实际时间可配置。续期要求原有效身份、目标端在线及授权仍有效;过期不能自动信任重签证书。根密钥轮换走独立确认。 +- 撤销 Agent:先持久化撤销记录及递增授权版本,再断开会话、清空待执行审批并终止相应作业。即使叶证书尚未过期也拒绝再次接入。 +- Relay 接入凭据和目标操作授权分别撤销。Relay 被攻陷后,攻击者最多造成拒绝服务或观察流量元数据,不能自行签发目标信任的操作证书。 +- 常规配置备份不包含设备私钥和可复用授权。恢复到新电脑生成新身份并重新配对;专门的密钥灾备需要加密封装、用户口令及明确恢复流程,另设功能。 + +### 5.4 Relay 能看到什么 + +Relay 可见随机路由 ID、接入 IP、连接时间、流量大小、在线状态和外层接入主体。不能承诺隐藏这些元数据。文件路径、内容、命令参数、操作结果均置于内层 TLS;设备友好名称也不必上传。 + +日志只记录必要的连接 ID 摘要、状态、计数和错误码;不持久化数据帧。关闭外层 WebSocket 压缩,设内存上限,避免压缩攻击和不必要的 CPU 开销。 + +## 6. 传输与协议实现 + +### 6.1 自建 Relay 数据流 + +目标与 Agent 均主动向 Relay 发起出站连接,目标不开放公网入站端口: + +```mermaid +sequenceDiagram + participant A as Agent 桥接 + participant R as 自建 Relay + participant D as 目标电脑 + D->>R: 认证并登记目标在线控制连接 + A->>R: 外层认证,请求已配置目标的通道 + R->>D: 通道邀请(不包含执行指令) + D->>R: 连接单次数据通道 + A->>R: 连接单次数据通道 + A->>D: 经 Relay 建立内层 TLS 双向认证 + A->>D: 加密 MCP 请求 + D->>D: 检查授权、审批及执行条件 + D->>A: 加密结果或作业 ID +``` + +首版不用自研多路复用协议:每端一个控制 WSS;数据连接按需成对转发,每对绑定一个目标和 Agent。HTTP 请求可复用数据连接,连接池有上限。并发规模验证确有需要后再评估成熟的多路复用库。 + +WSS 适配器需实现 `net.Conn` 的读取、写入、关闭及 deadline 语义,正确处理消息分片与 TLS 记录边界不一致的情况。初版内层 HTTP 使用明确的 HTTP/1.1 配置,不意外协商尚未实现的 HTTP/2;SSE、取消和背压纳入兼容性测试。 + +### 6.2 拟新增 Relay API + +以下为拟议版本化接口,尚不存在: + +| 接口 | 用途 | 限制 | +|---|---|---| +| `GET /healthz` | 进程存活 | 不暴露设备/版本明细及认证信息 | +| `GET /v1/control`(WSS) | 外层认证后登记、心跳与通道邀请 | 每主体限并发;消息严格 schema、大小与速率限制 | +| `POST /v1/channels` | 已授权外层主体申请目标数据通道 | 仅允许注册目标 ID,无任意 host/port/url 参数 | +| `GET /v1/data`(WSS) | 消耗一次性票据,连接成对字节管道 | 票据经认证 header 传递,绑定双方、角色和短有效期 | +| 本地管理 CLI | 发行/撤销 Relay 接入凭据、查看脱敏状态 | 首版不开放公网管理面板 | + +票据只保证 Relay 入口准入。即便恶意 Relay 绕过票据,目标仍必须通过内层 TLS 和本地授权拦截。外层控制帧不得出现“执行命令”“批准操作”等高权限语义。 + +### 6.3 Tunnel 适配 + +- 官方通道保留现有标准 MCP 路径,通过官方客户端转发;独立 connection/credential 绑定范围。不能把未验证的 HTTP header 当成终端用户身份,也不能由工具参数选择更高权限的 connection。 +- Cloudflare Agent 通道新增独立 WSS 路径和端点 TLS 入口,不能复用 Web 明文 MCP 路径冒充 E2EE。入口仍配置外层准入,内层身份是目标操作的最终依据。 +- 使用 Cloudflare 时,不把服务令牌发送到模型可见参数中;凭据由桥接进程安全加载。 +- Cloudflare 官方文档提示 WebSocket 可能因基础设施更新中断,因此所有适配器都有心跳、重连和状态恢复,不能把持久连接当作永久在线保证。[官方 WebSocket 说明](https://developers.cloudflare.com/network/websockets/) + +### 6.4 初始资源预算 + +以下是实现和压测起点,不是实测性能承诺;最终值写入配置 schema 和测试: + +| 项目 | 初始值/策略 | +|---|---| +| 控制消息上限 | 16 KiB,拒绝未知类型及过深结构 | +| 外层数据帧 | 最大 64 KiB,可分片传输,按字节流处理 | +| TLS 握手超时 | 10 秒;失败关闭双方通道 | +| 单次数据票据有效期 | 30 秒、一次性 | +| 心跳 / 离线判定 | 20 秒心跳,约 60 秒无响应判离线 | +| 重连 | 指数退避加随机抖动,1–30 秒;不无界堆积请求 | +| 数据通道 | 每对端初始最多 4 条,每设备总计 16 条,可配置 | +| 单向转发缓冲 | 每通道最多 256 KiB;慢端触发背压 | +| 文件/输出单页 | 原始内容建议最多 256 KiB;另外检查 JSON 编码后的完整消息上限 | +| 执行并发 | 每连接 1 个、目标设备全局 2 个起步,可按后端能力调整 | +| 作业默认超时 | 10 分钟;用户批准的任务可设置更长的有界时限 | +| 输出保存 | 单作业最多 10 MiB、默认 24 小时;达到上限明确截断 | + +限额同时按 IP、外层身份、目标设备和全局施加,防止创建大量小通道绕过单通道限制。拒绝新工作时返回可区分的错误,不牺牲其他连接的控制心跳。 + +## 7. 远程操作核心 + +### 7.1 工具与数据契约 + +保留原有只读工具名和行为。新增工具名在执行阶段结合现有契约冻结,以下为职责建议: + +| 工具/接口 | 职责 | +|---|---| +| `server_info` 扩展 | target identity、purpose、可用能力、禁用原因和原生访问建议 | +| `probe_tools` | 实际运行受限版本探查,区分 installed / verified / unavailable | +| `prepare_operation` | 校验并生成不可变操作计划和摘要,不产生用户文件副作用 | +| `submit_operation` | 使用目标端已授予的审批执行;返回持久化 operation ID | +| `operation_status` / `operation_output` | 状态与分页输出;游标绑定主体、连接、作业和授权版本 | +| `cancel_operation` | 取消授权范围内的作业,并等待子进程树清理结果 | +| `prepare_file_change` / `commit_file_change` | 准备写入/补丁、展示差异、版本校验与受控提交 | + +MCP 工具列表按每次请求的可信授权过滤,调用时再次校验;不能仅通过初始化时的客户端声明解锁工具。工具注解不承担安全检查。继续使用 SDK 进行协议协商和错误编码。[MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) + +operation 记录至少包括:operation ID、主体、device/connection/profile ID、授权 epoch、计划摘要、工作区版本、运行器身份、资源限额、审批引用、状态、输出引用和时间。**模型传入 `confirmed=true` 不构成审批。** + +### 7.2 作业、重试与断线 + +状态建议:`prepared → awaiting_approval → queued → running → succeeded/failed/cancelled/interrupted/unknown`。 + +- 请求带幂等 ID;同一主体、连接和 ID 但计划摘要不同则拒绝。已存在的相同请求返回已有作业,不再次执行。 +- 先持久化接受记录,再启动任务;记录启动过程。进程崩溃在外部副作用和记账之间时,不能保证恰好执行一次,应报告 `unknown` 并由用户检查。 +- 每次重连先查询作业状态。只有读取等明确定义为可安全重试的请求可以自动重试;写入、脚本、构建绝不因超时自动重新执行。 +- 通道丢失后默认最多保留 60 秒执行租约;超期取消并确认进程树退出。需要断线继续的长任务必须获得有期限的“脱机继续”授权,结果在目标本地有界保存。 +- 用户撤权不等待租约超时:立即停止后续操作并终止对应运行任务。无法确认终止时标记故障,禁止继续调度该执行后端。 +- 目标重启后通过运行实例身份对账,不使用可能复用的 PID 单独认领旧进程。 + +### 7.3 写文件与规则 + +直接写入由受控文件核心完成,不依赖把任意 shell 命令当成写文件 API: + +1. 绑定授权 root,拒绝路径穿越、符号链接/重解析点绕过及禁止路径。 +2. 准备时记录原文件内容摘要、身份和预期不存在条件,生成差异。 +3. 本地审批绑定差异摘要、主体、工作区和授权 epoch;明确有界重复授权时,记录批准范围及失效条件。 +4. 提交时重新检查规则和文件版本,通过安全句柄/目标平台可靠机制完成写入及替换。 +5. 单文件原子替换不等于多文件事务。多文件操作用清单、恢复记录和冲突报告,不能宣称任意失败均全量回滚。 + +deny 优先于 allow;ignore 是检索偏好,不能用于保护秘密。规则更新应同步使缓存、游标、排队操作、快照和旧审批失效。共享 profile 更新显示受影响连接,按 revision/CAS 提交。撤权不能追回之前已经返回给模型的内容。 + +首版不新增任意递归删除及越界目录移动能力;必要删除作为明确的独立授权能力后续扩展。写回冲突必须保留用户现有修改,不允许覆盖以“恢复一致”。 + +### 7.4 命令、版本、构建和脚本 + +- 命令按结构化 executable/argv 执行,避免字符串拼接 shell。需要脚本时显式选择运行器和批准脚本内容,PowerShell/Python/Node/cmd 分别验证。 +- 固定可执行文件身份,净化环境变量,避免从不可信工作区抢先解析工具;不得把所有宿主环境或凭据传给子进程。 +- 构建、测试、依赖脚本本质上都可能执行项目代码,不以“测试”名称豁免审批和隔离。 +- 快照执行默认只复制获准输入,排除秘密、链接与无关目录;运行期子进程、CPU、内存、时间、输出和网络策略由执行后端约束。 +- 输出和变更以结果返回;将快照结果写回真实工作区需独立审批及版本冲突检查。退出码 0 不代表代码正确或测试覆盖充分。 +- 版本探查也要受限,不能在宿主任意可执行文件上运行 `--version` 就当作安全读取。 +- 安装依赖、访问网络和调用凭据分别属于新增授权范围,不因批准 build/test 自动获得。 + +### 7.5 执行隔离的现实阻塞与决策门 + +当前代码的网络 enforcement 门未闭合;用户暂停相关检查且不允许修改系统网络策略。因此不能删掉 `network_enforcement_required`、伪造 capability 或把 TLS 成功当作执行安全成功。 + +执行阶段必须在 R12-00/01 形成 ADR,选择可兑现的产品执行契约: + +| 路线 | 能提供的承诺 | 当前约束与代价 | +|---|---|---| +| 隔离执行,保留原严格契约 | 受控文件视图、进程树和网络隔离均有真实证据 | 现有 Windows 后端仍未通过;需要解决 broker/网络能力,不可绕过用户限制 | +| 用户已有的独立 VM/隔离环境 | 将项目快照送入独立环境运行,再审查写回 | 必须实测边界;不能假定 WSL/普通容器天然满足要求,也不擅自启用系统组件 | +| 显式“受信任主机执行”产品模式 | 在当前用户 OS 权限内运行批准代码;不承诺文件/网络沙箱 | **属于安全模型变化,仅作为备选,必须另行获得用户明确选择;本计划不启用** | + +推荐默认继续隔离执行契约;先探测用户是否已有可用的独立隔离环境,并保留现有网络后端研究路径。若两条路径均不满足当前约束,则清楚报告命令执行受阻,交付读写/通道增量但不能称为完整 Agent 操作版本。 + +受信任模式若将来获准,应在 UI、协议和审计中使用独立 `execution_policy=trusted_host`,每个连接显式授权。任意脚本会继承该 OS 用户的实际文件/网络能力;路径规则只能限制项目工具,无法约束脚本自行访问其他文件。不得用一句“高级模式”掩盖这一差别。 + +不论选择哪条路线,本阶段最终完整验收仍必须包含真实命令、版本、构建、测试及脚本。隔离选择不是把这些目标永久推迟的理由。 + +## 8. 多连接、身份与兼容迁移 + +### 8.1 多连接运行注册表 + +将单个桌面 controller 演进为按 connection ID 管理的运行注册表,复用现有协调组件。每个条目有独立 transport、认证、profile、epoch、进程/监听实例、作业队列和状态。 + +- GUI 当前选中项只影响展示,不能导致其他连接被停止。 +- 端口、Tunnel、凭据和 scope 冲突在启动前验证。共享资源需要明确所有权和引用计数,不能一个连接退出就杀死共用子进程。 +- 设备全局调度器保证公平,限制总并发/内存;单个连接故障有界重试,不拖垮其他连接。 +- 相同文件上的不同连接写入通过版本冲突检测解决,不能最后写入静默覆盖。 +- 撤销连接与更新共享 profile 使用一致的 epoch 事务;所有入口使用同一权威配置快照。 + +### 8.2 拟议配置增量 + +以下是逻辑示意,不是可以直接加载的现有 schema;实际应扩展当前序列化结构并提供迁移器: + +```json +{ + "schema_version": "next", + "connection": { + "id": "connection-remote-a", + "purpose": "agent_remote", + "target_device_id": "device-example", + "transport": "self_hosted_relay", + "security_profile": "endpoint_mtls_v1", + "relay_url": "https://relay.example.com", + "credential_ref": "relay-access-ref", + "identity_ref": "paired-agent-ref", + "profile_id": "project-a", + "execution_policy": "isolated_required" + } +} +``` + +真实 schema 必须限制枚举和合法组合:例如 Relay 模式必须有端点加密身份;官方 MCP 通道不能填写 WSS 专属字段。内部只读单元测试的 `local` transport 保留,不意外映射为公网入口。 + +旧 connection 默认迁移为 `web_local`,保留原 transport、profile 和禁用状态;不新增写/执行授权。修改前备份配置并做 dry-run,CAS 提交;迁移失败继续使用旧版本。旧程序遇到新 schema 应明确拒绝,不静默忽略安全字段。 + +## 9. 拟改动模块与产物 + +路径是拟议边界,实施前结合已有接口调整,避免重复实现: + +| 路径 | 改动职责 | +|---|---| +| `internal/config/` | schema、用途/通道校验、迁移、密钥引用 | +| `internal/deviceidentity/`(新增) | 安装身份、配对、证书签发、撤销与轮换 | +| `internal/peertransport/`(新增) | WSS 字节流、TLS 与虚拟 listener;通道适配公共接口 | +| `internal/relay/`(新增) | 控制面、票据、配对转发、配额及运行状态 | +| `cmd/local-probe-relay/`(新增) | 公网服务及本地管理入口 | +| `internal/agentbridge/`、`cmd/local-probe-agent/`(新增) | stdio MCP、目标身份与原生访问建议 | +| `internal/operations/`(新增) | 持久化作业、幂等、审批、租约与恢复 | +| `internal/commandexec/`、`commandprofile/`、`confirmation/` | 接入真实执行后端;复用 R11 契约 | +| `internal/rootfs/`、`policy/`、`workspaceadmin/` | 安全写入、在线规则与撤权 | +| `internal/connectionmanager/`、`supervisor/`、`desktopbridge/` | 多实例生产接线及 GUI RPC | +| `internal/mcpserver/` | 新工具、可信 scope 绑定、能力投影 | +| 现有 GUI 前端目录 | 用途选择、设备/通道、作业及审批;沿用现有视觉样式 | +| `deploy/relay/`(新增) | 可审查的 systemd/容器/反向代理部署模板 | +| `docs/evidence/r12/`(新增) | 脱敏测试记录、跨机矩阵、性能与故障证据 | + +不在计划中锁定尚未评估的 WebSocket/数据库依赖。样机阶段比较维护状态、许可证、上下文取消、内存限制与 Go 版本兼容性后固定版本。使用成熟库不意味着省略自身资源与授权校验。 + +## 10. 自建服务器部署设计 + +### 10.1 首版部署形态 + +推荐:Linux 公网服务器 + 域名 + 自动续期公网 TLS 证书 + 支持 WSS 的反向代理 + 非特权 Relay 进程。Relay 只监听回环地址,反向代理对外提供 443。若采用 HTTP-01 证书挑战才需相应的 80 端口;也可选择 DNS 挑战。具体软件及配置在部署阶段查官方文档并固定版本。 + +目标电脑和 Agent 只需出站访问 443;不要求端口映射、固定家庭公网 IP 或把 SMB/RDP 暴露公网。已有服务器的域名、端口、反向代理规则先只读检查,部署时不覆盖其他业务。 + +首版建议 1 vCPU / 1 GiB 内存起步,仅为小规模规划值,实际容量由并发与带宽测试确定。转发大文件主要消耗用户服务器流量;预算需考虑双向转发与供应商计费,不给出未经测量的吞吐保证。 + +### 10.2 部署交付物 + +- Linux Relay 二进制、校验和、版本信息、第三方许可证与 SBOM。 +- 示例配置、systemd unit 和可选容器构建文件;默认非 root、只读程序目录、限定可写状态目录。 +- TLS/WSS 反向代理模板,明确超时、缓冲、请求上限、敏感 header 脱敏。 +- 本地初始化/凭据发行/撤销命令;第一次初始化无默认密码,认证秘密不通过命令行参数回显。 +- 健康检查、日志轮转、磁盘/内存/连接数告警、备份和升级回滚说明。 +- 针对“证书失败、目标离线、身份不匹配、权限拒绝、执行后端不可用”的诊断指引。 + +模板交付不等于已部署;对真实公网服务器的改动需要用户选择服务器及授权后执行。无需为本次研发新建外部账号。 + +### 10.3 状态与灾备 + +Relay 初版单实例,持久化注册主体、凭据摘要、撤销状态与配置 revision;数据管道和一次性票据只放有界内存。SQLite 是候选,需要核实所选驱动的跨平台、备份一致性和发布成本后确定。 + +Relay 重启只丢失连接,不应丢失目标端作业状态;终端退避重连。旧票据全部失效。控制元数据备份需加密并限制访问,备份中不得混入目标端私钥或工具输出。恢复旧备份不得复活已撤销凭据:无可靠撤销账本时撤销全部旧接入凭据并重新发行。 + +首版不做集群、多地域、复杂账户门户或公开设备目录。以后扩容也不能把目标端授权检查迁移到 Relay。 + +## 11. GUI 接入计划 + +仅在对应后端阶段验收后接入真实数据;保留当前排版、文件树、右键菜单、文本复制、主题和 DPI 方案。 + +| 页面 | 增量交互 | +|---|---| +| 新建连接 | 第一步选择“Web 访问本地 / Agent 远程操作”;随后显示该用途可选通道 | +| 概览 | 显示多个实际运行连接、目标设备、通道/认证/权限/执行后端各自状态;不以“已连接”代替“可执行” | +| 历史连接 | 保存通道与授权引用,允许多个连接同时运行;“使用”不隐式断开其他项 | +| 访问范围 | 文件树维持只读、命令、高级规则分区;编辑时显示实际受影响的连接 | +| 开发者功能 | 后端可用能力、执行策略、工具版本、脚本/构建配置、审批及作业取消 | +| 设备配对 | 导入/导出公开配对包、核对指纹、签发范围与撤销;默认不显示私钥 | +| 活动 | 按连接、设备、工作区、操作类别、结果和时间筛选;输出按权限和分页加载 | +| 设置/程序健康 | Relay 与 Tunnel 连通性、证书有效期、执行后端状态;诊断导出继续脱敏 | + +删除无用说明不等于删除必要状态。连接离线、权限不足、信任变化、真实执行不可用须明确展示;不显示“字体已加载”等实现噪声。 + +## 12. 分阶段执行与验收 + +### 12.1 顺序与依赖 + +`R12-00 → R12-01 → R12-02 → R12-03 → R12-04 → R12-05 → R12-06 → R12-07 → R12-08` + +R12-01 的执行安全路线是 R12-05 的强依赖。通道研究可以继续,但执行路线未确定时不得把整体任务标为即将完整交付。全程遵守后端先行,不提前制作假运行状态 GUI。 + +| 阶段 | 实施内容 | 产物与完成条件 | +|---|---|---| +| **R12-00 基线与契约** | 核对现有代码/回归;冻结用途/权限/通道矩阵;定义目标平台与执行安全 ADR;整理仍未完成的 R11 项 | 差距清单、威胁模型、接口/schema 草案、可运行的既有回归基线;不虚报外部测试 | +| **R12-01 技术样机与决策门** | Go TLS-over-WSS + 官方 MCP SDK 往返;独立测试暂停/取消/流式结果;评估可用执行隔离后端 | 本地两个独立测试进程完整往返、错误证书拒绝、可执行的安全路线决定;不以样机替代跨机验证 | +| **R12-02 身份与配置** | purpose/schema 迁移、身份存储、公开配对包、CSR 签发、epoch、撤销、原生优先提示 | 无隐式授权升级;错误目标/伪造 Agent/旧审批全部拒绝;旧配置可恢复 | +| **R12-03 Agent 桥接与 Tunnel** | stdio bridge;Cloudflare WSS 适配;保留官方标准 MCP 路径;能力与错误投影 | 一种通道失败不改变另一种授权;只读工具真实往返;协议与取消测试通过 | +| **R12-04 自建 Relay** | 控制/数据平面、认证、票据、限流、重连、部署模板 | 本地与隔离集成环境完整 Relay 往返;篡改/误路由失败;内存和日志无明文载荷 | +| **R12-05 补齐操作后端** | 真实版本探查、命令、写入、构建、测试、自选脚本、作业账本、审批、冲突与撤销 | 七项中的单连接功能均完成真实 OS 测试;隔离门/明确批准的执行契约满足;无假 capability | +| **R12-06 多连接与后端封板** | 多实例生产宿主、全局调度、在线规则、共享授权撤销、断线/重启恢复 | 至少 3 条连接同时运行,跨范围访问拒绝,撤销一条不影响其余;后端完整矩阵通过 | +| **R12-07 GUI 联调** | 将真实后端能力接到现有页面;配对/用途/状态/审批/作业交互 | 后端已封板后实施;人工操作与自动化均覆盖,主题/DPI/右键不回退 | +| **R12-08 跨机验收与发布候选** | 用户允许后在现有设备/账号、公网服务器或合适测试环境验证;升级回滚/备份/包审计 | 完整证据、清晰限制、可复现部署与独立安装包;正式发布另按发布授权执行 | + +### 12.2 后端测试矩阵 + +| 类别 | 必测场景 | 通过标准 | +|---|---|---| +| 配置迁移 | 旧配置、缺字段、未知枚举、部分写失败、并发保存、降级读取 | 无权限扩大、CAS 冲突明确、可恢复 | +| TLS/配对 | 错 CA、错用途、证书过期、设备换钥、CSR 替换、同名设备、被撤销 Agent | 不泄露工具数据;不自动接受新信任根 | +| Relay 攻击 | 误路由、截获重放、票据重复/超时、串连不同主体、恶意控制帧 | 认证/内层身份拒绝;目标不执行请求 | +| 传输健壮性 | 一字节分片、合帧、慢读、半关闭、超大消息、断线、代理重启 | 正确背压/取消,内存有界,无死锁 | +| MCP 兼容 | 初始化、工具列表、调用、授权变化、取消、SSE、错误结果 | SDK 语义保持;旧只读客户端不回归 | +| 文件安全 | Windows junction/reparse、链接替换、目录改名竞争、大小写/路径别名、读写版本冲突 | 不越界、不覆盖用户并发改动 | +| 执行 | 真实版本、命令、脚本、build/test、超时、输出洪泛、子进程逃逸尝试 | 有真实结果、全子树终止、限额可证;未支持后端明确拒绝 | +| 授权 | 跨连接 root/profile、伪造 confirmed、旧 epoch、运行中撤权、共享规则修改 | 越权拒绝、旧审批失效、对应作业停止 | +| 幂等与崩溃 | 提交前/后崩溃、启动中崩溃、结果丢失、重复提交、写入后响应丢失 | 无自动重执行;不可判定时报告 unknown | +| 原生访问 | 同机原生、WSL/VM、云 Agent、无身份、原生被拒绝 | 不误判环境、不建议绕过限制 | +| 多连接 | 3 条并行、单条断开、同文件写冲突、一条慢连接/输出洪泛 | 故障不串扰;公平调度与冲突可解释 | +| 保密与恢复 | 诊断、日志、备份、崩溃报告、旧备份恢复、密钥轮换 | 无令牌/私钥/默认工具内容泄露;不复活撤权 | + +### 12.3 真实环境验收 + +至少覆盖以下实际链路,使用合成测试工作区,不触碰用户生产文件: + +1. 现有 Web 客户端 → 原有官方/Cloudflare MCP → Windows 目标:读取回归,并验证用户授权范围内的新能力。 +2. Agent 电脑 A → Cloudflare WSS → 目标电脑 B:设备配对、读取、文件修改、命令和脚本。 +3. Agent 电脑 A → Linux 公网 Relay C → 目标电脑 B:同一操作集合、断网恢复、证书拒绝及撤销。 +4. 同一台物理电脑上的原生、WSL/容器等环境:检验原生优先判定,不以物理同机强制禁用合法跨环境场景。 +5. 3 条独立授权连接并行执行;撤销一条、更新共享规则、重启 Relay,检查其他连接及作业状态。 + +没有第二设备、公网服务器或实际客户端能力时,分别记录“未验收”及原因;localhost、模拟器、交叉编译和 mock 不能替代这些结果。不为补测试自行创建账号或修改用户已禁止的系统策略。 + +### 12.4 自动化与发布门 + +实现阶段运行 `go test ./...`、`go test -race ./...`、`go vet ./...`;新增协议/配置解析 fuzz、真实 OS 隔离/路径/进程集成、跨进程 CAS 与前端回归。明确列出 opt-in 测试、skip 和失败;失败后修原因,不删除安全断言。 + +证据记录代码 revision、工具链、OS/架构、实际命令、时间、结果、覆盖范围与脱敏输出。性能测量记录网络 RTT、CPU、内存与带宽条件。初始压测建议 10 个在线目标、20 个并发只读会话及 30 分钟有界稳定性运行,再按用户规模修订;这不是首版承诺容量。 + +发布等级: + +- **通道预览版**:可安全配对、加密访问和恢复连接;若执行受阻,只能按真实能力命名。 +- **后端功能候选版**:本阶段七项能力、多连接和两类 Agent 通道全部通过后端测试;GUI 可尚未接入。 +- **GUI 可用候选版**:GUI 接入真实状态,人工与跨机验收通过,具备安装/部署/回滚手册。 +- **正式可用版**:候选版发现的阻塞项清零;公开制品完成敏感扫描、许可证、校验和及发布检查。不把未经授权的发布操作包含在计划编写中。 + +## 13. 成本、风险与优先级 + +### 13.1 工作量区间 + +以下是单名熟悉代码的工程师净开发/测试工作量估算,不含等待设备、外部权限、证书及安全模型决策的时间;不是日历承诺: + +| 工作包 | 估计 | +|---|---| +| 基线、协议样机和执行安全路线 | 1–2 人周;隔离研究可能超出 | +| 身份、配对、迁移、Agent 桥接 | 2–3 人周 | +| Relay、Tunnel 适配和部署包 | 2–3 人周 | +| 操作后端与多连接生产接线 | 3–5 人周,执行隔离为最大不确定项 | +| GUI、跨机回归及发布候选 | 2–3 人周 | + +合计约 10–16 人周,前提是找到符合约束的执行后端;若必须新建 Windows 可信 broker/系统网络执行机制,应重新估算,不能在前端已完成的情况下继续乐观宣称“只差接线”。 + +### 13.2 主要风险与处理 + +| 风险 | 对策 / 停止条件 | +|---|---| +| 严格隔离与不改系统策略冲突 | R12-01 前置 ADR;无合规可执行路线就明确阻塞,不削弱能力声明 | +| 把“官方 Tunnel”当通用代理 | 固定矩阵和协议边界;桥接密文走 WSS 适配或自建 Relay | +| 用户以为所有 HTTPS 都对中转方不可见 | 每连接显示加密终点;平台 MCP 与端点 TLS 两种安全配置分别说明 | +| 配对被中转服务器劫持 | 带外核对指纹,信任根在终端,Relay 无签发权 | +| 操作重试导致重复写入/运行 | 持久化幂等记录、计划摘要、unknown 状态与显式人工恢复 | +| 多连接共享权限/缓存串扰 | 请求身份绑定、epoch、游标范围和全局公平调度 | +| 自建 Relay 成为开放代理 | 无任意目的地址、单次票据、主体准入、配额与内层认证 | +| 跨机实际效果不同于单机测试 | 明确 A/B/C 三端环境证据,未测不作承诺 | +| 桥接协议维护成本增加 | 官方 SDK + 标准 TLS/HTTP,控制协议小而版本化,避免自研密码学和大型 mux | + +### 13.3 暂缓项 + +暂缓搜索索引加速、语义向量库、P2P 打洞、QUIC、复杂多路复用、Relay 集群、多租户计费、远程桌面和插件市场发布。理由是这些工作不能替代本阶段必须完成的访问、执行与可靠性闭环。 + +保留现有直接搜索。若后续有实际大仓库数据证明瓶颈,再以基准测试决定是否加索引,不以“拥有命令行”推导任何规模都无需优化。 + +## 14. 执行前决策清单 + +本方案已给出可开工的推荐值;当前无需为了编写计划新增审批。实际实施时按下表处理: + +| 决策 | 当前推荐 | 何时必须明确 | +|---|---|---| +| 第一目标平台 | Windows 目标、Windows/Linux Agent、Linux Relay | R12-00 | +| 执行安全模型 | 默认隔离;不更改系统策略,不自动改为受信任主机执行 | R12-01,决定真实命令实现路径 | +| 首个公网测试位置 | 使用用户现有服务器与账号;没有则先完成本地后端 | R12-08 前;部署须有确切目标与授权 | +| 配对方式 | 首版公开文件/CSR 往返并核对指纹 | R12-02 | +| Agent 无桥接能力 | 使用其支持的标准 MCP 路径;暂不做明文网关 | R12-03 | +| 长任务断线策略 | 60 秒租约后取消;继续运行需单独有界授权 | R12-05 | +| 对外发布 | 先独立候选包,实测后再按发布授权处理 | R12-08 | + +建议开始执行时首先完成 R12-00 和 R12-01。它们会尽早验证两件最影响成败的事情:端点 TLS 与官方 MCP SDK 是否可靠组合,以及在用户现有限制下真实命令执行能采用哪种可验证的后端。 + +## 15. 参考与核验说明 + +本方案的产品选择、模块划分、参数和工作量属于设计建议,不是第三方官方承诺。以下是本轮查阅的技术依据: + +- [OpenAI Secure MCP Tunnel](https://developers.openai.com/api/docs/guides/secure-mcp-tunnels):平台通道、适用范围及限制。通过 OpenAI Docs 工作流核对官方页面,避免将其规划为通用 WSS 隧道。 +- [Cloudflare WebSockets](https://developers.cloudflare.com/network/websockets/):WebSocket 通道和连接中断考虑;通过 Context7 查询并核对官方文档。 +- [Go crypto/tls](https://pkg.go.dev/crypto/tls):标准 TLS、双向证书验证、`net.Conn` 与连接校验;通过 Context7 查询文档。 +- [MCP 工具规范](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) 与 [MCP schema](https://modelcontextprotocol.io/specification/2026-07-28/schema):工具能力和客户端信息边界;实施时仍需与固定 SDK 实际兼容版本对照。 +- 项目依据:[总体计划](MASTER_PLAN.zh-CN.md)、[实施状态](IMPLEMENTATION_STATUS.md)、[R11 计划](R11_BACKEND_FIRST_PLAN.zh-CN.md)、[R11 进展](R11_BACKEND_PROGRESS.zh-CN.md)。 + +后续变更本方案时保留版本、日期与关键决策记录。代码实现和测试证据分别更新实施状态,不能仅修改本计划的措辞就认定功能已交付。 diff --git a/docs/R12_EXECUTION_DECISION.zh-CN.md b/docs/R12_EXECUTION_DECISION.zh-CN.md new file mode 100644 index 0000000..e9018b1 --- /dev/null +++ b/docs/R12_EXECUTION_DECISION.zh-CN.md @@ -0,0 +1,13 @@ +# R12-01 执行安全决策 + +日期:2026-10-23。状态:用户明确选择;实现进行中。 + +用户在本次开发中明确允许新增“受信任主机执行”模式,已知其使用当前用户实际的文件与网络权限,不承诺沙箱隔离。因此新增独立 `execution_policy=trusted_host`。不再将严格网络 enforcement 作为该模式的准入条件,也不更改系统网络策略。 + +`isolated_required` 保持原门禁,作为所有旧连接的默认策略。新增策略不等于授权:开发者开启、连接范围、具体操作审批、版本/身份绑定、资源限制与撤销仍是必要条件。默认配置不会自动启用命令或写入。 + +命令运行器继承当前用户 OS 权限,路径规则无法限制其自行读取/修改其他文件或访问网络。该事实必须在本地授权界面中明确显示,不能只标注“高级”。 + +实现优先复用已有 Windows suspended launch、映像身份校验、Job Object 和有界输出;固定版本探针继续保持其原有限制。受信任执行独立入口支持受批准的子进程树,不把原有固定探针放宽成任意命令。 + +配对、Relay、工具调用与执行策略仍须按阶段完成,不以这项决策声称已经实现远程执行。 diff --git a/docs/R12_OPERATIONS.md b/docs/R12_OPERATIONS.md new file mode 100644 index 0000000..98e1ed7 --- /dev/null +++ b/docs/R12_OPERATIONS.md @@ -0,0 +1,112 @@ +# R12 locally approved operations + +Updated: 2026-10-24. The implementation is in the independent paired target/CLI backend. The existing desktop and Web advanced-operation ingress are not connected. See [detailed Chinese notes](R12_OPERATIONS_BACKEND.zh-CN.md). + +## Execution contract + +Windows `trusted_host` runs commands with the current user's actual OS file/network permissions. It **does not provide sandbox isolation**, including confinement of a runtime's own file access to the configured root. Job limits and clean environment handling do not change this contract. The owner explicitly approved this mode; existing `isolated_required` gates remain intact and old configurations are not upgraded. + +All conditions are required: + +1. A `local-probe.config.v2` explicitly writable profile (`read_only=false`); v1/default profiles remain read-only. +2. An enabled paired connection with `purpose=agent_remote` and `execution_policy=trusted_host`. +3. Developer mode enabled with the connection in `allowed_connections`, and the relevant tools allowed by its profile. +4. A local reviewed runner catalog and private journal outside all authorized roots, supplied explicitly at target startup. +5. The local owner approves the immutable plan's exact ID/digest before execution. Subject, config revision, runner identity/hash and file version are rechecked. + +The legacy `network_default=deny` configuration does not establish network denial for `trusted_host`. GUI text must say so. The remote caller cannot approve itself; a remote `confirmed=true` is rejected. + +Relevant profile tools are `probe_tools`, `prepare_operation`, `submit_operation`, `operation_status`, `operation_output`, `cancel_operation`, `prepare_file_change` and `commit_file_change`, alongside selected read tools. Authenticated subject/connection scope is bound by the server, not model arguments. See the [Chinese configuration fragment](R12_OPERATIONS_BACKEND.zh-CN.md) and config validation code; fragments are not full deployable configurations. + +## Local setup + +[The empty catalog](../deploy/operations/catalog.example.json) grants no runner by default. Each entry requires a reviewed physical executable path and actual lowercase SHA-256; optional `script_type` is python/node/powershell/cmd. Explicitly list necessary environment variables. An executable update changes its hash and requires review. + +```json +{ + "version": "local-probe.operations.v1", + "tools": [{ + "id": "python", + "executable": "C:\\TrustedTools\\python.exe", + "sha256": "", + "script_type": "python", + "environment": ["SystemRoot=C:\\Windows"] + }] +} +``` + +The host's complete environment/PATH/tokens are not inherited. Build/test dependencies such as PATH/GOROOT must be explicitly configured. TEMP/TMP use private per-job directories. cmd scripts currently reject extra arguments and journal paths with spaces/cmd metacharacters; use approved script content and do not work around this by shell string concatenation. + +```text +local-probe-operations -action init -journal +``` + +Add **both** `-operations-journal ` and `-operations-catalog ` to the [target startup](R12_PAIRING_AND_TRANSPORT.md). Without them the target stays read-only. These are suffix flags, not a complete command by themselves. + +On Windows, private records use current-user DPAPI and a protected current-user/SYSTEM DACL. Shared approval directories are rejected. The engine holds an exclusive storage lock; the local control CLI can publish separate approval records concurrently. The journal cannot overlap authorized roots. Corrupt/unavailable storage closes admission and cancels active work. + +## Remote request and local decision + +Prepare a plan through the paired MCP tool: + +```json +{ + "nonce": "unique-intent-1", + "kind": "script", + "tool_id": "python", + "root_id": "workspace", + "script": "print('hello')\n", + "args": [], + "timeout_seconds": 60 +} +``` + +Kinds: command, script, version, build, test, file_write and file_patch. Preparation validates/persists the plan; it does not run it. `probe_tools` lists reviewed runner identities; an actual version requires an approved `kind=version` process and real output. + +Submit the returned ID/digest with `submit_operation`; it waits for local approval. File tools `prepare_file_change`/`commit_file_change` use the same local-approval boundary; “commit” does not bypass it. + +The owner uses a local terminal: + +```text +local-probe-operations -action list -journal +local-probe-operations -action inspect -journal -id +local-probe-operations -action approve -journal -id -digest -ack-trusted-host +local-probe-operations -action reject -journal -id -digest +local-probe-operations -action cancel -journal -id -digest +``` + +Inspect shows subject/connection, workspace, arguments/script and file before/after content. Approval binds that complete plan and expires five minutes after preparation. Changed plan/configuration/identity cannot reuse it. Local cancel confirms a durable request, not completed process cleanup; query until terminal. Remote `cancel_operation` waits for cleanup. + +## Jobs, retry and output + +Poll `operation_status` at least once per 60 seconds while running to maintain the Agent lease. A GUI local projection must not renew that lease on behalf of the Agent. Default timeout is 60 seconds; maximum 30 minutes. Output is available after completion, paged by stdout/stderr byte offset as base64 raw bytes. No interactive terminal or live output stream is implemented. + +Same subject/connection/nonce and same input returns the original job, even after side effects. Changed content with that nonce is rejected. After a network failure query the original ID; do not create a new nonce to replay writes/builds automatically. + +Restart marks unstarted jobs interrupted and previously recorded-running jobs unknown; it does not automatically rerun them. Storage publication uses complete encrypted temporary records and no-overwrite atomic publication. The journal is bounded to 128 historical jobs/about 64 MiB and rejects admission when full; automatic archival is not implemented. + +Windows limits: 32 processes, 1 GiB aggregate committed memory, cumulative user CPU budget plus wall timeout, 64 KiB each stdout/stderr. Natural parent exit and termination both require actual process-tree cleanup. Unconfirmed cleanup after the bounded wait yields unknown and disables admission. These limits are not network/file isolation or CPU percentage quotas. + +## File changes and recovery + +UTF-8 text is limited to 128 KiB. New files use exclusive creation; existing files bind content digest and file identity. Exact patches support at most 32 `{old,new}` edits with unique old context, without fuzzy merging, full unified diff or multi-file transactions. + +```json +{ + "nonce": "patch-1", + "kind": "file_patch", + "root_id": "workspace", + "path": "main.py", + "edits": [{"old": "answer = 1", "new": "answer = 2"}] +} +``` + +Commit rechecks writable scope, rules, directory handles, reparse points, hard links, identity and version. Existing files are updated through a locked handle after a private before image is saved. This is **not atomic file replacement**: crash/disk failure may partially write, returning unknown and retaining manual recovery material. No automatic restoration or replay is performed. + +Local `-action before -journal -id -digest ` returns the before image as base64; it does not restore it. Inspect the current file before manual recovery. Linux target operations are unsupported and do not fall back to an uncontrolled Unix launcher. + +## Validation and remaining integration + +The [operation evidence](evidence/r12/2026-10-24-operations.md) records actual Windows runtimes, build/test, local CLI approval, WSS/mTLS operations, conflicts/revocation, two-connection concurrency, cleanup and restart behavior. The [source-upload evidence](evidence/r12/2026-10-24-source-upload.md) records the latest repository handoff checks separately. + +Remaining: trusted GUI management, advanced Web ingress, production multi-connection host, online rules/selective authorization epochs, retention and real Linux Agent/public Relay operation tests. A global config revision change currently invalidates old approvals; selective hot reload is not complete. diff --git a/docs/R12_OPERATIONS_BACKEND.zh-CN.md b/docs/R12_OPERATIONS_BACKEND.zh-CN.md new file mode 100644 index 0000000..09018f1 --- /dev/null +++ b/docs/R12_OPERATIONS_BACKEND.zh-CN.md @@ -0,0 +1,142 @@ +# R12 受信任操作后端开发版 + +日期:2026-10-24。当前为独立 CLI/MCP 后端增量;没有替换既有 GUI,没有更改用户连接或授权,没有重新连接公网 Relay。 + +## 已实现 + +Windows 目标可接收配对 Agent 的命令、脚本、版本、build/test、文本文件创建/更新和精确文本补丁申请。目标所有者通过本地 CLI 检查完整计划并逐次批准,MCP 没有批准接口,`confirmed=true` 无效。 + +作业持久化,支持主体/连接隔离、幂等、取消、分页输出、审批失效、运行租约及重启后不自动重跑。两个连接可同时各运行一个作业,取消其中一个不影响另一个。Linux Agent 已准备构建;Linux 目标目前保持只读,启用操作参数会明确拒绝,不能称为 Linux 执行功能已经交付。 + +## 执行契约与准入 + +`trusted_host` 使用当前 OS 用户实际的文件和网络权限,**不是沙箱**。运行器可以访问工作目录之外的当前用户文件,也可能访问该用户的身份/作业存储。命令按结构化 executable/argv 启动;脚本正文冻结到私有文件后交给明确的运行器,不拼接远程 shell 命令。 + +需同时满足以下条件,没有自动升级旧配置: + +1. `local-probe.config.v2` 中显式可写 profile:`read_only=false`。v1 继续拒绝写权限,默认 profile 仍只读,文件写入核心也独立检查。 +2. 配对连接选择 `purpose=agent_remote`、`execution_policy=trusted_host`。 +3. `developer_mode.enabled=true`、`allowed_connections` 包含连接,profile.tools 包含所需工具。 +4. 目标启动时显式配置本地运行器目录表、位于所有授权根之外的私有作业目录。 +5. 本地所有者逐次批准精确计划摘要;运行前复核主体、配置版本、执行映像身份及 SHA-256。 + +配置片段(并非完整文件,根和凭据等字段须保留): + +```json +{ + "profiles": [{ + "id": "developer", "roots": ["workspace"], "read_only": false, + "tools": ["server_info", "read_file", "probe_tools", + "prepare_operation", "submit_operation", "operation_status", + "operation_output", "cancel_operation", + "prepare_file_change", "commit_file_change"] + }], + "connections": [{ + "id": "agent-remote", "label": "Agent", "enabled": true, + "profile_id": "developer", "credential_ref": "agent-credential", + "purpose": "agent_remote", "execution_policy": "trusted_host" + }], + "developer_mode": { + "enabled": true, "allowed_connections": ["agent-remote"], + "default_confirmation": "per_call", "network_default": "deny" + } +} +``` + +`network_default=deny` 保留既有隔离配置的默认值;明确选择的 `trusted_host` 是独立执行契约,不提供网络拒绝保证,不能把此字段当作网络隔离证据。旧 GUI 和旧隔离门保持原行为。当前操作适配器仅接入配对目标,Web/桌面高级入口尚未接线。 + +## 运行器与启动 + +[空目录表示例](../deploy/operations/catalog.example.json)不自动授权任何程序。条目使用所有者核对的物理安装路径、SHA-256 和必要的环境变量: + +```json +{ + "version": "local-probe.operations.v1", + "tools": [{ + "id": "python", "executable": "C:\\TrustedTools\\python.exe", + "sha256": "<本机实际映像的64位小写SHA-256>", + "script_type": "python", "environment": ["SystemRoot=C:\\Windows"] + }] +} +``` + +script_type 支持 python/node/powershell/cmd;普通命令可省略。映像更新后哈希不符会拒绝,维护者需重新核对。默认不继承完整宿主环境、PATH 或令牌;build/test 如需 PATH/GOROOT 等,须明确配置。TEMP/TMP 使用每个作业的私有临时目录。 + +当前 cmd 脚本不接受额外 args,作业目录不能包含空格或 cmd 元字符;输入应直接写入并批准脚本正文。不满足时在准备阶段拒绝,避免将 Windows CRT 参数转义误当成 cmd shell 转义。Python/Node/PowerShell 不受此 cmd 限制。 + +私有作业目录不得位于授权根内,也不得包含授权根。Windows 创建时使用当前用户/SYSTEM DACL,打开时核对实际受保护 DACL 的两条权限记录,拒绝共享目录;记录用当前用户 DPAPI 保护。存储为单引擎独占;本地控制 CLI 可同时读写独立审批记录。 + +```text +local-probe-operations -action init -journal <新的私有作业目录绝对路径> +local-probe-target ... -operations-journal <私有作业目录> -operations-catalog <运行器JSON绝对路径> +``` + +两个启动参数必须一起提供;身份、配置、审计和传输参数按[配对说明](R12_PAIRING_AND_TRANSPORT.zh-CN.md)填写。不提供操作参数时仍只读。 + +## 申请与本地审批 + +Agent 调用 prepare_operation: + +```json +{ + "nonce": "本次意图的唯一请求ID", "kind": "script", + "tool_id": "python", "root_id": "workspace", + "script": "print('hello')\n", "args": [], "timeout_seconds": 60 +} +``` + +kind 支持 command/script/version/build/test/file_write/file_patch。准备只校验和保存计划,不执行或改变用户工作文件。probe_tools 仅列出已审核运行器身份;实际版本需批准 kind=version 并读取真实进程输出,不能把安装发现当成版本验证。 + +获得 ID/digest 后 submit_operation 进入 awaiting_approval。文件可使用 prepare_file_change / commit_file_change;commit 同样提交审批请求,不是立即绕过审批写入。 + +所有者在本地操作: + +```text +local-probe-operations -action list -journal <目录> +local-probe-operations -action inspect -journal <目录> -id +local-probe-operations -action approve -journal <目录> -id -digest <已核对摘要> -ack-trusted-host +local-probe-operations -action reject -journal <目录> -id -digest <摘要> +local-probe-operations -action cancel -journal <目录> -id -digest <摘要> +``` + +inspect 显示主体/连接、工作区、参数、脚本正文、原文件与补丁结果;本地用户依据这些内容批准。审批绑定摘要、主体、配置版本及准备后五分钟的期限,不能复用于其它计划。 + +cancel 是本地所有者的持久化取消请求,后台读取后终止对应任务;CLI 返回仅表示请求已落盘,需通过 list/inspect 确认终态,不等于已确认进程退出。Agent 的 cancel_operation 则等待执行器回收后返回。 + +运行中至少每 60 秒轮询 operation_status 维持租约,租约到期取消。执行超时默认 60 秒,上限 30 分钟。operation_output 在结束后按 stdout/stderr 和字节偏移分页,返回 base64 原始字节,不将 cmd 本地编码冒充 UTF-8。cancel_operation 等待子树回收后返回终态。 + +相同主体/连接/nonce 的相同请求返回已有作业,即使该作业已改变文件;不同内容拒绝。网络失败应查询原 ID,不换 nonce 自动重跑。重启将未启动任务标记 interrupted、已记录启动但结果不确定的任务标记 unknown,均不自动执行。 + +## 文件语义与恢复材料 + +- UTF-8 文本上限 128 KiB。创建使用独占模式;已有文件绑定内容摘要和文件身份。 +- file_patch 接受最多 32 个 `{old,new}` 精确编辑,每个 old 必须唯一出现;不模糊合并。计划保存旧内容与最终结果,审批绑定两者。 +- 提交复核只读/可写权限、规则、目录链、重解析点、硬链接和版本。固定目录链句柄并核对实际根解析位置,拒绝路径穿越与绕链。 +- 已有文件通过禁止其他写入/删除共享的句柄更新,先保存私有 before image。**不是原子替换**:磁盘失败/崩溃时可能部分写入,明确 unknown 并保留恢复材料,不自动重放/覆盖恢复。 + +```json +{ + "nonce": "patch-1", "kind": "file_patch", "root_id": "workspace", + "path": "main.py", "edits": [{"old": "answer = 1", "new": "answer = 2"}] +} +``` + +本地 `-action before -id -digest <摘要>` 可读取 base64 原始备份;此命令不恢复文件,需先检查当前内容。当前无多文件事务、递归删除、完整 unified diff 或自动灾难恢复。 + +## 资源与存储限制 + +Windows Job Object 实际配置:最多 32 进程、1 GiB 汇总提交内存、与请求时长对应的累计用户态 CPU 时间预算,另有墙钟超时、每路输出 64 KiB 和退出后子树清理。TerminateJobObject 后继续核对内核进程列表为空,最多等待五秒;无法确认时保留 unknown 并关闭执行准入,不把父进程退出或管道关闭当作全部子进程退出。内核读取验证通过;不是 CPU 百分比配额,也不是防恶意代码沙箱。[Windows Job 基本限制](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_basic_limit_information)、[扩展限制](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_extended_limit_information)、[Job 进程列表](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_basic_process_id_list)。 + +账本最多 128 个历史作业,约 64 MiB 存储预算和有限文件数;满额拒绝新请求。尚无自动归档,不适合无人维护长期队列。记录用临时密文、同步写入及禁止覆盖的完整原子发布;损坏记录/存储异常关闭准入并取消活跃任务。超大 JSON 序列化申请在写入前拒绝,不关闭整个引擎。 + +## 本机验证与后续 + +已实际运行 Python 3.13.1、Node v24.19.0、PowerShell 7.6.5、cmd 版本和批准脚本,并生成合成文件;Go 项目实际编译出 EXE 并执行单元测试,禁用依赖下载。官方 SDK 经本机 WSS/mTLS 完成申请→CLI批准→实际写入→查询/冲突拒绝/撤销。另有双连接并行、取消、环境净化、输出限制、补丁、记录发布、重启恢复和只读兼容回归。默认测试跳过真实安装运行器的 opt-in 场景,本轮已另行显式运行。 + +开发中的失败保留:首个真实进程夹具直接启动 race 测试 EXE,在净化环境中以 `0xc0000135` 退出;改为单独构建 CGO=0 的合成 helper,未放宽宿主环境继承。配置内容不变但 revision 更新的撤权回归最初失败,现将 revision 纳入计划 epoch。审批 ACL 校验最初以 SDDL 字符串比较导致合法目录误拒绝,改为核对实际控制位和每条 ACE,合法/共享目录回归均通过。没有把失败用例跳过或弱化断言。 + +最终全项目结果见[进展](R12_PROGRESS.zh-CN.md)。独立构建位于 `bin/r12-operations/`,Linux 构建不等于实机验证。 + +仍需在线规则/配置控制、连接级选择性 epoch、多连接生产宿主、GUI 用途选择/配对/审批/作业视图和 Web 高级入口。当前配置整体变化会使旧审批失效,不能声称连接级热更新已全部完成。 + +按用户要求先继续本地开发;之后使用新增 Linux 电脑作为 Agent、Windows 作为目标,再通过公网 Relay 验证真实跨机操作。届时再取得 Linux 访问方式;本轮未扫描局域网、连接 Linux 或修改真实中转。 diff --git a/docs/R12_PAIRING_AND_TRANSPORT.md b/docs/R12_PAIRING_AND_TRANSPORT.md new file mode 100644 index 0000000..ee54aba --- /dev/null +++ b/docs/R12_PAIRING_AND_TRANSPORT.md @@ -0,0 +1,105 @@ +# R12 pairing and transport + +Updated: 2026-10-24. The native Agent bridge supports direct WSS/Tunnel and a static self-hosted Relay. Start with scoped read-only access; [operations](R12_OPERATIONS.md) are a separate explicit opt-in. [Detailed Chinese reference](R12_PAIRING_AND_TRANSPORT.zh-CN.md). + +## Programs and trust boundaries + +| Program | Role | +| --- | --- | +| `local-probe-pair` | Local offline identities, fingerprints, issue/install/revoke | +| `local-probe-target` | Paired MCP target; loopback WSS origin or outbound Relay channels | +| `local-probe-agent` | Official SDK stdio MCP bridge launched by a native Agent | +| `local-probe-relay` | Fixed-route forwarding on loopback behind HTTPS | +| `local-probe-relay-edge` | Narrow TLS reverse proxy with a fixed loopback upstream | +| `local-probe-operations` | Local owner inspection/approval/rejection/cancellation | + +Outer HTTPS/WSS authenticates transport admission and protects the Internet hop. Inner TLS 1.3 mutual authentication independently verifies paired endpoints and encrypts MCP payloads through the Relay. The Relay sees route/admission metadata, not operation/file plaintext. A Relay token is not target authorization; a relayed connection to a wrong device still fails endpoint verification. + +The official OpenAI Secure MCP Tunnel continues through the existing standard MCP integration. It is not a generic WSS byte-stream tunnel for `/v1/peer`. The new native bridge is needed for endpoint-held keys; a generic Web MCP client cannot automatically speak this inner transport. + +## Pairing sequence + +All placeholders must be replaced locally. Use UTF-8 JSON for public exchange files. Private keys and identity directories never leave their endpoints or enter source control. These steps require the owner to stop any runtime using the store; `-offline` is an explicit declaration, not an automatic process terminator. + +1. On the target: `local-probe-pair -action target-init -store -approve -offline`. Parent directory must exist. Existing identities are not overwritten. Save the public bundle output. +2. Use `local-probe-pair -action fingerprint-bundle` with that JSON on stdin. Independently verify/transmit the fingerprint to the Agent owner; trusting a bundle and fingerprint delivered only by the Relay does not establish identity. +3. On the Agent machine: `local-probe-pair -action agent-init -store -approve -offline`. Save its public CSR JSON. +4. Use `local-probe-pair -action fingerprint-request` with the CSR on stdin; deliver the request and independently verify its fingerprint with the target owner. +5. Configure an enabled v2 `purpose=agent_remote` connection bound to an appropriate profile. On the target, run `local-probe-pair -action issue -store -config -connection-id -fingerprint -approve -offline` with the CSR on stdin. Save the public pairing output, including the target bundle and 30-day Agent certificate. +6. On the Agent, run `local-probe-pair -action install -store -fingerprint -approve -offline` with pairing JSON on stdin. Wrong device, mismatched Agent key and tampered grant metadata are rejected. + +`-action request -store ` can produce a new CSR if needed; its fingerprint changes and must be reverified. `-action show` exports public target material. Do not reissue the same key to recover lost output or change its scope; retain the original public output or create a new Agent identity. + +## Direct WSS/Tunnel + +Target: + +```text +local-probe-target -store -config -audit-dir -listen 127.0.0.1:8791 +``` + +Set `LOCAL_PROBE_TARGET_ACCESS_TOKEN` in the local process environment to a fresh high-entropy secret. Forward the controlled Cloudflare Named Tunnel WSS `/v1/peer` path to this loopback origin. Do not change an existing user's tunnel to test the source checkout. + +Native Agent MCP command: + +```text +local-probe-agent -store -transport tunnel -endpoint wss:///v1/peer +``` + +Use `LOCAL_PROBE_AGENT_ACCESS_TOKEN` for the matching outer admission secret. Optional Cloudflare Access service credentials use both `LOCAL_PROBE_CF_CLIENT_ID` and `LOCAL_PROBE_CF_CLIENT_SECRET`. Keep command and args structured; never put secrets in argv, URLs, logs or commits. + +## Self-hosted Relay + +See the [generic route configuration](../deploy/relay/relay.example.json). Configure distinct random target/Agent role tokens through the named local environment references. Roles/routes cannot share credentials. The Relay does not possess endpoint private keys or the endpoint signing CA. + +Server: + +```text +local-probe-relay -config -listen 127.0.0.1:8792 +``` + +Expose WSS `/v1/target` and `/v1/agent` through the owner's HTTPS reverse proxy; it must support WebSocket Upgrade without logging Authorization/data frames. The Relay itself refuses public listening addresses. The narrow `local-probe-relay-edge` can terminate TLS using explicitly supplied cert/key files; review its flags and deployment example before use. + +Target (outbound only): + +```text +local-probe-target -store -config -audit-dir -relay-endpoint wss:///v1/target +``` + +Use `LOCAL_PROBE_RELAY_TARGET_TOKEN`; no inbound target port is created. The target maintains four outbound channels, reconnecting with jittered backoff. + +Agent: + +```text +local-probe-agent -store -transport relay -endpoint wss:///v1/agent +``` + +Use the Relay Agent role secret in `LOCAL_PROBE_AGENT_ACCESS_TOKEN`. No arbitrary destination host/port/query routing is accepted. Once paired by the static route, endpoints perform inner mutual TLS. + +For a private outer CA, the Agent and Relay-mode target can use `-outer-ca-file `. Only CA certificates are accepted; hostname verification stays enabled. Without this flag, normal system trust is used. Never use a skip-verification workaround or confuse the outer CA with the endpoint pairing CA. + +### Current implementation limits + +The first Relay uses authenticated, role-bound static waiting channels instead of the plan's dynamic control connection/one-time tickets. This removes dynamic remote registration from the initial implementation; it does not add arbitrary forwarding or weaken inner authentication. + +Per route: up to 16 target channels; global 128. Unmatched wait is bounded to 30 seconds. Binary messages are limited to 64 KiB, heartbeat every 20 seconds, read deadline 60 seconds. Errors close both sides. Admission rate limits use the actual peer address, ignoring forwarded headers; clients behind one proxy currently share that source budget. + +The [deployment record](R12_RELAY_DEPLOYMENT.zh-CN.md) describes the authorized Linux test instance and its read-only public validation. It is not a production deployment recipe or current access credential. Its short-lived test leaf certificate expires on 2026-11-07; verify/renew appropriately before later acceptance. Automatic renewal, dynamic credential/route control and full operations telemetry remain incomplete. + +## Revocation and private storage + +Offline revoke: + +```text +local-probe-pair -action revoke -store -key-pin -approve -offline +``` + +Revocation persists across restart and the same key cannot be reissued into a different scope. Use a new key for a new pairing. Runtime revocation APIs can cancel active leases, but GUI/trusted management wiring remains incomplete; the offline CLI is not a live management interface. + +Windows uses current-user DPAPI and protected current-user/SYSTEM DACLs. Unix uses private directories/files (0700/0600); it does not claim encrypted-at-rest storage against the user/root. Damaged/unavailable records fail closed instead of silently generating identities. + +The target runtime loads its leaf key and public records without needing the CA signing key. This separates duties but does not isolate against the same OS user: trusted-host scripts may access that user's identity storage. Identity backup/recovery is not implemented; copying an old store could lose revocations, so re-pair new identities rather than restoring stale authority. + +## Validation boundary + +Local WSS/mTLS and Relay integration, native EXE forwarding, scoped reads/refusals, revocation, role confusion and transport recovery have tests. Public read-only Relay checks passed with Agent and target on the same Windows machine. New commands/writes through a Linux Agent and the real Relay remain untested. See [status](IMPLEMENTATION_STATUS.md) and [evidence index](README.md). diff --git a/docs/R12_PAIRING_AND_TRANSPORT.zh-CN.md b/docs/R12_PAIRING_AND_TRANSPORT.zh-CN.md new file mode 100644 index 0000000..27a32c6 --- /dev/null +++ b/docs/R12_PAIRING_AND_TRANSPORT.zh-CN.md @@ -0,0 +1,98 @@ +# R12 配对与远程通道开发版 + +日期:2026-10-24。本说明适用于工作树中的后端开发版,不代表公网、不同电脑或 GUI 已验收。 + +## 程序与能力 + +| 程序 | 职责 | +|---|---| +| `local-probe-pair` | 本地离线创建身份、指纹检查、签发、安装和撤销 | +| `local-probe-target` | 默认只读 MCP,可选本地审批操作引擎;接收 Tunnel 或主动连接 Relay | +| `local-probe-agent` | 原生 Agent 启动的 stdio MCP 桥接 | +| `local-probe-relay` | 自建服务器上的密文转发,监听回环地址等待 HTTPS 反向代理 | +| `local-probe-operations` | 目标所有者的本地检查、批准/拒绝和恢复材料读取,无远程批准入口 | + +默认仍只读。2026-10-24 新增可选真实操作后端,须独立配置和逐次本地批准,见[操作说明](R12_OPERATIONS_BACKEND.zh-CN.md);GUI 配对/审批尚未接线。 + +## 配对顺序 + +下面是操作约定,命令中的路径/连接/指纹均须由实际部署替换。公有文件用 UTF-8 JSON 保存。CLI 不打印私钥,身份目录不得作为普通配置备份或上传到服务器。 + +1. 目标电脑:`local-probe-pair -action target-init -store <新的绝对身份目录> -approve -offline`。目录的父级须已存在;输出公开 bundle JSON。已有目录或身份不会被覆盖。 +2. 对目标输出执行 `local-probe-pair -action fingerprint-bundle`,从 stdin 读取 bundle,保存/独立核对显示的指纹。该指纹必须经可信途径交给 Agent 侧用户,不能仅相信 Relay 同时提供的 bundle 和指纹。 +3. Agent 电脑:`local-probe-pair -action agent-init -store <新的绝对身份目录> -approve -offline`,输出公开 CSR 请求。 +4. 对 CSR 执行 `local-probe-pair -action fingerprint-request`;将请求文件交给目标所有者,并经独立途径核对这一请求的指纹。 +5. 目标配置使用 v2,明确设置一个已启用的 `purpose=agent_remote` 连接,授权到所需的只读 profile。签发命令:`local-probe-pair -action issue -store <目标身份目录> -config <绝对配置路径> -connection-id <连接ID> -fingerprint <已核对的CSR指纹> -approve -offline`。stdin 为 CSR;输出 pairing JSON,包含公开目标 bundle 与签发的 30 天 Agent 证书。 +6. Agent 安装:`local-probe-pair -action install -store -fingerprint <第2步独立核对的目标指纹> -approve -offline`。stdin 为 pairing JSON。错误目标、Agent 私钥不匹配、证书元数据被改动均拒绝。 + +如果 CSR 输出丢失,可用 `-action request -store ` 生成新的 CSR;签名随机性会使其指纹变化,必须重新核对。目标 bundle 可用 `-action show` 重新导出。签发后输出丢失时不重新签发同一公钥,避免覆盖既有范围;使用本地的原始公开输出或重新创建新的 Agent 身份。 + +签发工具必须在使用身份目录的运行时停止后操作。运行中撤销 API 已能取消租约,但 GUI/本地管理 IPC 尚未接入;CLI 的 `-offline` 是用户对已停止运行时的明确声明,不会自行结束任何进程。 + +## Tunnel 方式 + +目标端: + +```text +local-probe-target -store <目标身份目录> -config <绝对配置路径> -audit-dir <绝对私有审计目录> -listen 127.0.0.1:8791 +``` + +目标进程从本地环境读取 `LOCAL_PROBE_TARGET_ACCESS_TOKEN`。使用至少 32 字节随机凭据,不要把令牌写进命令参数、日志或本说明。将已有受控 Cloudflare Named Tunnel 的 WSS 路径转发到回环 origin 的 `/v1/peer`;本轮没有修改用户现有 Tunnel。 + +Agent 端的 MCP stdio 命令: + +```text +local-probe-agent -store -transport tunnel -endpoint wss://<受控域名>/v1/peer +``` + +桥接从本地环境读取 `LOCAL_PROBE_AGENT_ACCESS_TOKEN`,其值对应目标的外层准入凭据。Cloudflare Access 服务凭据可另外通过 `LOCAL_PROBE_CF_CLIENT_ID` 和 `LOCAL_PROBE_CF_CLIENT_SECRET` 加载,两项必须同时存在。配置 Agent 的 `command/args` 时保留参数数组,不拼接 shell 命令,也不把凭据放进 args。 + +这条 WSS 通道承载额外的端点 TLS。官方 Secure MCP Tunnel 继续使用原有标准 MCP 路径,不能把 `/v1/peer` 填进官方 Tunnel 冒充通用字节流。 + +## 自建 Relay 方式 + +首版使用静态环境引用路由,示例见 [Relay 配置](../deploy/relay/relay.example.json)。Relay 只知道路由 ID 和外层凭据摘要,不拥有端点 CA 或设备私钥。 + +服务器: + +```text +local-probe-relay -config <绝对Relay配置路径> -listen 127.0.0.1:8792 +``` + +在进程环境中分别设置配置引用的目标/Agent 两个独立高熵令牌;不允许两种角色共享令牌,也不允许多个路由复用凭据。通过用户控制的 HTTPS 反向代理暴露 WSS 的 `/v1/target` 和 `/v1/agent`。代理必须支持 WebSocket Upgrade;不得记录 Authorization、数据帧或工具内容。首版程序拒绝直接监听公网地址,TLS 终止交给已配置的反向代理。 + +目标电脑: + +```text +local-probe-target -store <目标身份目录> -config <绝对配置路径> -audit-dir <绝对私有审计目录> -relay-endpoint wss:///v1/target +``` + +此时读取 `LOCAL_PROBE_RELAY_TARGET_TOKEN`,不创建回环监听或公网入站端口。目标维护 4 条主动出站的等待/已配对通道,断线后抖动退避重连。 + +Agent 电脑: + +```text +local-probe-agent -store -transport relay -endpoint wss:///v1/agent +``` + +Agent 的 `LOCAL_PROBE_AGENT_ACCESS_TOKEN` 对应 Relay 配置中的 Agent 角色凭据。Relay 按角色绑定的固定路由匹配双方,不接受任意 host、port、URL 或 query 参数。双方匹配后,Agent 和目标直接进行内层双向 TLS;路由发错到别的目标时仍因设备公钥不匹配而失败。 + +如使用用户自有的私有证书颁发机构,Agent 和 Relay 模式的目标端可显式提供 `-outer-ca-file <绝对公开CA PEM路径>`。只接受 CA 证书,不接受私钥,不跳过域名验证;未提供时使用正常系统信任库。 + +### 首版 Relay 的设计调整 + +计划书中的单独控制连接/一次性票据机制暂以**已认证、按角色静态绑定的 WSS 等待通道**实现第一增量。原因是首版不需要远程动态注册或动态路由管理,省去可以扩张路由权限的控制 API。每一对数据通道仍只连接固定路由的双方;它不具备任意端口转发能力。 + +容量:每路由最多 16 条目标通道、全局 128 条;未配对等待 30 秒后关闭。数据消息最多 64 KiB;配对后的流只有二进制密文。活跃通道每 20 秒心跳,60 秒读期限;读写异常关闭两侧。入口按实际对端地址限制速率,忽略 forwarded headers;反向代理后多个客户端暂共享来源预算。 + +2026-10-24 已补充 Linux systemd 测试部署脚本、窄范围 TLS 前端及真实公网只读验收,见[部署记录](R12_RELAY_DEPLOYMENT.zh-CN.md)。动态设备登记、运行期凭据管理、完整运维指标和证书自动续期仍未完成,不能把这个基础 Relay 称为生产服务。 + +## 撤销与存储 + +离线撤销:`local-probe-pair -action revoke -store <目标身份目录> -key-pin <签发结果中的公钥pin> -approve -offline`。撤销文件只写一次,重启后仍拒绝;同一公钥不能通过重新签发切换范围。新配对使用新 Agent 私钥。 + +Windows 私有记录使用当前用户 DPAPI,并在新建目录设置当前用户/SYSTEM 的受保护 DACL。Unix 首版依赖 0700 目录和 0600 文件,不声称对用户本人/root 加密。记录写入失败/损坏会拒绝加载,不自动生成新身份。 + +运行端读取独立的目标叶密钥及公开记录,不需要加载 CA 签名私钥。它是职责分离,不是抵御当前 OS 用户的隔离:将来的 `trusted_host` 脚本使用同一用户权限,可能访问该用户的身份存储;不能把这个模式宣传成沙箱。 + +此版本无身份备份恢复功能。不要复制旧身份目录来恢复授权,否则可能丢失撤销记录;应生成新身份并重新配对。 diff --git a/docs/R12_PROGRESS.zh-CN.md b/docs/R12_PROGRESS.zh-CN.md new file mode 100644 index 0000000..ba469a2 --- /dev/null +++ b/docs/R12_PROGRESS.zh-CN.md @@ -0,0 +1,138 @@ +# R12 开发进展与验证 + +初始日期:2026-10-23;最新更新:2026-10-24。工作分支:`feat/r12-dual-mode`。起点:`dd0a6b73981d8006403913e400d698c3b8fee291`。 + +本记录描述开发实现,不是已发布版本。R12 完整源码现通过 `feat/r12-dual-mode` 分支交付,英文入口见[开发指南](R12_DEVELOPMENT.md)和[当前状态](IMPLEMENTATION_STATUS.md)。后文“未提交/未推送”等措辞保留各轮历史状态;本次上传不替换现有 GUI/MCP/Tunnel,也不合并 main 或发布 Release。 + +## 2026-10-24:仓库源码与英文开发交接 + +- 将先前未提交修改和新增 R12 源码统一纳入交付分支,保留 MIT 与第三方许可证;同步 main 的四语言首页,英文为默认入口。 +- 新增英文开发、GUI、操作及配对说明,更新中文接手文档,避免继续要求接手人只能索取本机快照。 +- 本轮完整 test/race/vet 与24项前端VM复测通过;上传检查与未验收范围见[交付证据](evidence/r12/2026-10-24-source-upload.md)。未连接用户 Linux 或真实 Relay,未改权限/系统策略。 + +## 2026-10-24 第四增量:本地批准的真实操作后端 + +- 新增 `internal/operations`、`local-probe-operations` 本地控制 CLI、配对目标的可选操作引擎与八个 MCP 工具。支持逐次批准的命令、真实版本、四类脚本、build/test、文本创建/更新及精确补丁。 +- v2 增加显式可写 profile,v1/默认 profile 及写入核心保持只读门。还需 trusted_host、开发者白名单、工具许可、本地目录表哈希及精确审批;远程 confirmed 无效。 +- Windows 私有账本 DACL/DPAPI、OS 独占锁、完整密文原子发布;主体/连接/计划/配置版本绑定、幂等、取消、五分钟审批、60秒轮询租约、重启不自动重跑。 +- 打开审批目录会核对实际 DACL,拒绝共享目录;新增本地所有者取消入口,停止任务无需依赖 Agent。失效/损坏存储立即关闭准入并取消活跃任务。 +- 两连接实际并行、取消一方不影响另一方;全局两作业/每连接一作业。内核读取验证 32 进程、1 GiB 汇总提交内存和累计用户态 CPU 时间预算;不承诺网络沙箱。 +- Python 3.13.1、Node v24.19.0、PowerShell 7.6.5、cmd 版本与脚本,以及真实 Go 编译/单元测试通过。本机官方 SDK/WSS/mTLS→申请→CLI批准→实际写入/冲突拒绝通过。 +- 写入绑定身份/内容版本、规则、目录链、硬链接;保存 before image。已有文件为锁定句柄更新,非原子替换,异常明确 unknown 并保留人工恢复材料。 +- 已准备 Windows 后端和 Linux Agent 构建;本轮未连接用户 Linux 或真实 Relay。操作目标仍限 Windows,GUI/Web 高级入口、在线规则、选择性 epoch 与完整多连接宿主尚未完成。 +- 用法与限制见[操作后端说明](R12_OPERATIONS_BACKEND.zh-CN.md)。 +- 最终源码完整 test/race/vet、Windows 构建与 Linux 交叉编译均 PASS;敏感信息扫描未命中,diff/文档链接通过。实际版本/脚本及 build/test 的 opt-in 检查单独运行通过,子进程退出列表核对与本地取消通过;见[验证证据](evidence/r12/2026-10-24-operations.md)。没有用先前只读中转结果代替本轮操作测试。 + +## 2026-10-24 第三增量:授权服务器上的公网 Relay 验证 + +- 经用户授权部署到既有 Ubuntu 24.04 x86_64 服务器,使用既有 nobody 账号;仅开放 Relay TCP 8080,保留原 443 与其他服务。新 TLS 前端只向固定回环 Relay 转发三个受限路由,采用 TLS 1.3、systemd 私有凭据、资源限制和单元日志限流。 +- 限制前端只绑定公网 NAT 网卡,避免已有 Docker 的明文 HTTP/2 误连;仅对新 listener 设置 MSS=1100 后,公网 TLS 超时消失,未改变全局 MTU/路由或关闭证书校验。 +- 公网重复测试发现旧等待槽未及时感知目标断开,首轮 PASS/FAIL/FAIL。修复为单一持续读循环和有界队列,断开立即释放;race 定向 30 次通过。修复部署后,关闭临时 SSH 转发,直接公网 race 连续三次 PASS(1.67/1.63/1.62 秒),覆盖真实文件读取、范围拒绝及内外两层认证。 +- Linux 主机实际运行前端测试通过。两个单元都以 nobody 运行,原 xray 的 443 监听未变。当前是私有 CA 的短期测试证书,叶证书 2026-11-07 到期,没有自动续期。 +- 最终修复源码完整 test/race/vet 均 PASS;cmd/internal/deploy/docs 脱敏敏感信息扫描未命中,diff 与文档链接检查通过。没有用修复前结果代替本轮最终检查。 +- 部署、故障、哈希、验收范围及维护步骤见[公网 Relay 运维记录](R12_RELAY_DEPLOYMENT.zh-CN.md)。真实公网中转已经验证;Agent/目标仍在同一 Windows 电脑,不能称不同目标电脑的完整操作已经验收。命令/写入/GUI 等后续范围不变。 + +## 2026-10-24 第二增量:持久化配对、原生桥接与 Relay 只读闭环 + +### 已实现 + +- 新 `internal/deviceidentity`:随机设备/Agent 身份、公开 bundle/CSR 指纹、所有者签发、证书绑定设备/Agent/连接、公钥级终端撤销;授权文件与撤销标记只写一次,拒绝覆盖和损坏记录。 +- Windows 新身份目录设置当前用户/SYSTEM 的受保护 DACL,记录以当前用户 DPAPI 加密;Unix 使用私有权限,不声称实现磁盘加密。目标运行时只加载叶密钥,不加载所有者 CA 签发私钥。 +- Registry 将可信连接授权放入私有 context,逐请求复核;运行中撤销取消活跃租约,租约同时受证书到期约束。CLI 变更仍要求离线;GUI/IPC 撤销尚未接入。 +- `local-probe-pair` 可在本地创建、检查、签发、安装、查看及撤销。签发要求已有、启用的 `agent_remote` 配置连接;公开输出不含私钥。 +- `local-probe-agent` 是可运行的官方 SDK stdio 桥接,逐请求转发工具发现与调用,不缓存过期工具列表,不自动重放调用;支持 Tunnel WSS 与 Relay WSS。 +- `local-probe-target` 将配对主体接入现有只读 MCP/policy/rootfs,认证入口与 bearer/Cloudflare 模式互斥;验证原有文件范围仍生效。支持回环 Tunnel origin,或 4 路主动出站 Relay 通道。 +- 新 `local-probe-relay`:按静态路由绑定两种独立角色凭据,仅转发内层 TLS 密文;有界通道、等待超时、心跳、速率/消息限制、取消和关闭。当前只监听回环地址,公网 HTTPS/WSS 由用户受控反向代理提供。 +- 新命令行程序支持 SIGTERM/中断退出、显式私有外层 CA 文件;不提供跳过证书验证选项。 + +### 实现调整与限制 + +首版 Relay 用按角色认证的静态 WSS 等待通道替代计划中的动态控制连接/票据接口;不提供动态路由或任意地址转发。两端仍必须独立通过配对的内层 mTLS 和目标授权。调整理由和完整操作顺序见 [配对与通道说明](R12_PAIRING_AND_TRANSPORT.zh-CN.md)。 + +R12-02 的离线身份/配对与运行期撤销 API 已实现;证书续期/轮换、管理 IPC/GUI、身份灾备仍未完成。R12-03/04 已有只读通道闭环,但缺少真实外部 Tunnel/公网/不同电脑验收和正式运维交付,不能标记整阶段完成。 + +### 本轮验证与故障 + +- 配对包/CSR 替换、修改连接元数据、重复签发、损坏记录、重启后撤销、活跃租约取消及并发签发测试通过。 +- 官方 MCP 经直接 WSS 和 Relay WSS 的桥接通过;越范围读取返回 `denied` 且无文件内容;伪造 bearer 不能进入 peer ingress;角色混用、目标离线及任意目的地址被拒绝。 +- Windows **真实目标 EXE + 真实 Agent EXE** 集成测试通过:官方 SDK `CommandTransport` 通过 stdio 连接 Agent,经本机 HTTPS Relay 和内层 mTLS 读取合成工作区的实际文件。这是同机多进程证据,不是跨机或公网验收。 +- 公共配对 JSON 解码器 5 秒 fuzz 通过,237,185 次执行;嵌套深度/输入大小/重复和未知键受限。 +- 本轮首个最终全量回归出现 peer 调用间歇 EOF。发现 WebSocket 适配器直接传递读取 deadline 与 Go HTTP 的后台读中断语义不兼容:Gorilla 会永久缓存读取超时。改用有界后台读取和独立可恢复读取 deadline,新增“超时后重置并成功读取”回归;实际 peer 文件测试在 race 下重复 100 次通过。没有用自动重试掩盖问题。 +- 全量 race 又复现既有 workspaceadmin 暂停/恢复持久化失败;定向 300 次捕获底层 `replace configuration (os code 5)`。Windows 原子替换现在只对 access denied/sharing/lock violation 最多重试 16 次(5ms 间隔),保持 CAS 写锁、同一临时文件和原子替换,不修改 ACL。定向 race 300 次及实际替换字节校验通过;永久拒绝/未知错误仍失败。存储诊断只保留数字错误码,不输出原始路径或 OS 错误内容。 +- 增加撤销持久化失败用例:不把目录读取失败误报为撤销成功;当前运行时即使磁盘恢复可读,也维持拒绝该主体,明确报告未持久化,不能承诺重启后的撤权。 +- 一轮 vet 因工作区 `tmp/go-build*` 正被清理而扫描失败;后续将进程级 TEMP/TMP 改到 Go 忽略的 `.tools/r12-tmp`,不改系统环境,也不删除用户临时目录。 +- 最终源码全项目 `go test ./...`、`go test -race ./...`、`go vet ./...` 均 PASS(正常主机账号,Go 1.26.5,临时目录 `.tools/r12-tmp`)。默认跳过的 opt-in 网络隔离实验和公网/跨机门仍未执行,不能据此称全部外部验收通过。构建识别和补充证据见 [本轮证据](evidence/r12/2026-10-24-transport.md)。 + +### 开发制品 + +`bin/r12/` 含 Windows pair/agent/target/relay 四个独立 EXE;另有 `bin/r12/linux-amd64/local-probe-relay`。Linux 产物仅交叉编译,未在 Linux 主机运行。它们是本地开发构建,不是完整发布包,未覆盖现有 GUI。 + +### 当前后续顺序 + +继续 R12-05 的操作计划/本地明确审批、持久化作业、幂等、取消、命令/脚本/build/test 与受控文件写回;随后接多连接/在线规则与 GUI。原先末尾“未完成与下一步”保留为第一增量的历史状态,以本节和最新源码为准。 + +## 已实现的第一增量 + +### R12-00:基线与执行契约 + +- 实际核对现有只读 MCP、单一桌面 controller 与关闭的隔离执行门。 +- 用户明确允许新增 `trusted_host`,使用当前用户实际权限;保留旧 `isolated_required` 策略。[决策记录](R12_EXECUTION_DECISION.zh-CN.md)。这项授权持续有效,不需要再次询问同一产品选择。 +- 使用仓库已有 Go 1.26.5 工具链,独立工作区缓存/临时目录,未更改系统 Go 或全局 Git 配置。 + +### R12-01:加密兼容性样机 + +新增 `internal/peertransport`: + +- Gorilla WebSocket v1.5.3 二进制消息流适配 `net.Conn`,限制单消息 64 KiB,关闭发送压缩,保留网络 deadline。 +- Go 标准 TLS 1.3 双向认证,正常 CA/主机名验证后核对预配对目标公钥;目标端验证 Agent 授权回调,关闭服务端会话票据。 +- 每个 HTTP 请求重新检查主体撤销,不从 header/JSON 接受身份;可信主体以私有 context key 传递。调用方仍须绑定实际 connection/profile,不能直接把这个中间件当成文件授权。 +- 官方 MCP Go SDK 通过真实回环 WSS + 内层 mTLS 完成初始化和工具调用;超过 64 KiB 的结果跨消息传输无损。 +- 错误目标 pin、撤销 Agent、明文/伪造 header、文本消息和超大消息拒绝;错误流重复读取不会触发 Gorilla 的失败读取 panic。 +- 新依赖来自已有缓存,经 Go 模块校验取得固定 checksum;增加独立 BSD 许可证。后续发布制品仍须重新生成第三方依赖清单。 + +这里的证书由测试临时生成,未安装到系统信任库。此样机不等于设备配对、生产 Relay 或公网通道已经交付。 + +### R12-02:配置基础(部分) + +- 增加 `local-probe.config.v2`,支持 `purpose=web_local|agent_remote` 与 `execution_policy=isolated_required|trusted_host`。 +- 旧配置仍使用 v1,默认 Web 用途和隔离要求,不自动改授权。 +- v1 不接受新字段;v2 拒绝未知用途/策略;持久化往返保留选择。旧二进制按未知 schema 拒绝 v2,避免静默忽略新语义。 +- MCP 初始化增加原生合法访问优先说明;没有把客户端名称或路径相同当作可靠的同机识别。 + +### R12-05:受信任执行启动基础(部分) + +- 新增本地 `probe.RunTrustedProcess`,要求已审计可执行文件描述、SHA-256、明确 argv/cwd/env、超时与输出限额。 +- 复用 Windows 挂起启动、执行映像核对和 Job Object;固定探针仍限制一个进程,独立受信任入口允许最多 32 个进程。 +- 进程退出后清理后代;超时和输出超限终止作业;不继承全部宿主环境。当前不承诺 CPU/内存限额已完成。 +- 实际启动测试 helper 验证正常返回、超时及输出超限的具体错误类型。这不是用户实际 Node/Python/build/test 全流程验收。 +- 该入口尚未接入 MCP/GUI。审批、审计、连接授权、在线撤销和持久化作业必须由后续上层完成后才能对外开放;现有 GUI 的执行状态继续关闭。 +- 非 Windows 平台明确返回不支持,没有临时使用不受控的 Unix launcher。 + +## 验证结果 + +环境:Windows amd64,Go 1.26.5;全部临时输入为合成工作区/测试 helper。没有新建账号或修改 WFP/防火墙规则。 + +| 检查 | 结果 | +|---|---| +| `go test ./...` | 正常主机账号环境下 PASS | +| `go test -race ./...` | 首轮出现既有连接切换测试失败;完整复测 PASS,见下面限制 | +| `go vet ./...` | PASS | +| `go test -race ./internal/desktopbridge -run TestDesktopHistoryPersistsIndependentScopesAndSelection -count=25` | PASS;增强失败输出,未改原断言 | +| config / peertransport 定向测试 | PASS | +| Windows TrustedHost 实际进程测试 | PASS,含正常运行/超时/输出超限 | +| `git diff --check` | PASS;只存在 Git 的 LF/CRLF 提示 | + +最初测试环境存在 GOROOT 与执行工具版本不同、共享缓存拒绝访问以及临时目录问题,已通过进程级环境设置解决,没有修改全局环境。沙箱账号的既有 `TestCurrentAccountRestrictedDefaultDACL` 失败;正常主机账号完整回归通过,未放宽测试断言。 + +**仍须保留的失败记录**:第一次完整 race 回归中,`TestDesktopHistoryPersistsIndependentScopesAndSelection` 报告 selection mixed scopes。定向 25 次及第二次完整 race 均通过,尚不能确定首轮原因;新增详细失败投影以便追踪。不能将“复测通过”写成“根因已修复”。 + +## 未完成与下一步 + +1. R12-02:持久化设备身份、DPAPI/权限保护、配对包、CSR 签发、授权 epoch 与完整撤销。 +2. R12-03:可运行的 stdio Agent 桥接与生产 Tunnel 适配。 +3. R12-04:自建 Relay 控制面、数据面、票据、配额、恢复与 Linux 部署制品。 +4. R12-05:不可变操作计划、每连接明确授权与本地审批、审计、作业账本、幂等、取消、真实脚本/build/test 和受控文件写入。 +5. R12-06:多连接生产宿主、在线规则和公平调度;继续追踪连接切换偶发失败。 +6. R12-07/08:后端封板后 GUI 接线、真实跨机与服务器验收、发布候选。 + +当前不具备“完整远程操作可用版”的条件。后续执行按 [技术实现书](R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md) 继续,不重新请求已经明确的受信任执行产品授权。 diff --git a/docs/R12_RELAY_DEPLOYMENT.zh-CN.md b/docs/R12_RELAY_DEPLOYMENT.zh-CN.md new file mode 100644 index 0000000..3ca6f04 --- /dev/null +++ b/docs/R12_RELAY_DEPLOYMENT.zh-CN.md @@ -0,0 +1,114 @@ +# R12 公网 Relay 测试部署与运维 + +日期:2026-10-24。此文记录已部署、实测的只读中转增量,不代表完整远程操作已经交付。实际测试域名、角色凭据及 SSH 主机记录只保存在忽略目录 `.tools/r12-public-deploy/`,本文使用占位符。 + +## 已部署结构 + +```text +目标程序(主动出站 WSS) ─┐ + ├─ 公网 TCP 8080 / TLS 1.3 +Agent 桥接(主动出站 WSS)┘ ↓ + local-probe-relay-edge + ↓ 固定回环 HTTP / WebSocket + local-probe-relay :8792 + ↓ + 仅转发端点之间的内层 mTLS 密文 +``` + +运行环境为用户授权的 Ubuntu 24.04 x86_64 服务器。原有 443 服务保持运行。仅为本项目开放 TCP 8080;未新建账号、安装系统包或修改其他服务。 + +| 项目 | 实际配置 | +|---|---| +| Relay 单元 | `local-probe-relay-r12.service` | +| TLS 前端单元 | `local-probe-relay-edge-r12.service` | +| Relay 监听 | `127.0.0.1:8792` | +| TLS 前端监听 | 仅公网 NAT 对应网卡的 IPv4 地址,端口 8080;不监听 Docker 网桥 | +| 运行用户 | 既有 `nobody:nogroup`,不是 root | +| 二进制/脚本 | `/opt/local-probe-relay-r12/` | +| 私有配置/外层证书 | `/etc/local-probe-relay-r12/`,root 私有目录 | +| 凭据交付 | systemd `LoadCredential`;角色令牌从 root 私有环境文件读取 | +| 单元限制 | `NoNewPrivileges`、只读系统目录、私有临时目录、192 MiB 内存、64 tasks、1024 文件句柄 | +| 日志 | 不记录 Authorization 或数据帧;每单元 30 秒最多 20 条日志 | +| TCP 分段 | 当前前端仅对自身 listener 设置 `TCP_MAXSEG=1100`;未调整系统路由/MTU或全局防火墙策略 | + +前端仅转发 GET `/healthz`、`/v1/target`、`/v1/agent`,拒绝 query 和请求体;固定上游必须为回环 HTTP,不提供任意地址代理。中转角色认证与目标端配对授权互相独立。 + +外层 TLS 在 Relay 前端终止,因此服务器能看到角色准入信息及连接元数据。工具调用、文件内容和结果仍由目标与 Agent 的内层 TLS 1.3 双向认证加密;Relay 不持有这些端点的签发私钥。不能将外层 CA 与端点配对 CA 混用。 + +## 部署脚本与客户端 + +[部署脚本](../deploy/relay/bootstrap-test-server.py)只管理自身标记的目录和单元,拒绝覆盖不属于本项目的配置;更新单元前保存备份。脚本不会配置防火墙。已有证书和凭据被保留,运行脚本不等于证书续期。 + +先交叉编译并校验 Linux amd64 二进制,将文件上传为候选文件,核对 SHA-256 后原子重命名。不要用 scp 直接覆盖正在执行的二进制。部署参数示意: + +```text +python3 /opt/local-probe-relay-r12/bootstrap-test-server.py \ + --host <实际测试域名> --port 8080 \ + --bind-address <公网NAT对应网卡的本机IPv4> \ + --tcp-max-segment 1100 \ + --relay-sha256 <已验证的Relay哈希> \ + --edge-sha256 <已验证的前端哈希> --update-owned-units +``` + +替换二进制后,需要显式重启对应单元;脚本只有在单元内容改变时才自动重启。首次部署会 enable/start 两个单元,服务器重启后也会启动。此次主机上的确切 8080 iptables 放行规则为运行期规则,未安装全局持久化工具;云端规则由用户放行。重启后仍需复核公网入站,而不能只检查服务 active。应定期检查证书和磁盘。 + +目标端和 Agent 都需要明确配置可信公开 CA: + +```text +local-probe-target -store <目标私有身份目录> -config <目标配置绝对路径> \ + -audit-dir <私有审计目录> \ + -relay-endpoint wss://<实际测试域名>:8080/v1/target \ + -outer-ca-file <公开外层CA的绝对路径> + +local-probe-agent -store -transport relay \ + -endpoint wss://<实际测试域名>:8080/v1/agent \ + -outer-ca-file <公开外层CA的绝对路径> +``` + +目标端读取 `LOCAL_PROBE_RELAY_TARGET_TOKEN`,Agent 读取 `LOCAL_PROBE_AGENT_ACCESS_TOKEN`。两者使用服务器路由中对应角色的不同凭据;不要放入命令行参数、截图或日志。配对与授权另按[配对说明](R12_PAIRING_AND_TRANSPORT.zh-CN.md)完成;仅有 Relay 凭据不能读取文件。 + +## 实际故障、修复与证据 + +1. 最初 TCP 8080/8443 均不可达。用户授权且放行 TCP 8080 后继续测试;没有占用或替换原有 443 服务。 +2. 前端通配地址监听导致已有 Docker 容器的明文 HTTP/2 流量误连 TLS 端口,并持续产生错误日志。将本服务限制为公网 NAT 网卡地址,另加自身日志限流;最终最近两分钟 TLS 错误为 0。未修改该容器。 +3. 公网 TCP 能连接但 TLS 超时;抓包只记录 TCP 元数据,观察到服务端握手数据重传。调整本服务 socket MSS 后,保持默认 TLS 密钥交换、域名和 CA 校验的公网测试在约 1.6–1.8 秒内完成。此证据支持路径分段兼容问题;没有确认是哪一跳设备丢包,也未通过降低 TLS 版本或跳过证书检查解决。 +4. 首轮公网连续三次测试结果为 PASS/FAIL/FAIL。定位到等待配对的目标 WebSocket 没有读循环,断开后旧槽要等 30 秒才释放。新增从注册到转发始终唯一的目标读循环与有界消息队列,断开即清理槽;不自动重放 Agent 操作。新增断开等待目标的回归,race 重复 30 次通过。 +5. 修复后的 Relay 已原子部署并重启;临时 SSH 本地转发已关闭。真实公网 race 测试连续三次 PASS,耗时分别为 1.67、1.63、1.62 秒。外层角色混用/错误凭据拒绝、内层 mTLS、真实合成文件读取、跨 root 拒绝、未登记证书拒绝均通过。 +6. Linux 主机实际执行前端测试二进制通过:listener MSS 的内核读取值、WebSocket 双向转发、角色认证及固定上游约束。不是仅凭交叉编译判断 Linux 可运行。 +7. 等待槽修复后的最终源码全项目 `go test ./...`、`go test -race ./...`、`go vet ./...` 均 PASS(正常主机账号、Go 1.26.5)。cmd/internal/deploy/docs 的 Gitleaks 脱敏扫描未发现命中,`git diff --check` 与相关文档链接检查通过。未执行默认跳过的隔离实验,不据此扩张执行能力。 + +公网用例是 `internal/relay/public_test.go` 的 `TestPublicRelayReadOnlyEndToEnd`。仅在显式提供端点、私有测试凭据路径和公开 CA 路径时运行。可选的 SSH 诊断目的地址会明确标记“不是直接公网证据”;最终三次测试未使用该选项。 + +本次 Agent 和目标测试端点都在同一 Windows 电脑,Relay 在真实公网 Linux 服务器;没有访问用户工作目录。该结果证明真实跨机中转与加密只读链路,不等于两台不同电脑上的 Agent/目标完整操作验收。 + +部署二进制 SHA-256: + +```text +local-probe-relay 12ec97f38b0a2c9fad366a0ec643289b676a921e708fa0db14d86d3b2cc7a3af +local-probe-relay-edge bc7742f43df048897853c26084b948e5ea6d055ec0bdc5322cdc0abbdf548b03 +``` + +## 运维、有效期与停止 + +测试证书没有安装到操作系统信任库,客户端必须显式提供公开 CA,并保持主机名验证。当前叶证书到期为 **2026-11-07 04:23:44 UTC(北京时间 12:23:44)**,测试 CA 到期为 **2026-11-23 04:23:44 UTC**。当前没有自动续期;到期前需重新签发或接入正式证书流程。不能将当前测试部署作为无人维护的长期服务。 + +检查状态(不会输出凭据): + +```sh +systemctl is-active local-probe-relay-r12.service local-probe-relay-edge-r12.service +openssl x509 -in /etc/local-probe-relay-r12/edge-cert.pem -noout -dates +``` + +停止并取消开机启动本项目服务(按需由维护者执行,本轮没有停止): + +```sh +systemctl disable --now local-probe-relay-edge-r12.service local-probe-relay-r12.service +``` + +单元和旧二进制有备份,但回滚时需同时核对 CLI 参数,旧前端不支持 `-tcp-max-segment`。不要简单恢复旧二进制而保留新参数。不要重置整台服务器防火墙;若撤销本项目规则,仅处理带 `local-probe-r12-relay` 注释的确切 TCP 8080 规则,云安全组由用户按实际归属维护。 + +最终检查磁盘约剩 2.8 GiB(使用率 93%)。本项目部署目录为数十 MiB;此前错误曾增加 journal,已有容器日志也占用空间。未清空或截断其他服务日志。正式持续运行前需另行安排日志留存和容量治理。 + +## 仍未交付 + +此部署不新增命令/脚本/build/test/文件写回能力。操作审批与作业账本、多连接管理、GUI 接入、凭据动态轮换、证书自动续期、监控与正式发布仍按 [R12 计划](R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md)继续。 diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..edb389b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,30 @@ +# Documentation + +English is the default language for the repository and current R12 developer handoff. Existing `.zh-CN.md` documents retain the detailed designs, historical evidence and Chinese translation. A design describes intended work; the latest status and actual code determine what is implemented. + +## R12 developer entry points + +| Document | Read it for | +| --- | --- | +| [Developer guide](R12_DEVELOPMENT.md) | Getting the complete branch, source map, checks and implementation sequence | +| [GUI handoff](GUI_HANDOFF.md) | Accepted visual baseline, workflows, actual desktop RPC and missing interfaces | +| [Operations](R12_OPERATIONS.md) | Trusted-host execution, local approval, jobs and file changes | +| [Pairing and transport](R12_PAIRING_AND_TRANSPORT.md) | Pairing, native Agent, WSS/Relay startup and identity handling | +| [Implementation status](IMPLEMENTATION_STATUS.md) | Current English summary followed by dated historical records | +| [Upload verification](evidence/r12/2026-10-24-source-upload.md) | Checks performed for the repository handoff | + +## Detailed design and evidence (Simplified Chinese) + +- [R12 implementation plan](R12_DUAL_MODE_REMOTE_IMPLEMENTATION_PLAN.zh-CN.md), [trusted-host decision](R12_EXECUTION_DECISION.zh-CN.md), [progress](R12_PROGRESS.zh-CN.md). +- [GUI requirements](GUI_HANDOFF.zh-CN.md), [developer handoff](R12_DEVELOPER_START.zh-CN.md), [operation details](R12_OPERATIONS_BACKEND.zh-CN.md). +- [Pairing/transport details](R12_PAIRING_AND_TRANSPORT.zh-CN.md), [public Relay deployment evidence](R12_RELAY_DEPLOYMENT.zh-CN.md). +- [Local operation evidence](evidence/r12/2026-10-24-operations.md), [transport evidence](evidence/r12/2026-10-24-transport.md). + +## Existing Preview and architecture + +- [Desktop guide](DESKTOP_PREVIEW.zh-CN.md), [deployment](DEPLOYMENT_PREVIEW.zh-CN.md), [development](DEVELOPMENT.zh-CN.md). +- [Architecture](ARCHITECTURE.zh-CN.md), [tool contracts](TOOL_CONTRACTS.md), [threat model](THREAT_MODEL.md). +- [OpenAI Tunnel](TUNNEL_SETUP.zh-CN.md), [Cloudflare Tunnel/Access](CLOUDFLARE_TUNNEL_SETUP.zh-CN.md). +- [Master plan](MASTER_PLAN.zh-CN.md), [R11 backend plan](R11_BACKEND_FIRST_PLAN.zh-CN.md), [release checklist](R9_RELEASE_CHECKLIST.zh-CN.md). + +R11 documents describe the older desktop ingress and execution gates. The explicitly approved R12 `trusted_host` path is a separate execution contract; it does not implement strict network isolation or silently enable the old desktop execution path. diff --git a/docs/evidence/r12/2026-10-24-operations.md b/docs/evidence/r12/2026-10-24-operations.md new file mode 100644 index 0000000..5b32643 --- /dev/null +++ b/docs/evidence/r12/2026-10-24-operations.md @@ -0,0 +1,49 @@ +# R12 本地操作后端验证证据 + +日期:2026-10-24。环境:Windows amd64,Go 1.26.5。分支 `feat/r12-dual-mode` 工作树开发构建;没有提交、推送或发布。 + +## 最终检查 + +| 检查 | 结果 | +|---|---| +| `go test ./...` | PASS | +| `go test -race ./...` | PASS | +| `go vet ./...` | PASS | +| Windows 目标/Agent/配对/本地控制 CLI 构建 | PASS,独立输出目录 | +| Linux amd64 Agent/配对/默认只读目标交叉编译 | PASS;未在新增 Linux 电脑运行 | +| cmd/internal/deploy/docs 的 Gitleaks 脱敏扫描 | 未命中 | +| `git diff --check`、相关文档相对链接 | PASS | + +完整日志在 Git 忽略目录 `.tools/r12-operations-finalized-{test,race,vet}.log`。最终构建为 `bin/r12-operations/{windows-amd64,linux-amd64}/`,各有 `SHA256SUMS.txt`。 + +## 实际功能验证 + +- Python 3.13.1、Node v24.19.0、PowerShell 7.6.5、cmd 实际版本与批准脚本全部 PASS。脚本实际创建临时文件。cmd 额外 shell 参数在准备阶段拒绝。 +- Go 合成项目真实 `go build` 产出 EXE,真实 `go test` 执行单元测试 PASS。没有下载依赖或安装新工具。 +- 本机官方 MCP SDK、Agent 桥接、WSS、内层 mTLS:工具发现、真实执行策略声明、申请、等待本地批准、文件提交、状态查询、冲突拒绝和配对撤销通过。 +- 独立本地 CLI EXE 在目标运行期间 inspect/approve;没有 acknowledgement 时拒绝,批准后实际写入。 +- 不批准/拒绝/取消不产生工作文件副作用;相同 nonce 不重复执行,同 nonce 不同计划拒绝。任务改变文件后,重复 prepare 仍返回原 ID。 +- 两个连接实际同时运行进程,跨主体取消拒绝,取消一个不影响另一个。本地所有者也能不依赖 Agent 取消运行作业。 +- 进程环境不继承未批准标记;输出超限终止;取消和父进程正常退出后,核对 Job 内进程列表为空。专门测试不继承输出管道的子进程,避免仅靠 EOF 推断子树已经停止。 +- Windows Job 内核读取证明 32 进程、1 GiB 总提交内存和累计用户态 CPU 时间限制已设置。不是网络/文件沙箱证明。 +- v1 拒绝可写 profile,v2 显式可写权限往返保留,默认只读不变;只读 profile 在操作层与写入核心均拒绝写入。 +- 文件身份/内容冲突、硬链接、路径穿越、deny、备份失败、独占创建与精确补丁上下文不唯一均拒绝;用户期间修改保持不变。 +- 存储损坏拒绝、单引擎 OS 锁、审批记录完整原子发布、共享审批目录拒绝、目标重启 unknown/interrupted 且不重跑通过。 + +真实运行器为 opt-in 检查,设置 `LOCAL_PROBE_OPERATIONS_REAL_TOOLS=1` 和四个明确的运行器路径环境变量,再执行: + +```text +go test -race ./internal/operations -run 'Test(InstalledPython|RealGoBuild)' -count=1 -v +``` + +最终一次真实 Go build/test 为 14.77 秒;之后的 cmd 参数准入补充检查也重新运行四种已安装运行器,全部 PASS。常规回归默认跳过这些 opt-in 场景,不能将默认 skip 写成实测。 + +## 失败保留及边界 + +初版 race 测试 EXE 作为子进程夹具因净化环境缺 DLL,以 `0xc0000135` 退出;改用 CGO=0 的独立合成 helper,没有继承全部宿主环境。相同配置内容的新 revision 最初未撤销旧审批,已将 revision 纳入 epoch 并通过回归。SDDL 字符串对比最初误拒绝合法私有目录,现按实际控制位及 ACE 验证;合法与共享目录测试同时保留。 + +已有文件采用锁定句柄更新并先保存私有 before image,不是原子替换;写入失败/崩溃可能部分更新,状态明确 unknown,需人工核对恢复。本轮未声称实现多文件事务。 + +没有访问用户真实项目文件,没有新建账号,没有修改系统网络策略,没有连接用户新增 Linux 电脑或公网 Relay,也没有替换 GUI。Linux 作为 Agent 的实机与真实 Relay 操作验收安排在后续开发完成后。 + +在线规则/选择性授权 epoch、完整多连接宿主、GUI/Web 高级入口仍未完成,详见[操作后端说明](../../R12_OPERATIONS_BACKEND.zh-CN.md)。 diff --git a/docs/evidence/r12/2026-10-24-source-upload.md b/docs/evidence/r12/2026-10-24-source-upload.md new file mode 100644 index 0000000..6f25d19 --- /dev/null +++ b/docs/evidence/r12/2026-10-24-source-upload.md @@ -0,0 +1,29 @@ +# R12 source-upload verification + +Date: 2026-10-24. Branch: `feat/r12-dual-mode`. R12 started from `dd0a6b73981d8006403913e400d698c3b8fee291`; the branch was fast-forwarded to main's documentation-only update `823e7513327d538ec2aadb139998e2fd85232648` before preparing this upload. No main merge, Release, live deployment or permission expansion is part of the source handoff. + +## Fresh checks + +Windows amd64, Go 1.26.5, normal Windows account. Private process-local temp/cache settings were used, without changing global environment settings. Tests used synthetic data; public-network and actual installed-runtime opt-in tests were not rerun for this upload. + +| Command/check | Result | +| --- | --- | +| `go test -count=1 ./...` | PASS, 50.28 seconds | +| `go test -race -count=1 ./...` | PASS, 70.06 seconds | +| `go vet ./...` | PASS, 3.58 seconds | +| `node scripts/Test-LocalProbeDesktopFrontend.mjs` | PASS, 24 VM scenarios | +| `gofmt -l internal cmd` | PASS, no unformatted files | +| Pairing public-decoder fuzz, five-second target/two workers | PASS, 74,554 executions (9.16-second total test including startup/shutdown) | +| `go build -mod=readonly ./cmd/...` | PASS, Windows CLI/GUI entry points | +| Updated documentation relative links | PASS, 14 entry/handoff/status documents | +| `git diff --cached --check` | PASS | +| Staged source export, Gitleaks 8.30.1 redacted scan | PASS, no findings | +| Staged path exclusions | PASS, 96 changed files; no private runtime/build paths | + +The complete index was exported to an ignored directory for scanning; credentials and private identities were not exported. The upload adds the Gorilla WebSocket BSD license alongside its pinned module checksum. Raw local logs, private configuration and development ZIPs are intentionally excluded from Git. These checks are local verification, not a claim that GitHub Actions or external acceptance has passed. + +## Previous evidence remains separate + +Actual installed runtimes, real synthetic Go build/test, local owner CLI approval, WSS/mTLS file operations, cancellation/process limits and conflicts were verified in the [earlier operation round](2026-10-24-operations.md). Public read-only Relay validation is in the [deployment record](../../R12_RELAY_DEPLOYMENT.zh-CN.md). These do not establish Linux Agent → real Relay → Windows execution, GUI operation wiring or production multi-connection lifecycle. + +The English README and developer/GUI/operation/pairing guides distinguish implemented behavior from planned interfaces. Chinese design and historical evidence remain available. No credentials, private keys, live configuration, SSH data, job journal, backup, toolchain/cache or developer ZIP is intended for this source commit. diff --git a/docs/evidence/r12/2026-10-24-transport.md b/docs/evidence/r12/2026-10-24-transport.md new file mode 100644 index 0000000..445df91 --- /dev/null +++ b/docs/evidence/r12/2026-10-24-transport.md @@ -0,0 +1,36 @@ +# R12 配对/传输后端开发证据 + +日期:2026-10-24;Windows amd64;Go 1.26.5;分支 `feat/r12-dual-mode`,未提交工作树,基准 HEAD `dd0a6b73981d8006403913e400d698c3b8fee291`。 + +## 本地证据 + +| 检查 | 结果与边界 | +|---|---| +| 身份/配对/撤销相关包 race | PASS;含替换与篡改、并发、损坏、重启和撤销存储失败 | +| `TestPairedAgentUsesExistingFileScopeAndRejectsMixedAuthentication` race ×100 | PASS;真实 rootfs 授权范围、独立目标设备 ID,非公网测试 | +| `TestWindowsRealCLIReadsFileThroughRelay` | PASS;启动真实目标/Agent EXE,由官方 SDK stdio 调用,经本机 HTTPS Relay 读取实际合成文件 | +| `TestReadDeadlineCanBeResetWithoutPoisoningWebSocket` | PASS;HTTP 后台读中断后可恢复,不依赖重试工具调用 | +| `TestUpdatePauseAndResumeAreProfileScoped` race ×300 | PASS;在 Windows 原子替换有限重试修复后运行 | +| `FuzzPublicPairingDecoder`,请求 5s | PASS;237,185 次执行;不是长期 fuzz 或安全审计结论 | +| Windows 四程序 build | PASS;本地开发构建,未打完整发布包 | +| Linux amd64 Relay build | PASS;只证明交叉编译,不是 Linux 运行证据 | + +全项目 test/race/vet 的最终结果记录在 [R12 进展](../../R12_PROGRESS.zh-CN.md)。保留修复前的失败,不能用定向结果覆盖全项目失败。 + +## 最终开发产物 SHA-256 + +以下文件位于忽略目录 `bin/r12/`,没有进入 Git 源码或替换现有 GUI: + +```text +9236B11B17221F928F3F384E97990D58F5D4C75C2F859AF8E491DCDFE0F66A1F local-probe-agent.exe +ECEC83504312BE87ECCBF2F56DBD006CE054F176A98B75D7B2894596BC727C3A local-probe-pair.exe +957350AE90474DA03BEBB2A91A21B177940DF28C27909DB68A5DA65C1956EF85 local-probe-relay.exe +533A3CCBD7C4819C96C79CF90F544D59F7ED29DFB75BD0BF5F0E5A9CEA7F3F26 local-probe-target.exe +F95F52C0917E832A159FCB96692CA1DFFD4F382644693E6339EF829EC77D9AC3 linux-amd64/local-probe-relay +``` + +哈希用于识别本次本地构建,不代表签名、可重现构建或正式发布批准。二进制由未提交源码构建,重新构建后应重新计算,不能沿用旧哈希。 + +## 未进行的外部操作 + +没有创建外部/Windows 账号,没有修改 WFP 或防火墙规则,没有连接实际公网 Relay、修改现有 Tunnel 或发布制品。全部身份、路由凭据、端口和文件输入来自临时测试夹具。 diff --git a/go.mod b/go.mod index cc80dc7..c10a3c9 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.25.0 require ( github.com/coreos/go-oidc/v3 v3.21.0 + github.com/gorilla/websocket v1.5.3 github.com/jchv/go-webview2 v0.0.0 github.com/modelcontextprotocol/go-sdk v1.7.0 golang.org/x/sys v0.41.0 diff --git a/go.sum b/go.sum index 32afdce..798bb7f 100644 --- a/go.sum +++ b/go.sum @@ -10,6 +10,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0= github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ= github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs= github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44= diff --git a/internal/agentbridge/bridge.go b/internal/agentbridge/bridge.go new file mode 100644 index 0000000..81043f4 --- /dev/null +++ b/internal/agentbridge/bridge.go @@ -0,0 +1,51 @@ +// Package agentbridge presents a local stdio MCP server backed by an +// authenticated remote MCP session. It does not grant extra tools or retry writes. +package agentbridge + +import ( + "context" + "errors" + "io" + "net/http" + + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// New uses the official SDK at both ends. Tool discovery and calls are forwarded +// on every request, so cached tool registration cannot hide remote revocation. +// No clientInfo, approval booleans, sampling, roots or credentials are forwarded. +func New(ctx context.Context, httpClient *http.Client) (*mcp.Server, io.Closer, error) { + if httpClient == nil { + return nil, nil, errors.New("encrypted HTTP client required") + } + client := mcp.NewClient(&mcp.Implementation{Name: "local-probe-agent", Version: "r12-dev"}, nil) + upstream, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: "https://127.0.0.1/mcp", HTTPClient: httpClient, DisableStandaloneSSE: true, MaxRetries: -1}, nil) + if err != nil { + return nil, nil, errors.New("paired target connection failed") + } + server := mcp.NewServer(&mcp.Implementation{Name: "local-probe-agent", Version: "r12-dev"}, &mcp.ServerOptions{ + Instructions: "This bridge accesses the explicitly paired target environment. If authorized native tools already access that workspace in your current environment, prefer native tools. Never bypass native access or approval restrictions through this bridge. A successful connection grants no extra file or execution permissions.", + Capabilities: &mcp.ServerCapabilities{Tools: &mcp.ToolCapabilities{}}, + }) + server.AddReceivingMiddleware(func(next mcp.MethodHandler) mcp.MethodHandler { + return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) { + switch method { + case "tools/list": + params, ok := req.GetParams().(*mcp.ListToolsParams) + if !ok { + return nil, errors.New("invalid tool listing") + } + return upstream.ListTools(ctx, params) + case "tools/call": + params, ok := req.GetParams().(*mcp.CallToolParamsRaw) + if !ok || params == nil { + return nil, errors.New("invalid tool call") + } + return upstream.CallTool(ctx, &mcp.CallToolParams{Name: params.Name, Arguments: params.Arguments}) + default: + return next(ctx, method, req) + } + } + }) + return server, upstream, nil +} diff --git a/internal/agentbridge/bridge_test.go b/internal/agentbridge/bridge_test.go new file mode 100644 index 0000000..9e2e11b --- /dev/null +++ b/internal/agentbridge/bridge_test.go @@ -0,0 +1,115 @@ +package agentbridge + +import ( + "context" + "crypto/x509" + "encoding/hex" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestPairedWSSBridgeForwardsOfficialMCPAndLiveRevocation(t *testing.T) { + base := t.TempDir() + store, err := deviceidentity.CreateStore(filepath.Join(base, "target")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + a, err := deviceidentity.NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = store.SaveAuthority(a); err != nil { + t.Fatal(err) + } + agent, request, err := deviceidentity.NewAgent() + if err != nil { + t.Fatal(err) + } + fp, _ := request.Fingerprint() + grant, err := store.IssueGrant(request, fp, "connection-a", time.Hour) + if err != nil { + t.Fatal(err) + } + registry, err := deviceidentity.NewRegistry(store) + if err != nil { + t.Fatal(err) + } + target := mcp.NewServer(&mcp.Implementation{Name: "target-test", Version: "test"}, nil) + target.AddTool(&mcp.Tool{Name: "check_scope", InputSchema: map[string]any{"type": "object"}}, func(ctx context.Context, _ *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + g, ok := deviceidentity.GrantFromContext(ctx) + if !ok || g.ConnectionID != "connection-a" { + t.Fatal("scope lost") + } + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: g.ConnectionID}}}, nil + }) + handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return target }, &mcp.StreamableHTTPOptions{Stateless: true}) + inner, err := registry.ServerTLS() + if err != nil { + t.Fatal(err) + } + endpoint, err := peertransport.NewEndpoint(inner, registry.Handler(handler), func(r *http.Request) bool { return r.Header.Get("Authorization") == "Bearer test-admission" }) + if err != nil { + t.Fatal(err) + } + defer endpoint.Close() + outer := httptest.NewTLSServer(endpoint) + defer outer.Close() + roots := x509.NewCertPool() + roots.AddCert(outer.Certificate()) + bundle := a.Bundle() + bf, _ := bundle.Fingerprint() + clientTLS, err := agent.ClientTLS(bundle, grant, bf) + if err != nil { + t.Fatal(err) + } + httpClient, closeClient, err := peertransport.HTTPClientWithRoots("wss"+strings.TrimPrefix(outer.URL, "https"), clientTLS, http.Header{"Authorization": []string{"Bearer test-admission"}}, roots) + if err != nil { + t.Fatal(err) + } + defer closeClient() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + bridge, remote, err := New(ctx, httpClient) + if err != nil { + t.Fatal(err) + } + defer remote.Close() + local, remoteTransport := mcp.NewInMemoryTransports() + bridgeSession, err := bridge.Connect(ctx, remoteTransport, nil) + if err != nil { + t.Fatal(err) + } + defer bridgeSession.Close() + client := mcp.NewClient(&mcp.Implementation{Name: "native-agent", Version: "test"}, nil) + session, err := client.Connect(ctx, local, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + list, err := session.ListTools(ctx, nil) + if err != nil || len(list.Tools) != 1 || list.Tools[0].Name != "check_scope" { + t.Fatalf("list=%+v err=%v", list, err) + } + result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "check_scope", Arguments: map[string]any{}}) + if err != nil || result.IsError || result.Content[0].(*mcp.TextContent).Text != "connection-a" { + t.Fatalf("call=%+v err=%v", result, err) + } + var pin peertransport.Pin + raw, _ := hex.DecodeString(grant.KeyPin) + copy(pin[:], raw) + if err = registry.Revoke(pin); err != nil { + t.Fatal(err) + } + if _, err = session.ListTools(ctx, nil); err == nil { + t.Fatal("revoked tool list cached by bridge") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 7e03619..9b2aef3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -20,6 +20,8 @@ import ( const SchemaVersionV1 = "local-probe.config.v1" +const SchemaVersionV2 = "local-probe.config.v2" + const MaxConfigBytes = 1 << 20 var ( @@ -64,7 +66,8 @@ func (r Root) clone() Root { return r } -// Profile is a read-only access profile. A profile can be referenced by more +// Profile defaults to read-only; explicit write grants require schema v2. +// A profile can be referenced by more // than one connection, but its slices are never exposed for mutation. type Profile struct { id string @@ -97,6 +100,10 @@ func (p Profile) IgnorePatterns() []string { return append([]string(nil), p.igno func (p Profile) ReadOnly() bool { return p.readOnly } +// WithWriteAccess is an explicit local grant. Only schema v2 can persist it; +// operation tools still require developer mode, trusted_host and local approval. +func (p Profile) WithWriteAccess() Profile { p = p.clone(); p.readOnly = false; return p } + func (p Profile) clone() Profile { p.rootIDs = append([]string(nil), p.rootIDs...) p.workspaceRoots = cloneWorkspaceRootMetadata(p.workspaceRoots) @@ -140,6 +147,8 @@ func cloneWorkspaceRootMetadata(values []WorkspaceRootMetadata) []WorkspaceRootM // credential reference. The reference is not a secret and is never resolved // by this package. type Connection struct { + executionPolicy ExecutionPolicy + purpose ConnectionPurpose id string label string profileID string @@ -479,6 +488,8 @@ func (c Config) MarshalJSON() ([]byte, error) { enabled := connection.enabled transport := string(connection.Transport()) raw.Connections[i] = rawConnection{ + ExecutionPolicy: connection.executionPolicy, + Purpose: connection.purpose, ID: connection.id, Label: connection.label, ProfileID: connection.profileID, @@ -658,6 +669,8 @@ func parseWorkspaceRootMetadata(values []rawWorkspaceRootMetadata) ([]WorkspaceR } type rawConnection struct { + ExecutionPolicy ExecutionPolicy `json:"execution_policy,omitempty"` + Purpose ConnectionPurpose `json:"purpose,omitempty"` DesktopTransport ConnectionTransport `json:"desktop_transport,omitempty"` DesktopPort int `json:"desktop_port,omitempty"` ID string `json:"id"` @@ -723,6 +736,8 @@ func fromRaw(raw rawConfig) (Config, error) { transport = ConnectionTransport(*connection.Transport) } c.connections[i] = Connection{ + executionPolicy: connection.ExecutionPolicy, + purpose: connection.Purpose, id: connection.ID, label: connection.Label, profileID: connection.ProfileID, @@ -766,7 +781,7 @@ func fromRaw(raw rawConfig) (Config, error) { } func (c Config) validate() error { - if c.schemaVersion != SchemaVersionV1 { + if c.schemaVersion != SchemaVersionV1 && c.schemaVersion != SchemaVersionV2 { return invalid("schema_version", "unsupported schema version") } rootIDs := make(map[string]struct{}, len(c.roots)) @@ -792,6 +807,9 @@ func (c Config) validate() error { profileIDs := make(map[string]struct{}, len(c.profiles)) for i, profile := range c.profiles { field := fmt.Sprintf("profiles[%d]", i) + if !profile.readOnly && c.schemaVersion != SchemaVersionV2 { + return invalid(field+".read_only", "write profiles require schema v2") + } if err := validateProfile(profile, field); err != nil { return err } @@ -836,6 +854,18 @@ func (c Config) validate() error { if err := validateConnectionTransport(connection.Transport(), connection.tunnelID, connection.tunnelAlias, field); err != nil { return err } + if c.schemaVersion == SchemaVersionV1 && connection.purpose != "" { + return invalid(field+".purpose", "requires schema v2") + } + if c.schemaVersion == SchemaVersionV1 && connection.executionPolicy != "" { + return invalid(field+".execution_policy", "requires schema v2") + } + if !connection.Purpose().valid() { + return invalid(field+".purpose", "unsupported purpose") + } + if !connection.ExecutionPolicy().valid() { + return invalid(field+".execution_policy", "unsupported execution policy") + } } if err := validateEnvironmentTools(c.environmentTools); err != nil { return err @@ -880,9 +910,6 @@ func validateProfile(profile Profile, field string) error { if !validIdentifier(profile.id) { return invalid(field+".id", "invalid id") } - if !profile.readOnly { - return invalid(field+".read_only", "write profiles are not enabled") - } if err := validateIDList(profile.rootIDs, field+".roots"); err != nil { return err } diff --git a/internal/config/filestore.go b/internal/config/filestore.go index 8175b91..71ce4d9 100644 --- a/internal/config/filestore.go +++ b/internal/config/filestore.go @@ -15,6 +15,7 @@ import ( "sort" "strings" "sync" + "syscall" "unicode/utf8" ) @@ -627,7 +628,13 @@ func sameFileStorePath(left, right string) bool { return left == right } -func fileStoreIO(operation string, _ error) error { +func fileStoreIO(operation string, cause error) error { + // Retain only the numeric OS category, never PathError paths or raw cause + // text. This distinguishes transient sharing from permanent I/O failures. + var code syscall.Errno + if errors.As(cause, &code) { + return fmt.Errorf("%w: %s (os code %d)", ErrFileStoreIO, operation, uint64(code)) + } return fmt.Errorf("%w: %s", ErrFileStoreIO, operation) } diff --git a/internal/config/filestore_replace_windows.go b/internal/config/filestore_replace_windows.go index 006f4b5..1333021 100644 --- a/internal/config/filestore_replace_windows.go +++ b/internal/config/filestore_replace_windows.go @@ -3,7 +3,9 @@ package config import ( + "errors" "golang.org/x/sys/windows" + "time" ) func replaceFile(oldPath, newPath string) error { @@ -15,5 +17,28 @@ func replaceFile(oldPath, newPath string) error { if err != nil { return err } - return windows.MoveFileEx(oldName, newName, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH) + return retryWindowsReplacement(func() error { + return windows.MoveFileEx(oldName, newName, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH) + }, time.Sleep) +} + +// Windows can return access denied while a scanner temporarily opens a recently +// replaced destination without delete sharing. Retry the SAME atomic rename +// under the FileStore writer/CAS lock, without rewriting data or changing ACLs. +// Permanent denial and every unknown error remain failures. +func retryWindowsReplacement(replace func() error, pause func(time.Duration)) error { + var err error + for attempt := 0; attempt < 16; attempt++ { + err = replace() + if err == nil { + return nil + } + if !errors.Is(err, windows.ERROR_ACCESS_DENIED) && !errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_LOCK_VIOLATION) { + return err + } + if attempt < 15 { + pause(5 * time.Millisecond) + } + } + return err } diff --git a/internal/config/purpose.go b/internal/config/purpose.go new file mode 100644 index 0000000..27e9289 --- /dev/null +++ b/internal/config/purpose.go @@ -0,0 +1,59 @@ +package config + +// ConnectionPurpose describes user intent, never authentication or permission. +type ConnectionPurpose string + +// ExecutionPolicy states the isolation contract; it grants no tools itself. +type ExecutionPolicy string + +const ( + ExecutionIsolatedRequired ExecutionPolicy = "isolated_required" + ExecutionTrustedHost ExecutionPolicy = "trusted_host" +) + +func (p ExecutionPolicy) valid() bool { + return p == ExecutionIsolatedRequired || p == ExecutionTrustedHost +} + +func (c Connection) ExecutionPolicy() ExecutionPolicy { + if c.executionPolicy == "" { + return ExecutionIsolatedRequired + } + return c.executionPolicy +} + +// WithExecutionPolicy is a local configuration operation. Selecting trusted_host +// acknowledges current-user OS access; independent operation approvals remain required. +func (c Connection) WithExecutionPolicy(p ExecutionPolicy) (Connection, error) { + if !p.valid() { + return Connection{}, invalid("connection.execution_policy", "unsupported execution policy") + } + c.executionPolicy = p + return c, nil +} + +const ( + PurposeWebLocal ConnectionPurpose = "web_local" + PurposeAgentRemote ConnectionPurpose = "agent_remote" +) + +func (p ConnectionPurpose) valid() bool { + return p == PurposeWebLocal || p == PurposeAgentRemote +} + +func (c Connection) Purpose() ConnectionPurpose { + if c.purpose == "" { + return PurposeWebLocal + } + return c.purpose +} + +// WithPurpose requires the containing Config to use schema v2 when serialized. +// Older readers reject that schema instead of silently ignoring new intent. +func (c Connection) WithPurpose(p ConnectionPurpose) (Connection, error) { + if !p.valid() { + return Connection{}, invalid("connection.purpose", "unsupported purpose") + } + c.purpose = p + return c, nil +} diff --git a/internal/config/purpose_test.go b/internal/config/purpose_test.go new file mode 100644 index 0000000..51d84b3 --- /dev/null +++ b/internal/config/purpose_test.go @@ -0,0 +1,77 @@ +package config + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestPurposeMigrationDoesNotGrantCapabilities(t *testing.T) { + legacy, err := Parse([]byte(validJSON)) + if err != nil { + t.Fatal(err) + } + conn, _ := legacy.Connection("account-a") + if conn.Purpose() != PurposeWebLocal { + t.Fatal("legacy purpose changed") + } + if conn.ExecutionPolicy() != ExecutionIsolatedRequired { + t.Fatal("legacy execution policy changed") + } + data := strings.Replace(validJSON, SchemaVersionV1, SchemaVersionV2, 1) + data = strings.Replace(data, `"label": "A"`, `"label": "A", "purpose": "agent_remote"`, 1) + cfg, err := Parse([]byte(data)) + if err != nil { + t.Fatal(err) + } + remote, _ := cfg.Connection("account-a") + if remote.Purpose() != PurposeAgentRemote || remote.ProfileID() != conn.ProfileID() || remote.CredentialRef() != conn.CredentialRef() || remote.Enabled() != conn.Enabled() { + t.Fatal("migration changed scope") + } + encoded, err := json.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + again, err := Parse(encoded) + if err != nil { + t.Fatal(err) + } + remote, _ = again.Connection("account-a") + if remote.Purpose() != PurposeAgentRemote { + t.Fatal("purpose lost on roundtrip") + } + for _, bad := range []string{ + strings.Replace(data, SchemaVersionV2, SchemaVersionV1, 1), + strings.Replace(data, "agent_remote", "execute_everything", 1), + } { + if _, err := Parse([]byte(bad)); err == nil { + t.Fatal("unsafe config accepted") + } + } +} + +func TestTrustedExecutionPolicyRequiresExplicitV2(t *testing.T) { + data := strings.Replace(validJSON, `"label": "A"`, `"label": "A", "execution_policy": "trusted_host"`, 1) + if _, err := Parse([]byte(data)); err == nil { + t.Fatal("v1 accepted execution policy") + } + data = strings.Replace(data, SchemaVersionV1, SchemaVersionV2, 1) + cfg, err := Parse([]byte(data)) + if err != nil { + t.Fatal(err) + } + c, _ := cfg.Connection("account-a") + if c.ExecutionPolicy() != ExecutionTrustedHost { + t.Fatal("explicit policy lost") + } + encoded, err := json.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + if _, err = Parse(encoded); err != nil { + t.Fatal(err) + } + if _, err = Parse([]byte(strings.Replace(data, "trusted_host", "unrestricted", 1))); err == nil { + t.Fatal("unknown execution policy accepted") + } +} diff --git a/internal/config/replace_windows_test.go b/internal/config/replace_windows_test.go new file mode 100644 index 0000000..f7ae768 --- /dev/null +++ b/internal/config/replace_windows_test.go @@ -0,0 +1,77 @@ +//go:build windows + +package config + +import ( + "errors" + "golang.org/x/sys/windows" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +func TestWindowsRepeatedConfigReplacement(t *testing.T) { + dir := t.TempDir() + destination := filepath.Join(dir, "config.json") + if err := os.WriteFile(destination, []byte("initial"), 0600); err != nil { + t.Fatal(err) + } + for i := range 300 { + temp := filepath.Join(dir, "next.tmp") + data := []byte(strconv.Itoa(i)) + if err := os.WriteFile(temp, data, 0600); err != nil { + t.Fatal(err) + } + if err := replaceFile(temp, destination); err != nil { + t.Fatalf("Windows replacement error: %T %v", err, err) + } + actual, err := os.ReadFile(destination) + if err != nil || string(actual) != string(data) { + t.Fatal("replacement bytes lost") + } + } +} + +func TestWindowsReplacementRetryIsBoundedAndCategorySpecific(t *testing.T) { + for _, tc := range []struct { + name string + failure error + recoverAfter, wantCalls int + }{ + {"transient-denial", windows.ERROR_ACCESS_DENIED, 3, 4}, + {"permanent-denial", windows.ERROR_ACCESS_DENIED, 100, 16}, + {"sharing", windows.ERROR_SHARING_VIOLATION, 2, 3}, + {"unknown", windows.ERROR_INVALID_HANDLE, 100, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + err := retryWindowsReplacement(func() error { + calls++ + if calls <= tc.recoverAfter { + return tc.failure + } + return nil + }, func(time.Duration) {}) + if calls != tc.wantCalls { + t.Fatalf("calls=%d want=%d", calls, tc.wantCalls) + } + if tc.recoverAfter < 16 { + if err != nil { + t.Fatal(err) + } + } else if !errors.Is(err, tc.failure) { + t.Fatal("failure hidden") + } + }) + } +} + +func TestFileStoreNumericErrorDoesNotExposePath(t *testing.T) { + err := fileStoreIO("replace configuration", &os.PathError{Op: "rename", Path: "private-sentinel-path", Err: windows.ERROR_ACCESS_DENIED}) + if !errors.Is(err, ErrFileStoreIO) || !strings.Contains(err.Error(), "os code 5") || strings.Contains(err.Error(), "private-sentinel") { + t.Fatal("unsafe storage diagnostic") + } +} diff --git a/internal/config/writeprofile_test.go b/internal/config/writeprofile_test.go new file mode 100644 index 0000000..947a308 --- /dev/null +++ b/internal/config/writeprofile_test.go @@ -0,0 +1,38 @@ +package config + +import ( + "strings" + "testing" +) + +func TestExplicitWriteProfileRequiresV2AndSurvivesRoundTrip(t *testing.T) { + data := strings.Replace(validJSON, `"id": "read-project",`, `"id": "read-project", "read_only": false,`, 1) + if _, err := Parse([]byte(data)); err == nil { + t.Fatal("v1 silently accepted write permission") + } + data = strings.Replace(data, SchemaVersionV1, SchemaVersionV2, 1) + cfg, err := Parse([]byte(data)) + if err != nil { + t.Fatal(err) + } + p, ok := cfg.Profile("read-project") + if !ok || p.ReadOnly() { + t.Fatal("explicit write profile was lost") + } + b, err := cfg.MarshalJSON() + if err != nil { + t.Fatal(err) + } + again, err := Parse(b) + if err != nil { + t.Fatal(err) + } + p, _ = again.Profile("read-project") + if p.ReadOnly() { + t.Fatal("write permission was not preserved") + } + readonly, _ := again.Profile("read-private") + if !readonly.ReadOnly() { + t.Fatal("unrelated default profile became writable") + } +} diff --git a/internal/desktopbridge/desktop_test.go b/internal/desktopbridge/desktop_test.go index 2462180..2da6af0 100644 --- a/internal/desktopbridge/desktop_test.go +++ b/internal/desktopbridge/desktop_test.go @@ -30,7 +30,7 @@ func TestDesktopHistoryPersistsIndependentScopesAndSelection(t *testing.T) { secondID := added.Desktop.ActiveID selected := desktopWrite(t, f.service, "connections.select", map[string]any{"expected_revision": added.Desktop.Revision, "id": original.Desktop.ActiveID}) if len(selected.Workspace.Roots) != 1 || selected.Workspace.Roots[0].ID != f.rootID { - t.Fatal("selection mixed scopes") + t.Fatalf("selection mixed scopes: connection=%+v workspace=%+v desktop=%+v", selected.Connection, selected.Workspace, selected.Desktop) } again := desktopWrite(t, f.service, "connections.select", map[string]any{"expected_revision": selected.Desktop.Revision, "id": secondID}) next, err := New(f.service.options) diff --git a/internal/deviceidentity/identity.go b/internal/deviceidentity/identity.go new file mode 100644 index 0000000..fa0e63d --- /dev/null +++ b/internal/deviceidentity/identity.go @@ -0,0 +1,431 @@ +// Package deviceidentity owns local pairing keys and public pairing artifacts. +// Its signing methods belong to the owner's local management boundary only. +package deviceidentity + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "io" + "math/big" + "time" + + "github.com/LE-saber/Local-Probe/internal/peertransport" +) + +const Version = "local-probe.pairing.v1" +const MaxArtifactBytes = 64 << 10 + +var ( + ErrInvalid = errors.New("invalid pairing artifact") + ErrTrust = errors.New("pairing fingerprint or identity mismatch") + ErrStorage = errors.New("identity storage unavailable") + ErrExists = errors.New("identity record already exists") + ErrRevoked = errors.New("paired identity revoked") +) + +// Bundle is public. Fingerprint must be compared via an independently trusted +// path; an attacker-provided bundle and its matching hash do not establish trust. +type Bundle struct { + Version string `json:"version"` + DeviceID string `json:"device_id"` + ServerName string `json:"server_name"` + CA []byte `json:"ca_pem"` + Target []byte `json:"target_pem"` +} + +type Request struct { + Version string `json:"version"` + AgentID string `json:"agent_id"` + CSR []byte `json:"csr_pem"` +} + +// Grant contains no private key. ConnectionID is chosen locally by the owner, +// not copied from a caller's CSR. Epoch 1 is terminally revoked by a tombstone. +type Grant struct { + Version string `json:"version"` + DeviceID string `json:"device_id"` + AgentID string `json:"agent_id"` + ConnectionID string `json:"connection_id"` + KeyPin string `json:"key_pin"` + Epoch uint64 `json:"epoch"` + Certificate []byte `json:"certificate_pem"` + ExpiresAt time.Time `json:"expires_at"` +} + +// Private state is deliberately unexported: default JSON marshaling cannot leak +// keys into a diagnostic or public pairing response. +type Authority struct { + id string + ca, caKey, target, targetKey []byte +} +type Agent struct { + id string + key []byte +} + +func NewAuthority() (*Authority, error) { + id, err := randomID("device-") + if err != nil { + return nil, err + } + caKey, err := newKey() + if err != nil { + return nil, err + } + key, err := newKey() + if err != nil { + return nil, err + } + now := time.Now().UTC() + ca := template(now, 5*365*24*time.Hour) + ca.Subject = pkix.Name{CommonName: id} + ca.IsCA = true + ca.BasicConstraintsValid = true + ca.MaxPathLenZero = true + ca.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageCRLSign + der, err := x509.CreateCertificate(rand.Reader, ca, ca, &caKey.PublicKey, caKey) + if err != nil { + return nil, err + } + parsed, err := x509.ParseCertificate(der) + if err != nil { + return nil, err + } + target := template(now, 365*24*time.Hour) + target.Subject = pkix.Name{CommonName: id} + target.DNSNames = []string{id + ".local-probe.invalid"} + target.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + leaf, err := x509.CreateCertificate(rand.Reader, target, parsed, &key.PublicKey, caKey) + if err != nil { + return nil, err + } + caPrivate, _ := x509.MarshalPKCS8PrivateKey(caKey) + private, _ := x509.MarshalPKCS8PrivateKey(key) + return &Authority{id, der, caPrivate, leaf, private}, nil +} + +func NewAgent() (*Agent, Request, error) { + id, err := randomID("agent-") + if err != nil { + return nil, Request{}, err + } + key, err := newKey() + if err != nil { + return nil, Request{}, err + } + der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: id}}, key) + if err != nil { + return nil, Request{}, err + } + private, _ := x509.MarshalPKCS8PrivateKey(key) + return &Agent{id, private}, Request{Version, id, encodePEM("CERTIFICATE REQUEST", der)}, nil +} + +func (a *Authority) Bundle() Bundle { + return Bundle{Version, a.id, a.id + ".local-probe.invalid", encodePEM("CERTIFICATE", a.ca), encodePEM("CERTIFICATE", a.target)} +} + +func (b Bundle) Fingerprint() (string, error) { + if _, _, err := b.validate(); err != nil { + return "", err + } + data, err := json.Marshal(b) + if err != nil { + return "", ErrInvalid + } + hash := sha256.Sum256(data) + return hex.EncodeToString(hash[:]), nil +} + +func (b Bundle) Verify(expected string) error { + actual, err := b.Fingerprint() + if err != nil { + return err + } + if !validHash(expected) || actual != expected { + return ErrTrust + } + return nil +} + +func (r Request) Fingerprint() (string, error) { + csr, err := r.validate() + if err != nil { + return "", err + } + hash := sha256.Sum256(append([]byte(Version+"\x00"+r.AgentID+"\x00"), csr.Raw...)) + return hex.EncodeToString(hash[:]), nil +} + +// Issue requires the exact CSR fingerprint reviewed by the owner. Extensions in +// the CSR are ignored: clients cannot request CA status, names or server usage. +func (a *Authority) Issue(r Request, expected, connection string, lifetime time.Duration) (Grant, error) { + actual, err := r.Fingerprint() + if err != nil { + return Grant{}, err + } + if actual != expected || !validHash(expected) { + return Grant{}, ErrTrust + } + if !validID(connection) || lifetime <= 0 || lifetime > 30*24*time.Hour { + return Grant{}, ErrInvalid + } + csr, _ := r.validate() + ca, err := x509.ParseCertificate(a.ca) + if err != nil { + return Grant{}, ErrInvalid + } + caKey, err := x509.ParsePKCS8PrivateKey(a.caKey) + if err != nil { + return Grant{}, ErrInvalid + } + cert := template(time.Now().UTC(), lifetime) + cert.Subject = pkix.Name{CommonName: r.AgentID, Organization: []string{connection}, OrganizationalUnit: []string{a.id}} + cert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} + if cert.NotAfter.After(ca.NotAfter) { + return Grant{}, ErrInvalid + } + der, err := x509.CreateCertificate(rand.Reader, cert, ca, csr.PublicKey, caKey) + if err != nil { + return Grant{}, ErrInvalid + } + leaf, err := x509.ParseCertificate(der) + if err != nil { + return Grant{}, ErrInvalid + } + pin := peertransport.PublicKeyPin(leaf) + return Grant{Version, a.id, r.AgentID, connection, hex.EncodeToString(pin[:]), 1, encodePEM("CERTIFICATE", der), leaf.NotAfter}, nil +} + +func (a *Authority) ServerTLS(authorize func(peertransport.Pin) bool) (*tls.Config, error) { + identity, err := tls.X509KeyPair(encodePEM("CERTIFICATE", a.target), encodePEM("PRIVATE KEY", a.targetKey)) + if err != nil { + return nil, ErrInvalid + } + ca, _, err := a.Bundle().validate() + if err != nil { + return nil, err + } + roots := x509.NewCertPool() + roots.AddCert(ca) + return peertransport.ServerTLS(identity, roots, authorize) +} + +// ClientTLS validates the trusted public bundle, grant, own key and target pin. +// It never accepts a private key in a grant or pairing bundle. +func (a *Agent) ClientTLS(b Bundle, g Grant, expectedBundle string) (*tls.Config, error) { + if err := b.Verify(expectedBundle); err != nil { + return nil, err + } + if err := g.validate(b); err != nil { + return nil, err + } + if g.AgentID != a.id { + return nil, ErrTrust + } + identity, err := tls.X509KeyPair(g.Certificate, encodePEM("PRIVATE KEY", a.key)) + if err != nil { + return nil, ErrTrust + } + ca, target, err := b.validate() + if err != nil { + return nil, err + } + roots := x509.NewCertPool() + roots.AddCert(ca) + return peertransport.ClientTLS(identity, roots, b.ServerName, peertransport.PublicKeyPin(target)) +} + +func (b Bundle) validate() (*x509.Certificate, *x509.Certificate, error) { + if b.Version != Version || !validID(b.DeviceID) || b.ServerName != b.DeviceID+".local-probe.invalid" { + return nil, nil, ErrInvalid + } + ca, err := parseCert(b.CA) + if err != nil || !ca.IsCA || ca.CheckSignatureFrom(ca) != nil || ca.Subject.CommonName != b.DeviceID { + return nil, nil, ErrInvalid + } + leaf, err := parseCert(b.Target) + if err != nil || leaf.IsCA || leaf.Subject.CommonName != b.DeviceID { + return nil, nil, ErrInvalid + } + roots := x509.NewCertPool() + roots.AddCert(ca) + if _, err = leaf.Verify(x509.VerifyOptions{Roots: roots, DNSName: b.ServerName, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}); err != nil { + return nil, nil, ErrInvalid + } + return ca, leaf, nil +} + +func (g Grant) validate(b Bundle) error { + ca, _, err := b.validate() + if err != nil { + return err + } + if g.Version != Version || g.DeviceID != b.DeviceID || !validID(g.AgentID) || !validID(g.ConnectionID) || g.Epoch != 1 || !validHash(g.KeyPin) { + return ErrInvalid + } + cert, err := parseCert(g.Certificate) + if err != nil || cert.IsCA || cert.Subject.CommonName != g.AgentID || !cert.NotAfter.Equal(g.ExpiresAt) { + return ErrInvalid + } + if len(cert.Subject.Organization) != 1 || cert.Subject.Organization[0] != g.ConnectionID || len(cert.Subject.OrganizationalUnit) != 1 || cert.Subject.OrganizationalUnit[0] != g.DeviceID { + return ErrTrust + } + roots := x509.NewCertPool() + roots.AddCert(ca) + if _, err = cert.Verify(x509.VerifyOptions{Roots: roots, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}); err != nil { + return ErrInvalid + } + pin := peertransport.PublicKeyPin(cert) + if hex.EncodeToString(pin[:]) != g.KeyPin { + return ErrTrust + } + return nil +} + +func (r Request) validate() (*x509.CertificateRequest, error) { + if r.Version != Version || !validID(r.AgentID) { + return nil, ErrInvalid + } + der, err := decodePEM(r.CSR, "CERTIFICATE REQUEST") + if err != nil { + return nil, err + } + csr, err := x509.ParseCertificateRequest(der) + if err != nil || csr.CheckSignature() != nil { + return nil, ErrInvalid + } + pub, ok := csr.PublicKey.(*ecdsa.PublicKey) + if !ok || pub.Curve != elliptic.P256() { + return nil, ErrInvalid + } + return csr, nil +} + +func template(now time.Time, lifetime time.Duration) *x509.Certificate { + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 159)) + if err != nil { + return &x509.Certificate{} + } + return &x509.Certificate{SerialNumber: serial, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(lifetime).Truncate(time.Second), KeyUsage: x509.KeyUsageDigitalSignature, BasicConstraintsValid: true} +} +func newKey() (*ecdsa.PrivateKey, error) { return ecdsa.GenerateKey(elliptic.P256(), rand.Reader) } +func randomID(prefix string) (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", err + } + return prefix + hex.EncodeToString(b[:]), nil +} +func encodePEM(kind string, b []byte) []byte { + return pem.EncodeToMemory(&pem.Block{Type: kind, Bytes: b}) +} +func decodePEM(data []byte, kind string) ([]byte, error) { + if len(data) == 0 || len(data) > MaxArtifactBytes { + return nil, ErrInvalid + } + b, rest := pem.Decode(data) + if b == nil || b.Type != kind || len(bytes.TrimSpace(rest)) != 0 { + return nil, ErrInvalid + } + return b.Bytes, nil +} +func parseCert(b []byte) (*x509.Certificate, error) { + der, err := decodePEM(b, "CERTIFICATE") + if err != nil { + return nil, err + } + cert, err := x509.ParseCertificate(der) + if err != nil { + return nil, ErrInvalid + } + return cert, nil +} +func validID(s string) bool { + if len(s) == 0 || len(s) > 128 { + return false + } + for _, c := range s { + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') { + return false + } + } + return true +} +func validHash(s string) bool { + b, err := hex.DecodeString(s) + return err == nil && len(b) == sha256.Size && hex.EncodeToString(b) == s +} + +// DecodePublic parses a bounded public artifact; duplicate keys are rejected. +func DecodePublic(data []byte, out any) error { + if len(data) == 0 || len(data) > MaxArtifactBytes { + return ErrInvalid + } + d := json.NewDecoder(bytes.NewReader(data)) + d.DisallowUnknownFields() + if err := rejectDuplicates(json.NewDecoder(bytes.NewReader(data)), 0); err != nil { + return err + } + if d.Decode(out) != nil { + return ErrInvalid + } + if _, err := d.Token(); err != io.EOF { + return ErrInvalid + } + return nil +} +func rejectDuplicates(d *json.Decoder, depth int) error { + if depth > 32 { + return ErrInvalid + } + t, err := d.Token() + if err != nil { + return ErrInvalid + } + delim, ok := t.(json.Delim) + if !ok { + return nil + } + switch delim { + case '{': + seen := map[string]bool{} + for d.More() { + k, err := d.Token() + if err != nil { + return ErrInvalid + } + s, ok := k.(string) + if !ok || seen[s] { + return ErrInvalid + } + seen[s] = true + if err := rejectDuplicates(d, depth+1); err != nil { + return err + } + } + case '[': + for d.More() { + if err := rejectDuplicates(d, depth+1); err != nil { + return err + } + } + default: + return ErrInvalid + } + _, err = d.Token() + if err != nil { + return ErrInvalid + } + return nil +} diff --git a/internal/deviceidentity/identity_test.go b/internal/deviceidentity/identity_test.go new file mode 100644 index 0000000..fc313d6 --- /dev/null +++ b/internal/deviceidentity/identity_test.go @@ -0,0 +1,284 @@ +package deviceidentity + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/hex" + "encoding/json" + "errors" + "net" + "os" + "path/filepath" + "runtime" + "sync" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/peertransport" +) + +type fixture struct { + target, agent *Store + authority *Authority + request Request + pairing Pairing + pin peertransport.Pin +} + +func newFixture(t *testing.T) fixture { + t.Helper() + base := t.TempDir() + target, err := CreateStore(filepath.Join(base, "target")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = target.Close() }) + a, err := NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = target.SaveAuthority(a); err != nil { + t.Fatal(err) + } + agent, err := CreateStore(filepath.Join(base, "agent")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = agent.Close() }) + client, r, err := NewAgent() + if err != nil { + t.Fatal(err) + } + if err = agent.SaveAgent(client); err != nil { + t.Fatal(err) + } + fp, err := r.Fingerprint() + if err != nil { + t.Fatal(err) + } + g, err := target.IssueGrant(r, fp, "connection-a", time.Hour) + if err != nil { + t.Fatal(err) + } + b := a.Bundle() + bfp, err := b.Fingerprint() + if err != nil { + t.Fatal(err) + } + p := Pairing{Version, b, g, bfp} + if err = agent.InstallPairing(p, bfp); err != nil { + t.Fatal(err) + } + var pin peertransport.Pin + raw, _ := hex.DecodeString(g.KeyPin) + copy(pin[:], raw) + return fixture{target, agent, a, r, p, pin} +} + +func TestPersistentPairingAuthenticatesAndRevokesActiveLease(t *testing.T) { + f := newFixture(t) + r, err := NewRegistry(f.target) + if err != nil { + t.Fatal(err) + } + scfg, err := r.ServerTLS() + if err != nil { + t.Fatal(err) + } + ccfg, err := f.agent.ClientTLS() + if err != nil { + t.Fatal(err) + } + a, b := net.Pipe() + defer a.Close() + defer b.Close() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { done <- tls.Server(a, scfg).HandshakeContext(ctx) }() + if err = tls.Client(b, ccfg).HandshakeContext(ctx); err != nil { + t.Fatal(err) + } + if err = <-done; err != nil { + t.Fatal(err) + } + lease, release, err := r.Acquire(ctx, f.pin) + if err != nil { + t.Fatal(err) + } + defer release() + g, ok := GrantFromContext(lease) + if !ok || g.ConnectionID != "connection-a" || g.Epoch != 1 { + t.Fatal("grant binding lost") + } + if err = r.Revoke(f.pin); err != nil { + t.Fatal(err) + } + select { + case <-lease.Done(): + case <-time.After(time.Second): + t.Fatal("revocation did not cancel lease") + } + if r.Allows(f.pin) { + t.Fatal("revoked identity allowed") + } + if _, _, err = r.Acquire(ctx, f.pin); !errors.Is(err, ErrRevoked) { + t.Fatalf("reacquire=%v", err) + } + // Reconstructing the registry simulates target restart; no cached grant may + // resurrect a revoked identity, and issuing the same key again must fail. + newRegistry, err := NewRegistry(f.target) + if err != nil { + t.Fatal(err) + } + if newRegistry.Allows(f.pin) { + t.Fatal("revocation lost on restart") + } + fp, _ := f.request.Fingerprint() + if _, err = f.target.IssueGrant(f.request, fp, "connection-b", time.Hour); !errors.Is(err, ErrRevoked) { + t.Fatalf("revoked key reissued: %v", err) + } +} + +func TestRevocationStorageFailureIsReportedAndBlocksRuntime(t *testing.T) { + f := newFixture(t) + registry, err := NewRegistry(f.target) + if err != nil { + t.Fatal(err) + } + path := f.target.root.Name() + if err = f.target.Close(); err != nil { + t.Fatal(err) + } + if err = registry.Revoke(f.pin); !errors.Is(err, ErrStorage) { + t.Fatalf("revocation storage failure hidden: %v", err) + } + // Recover readable storage containing the old grant. This runtime must keep + // the failed revocation blocked rather than silently resuming authorization. + recovered, err := OpenStore(path) + if err != nil { + t.Fatal(err) + } + defer recovered.Close() + registry.mu.Lock() + registry.store = recovered + registry.mu.Unlock() + if registry.Allows(f.pin) { + t.Fatal("failed revocation silently reenabled") + } +} + +func TestPairingRejectsReplacedArtifactsAndMetadata(t *testing.T) { + f := newFixture(t) + agent, err := f.agent.LoadAgent() + if err != nil { + t.Fatal(err) + } + other, err := NewAuthority() + if err != nil { + t.Fatal(err) + } + if _, err = agent.ClientTLS(other.Bundle(), f.pairing.Grant, f.pairing.Fingerprint); err == nil { + t.Fatal("target replaced") + } + changed := f.pairing.Grant + changed.ConnectionID = "connection-b" + if _, err = agent.ClientTLS(f.pairing.Bundle, changed, f.pairing.Fingerprint); err == nil { + t.Fatal("grant scope replaced") + } + _, request, err := NewAgent() + if err != nil { + t.Fatal(err) + } + fp, _ := f.request.Fingerprint() + if _, err = f.authority.Issue(request, fp, "connection-a", time.Hour); !errors.Is(err, ErrTrust) { + t.Fatal("CSR replaced") + } + if _, err = f.authority.Issue(request, fp, "connection-a", 31*24*time.Hour); err == nil { + t.Fatal("unbounded certificate lifetime") + } +} + +func TestPrivateStoreIsWriteOnceAndSecretsStayPrivate(t *testing.T) { + path := filepath.Join(t.TempDir(), "private") + s, err := CreateStore(path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + a, err := NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = s.SaveAuthority(a); err != nil { + t.Fatal(err) + } + if err = s.SaveAuthority(a); !errors.Is(err, ErrExists) { + t.Fatal("identity overwritten") + } + if _, err = CreateStore(path); !errors.Is(err, ErrExists) { + t.Fatal("existing directory reused") + } + public, _ := json.Marshal(a) + if bytes.Contains(public, a.targetKey) || bytes.Contains(public, a.caKey) { + t.Fatal("JSON exposed private keys") + } + data, err := os.ReadFile(filepath.Join(path, "device.bin")) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS == "windows" && bytes.Contains(data, []byte("ca_key")) { + t.Fatal("Windows identity was not encrypted") + } + if err = os.WriteFile(filepath.Join(path, "device.bin"), []byte("damaged"), 0600); err != nil { + t.Fatal(err) + } + if _, err = s.LoadAuthority(); err == nil { + t.Fatal("corrupt identity silently accepted") + } +} + +func TestConcurrentIssueCannotReplaceExistingScope(t *testing.T) { + f := newFixture(t) + fp, _ := f.request.Fingerprint() + var wg sync.WaitGroup + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + _, err := f.target.IssueGrant(f.request, fp, "connection-b", time.Hour) + if !errors.Is(err, ErrExists) { + t.Errorf("duplicate issue: %v", err) + } + }() + } + wg.Wait() + g, err := f.target.Resolve(f.pin) + if err != nil || g.ConnectionID != "connection-a" { + t.Fatal("scope overwritten") + } +} + +func TestPublicDecoderRejectsDuplicateUnknownAndOversizedInput(t *testing.T) { + for _, data := range [][]byte{[]byte(`{"version":"x","version":"y"}`), []byte(`{"private_key":"x"}`), []byte(`{} {}`), bytes.Repeat([]byte("x"), MaxArtifactBytes+1)} { + var bundle Bundle + if DecodePublic(data, &bundle) == nil { + t.Fatal("invalid public input accepted") + } + } +} + +func FuzzPublicPairingDecoder(f *testing.F) { + for _, seed := range []string{`{}`, `{"version":"x","version":"y"}`, `{"ca_pem":"eA=="}`, `{"bundle":[[[[]]]]}`} { + f.Add([]byte(seed)) + } + f.Fuzz(func(t *testing.T, data []byte) { + var b Bundle + _ = DecodePublic(data, &b) + var r Request + _ = DecodePublic(data, &r) + var p Pairing + _ = DecodePublic(data, &p) + }) +} diff --git a/internal/deviceidentity/pairing.go b/internal/deviceidentity/pairing.go new file mode 100644 index 0000000..42fd68a --- /dev/null +++ b/internal/deviceidentity/pairing.go @@ -0,0 +1,71 @@ +package deviceidentity + +import ( + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" +) + +type Pairing struct { + Version string `json:"version"` + Bundle Bundle `json:"bundle"` + Grant Grant `json:"grant"` + Fingerprint string `json:"fingerprint"` +} + +func (a *Agent) Request() (Request, error) { + key, err := agentKey(a.key) + if err != nil { + return Request{}, err + } + csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: a.id}}, key) + if err != nil { + return Request{}, ErrInvalid + } + return Request{Version, a.id, encodePEM("CERTIFICATE REQUEST", csr)}, nil +} + +// InstallPairing is explicitly local and write-once. Expected must be the target +// bundle fingerprint the user independently reviewed, not the response's value. +func (s *Store) InstallPairing(p Pairing, expected string) error { + if p.Version != Version || p.Fingerprint != expected { + return ErrTrust + } + a, err := s.LoadAgent() + if err != nil { + return err + } + if _, err = a.ClientTLS(p.Bundle, p.Grant, expected); err != nil { + return err + } + return s.write("pairing.bin", p) +} +func (s *Store) LoadPairing() (Pairing, error) { + var p Pairing + if err := s.read("pairing.bin", &p); err != nil { + return Pairing{}, err + } + if p.Version != Version { + return Pairing{}, ErrInvalid + } + a, err := s.LoadAgent() + if err != nil { + return Pairing{}, err + } + if _, err = a.ClientTLS(p.Bundle, p.Grant, p.Fingerprint); err != nil { + return Pairing{}, err + } + return p, nil +} +func (s *Store) ClientTLS() (*tls.Config, error) { + p, err := s.LoadPairing() + if err != nil { + return nil, err + } + a, err := s.LoadAgent() + if err != nil { + return nil, err + } + return a.ClientTLS(p.Bundle, p.Grant, p.Fingerprint) +} diff --git a/internal/deviceidentity/protect_unix.go b/internal/deviceidentity/protect_unix.go new file mode 100644 index 0000000..b8d56f1 --- /dev/null +++ b/internal/deviceidentity/protect_unix.go @@ -0,0 +1,37 @@ +//go:build !windows + +package deviceidentity + +import ( + "bytes" + "io/fs" + "os" +) + +var protectionHeader = []byte("LPID1-PRIVATE-FILE\x00") + +func protectDirectory(path string) error { return os.Chmod(path, 0700) } +func checkDirectory(info fs.FileInfo) error { + if info.Mode().Perm()&0077 != 0 { + return ErrStorage + } + return nil +} +func checkRecord(info fs.FileInfo) error { + if info.Mode().Perm()&0077 != 0 { + return ErrStorage + } + return nil +} + +// Unix v1 relies on owner-only filesystem permissions; this is not encryption +// against the OS owner or root. Windows uses current-user DPAPI instead. +func seal(data []byte) ([]byte, error) { + return append(append([]byte(nil), protectionHeader...), data...), nil +} +func unseal(data []byte) ([]byte, error) { + if !bytes.HasPrefix(data, protectionHeader) { + return nil, ErrStorage + } + return append([]byte(nil), data[len(protectionHeader):]...), nil +} diff --git a/internal/deviceidentity/protect_windows.go b/internal/deviceidentity/protect_windows.go new file mode 100644 index 0000000..323f83b --- /dev/null +++ b/internal/deviceidentity/protect_windows.go @@ -0,0 +1,65 @@ +//go:build windows + +package deviceidentity + +import ( + "bytes" + "io/fs" + "runtime" + "unsafe" + + "golang.org/x/sys/windows" +) + +var protectionHeader = []byte("LPID1-DPAPI\x00") + +func protectDirectory(path string) error { + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + return err + } + sd, err := windows.SecurityDescriptorFromString("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;" + user.User.Sid.String() + ")") + if err != nil { + return err + } + dacl, _, err := sd.DACL() + if err != nil { + return err + } + return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil) +} +func checkDirectory(fs.FileInfo) error { return nil } +func checkRecord(fs.FileInfo) error { return nil } + +func seal(data []byte) ([]byte, error) { + var out windows.DataBlob + in := windows.DataBlob{Size: uint32(len(data)), Data: &data[0]} + err := windows.CryptProtectData(&in, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &out) + runtime.KeepAlive(data) + if err != nil { + return nil, err + } + defer windows.LocalFree(windows.Handle(unsafe.Pointer(out.Data))) + if out.Size > 2*MaxArtifactBytes { + return nil, ErrStorage + } + return append(append([]byte(nil), protectionHeader...), unsafe.Slice(out.Data, int(out.Size))...), nil +} +func unseal(data []byte) ([]byte, error) { + if !bytes.HasPrefix(data, protectionHeader) || len(data) == len(protectionHeader) { + return nil, ErrStorage + } + data = data[len(protectionHeader):] + in := windows.DataBlob{Size: uint32(len(data)), Data: &data[0]} + var out windows.DataBlob + err := windows.CryptUnprotectData(&in, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &out) + runtime.KeepAlive(data) + if err != nil { + return nil, err + } + defer windows.LocalFree(windows.Handle(unsafe.Pointer(out.Data))) + if out.Size > MaxArtifactBytes { + return nil, ErrStorage + } + return append([]byte(nil), unsafe.Slice(out.Data, int(out.Size))...), nil +} diff --git a/internal/deviceidentity/registry.go b/internal/deviceidentity/registry.go new file mode 100644 index 0000000..f7753ee --- /dev/null +++ b/internal/deviceidentity/registry.go @@ -0,0 +1,120 @@ +package deviceidentity + +import ( + "context" + "crypto/tls" + "net/http" + "sync" + + "github.com/LE-saber/Local-Probe/internal/peertransport" +) + +// Registry is owned by one running target process. Offline CLI writes must not +// race it. Revoke persists a tombstone before cancelling all active leases. +type Registry struct { + mu sync.Mutex + store *Store + next uint64 + active map[peertransport.Pin]map[uint64]context.CancelFunc + blocked map[peertransport.Pin]bool +} +type grantKey struct{} + +func NewRegistry(store *Store) (*Registry, error) { + if store == nil { + return nil, ErrStorage + } + if _, err := store.LoadBundle(); err != nil { + return nil, err + } + return &Registry{store: store, active: make(map[peertransport.Pin]map[uint64]context.CancelFunc), blocked: make(map[peertransport.Pin]bool)}, nil +} +func (r *Registry) Allows(pin peertransport.Pin) bool { + r.mu.Lock() + defer r.mu.Unlock() + if r.blocked[pin] { + return false + } + _, err := r.store.Resolve(pin) + return err == nil +} +func (r *Registry) Acquire(ctx context.Context, pin peertransport.Pin) (context.Context, func(), error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.blocked[pin] { + return nil, nil, ErrRevoked + } + if err := ctx.Err(); err != nil { + return nil, nil, err + } + g, err := r.store.Resolve(pin) + if err != nil { + return nil, nil, err + } + lease, cancel := context.WithDeadline(context.WithValue(ctx, grantKey{}, g), g.ExpiresAt) + r.next++ + id := r.next + if r.active[pin] == nil { + r.active[pin] = make(map[uint64]context.CancelFunc) + } + r.active[pin][id] = cancel + var once sync.Once + release := func() { + once.Do(func() { + r.mu.Lock() + defer r.mu.Unlock() + cancel() + delete(r.active[pin], id) + if len(r.active[pin]) == 0 { + delete(r.active, pin) + } + }) + } + return lease, release, nil +} +func (r *Registry) Revoke(pin peertransport.Pin) error { + r.mu.Lock() + defer r.mu.Unlock() + err := r.store.Revoke(pin) + r.blocked[pin] = true + // Failed persistence is also fail-closed for current work. Future accesses + // check the storage state and reject any partial tombstone. + for _, cancel := range r.active[pin] { + cancel() + } + delete(r.active, pin) + return err +} +func GrantFromContext(ctx context.Context) (Grant, bool) { + g, ok := ctx.Value(grantKey{}).(Grant) + g.Certificate = append([]byte(nil), g.Certificate...) + return g, ok +} + +func (r *Registry) ServerTLS() (*tls.Config, error) { + return r.store.ServerTLS(r.Allows) +} + +// Handler attaches a verified local Grant and a cancellable lease. Tools must +// still resolve ConnectionID through the authoritative policy manager. No caller +// header, argument or CSR can choose a different connection/profile. +func (r *Registry) Handler(next http.Handler) http.Handler { + return peertransport.AuthorizeHTTP(r.Allows, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if next == nil { + http.Error(w, "handler unavailable", http.StatusServiceUnavailable) + return + } + pin, ok := peertransport.Identity(req.Context()) + if !ok { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + ctx, release, err := r.Acquire(req.Context(), pin) + if err != nil { + http.Error(w, "revoked", http.StatusForbidden) + return + } + defer release() + next.ServeHTTP(w, req.WithContext(ctx)) + })) +} diff --git a/internal/deviceidentity/runtime.go b/internal/deviceidentity/runtime.go new file mode 100644 index 0000000..7150c90 --- /dev/null +++ b/internal/deviceidentity/runtime.go @@ -0,0 +1,49 @@ +package deviceidentity + +import ( + "bytes" + "crypto/tls" + "crypto/x509" + + "github.com/LE-saber/Local-Probe/internal/peertransport" +) + +func (s *Store) LoadBundle() (Bundle, error) { + var b Bundle + if err := s.read("device-public.bin", &b); err != nil { + return Bundle{}, err + } + if _, _, err := b.validate(); err != nil { + return Bundle{}, err + } + return b, nil +} + +// ServerTLS loads the runtime leaf key, never the owner's CA signing key. +func (s *Store) ServerTLS(authorize func(peertransport.Pin) bool) (*tls.Config, error) { + b, err := s.LoadBundle() + if err != nil { + return nil, err + } + var r secretRecord + if err = s.read("device-runtime.bin", &r); err != nil { + return nil, err + } + if r.Version != Version || r.ID != b.DeviceID || len(r.CAKey) != 0 || len(r.CA) != 0 { + return nil, ErrInvalid + } + ca, leaf, err := b.validate() + if err != nil { + return nil, err + } + if !bytes.Equal(leaf.Raw, r.Target) { + return nil, ErrTrust + } + identity, err := tls.X509KeyPair(encodePEM("CERTIFICATE", r.Target), encodePEM("PRIVATE KEY", r.Key)) + if err != nil { + return nil, ErrTrust + } + roots := x509.NewCertPool() + roots.AddCert(ca) + return peertransport.ServerTLS(identity, roots, authorize) +} diff --git a/internal/deviceidentity/store.go b/internal/deviceidentity/store.go new file mode 100644 index 0000000..d81a201 --- /dev/null +++ b/internal/deviceidentity/store.go @@ -0,0 +1,265 @@ +package deviceidentity + +import ( + "crypto/ecdsa" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "encoding/json" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "sync" + "time" + + "github.com/LE-saber/Local-Probe/internal/peertransport" +) + +// Store is a private directory of write-once protected records. Existing files +// are never replaced: a crash during write fails closed on the next read. It +// must not be restored from an old backup to resurrect revoked credentials. +// CLI mutations are offline; a running service owns its Registry mutations. +type Store struct { + root *os.Root + mu sync.Mutex +} +type secretRecord struct { + Version string `json:"version"` + ID string `json:"id"` + CA []byte `json:"ca,omitempty"` + CAKey []byte `json:"ca_key,omitempty"` + Target []byte `json:"target,omitempty"` + Key []byte `json:"key"` +} + +// CreateStore requires a NEW explicitly selected directory in an existing +// parent. It never regenerates identity after a failed or partial initialization. +func CreateStore(path string) (*Store, error) { + if !filepath.IsAbs(path) { + return nil, ErrStorage + } + if err := os.Mkdir(path, 0700); err != nil { + if errors.Is(err, fs.ErrExist) { + return nil, ErrExists + } + return nil, ErrStorage + } + if err := protectDirectory(path); err != nil { + return nil, ErrStorage + } + return OpenStore(path) +} + +func OpenStore(path string) (*Store, error) { + if !filepath.IsAbs(path) { + return nil, ErrStorage + } + info, err := os.Lstat(path) + if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return nil, ErrStorage + } + if err := checkDirectory(info); err != nil { + return nil, err + } + root, err := os.OpenRoot(path) + if err != nil { + return nil, ErrStorage + } + return &Store{root: root}, nil +} +func (s *Store) Close() error { return s.root.Close() } + +func (s *Store) SaveAuthority(a *Authority) error { + if a == nil { + return ErrInvalid + } + if _, err := a.ServerTLS(func(peertransport.Pin) bool { return false }); err != nil { + return err + } + if _, err := tls.X509KeyPair(encodePEM("CERTIFICATE", a.ca), encodePEM("PRIVATE KEY", a.caKey)); err != nil { + return ErrInvalid + } + if err := s.write("device.bin", secretRecord{Version, a.id, a.ca, a.caKey, a.target, a.targetKey}); err != nil { + return err + } + if err := s.write("device-public.bin", a.Bundle()); err != nil { + return err + } + // Runtime operations never need to load the CA signing private key. + return s.write("device-runtime.bin", secretRecord{Version: Version, ID: a.id, Target: a.target, Key: a.targetKey}) +} +func (s *Store) LoadAuthority() (*Authority, error) { + var r secretRecord + if err := s.read("device.bin", &r); err != nil { + return nil, err + } + if r.Version != Version || !validID(r.ID) { + return nil, ErrInvalid + } + a := &Authority{r.ID, r.CA, r.CAKey, r.Target, r.Key} + if _, err := tls.X509KeyPair(encodePEM("CERTIFICATE", a.ca), encodePEM("PRIVATE KEY", a.caKey)); err != nil { + return nil, ErrInvalid + } + if _, err := a.ServerTLS(func(peertransport.Pin) bool { return false }); err != nil { + return nil, err + } + return a, nil +} +func (s *Store) SaveAgent(a *Agent) error { + if a == nil || !validID(a.id) { + return ErrInvalid + } + if _, err := agentKey(a.key); err != nil { + return err + } + return s.write("agent.bin", secretRecord{Version: Version, ID: a.id, Key: a.key}) +} +func (s *Store) LoadAgent() (*Agent, error) { + var r secretRecord + if err := s.read("agent.bin", &r); err != nil { + return nil, err + } + if r.Version != Version || !validID(r.ID) || len(r.CA) != 0 || len(r.CAKey) != 0 || len(r.Target) != 0 { + return nil, ErrInvalid + } + if _, err := agentKey(r.Key); err != nil { + return nil, err + } + return &Agent{r.ID, r.Key}, nil +} +func agentKey(b []byte) (*ecdsa.PrivateKey, error) { + v, err := x509.ParsePKCS8PrivateKey(b) + if err != nil { + return nil, ErrInvalid + } + key, ok := v.(*ecdsa.PrivateKey) + if !ok { + return nil, ErrInvalid + } + return key, nil +} + +// IssueGrant is local owner approval. Expected is the CSR fingerprint the owner +// reviewed, not a value supplied by the remote operation caller. +func (s *Store) IssueGrant(r Request, expected, connection string, lifetime time.Duration) (Grant, error) { + s.mu.Lock() + defer s.mu.Unlock() + a, err := s.LoadAuthority() + if err != nil { + return Grant{}, err + } + g, err := a.Issue(r, expected, connection, lifetime) + if err != nil { + return Grant{}, err + } + if s.exists("revoke-" + g.KeyPin + ".bin") { + return Grant{}, ErrRevoked + } + if err := s.write("grant-"+g.KeyPin+".bin", g); err != nil { + return Grant{}, err + } + return g, nil +} + +func (s *Store) Resolve(pin peertransport.Pin) (Grant, error) { + key := hex.EncodeToString(pin[:]) + if s.exists("revoke-" + key + ".bin") { + return Grant{}, ErrRevoked + } + b, err := s.LoadBundle() + if err != nil { + return Grant{}, err + } + var g Grant + if err := s.read("grant-"+key+".bin", &g); err != nil { + return Grant{}, err + } + if err := g.validate(b); err != nil { + return Grant{}, err + } + if g.KeyPin != key { + return Grant{}, ErrTrust + } + if s.exists("revoke-" + key + ".bin") { + return Grant{}, ErrRevoked + } + return g, nil +} + +// Revoke is durable and terminal for this key. Even a malformed revocation +// record denies access: it is never ignored to make a connection work. +func (s *Store) Revoke(pin peertransport.Pin) error { + s.mu.Lock() + defer s.mu.Unlock() + key := hex.EncodeToString(pin[:]) + name := "revoke-" + key + ".bin" + _, inspectErr := s.root.Lstat(name) + if inspectErr == nil { + return nil + } + if !errors.Is(inspectErr, fs.ErrNotExist) { + return ErrStorage + } + return s.write(name, struct { + Version string `json:"version"` + Key string `json:"key"` + Epoch uint64 `json:"epoch"` + }{Version, key, 2}) +} +func (s *Store) exists(name string) bool { + _, err := s.root.Lstat(name) + return !errors.Is(err, fs.ErrNotExist) +} +func (s *Store) write(name string, value any) error { + data, err := json.Marshal(value) + if err != nil || len(data) > MaxArtifactBytes { + return ErrInvalid + } + defer clear(data) + sealed, err := seal(data) + if err != nil { + return ErrStorage + } + file, err := s.root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + if errors.Is(err, fs.ErrExist) { + return ErrExists + } + return ErrStorage + } + // Keep a failed/partial file as a fail-closed record; never silently retry + // identity generation or remove a revocation tombstone on error. + _, writeErr := file.Write(sealed) + syncErr := file.Sync() + closeErr := file.Close() + if writeErr != nil || syncErr != nil || closeErr != nil { + return ErrStorage + } + return nil +} +func (s *Store) read(name string, out any) error { + info, err := s.root.Lstat(name) + if err != nil || !info.Mode().IsRegular() || info.Size() > 2*MaxArtifactBytes { + return ErrStorage + } + if err := checkRecord(info); err != nil { + return err + } + file, err := s.root.Open(name) + if err != nil { + return ErrStorage + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, 2*MaxArtifactBytes+1)) + if err != nil || len(data) > 2*MaxArtifactBytes { + return ErrStorage + } + plain, err := unseal(data) + if err != nil { + return ErrStorage + } + defer clear(plain) + return DecodePublic(plain, out) +} diff --git a/internal/mcpserver/operations.go b/internal/mcpserver/operations.go new file mode 100644 index 0000000..3972dd9 --- /dev/null +++ b/internal/mcpserver/operations.go @@ -0,0 +1,159 @@ +package mcpserver + +import ( + "context" + "errors" + + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/operations" + "github.com/LE-saber/Local-Probe/internal/policy" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +var operationTools = []string{"probe_tools", "prepare_operation", "submit_operation", "operation_status", "operation_output", "cancel_operation", "prepare_file_change", "commit_file_change"} + +func isOperationTool(name string) bool { + for _, v := range operationTools { + if name == v { + return true + } + } + return false +} +func (s *Server) operationSubject(ctx context.Context, b policy.BoundScope) (operations.Subject, bool) { + if s.operations == nil || s.peerRegistry == nil { + return operations.Subject{}, false + } + g, ok := deviceidentity.GrantFromContext(ctx) + subject := operations.Subject{Principal: g.KeyPin, Connection: b.ConnectionID()} + return subject, ok && g.ConnectionID == b.ConnectionID() && s.operations.Allows(subject) +} +func (s *Server) allowsTool(ctx context.Context, b policy.BoundScope, name string) bool { + if !b.AllowsTool(name) { + return false + } + if isOperationTool(name) { + _, ok := s.operationSubject(ctx, b) + return ok + } + return true +} +func (s *Server) addOperationTools(server *mcp.Server) { + if s.operations == nil { + return + } + properties := map[string]any{ + "nonce": map[string]any{"type": "string", "minLength": 1, "maxLength": 128}, + "kind": map[string]any{"type": "string", "enum": []string{"command", "script", "build", "test", "version", "file_write", "file_patch"}}, + "tool_id": map[string]any{"type": "string"}, "root_id": map[string]any{"type": "string"}, "directory": map[string]any{"type": "string"}, + "args": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "maxItems": 64}, + "script": map[string]any{"type": "string"}, "path": map[string]any{"type": "string"}, "content": map[string]any{"type": "string"}, + "edits": map[string]any{"type": "array", "maxItems": 32, "items": map[string]any{"type": "object", "properties": map[string]any{"old": map[string]any{"type": "string"}, "new": map[string]any{"type": "string"}}, "required": []string{"old", "new"}, "additionalProperties": false}}, + "timeout_seconds": map[string]any{"type": "integer", "minimum": 1, "maximum": 1800}, + } + for _, name := range operationTools { + name := name + required := []string{"id"} + props := map[string]any{"id": map[string]any{"type": "string"}, "digest": map[string]any{"type": "string"}} + switch name { + case "prepare_operation", "prepare_file_change": + props = properties + required = []string{"nonce", "root_id"} + case "submit_operation", "commit_file_change": + required = []string{"id", "digest"} + case "operation_output": + props = map[string]any{"id": map[string]any{"type": "string"}, "stream": map[string]any{"type": "string", "enum": []string{"stdout", "stderr"}}, "offset": map[string]any{"type": "integer", "minimum": 0}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 32768}} + required = []string{"id", "stream"} + case "probe_tools": + props = map[string]any{} + required = nil + } + schema := map[string]any{"type": "object", "properties": props, "additionalProperties": false} + if len(required) > 0 { + schema["required"] = required + } + tool := &mcp.Tool{Name: name, Description: "Trusted-host operation. Each execution/file change requires separate approval on the target computer. Poll operation_status at least every 60 seconds while running; never automatically resubmit with a new nonce after a timeout.", InputSchema: schema} + addTool(server, tool, func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + b, err := s.boundScope(ctx) + if err != nil { + return deniedToolResult(), nil + } + subject, ok := s.operationSubject(ctx, b) + if !ok { + return deniedToolResult(), nil + } + var out any + switch name { + case "prepare_operation", "prepare_file_change": + var input operations.Request + if decodeArguments(req, &input) != nil { + return operationError(operations.ErrInvalid), nil + } + if name == "prepare_file_change" { + if input.Kind != "" && input.Kind != "file_write" && input.Kind != "file_patch" { + return operationError(operations.ErrInvalid), nil + } + if input.Kind == "" { + input.Kind = "file_write" + } + } + out, err = s.operations.Prepare(ctx, subject, input) + case "probe_tools": + out = struct { + Tools any `json:"tools"` + Note string `json:"note"` + }{s.operations.Tools(), "Local runner catalog verified at target startup; each execution rechecks identity and image hash. Obtain an actual version by preparing and locally approving a kind=version job. This call does not execute runners."} + default: + var input struct { + ID string `json:"id"` + Digest string `json:"digest,omitempty"` + Stream string `json:"stream,omitempty"` + Offset int `json:"offset,omitempty"` + Limit int `json:"limit,omitempty"` + } + if decodeArguments(req, &input) != nil { + return operationError(operations.ErrInvalid), nil + } + switch name { + case "submit_operation", "commit_file_change": + if name == "commit_file_change" { + summary, statusErr := s.operations.Status(subject, input.ID) + if statusErr != nil || summary.Kind != "file_write" && summary.Kind != "file_patch" { + return operationError(operations.ErrInvalid), nil + } + } + out, err = s.operations.Submit(subject, input.ID, input.Digest) + case "operation_status": + out, err = s.operations.Status(subject, input.ID) + case "cancel_operation": + out, err = s.operations.Cancel(ctx, subject, input.ID) + case "operation_output": + if input.Limit == 0 { + input.Limit = 8192 + } + out, err = s.operations.Output(subject, input.ID, input.Stream, input.Offset, input.Limit) + } + } + if err != nil { + return operationError(err), nil + } + return s.jsonResult(out), nil + }) + } +} +func operationError(err error) *mcp.CallToolResult { + code := "operation_unavailable" + switch { + case errors.Is(err, operations.ErrInvalid): + code = "invalid_request" + case errors.Is(err, operations.ErrDenied): + code = "denied" + case errors.Is(err, operations.ErrConflict): + code = "operation_conflict" + case errors.Is(err, operations.ErrStorage): + code = "storage_unavailable" + case errors.Is(err, operations.ErrCapacity): + code = "capacity_reached" + } + return errorResult(code, "operation rejected; inspect the target's local control interface") +} diff --git a/internal/mcpserver/operations_windows_test.go b/internal/mcpserver/operations_windows_test.go new file mode 100644 index 0000000..2482c60 --- /dev/null +++ b/internal/mcpserver/operations_windows_test.go @@ -0,0 +1,258 @@ +package mcpserver + +import ( + "context" + "crypto/x509" + "encoding/hex" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/agentbridge" + "github.com/LE-saber/Local-Probe/internal/commandprofile" + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/operations" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "github.com/LE-saber/Local-Probe/internal/policy" + "github.com/LE-saber/Local-Probe/internal/rootfs" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestPairedMCPFileOperationRequiresLocalApprovalAndPreservesConflicts(t *testing.T) { + f := newFixture(t) + defer f.close() + f.profileOneTools = append([]string{ToolServerInfo, ToolReadFile}, operationTools...) + _ = newTestServer(t, f, []Credential{{ConnectionID: "connection-one", Token: testTokenOne}}) + initial := f.store.Snapshot().Config() + connections := initial.Connections() + var err error + connections[0], err = connections[0].WithPurpose(config.PurposeAgentRemote) + if err != nil { + t.Fatal(err) + } + connections[0], err = connections[0].WithExecutionPolicy(config.ExecutionTrustedHost) + if err != nil { + t.Fatal(err) + } + mode, err := commandprofile.NewDeveloperMode(true, []string{"connection-one"}, commandprofile.ConfirmationPerCall, commandprofile.NetworkDeny) + if err != nil { + t.Fatal(err) + } + profiles := initial.Profiles() + profiles[0] = profiles[0].WithWriteAccess() + cfg, err := config.NewWithCommandProfiles(config.SchemaVersionV2, initial.Roots(), profiles, connections, initial.Credentials(), nil, mode, nil) + if err != nil { + t.Fatal(err) + } + f.source.Close() + f.store, err = config.NewStore(cfg) + if err != nil { + t.Fatal(err) + } + f.manager, err = policy.NewManager(f.store) + if err != nil { + t.Fatal(err) + } + f.source, err = rootfs.New(f.store) + if err != nil { + t.Fatal(err) + } + identity, err := deviceidentity.CreateStore(filepath.Join(t.TempDir(), "identity")) + if err != nil { + t.Fatal(err) + } + defer identity.Close() + a, err := deviceidentity.NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = identity.SaveAuthority(a); err != nil { + t.Fatal(err) + } + agent, request, err := deviceidentity.NewAgent() + if err != nil { + t.Fatal(err) + } + fp, _ := request.Fingerprint() + grant, err := identity.IssueGrant(request, fp, "connection-one", time.Hour) + if err != nil { + t.Fatal(err) + } + registry, err := deviceidentity.NewRegistry(identity) + if err != nil { + t.Fatal(err) + } + journal, err := operations.OpenJournal(filepath.Join(t.TempDir(), "journal"), true) + if err != nil { + t.Fatal(err) + } + defer journal.Close() + if err = journal.Initialize(); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + engine, err := operations.New(ctx, operations.Options{Journal: journal, Config: f.store, Manager: f.manager, Workspace: f.source, Catalog: operations.Catalog{Version: operations.Version}, Acquire: func(parent context.Context, s operations.Subject) (context.Context, func(), error) { + b, err := hex.DecodeString(s.Principal) + if err != nil || len(b) != 32 { + return nil, nil, operations.ErrDenied + } + var pin peertransport.Pin + copy(pin[:], b) + lease, release, err := registry.Acquire(parent, pin) + if err != nil { + return nil, nil, err + } + g, ok := deviceidentity.GrantFromContext(lease) + if !ok || g.ConnectionID != s.Connection { + release() + return nil, nil, operations.ErrDenied + } + return lease, release, nil + }}) + if err != nil { + t.Fatal(err) + } + defer engine.Close() + server, err := New(Options{Manager: f.manager, Source: f.source, PeerRegistry: registry, Operations: engine}) + if err != nil { + t.Fatal(err) + } + inner, err := registry.ServerTLS() + if err != nil { + t.Fatal(err) + } + target, err := peertransport.NewEndpoint(inner, server.Handler(), func(*http.Request) bool { return true }) + if err != nil { + t.Fatal(err) + } + defer target.Close() + outer := httptest.NewTLSServer(target) + defer outer.Close() + roots := x509.NewCertPool() + roots.AddCert(outer.Certificate()) + bundle := a.Bundle() + bf, _ := bundle.Fingerprint() + clientTLS, err := agent.ClientTLS(bundle, grant, bf) + if err != nil { + t.Fatal(err) + } + hc, closeTransport, err := peertransport.HTTPClientWithRoots("wss"+strings.TrimPrefix(outer.URL, "https"), clientTLS, nil, roots) + if err != nil { + t.Fatal(err) + } + defer closeTransport() + bridge, remote, err := agentbridge.New(ctx, hc) + if err != nil { + t.Fatal(err) + } + defer remote.Close() + left, right := mcp.NewInMemoryTransports() + ss, err := bridge.Connect(ctx, right, nil) + if err != nil { + t.Fatal(err) + } + defer ss.Close() + client := mcp.NewClient(&mcp.Implementation{Name: "operation-native-agent", Version: "test"}, nil) + session, err := client.Connect(ctx, left, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + list, err := session.ListTools(ctx, nil) + if err != nil { + t.Fatal(err) + } + found := false + for _, tool := range list.Tools { + if strings.Contains(tool.Name, "approve") { + t.Fatal("remote approval tool exposed") + } + if tool.Name == "prepare_file_change" { + found = true + } + } + if !found { + t.Fatal("authorized operation tool missing") + } + var info serverInfoOutput + decodeToolJSON(t, callTool(t, ctx, session, "server_info", map[string]any{}), &info) + if info.ReadOnly || info.ExecutionPolicy != "trusted_host" { + t.Fatal("operation target incorrectly advertised read-only or isolated execution") + } + bad, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "prepare_file_change", Arguments: map[string]any{"nonce": "forged", "root_id": "workspace", "path": "new.txt", "content": "bad", "confirmed": true}}) + if err == nil && !bad.IsError { + t.Fatal("remote confirmation boolean was accepted") + } + for _, scenario := range []string{"new", "conflict"} { + path := scenario + ".txt" + if scenario == "conflict" { + if err = os.WriteFile(filepath.Join(f.root, path), []byte("before"), 0600); err != nil { + t.Fatal(err) + } + } + result := callTool(t, ctx, session, "prepare_file_change", map[string]any{"nonce": scenario, "root_id": "workspace", "path": path, "content": "approved"}) + var prepared operations.Summary + decodeToolJSON(t, result, &prepared) + if prepared.State != "prepared" { + t.Fatal("operation preparation failed") + } + result = callTool(t, ctx, session, "commit_file_change", map[string]any{"id": prepared.ID, "digest": prepared.Digest}) + var submitted operations.Summary + decodeToolJSON(t, result, &submitted) + if submitted.State != "awaiting_approval" { + t.Fatal("job skipped local approval") + } + if scenario == "new" { + if _, err = os.Stat(filepath.Join(f.root, path)); !os.IsNotExist(err) { + t.Fatal("unapproved write happened") + } + } else { + if err = os.WriteFile(filepath.Join(f.root, path), []byte("user-edit"), 0600); err != nil { + t.Fatal(err) + } + } + if err = journal.Decide(prepared.ID, prepared.Digest, true, true); err != nil { + t.Fatal(err) + } + var status operations.Summary + for { + decodeToolJSON(t, callTool(t, ctx, session, "operation_status", map[string]any{"id": prepared.ID}), &status) + if status.State == "succeeded" || status.State == "failed" { + break + } + select { + case <-ctx.Done(): + t.Fatal("operation did not finish") + case <-time.After(10 * time.Millisecond): + } + } + want := "approved" + if scenario == "conflict" { + want = "user-edit" + if status.State != "failed" || status.ErrorCode != "file_conflict" { + t.Fatalf("conflict outcome=%+v", status) + } + } else if status.State != "succeeded" { + t.Fatalf("write outcome=%+v", status) + } + content, err := os.ReadFile(filepath.Join(f.root, path)) + if err != nil || string(content) != want { + t.Fatalf("actual content=%q, want %q: %v", content, want, err) + } + } + var pin peertransport.Pin + decoded, _ := hex.DecodeString(grant.KeyPin) + copy(pin[:], decoded) + if err = registry.Revoke(pin); err != nil { + t.Fatal(err) + } + if result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "operation_status", Arguments: map[string]any{"id": strings.Repeat("0", 64)}}); err == nil && !result.IsError { + t.Fatal("revoked identity retained operation access") + } +} diff --git a/internal/mcpserver/peer_test.go b/internal/mcpserver/peer_test.go new file mode 100644 index 0000000..87d1e31 --- /dev/null +++ b/internal/mcpserver/peer_test.go @@ -0,0 +1,129 @@ +package mcpserver + +import ( + "context" + "crypto/x509" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/agentbridge" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestPairedAgentUsesExistingFileScopeAndRejectsMixedAuthentication(t *testing.T) { + f := newFixture(t) + defer f.close() + _ = newTestServer(t, f, []Credential{{ConnectionID: "connection-one", Token: testTokenOne}}) + store, err := deviceidentity.CreateStore(filepath.Join(t.TempDir(), "identity")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + a, err := deviceidentity.NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = store.SaveAuthority(a); err != nil { + t.Fatal(err) + } + agent, req, err := deviceidentity.NewAgent() + if err != nil { + t.Fatal(err) + } + fp, _ := req.Fingerprint() + g, err := store.IssueGrant(req, fp, "connection-one", time.Hour) + if err != nil { + t.Fatal(err) + } + registry, err := deviceidentity.NewRegistry(store) + if err != nil { + t.Fatal(err) + } + options := Options{Manager: f.manager, Source: f.source, PeerRegistry: registry} + server, err := New(options) + if err != nil { + t.Fatal(err) + } + options.Credentials = []Credential{{ConnectionID: "connection-one", Token: testTokenOne}} + if _, err = New(options); err == nil { + t.Fatal("mixed ingress accepted") + } + inner, err := registry.ServerTLS() + if err != nil { + t.Fatal(err) + } + endpoint, err := peertransport.NewEndpoint(inner, server.Handler(), func(*http.Request) bool { return true }) + if err != nil { + t.Fatal(err) + } + defer endpoint.Close() + outer := httptest.NewTLSServer(endpoint) + defer outer.Close() + roots := x509.NewCertPool() + roots.AddCert(outer.Certificate()) + b := a.Bundle() + bf, _ := b.Fingerprint() + innerClient, err := agent.ClientTLS(b, g, bf) + if err != nil { + t.Fatal(err) + } + hc, closeTransport, err := peertransport.HTTPClientWithRoots("wss"+strings.TrimPrefix(outer.URL, "https"), innerClient, nil, roots) + if err != nil { + t.Fatal(err) + } + defer closeTransport() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + bridge, remote, err := agentbridge.New(ctx, hc) + if err != nil { + t.Fatal(err) + } + defer remote.Close() + left, right := mcp.NewInMemoryTransports() + ss, err := bridge.Connect(ctx, right, nil) + if err != nil { + t.Fatal(err) + } + defer ss.Close() + client := mcp.NewClient(&mcp.Implementation{Name: "paired-native-agent", Version: "test"}, nil) + session, err := client.Connect(ctx, left, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + result := callTool(t, ctx, session, ToolReadFile, map[string]any{"root_id": "workspace", "path": "hello.txt", "max_bytes": 64}) + var output readFileOutput + decodeToolJSON(t, result, &output) + if output.Item.Content != "hello from Local-Probe\n" { + t.Fatal("read failed") + } + info := callTool(t, ctx, session, ToolServerInfo, map[string]any{}) + var identity serverInfoOutput + decodeToolJSON(t, info, &identity) + if identity.ConnectionID != "connection-one" || identity.ProfileID != "profile-one" || identity.TargetDeviceID != b.DeviceID || identity.Purpose != "agent_remote" { + t.Fatalf("wrong identity: %+v", identity) + } + denied, err := session.CallTool(ctx, &mcp.CallToolParams{Name: ToolReadFile, Arguments: map[string]any{"root_id": "private", "path": "hello.txt", "max_bytes": 64}}) + if err != nil { + t.Fatal(err) + } + var rejected readFileOutput + decodeToolJSON(t, denied, &rejected) + if rejected.Item.Error == nil || rejected.Item.Error.Code != "denied" || rejected.Item.Content != "" { + t.Fatal("cross-root read did not enforce scope") + } + // Forged HTTP bearer identity cannot enter the exclusive peer ingress. + recorder := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "http://127.0.0.1/mcp", strings.NewReader("{}")) + request.Header.Set(LocalTokenHeader, testTokenTwo) + server.Handler().ServeHTTP(recorder, request) + if recorder.Code != http.StatusUnauthorized { + t.Fatal("plaintext bearer entered peer ingress") + } +} diff --git a/internal/mcpserver/server.go b/internal/mcpserver/server.go index 2d0f97d..c03cd84 100644 --- a/internal/mcpserver/server.go +++ b/internal/mcpserver/server.go @@ -1,4 +1,4 @@ -// Package mcpserver exposes the read-only Local-Probe core through the +// Package mcpserver exposes the Local-Probe core through the // official MCP Go SDK. The package deliberately owns no listener: callers // choose the listener and should bind it to loopback. package mcpserver @@ -22,7 +22,9 @@ import ( "github.com/LE-saber/Local-Probe/internal/audit" "github.com/LE-saber/Local-Probe/internal/cfaccess" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" "github.com/LE-saber/Local-Probe/internal/environment" + "github.com/LE-saber/Local-Probe/internal/operations" "github.com/LE-saber/Local-Probe/internal/policy" "github.com/LE-saber/Local-Probe/internal/readcore" "github.com/LE-saber/Local-Probe/internal/search" @@ -83,14 +85,19 @@ type Credential struct { Token string } -// Options configures one read-only MCP endpoint. Manager and Source must be +// Options configures one MCP endpoint, read-only unless Operations is provided. +// Manager and Source must be // built from the same config.Store snapshot family. Credentials are runtime // values and are never serialized by this package. type Options struct { - Manager *policy.Manager - Source SourceBinder - Credentials []Credential - Audit audit.Recorder + Operations *operations.Engine + // PeerRegistry is an exclusive inner-mTLS ingress. It cannot be combined + // with bearer/Cloudflare authentication. Only verified local grants bind scope. + PeerRegistry *deviceidentity.Registry + Manager *policy.Manager + Source SourceBinder + Credentials []Credential + Audit audit.Recorder // EnvironmentTools is a local-only allowlist for non-executing tool // discovery. Candidate paths come from trusted configuration; MCP input // can select only logical IDs and never supplies paths or diagnostics. @@ -111,9 +118,11 @@ type Options struct { MaxResponseBytes int64 } -// Server is an authenticated, read-only MCP handler. It is safe to share +// Server is an authenticated MCP handler. It is safe to share // across concurrent HTTP requests. type Server struct { + operations *operations.Engine + peerRegistry *deviceidentity.Registry manager *policy.Manager source SourceBinder limits readcore.Limits @@ -146,6 +155,9 @@ type hostPattern struct { // It does not open a socket. The returned Handler uses bearer authentication // and the SDK's Streamable HTTP implementation. func New(opts Options) (*Server, error) { + if opts.Operations != nil && opts.PeerRegistry == nil { + return nil, ErrInvalidOptions + } if opts.Manager == nil || opts.Source == nil { return nil, fmt.Errorf("%w: manager and source are required", ErrInvalidOptions) } @@ -174,11 +186,18 @@ func New(opts Options) (*Server, error) { return nil, fmt.Errorf("%w: response size limit out of bounds", ErrInvalidOptions) } - if opts.CloudflareAccess != nil && len(opts.Credentials) > 0 { - return nil, fmt.Errorf("%w: local credentials and Cloudflare Access ingress cannot be combined", ErrInvalidOptions) + authModes := 0 + if opts.PeerRegistry != nil { + authModes++ + } + if opts.CloudflareAccess != nil { + authModes++ } - if opts.CloudflareAccess == nil && len(opts.Credentials) == 0 { - return nil, fmt.Errorf("%w: at least one credential is required", ErrInvalidOptions) + if len(opts.Credentials) > 0 { + authModes++ + } + if authModes != 1 { + return nil, fmt.Errorf("%w: exactly one authentication ingress is required", ErrInvalidOptions) } hosts := make(map[string]hostPattern) if opts.CloudflareAccess != nil { @@ -215,6 +234,8 @@ func New(opts Options) (*Server, error) { seenTokens = append(seenTokens, token) } s := &Server{ + operations: opts.Operations, + peerRegistry: opts.PeerRegistry, manager: opts.Manager, source: opts.Source, limits: limits, @@ -270,14 +291,16 @@ func usesModernMCPProtocol(r *http.Request) bool { func (s *Server) buildHandler() http.Handler { server := mcp.NewServer(&mcp.Implementation{Name: ServerName, Version: ServerVersion}, &mcp.ServerOptions{ + Instructions: "If the target workspace is already accessible through authorized native tools in your current execution environment, prefer those native tools. Do not use Local-Probe to bypass native sandbox, approval, or file-access restrictions. Client names and matching paths do not prove that the target is local.", // No server-side features other than the explicitly registered tools. Capabilities: &mcp.ServerCapabilities{}, }) server.AddReceivingMiddleware(s.authorizationMiddleware()) + s.addOperationTools(server) addTool(server, &mcp.Tool{ Name: ToolServerInfo, - Description: "Return the authenticated Local-Probe server identity and read-only capability summary.", + Description: "Return the authenticated Local-Probe server identity and connection capability summary.", InputSchema: emptyObjectSchema, OutputSchema: serverInfoSchema, Annotations: readOnlyAnnotations(), @@ -383,6 +406,24 @@ func (s *Server) buildHandler() http.Handler { } statefulHandler.ServeHTTP(w, r) }) + if s.peerRegistry != nil { + // Populate the SDK's session-user binding from a verified local Grant. + // This synthetic header exists only on an in-memory clone. The verifier + // never trusts its value without the private Registry context. + protected := auth.RequireBearerToken(func(ctx context.Context, _ string, _ *http.Request) (*auth.TokenInfo, error) { + grant, ok := deviceidentity.GrantFromContext(ctx) + if !ok { + return nil, auth.ErrInvalidToken + } + return &auth.TokenInfo{UserID: grant.KeyPin, Expiration: grant.ExpiresAt}, nil + }, nil)(mcpHandler) + return s.auditHTTP(s.peerRegistry.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clone := r.Clone(r.Context()) + clone.Header = r.Header.Clone() + clone.Header.Set("Authorization", "Bearer paired-peer") + protected.ServeHTTP(w, clone) + }))) + } // The SDK's auth middleware populates auth.TokenInfo in the context and // enforces session user binding. The token has no remote expiration; process // restart/credential rotation is the lifetime boundary for this local hop. @@ -617,7 +658,7 @@ func (s *Server) authorizationMiddleware() mcp.Middleware { } filtered := list.Tools[:0] for _, tool := range list.Tools { - if tool != nil && bound.AllowsTool(tool.Name) { + if tool != nil && s.allowsTool(ctx, bound, tool.Name) { filtered = append(filtered, tool) } } @@ -632,7 +673,7 @@ func (s *Server) authorizationMiddleware() mcp.Middleware { if ok && params != nil && isRegisteredAuditAction(params.Name) { action = params.Name } - denied := !ok || params == nil || !bound.AllowsTool(params.Name) + denied := !ok || params == nil || !s.allowsTool(ctx, bound, params.Name) inputBytes := 0 if params != nil { inputBytes = len(params.Arguments) @@ -736,6 +777,9 @@ func auditResultBytes(result mcp.Result) int64 { } func isRegisteredAuditAction(value string) bool { + if isOperationTool(value) { + return true + } switch value { case ToolServerInfo, ToolPing, ToolReadFile, ToolBatchRead, ToolListDirectory, ToolFindFiles, ToolSearchText, ToolTreeDirectory, ToolGetEnvironment, ToolDiscoverTools, @@ -748,6 +792,21 @@ func isRegisteredAuditAction(value string) bool { } func (s *Server) boundScope(ctx context.Context) (policy.BoundScope, error) { + if s.peerRegistry != nil { + grant, ok := deviceidentity.GrantFromContext(ctx) + if !ok { + return policy.BoundScope{}, ErrUnauthorized + } + info := auth.TokenInfoFromContext(ctx) + if info == nil || info.UserID != grant.KeyPin { + return policy.BoundScope{}, ErrUnauthorized + } + bound, err := s.manager.BindAuthenticated(grant.ConnectionID) + if err != nil { + return policy.BoundScope{}, ErrUnauthorized + } + return bound, nil + } info := auth.TokenInfoFromContext(ctx) if info == nil || info.UserID == "" { return policy.BoundScope{}, ErrUnauthorized @@ -805,15 +864,18 @@ type batchReadInput struct { } type serverInfoOutput struct { - SchemaVersion string `json:"schema_version"` - Server string `json:"server"` - Version string `json:"version"` - ReadOnly bool `json:"read_only"` - Transport string `json:"transport"` - ConnectionID string `json:"connection_id"` - ProfileID string `json:"profile_id"` - RootIDs []string `json:"root_ids"` - Tools []string `json:"tools"` + ExecutionPolicy string `json:"execution_policy,omitempty"` + TargetDeviceID string `json:"target_device_id,omitempty"` + Purpose string `json:"purpose,omitempty"` + SchemaVersion string `json:"schema_version"` + Server string `json:"server"` + Version string `json:"version"` + ReadOnly bool `json:"read_only"` + Transport string `json:"transport"` + ConnectionID string `json:"connection_id"` + ProfileID string `json:"profile_id"` + RootIDs []string `json:"root_ids"` + Tools []string `json:"tools"` } type discoverToolsInput struct { @@ -1155,17 +1217,37 @@ func (s *Server) handleServerInfo(ctx context.Context, _ *mcp.CallToolRequest) ( tools = append(tools, name) } } + readOnly := true + for _, name := range operationTools { + if s.allowsTool(ctx, bound, name) { + tools = append(tools, name) + if name == "submit_operation" || name == "commit_file_change" { + readOnly = false + } + } + } out := serverInfoOutput{ SchemaVersion: SchemaVersion, Server: ServerName, Version: ServerVersion, - ReadOnly: true, + ReadOnly: readOnly, Transport: "mcp-streamable-http", ConnectionID: bound.ConnectionID(), ProfileID: bound.ProfileID(), RootIDs: bound.RootIDs(), Tools: tools, } + if _, ok := s.operationSubject(ctx, bound); ok { + out.ExecutionPolicy = "trusted_host" + } + if s.peerRegistry != nil { + grant, ok := deviceidentity.GrantFromContext(ctx) + if !ok { + return errorResult("unauthorized", "paired identity required"), nil + } + out.TargetDeviceID = grant.DeviceID + out.Purpose = "agent_remote" + } return s.jsonResult(out), nil } diff --git a/internal/operations/catalog.go b/internal/operations/catalog.go new file mode 100644 index 0000000..d405321 --- /dev/null +++ b/internal/operations/catalog.go @@ -0,0 +1,31 @@ +package operations + +import ( + "bytes" + "encoding/json" + "io" + "os" + "path/filepath" +) + +func LoadCatalog(path string) (Catalog, error) { + var c Catalog + if !filepath.IsAbs(path) { + return c, ErrInvalid + } + f, err := os.Open(path) + if err != nil { + return c, ErrStorage + } + defer f.Close() + b, err := io.ReadAll(io.LimitReader(f, (64<<10)+1)) + if err != nil || len(b) > 64<<10 { + return c, ErrInvalid + } + d := json.NewDecoder(bytes.NewReader(b)) + d.DisallowUnknownFields() + if d.Decode(&c) != nil || d.Decode(new(any)) != io.EOF { + return c, ErrInvalid + } + return c, nil +} diff --git a/internal/operations/engine.go b/internal/operations/engine.go new file mode 100644 index 0000000..ebfef69 --- /dev/null +++ b/internal/operations/engine.go @@ -0,0 +1,729 @@ +package operations + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/policy" + "github.com/LE-saber/Local-Probe/internal/probe" + "github.com/LE-saber/Local-Probe/internal/rootfs" +) + +type Options struct { + Journal *Journal + Config *config.Store + Manager *policy.Manager + Workspace Workspace + Catalog Catalog + // Acquire must resolve the authenticated subject again and hold a cancellable + // identity lease until release. It is supplied by the target's peer registry. + Acquire func(context.Context, Subject) (context.Context, func(), error) +} +type runner struct { + tool Tool + descriptor probe.ExecutableDescriptor +} +type runningJob struct { + cancel context.CancelFunc + done chan struct{} + until time.Time +} +type Engine struct { + mu sync.Mutex + opts Options + runners map[string]runner + jobs map[string]Record + running map[string]*runningJob + ctx context.Context + cancel context.CancelFunc + done chan struct{} + wg sync.WaitGroup + lock fsLock + unhealthy bool + epoch string +} + +func (e *Engine) Allows(s Subject) bool { + _, err := e.authorize(s) + e.mu.Lock() + defer e.mu.Unlock() + return err == nil && !e.unhealthy && e.ctx.Err() == nil +} + +// Tools returns only logical runner identities, never executable paths or env. +func (e *Engine) Tools() []struct { + ID string `json:"id"` + SHA256 string `json:"sha256"` + ScriptType string `json:"script_type,omitempty"` +} { + out := make([]struct { + ID string `json:"id"` + SHA256 string `json:"sha256"` + ScriptType string `json:"script_type,omitempty"` + }, 0, len(e.runners)) + for _, r := range e.runners { + out = append(out, struct { + ID string `json:"id"` + SHA256 string `json:"sha256"` + ScriptType string `json:"script_type,omitempty"` + }{r.tool.ID, r.tool.SHA256, r.tool.ScriptType}) + } + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + return out +} + +func New(ctx context.Context, o Options) (*Engine, error) { + if ctx == nil || o.Journal == nil || o.Config == nil || o.Manager == nil || o.Workspace == nil || o.Acquire == nil || o.Catalog.Version != Version || len(o.Catalog.Tools) > 32 { + return nil, ErrInvalid + } + encoded, err := json.Marshal(o.Catalog) + if err != nil { + return nil, ErrInvalid + } + var cloned Catalog + if json.Unmarshal(encoded, &cloned) != nil { + return nil, ErrInvalid + } + o.Catalog = cloned + // Local operation state must never be reachable through an authorized root. + state, err := filepath.EvalSymlinks(o.Journal.Path) + if err != nil { + return nil, ErrStorage + } + for _, r := range o.Config.Snapshot().Config().Roots() { + root, err := filepath.EvalSymlinks(r.Path()) + if err != nil { + return nil, ErrStorage + } + if contained(root, state) || contained(state, root) { + return nil, ErrDenied + } + } + f, err := o.Journal.root.OpenFile("engine.lock", os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return nil, ErrStorage + } + e := &Engine{opts: o, runners: map[string]runner{}, running: map[string]*runningJob{}, done: make(chan struct{}), lock: fsLock{file: f}} + if lockEngine(&e.lock) != nil { + f.Close() + return nil, ErrConflict + } + ok := false + defer func() { + if !ok { + f.Close() + } + }() + for _, t := range o.Catalog.Tools { + if t.ID == "" || len(t.ID) > 64 || e.runners[t.ID].tool.ID != "" || !validID(t.SHA256) || len(t.Environment) > 64 { + return nil, ErrInvalid + } + if t.ScriptType != "" && t.ScriptType != "python" && t.ScriptType != "node" && t.ScriptType != "powershell" && t.ScriptType != "cmd" { + return nil, ErrInvalid + } + for _, v := range t.Environment { + if !strings.Contains(v, "=") || strings.ContainsRune(v, 0) || len(v) > 8192 { + return nil, ErrInvalid + } + } + d, err := probe.AuditExecutable(probe.ToolVersionGeneric, t.Executable) + if err != nil { + return nil, err + } + if h, err := hashFile(t.Executable); err != nil || h != t.SHA256 { + return nil, probe.ErrHashMismatch + } + t.Environment = append([]string(nil), t.Environment...) + e.runners[t.ID] = runner{t, d} + } + e.epoch = e.currentEpoch() + e.jobs, err = o.Journal.Records() + if err != nil { + return nil, err + } + if len(e.jobs) > 128 { + return nil, ErrCapacity + } + for id, r := range e.jobs { + if !terminal(r.Summary.State) { + state := "interrupted" + if r.Summary.State == "running" { + state = "unknown" + } + if err = e.transition(&r, state, "target_restarted"); err != nil { + return nil, err + } + e.jobs[id] = r + } + } + e.ctx, e.cancel = context.WithCancel(ctx) + ok = true + go e.loop() + return e, nil +} +func contained(parent, child string) bool { + r, err := filepath.Rel(strings.ToLower(parent), strings.ToLower(child)) + return err == nil && (r == "." || r != ".." && !strings.HasPrefix(r, ".."+string(filepath.Separator))) +} +func hashFile(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", ErrStorage + } + defer f.Close() + h := sha256.New() + n, err := io.Copy(h, io.LimitReader(f, (512<<20)+1)) + if err != nil || n > 512<<20 { + return "", ErrStorage + } + return hex.EncodeToString(h.Sum(nil)), nil +} +func (e *Engine) currentEpoch() string { + snapshot := e.opts.Config.Snapshot() + return digest(struct { + Config config.Config + Catalog Catalog + Revision string + }{snapshot.Config(), e.opts.Catalog, snapshot.Revision()}) +} +func (e *Engine) authorize(s Subject) (policy.BoundScope, error) { + if s.Principal == "" || len(s.Principal) > 256 || s.Connection == "" { + return policy.BoundScope{}, ErrDenied + } + cfg := e.opts.Config.Snapshot().Config() + c, ok := cfg.Connection(s.Connection) + if !ok || !c.Enabled() || c.Purpose() != config.PurposeAgentRemote || c.ExecutionPolicy() != config.ExecutionTrustedHost || !cfg.DeveloperMode().AllowsConnection(c.ID()) { + return policy.BoundScope{}, ErrDenied + } + profile, ok := cfg.Profile(c.ProfileID()) + if !ok || profile.ReadOnly() { + return policy.BoundScope{}, ErrDenied + } + b, err := e.opts.Manager.BindAuthenticated(c.ID()) + if err != nil { + return policy.BoundScope{}, ErrDenied + } + return b, nil +} +func validRequest(r Request) bool { + if r.Nonce == "" || len(r.Nonce) > 128 || !utf8.ValidString(r.Nonce) || strings.ContainsRune(r.Nonce, 0) || r.RootID == "" || len(r.Args) > 64 || len(r.Script) > MaxContent || len(r.Content) > MaxContent || r.TimeoutSeconds < 1 || r.TimeoutSeconds > 1800 { + return false + } + bytes := 0 + for _, s := range r.Args { + bytes += len(s) + if len(s) > 4096 || strings.ContainsRune(s, 0) || !utf8.ValidString(s) { + return false + } + } + if bytes > 16384 || !utf8.ValidString(r.Script) || !utf8.ValidString(r.Content) || strings.ContainsRune(r.Script, 0) { + return false + } + switch r.Kind { + case "command", "build", "test", "version": + return r.ToolID != "" && r.Script == "" && r.Path == "" && r.Content == "" && len(r.Edits) == 0 + case "script": + return r.ToolID != "" && r.Script != "" && r.Path == "" && r.Content == "" && len(r.Edits) == 0 + case "file_write": + return r.Path != "" && r.ToolID == "" && r.Script == "" && len(r.Args) == 0 && r.Directory == "" && len(r.Edits) == 0 + case "file_patch": + if r.Path == "" || r.ToolID != "" || r.Script != "" || len(r.Args) != 0 || r.Directory != "" || r.Content != "" || len(r.Edits) == 0 || len(r.Edits) > 32 { + return false + } + size := 0 + for _, edit := range r.Edits { + if edit.Old == "" || !utf8.ValidString(edit.Old) || !utf8.ValidString(edit.New) { + return false + } + size += len(edit.Old) + len(edit.New) + } + return size <= MaxContent + } + return false +} +func (e *Engine) Prepare(ctx context.Context, s Subject, r Request) (Summary, error) { + if r.TimeoutSeconds == 0 { + r.TimeoutSeconds = 60 + } + if !validRequest(r) { + return Summary{}, ErrInvalid + } + b, err := e.authorize(s) + if err != nil { + return Summary{}, err + } + if !b.AllowsRoot(r.RootID) || !b.AllowsDirectory(r.RootID, r.Directory) { + return Summary{}, ErrDenied + } + r.Args = append([]string(nil), r.Args...) + r.Edits = append([]Edit(nil), r.Edits...) + id := digest(struct { + Subject Subject + Nonce string + }{s, r.Nonce}) + e.mu.Lock() + old, exists := e.jobs[id] + unhealthy := e.unhealthy + e.mu.Unlock() + if unhealthy { + return Summary{}, ErrStorage + } + if exists { + if digest(old.Plan.Request) != digest(r) { + return Summary{}, ErrConflict + } + return old.Summary, nil + } + lease, release, err := e.opts.Acquire(ctx, s) + if err != nil { + return Summary{}, ErrDenied + } + defer release() + if lease.Err() != nil { + return Summary{}, ErrDenied + } + r.Args = append([]string(nil), r.Args...) + p := Plan{Subject: s, Request: r, Epoch: e.currentEpoch()} + if r.Kind == "file_write" || r.Kind == "file_patch" { + var before []byte + p.ExpectedFile, before, err = e.opts.Workspace.FilePreview(b, r.RootID, r.Path) + if err == nil && !utf8.Valid(before) { + return Summary{}, ErrInvalid + } + p.Before = string(before) + if err == nil && r.Kind == "file_patch" { + if p.ExpectedFile == "absent" { + return Summary{}, ErrConflict + } + patched := p.Before + for _, edit := range r.Edits { + if strings.Count(patched, edit.Old) != 1 { + return Summary{}, ErrConflict + } + patched = strings.Replace(patched, edit.Old, edit.New, 1) + if len(patched) > MaxContent { + return Summary{}, ErrInvalid + } + } + p.PatchedContent = patched + } + } else { + t, ok := e.runners[r.ToolID] + if !ok || r.Kind == "script" && t.tool.ScriptType == "" { + return Summary{}, ErrDenied + } + // cmd uses a shell parser rather than the Windows CRT argv grammar. + // This increment accepts a script body, not additional shell arguments + // or a private script path requiring cmd-specific escaping. + if r.Kind == "script" && t.tool.ScriptType == "cmd" && (len(r.Args) != 0 || strings.ContainsAny(e.opts.Journal.Path, " \t\r\n\"&|<>^()%!")) { + return Summary{}, ErrInvalid + } + p.ExecutableHash = t.tool.SHA256 + err = e.opts.Workspace.WithDirectory(b, r.RootID, r.Directory, func(string) error { return nil }) + } + if err != nil { + return Summary{}, err + } + e.mu.Lock() + defer e.mu.Unlock() + if e.unhealthy || e.ctx.Err() != nil { + return Summary{}, ErrStorage + } + if old, ok := e.jobs[id]; ok { + if digest(old.Plan.Request) != digest(r) { + return Summary{}, ErrConflict + } + return old.Summary, nil + } + if len(e.jobs) >= 128 { + return Summary{}, ErrCapacity + } + now := time.Now().UTC() + summary := Summary{ID: id, Digest: digest(p), State: "prepared", Kind: r.Kind, RootID: r.RootID, ToolID: r.ToolID, Created: now, Updated: now, Expires: now.Add(5 * time.Minute), ExitCode: -1} + job := Record{Version: Version, Summary: summary, Plan: p, Sequence: 1} + encoded, encodeErr := json.Marshal(job) + if encodeErr != nil || len(encoded) > maxRecord-(256<<10) { // reserve bounded result bytes and terminal metadata + return Summary{}, ErrInvalid + } + if err := e.opts.Journal.save(job); err != nil { + if errors.Is(err, ErrCapacity) { + return Summary{}, ErrCapacity + } + e.failStorage() + return Summary{}, ErrStorage + } + e.jobs[id] = job + return summary, nil +} +func (e *Engine) Submit(s Subject, id, expected string) (Summary, error) { + if !validID(id) || !validID(expected) { + return Summary{}, ErrInvalid + } + e.mu.Lock() + defer e.mu.Unlock() + r, ok := e.jobs[id] + if !ok || r.Plan.Subject != s { + return Summary{}, ErrDenied + } + if r.Summary.Digest != expected { + return Summary{}, ErrConflict + } + if _, err := e.authorize(s); err != nil || r.Plan.Epoch != e.currentEpoch() { + return Summary{}, ErrDenied + } + if e.unhealthy || e.ctx.Err() != nil { + return Summary{}, ErrStorage + } + if r.Summary.State == "prepared" { + if err := e.transition(&r, "awaiting_approval", ""); err != nil { + return Summary{}, err + } + e.jobs[id] = r + } + return r.Summary, nil +} +func (e *Engine) Status(s Subject, id string) (Summary, error) { + e.mu.Lock() + defer e.mu.Unlock() + r, ok := e.jobs[id] + if !ok || r.Plan.Subject != s { + return Summary{}, ErrDenied + } + if e.unhealthy { + return Summary{}, ErrStorage + } + if live := e.running[id]; live != nil { + if time.Now().After(live.until) { + live.cancel() + } else { + live.until = time.Now().Add(60 * time.Second) + } + } + return r.Summary, nil +} +func (e *Engine) Output(s Subject, id, stream string, offset, limit int) (Output, error) { + if offset < 0 || limit < 1 || limit > 32768 { + return Output{}, ErrInvalid + } + e.mu.Lock() + defer e.mu.Unlock() + r, ok := e.jobs[id] + if !ok || r.Plan.Subject != s { + return Output{}, ErrDenied + } + var b []byte + switch stream { + case "stdout": + b = r.Stdout + case "stderr": + b = r.Stderr + default: + return Output{}, ErrInvalid + } + if offset > len(b) { + return Output{}, ErrInvalid + } + end := min(len(b), offset+limit) + return Output{append([]byte(nil), b[offset:end]...), end, len(b)}, nil +} +func (e *Engine) Cancel(ctx context.Context, s Subject, id string) (Summary, error) { + e.mu.Lock() + r, ok := e.jobs[id] + if !ok || r.Plan.Subject != s { + e.mu.Unlock() + return Summary{}, ErrDenied + } + live := e.running[id] + if live != nil { + live.cancel() + e.mu.Unlock() + select { + case <-live.done: + return e.Status(s, id) + case <-ctx.Done(): + return Summary{}, ctx.Err() + } + } + if !terminal(r.Summary.State) { + if err := e.transition(&r, "cancelled", ""); err != nil { + e.mu.Unlock() + return Summary{}, err + } + e.jobs[id] = r + } + e.mu.Unlock() + return r.Summary, nil +} +func (e *Engine) transition(r *Record, state, code string) error { + if e.unhealthy { + return ErrStorage + } + next := *r + next.Sequence++ + next.Summary.State = state + next.Summary.ErrorCode = code + next.Summary.Updated = time.Now().UTC() + if err := e.opts.Journal.save(next); err != nil { + e.failStorage() + return ErrStorage + } + *r = next + return nil +} + +// All callers hold mu. Storage uncertainty stops every live task and admission. +func (e *Engine) failStorage() { + e.unhealthy = true + for _, job := range e.running { + job.cancel() + } +} +func (e *Engine) loop() { + defer close(e.done) + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-e.ctx.Done(): + return + case <-ticker.C: + e.advance() + } + } +} +func (e *Engine) advance() { + e.mu.Lock() + defer e.mu.Unlock() + if e.unhealthy { + return + } + now := time.Now() + epoch := e.currentEpoch() + ids := make([]string, 0, len(e.jobs)) + for id := range e.jobs { + ids = append(ids, id) + } + sort.Slice(ids, func(i, j int) bool { return e.jobs[ids[i]].Summary.Created.Before(e.jobs[ids[j]].Summary.Created) }) + for _, id := range ids { + r := e.jobs[id] + if terminal(r.Summary.State) { + continue + } + localCancel, err := e.opts.Journal.localCancel(r) + if err != nil { + e.failStorage() + return + } + if localCancel { + if live := e.running[id]; live != nil { + live.cancel() + } else { + if e.transition(&r, "cancelled", "local_owner_cancelled") != nil { + return + } + e.jobs[id] = r + } + continue + } + _, authErr := e.authorize(r.Plan.Subject) + valid := authErr == nil && r.Plan.Epoch == epoch + if live := e.running[id]; live != nil { + if !valid || now.After(live.until) { + live.cancel() + } + continue + } + if !valid || now.After(r.Summary.Expires) { + state, code := "expired", "approval_expired" + if !valid { + state, code = "cancelled", "authorization_changed" + } + if e.transition(&r, state, code) == nil { + e.jobs[id] = r + } + continue + } + if r.Summary.State == "awaiting_approval" { + d, present, err := e.opts.Journal.decision(id) + if err != nil { + e.failStorage() + return + } + if !present { + continue + } + if d.Version != Version || d.ID != id || d.Digest != r.Summary.Digest || d.Expires != r.Summary.Expires || now.After(d.Expires) { + e.failStorage() + return + } + state := "rejected" + if d.Approved && d.TrustedHostAcknowledged { + state = "queued" + } + if e.transition(&r, state, "") != nil { + return + } + e.jobs[id] = r + } + if r.Summary.State != "queued" || len(e.running) >= 2 { + continue + } + busy := false + for active := range e.running { + if e.jobs[active].Plan.Subject.Connection == r.Plan.Subject.Connection { + busy = true + } + } + if busy { + continue + } + if e.transition(&r, "running", "") != nil { + return + } + e.jobs[id] = r + ctx, cancel := context.WithTimeout(e.ctx, time.Duration(r.Plan.Request.TimeoutSeconds)*time.Second) + live := &runningJob{cancel: cancel, done: make(chan struct{}), until: now.Add(60 * time.Second)} + e.running[id] = live + e.wg.Add(1) + go e.execute(ctx, r, live) + } +} +func (e *Engine) execute(ctx context.Context, r Record, live *runningJob) { + defer e.wg.Done() + defer live.cancel() + lease, release, err := e.opts.Acquire(ctx, r.Plan.Subject) + if err == nil { + defer release() + } + var stdout, stderr []byte + exit := int64(-1) + if err == nil { + b, ae := e.authorize(r.Plan.Subject) + err = ae + if err == nil && r.Plan.Epoch != e.currentEpoch() { + err = ErrDenied + } + if err == nil { + request := r.Plan.Request + if request.Kind == "file_write" || request.Kind == "file_patch" { + content := request.Content + if request.Kind == "file_patch" { + content = r.Plan.PatchedContent + } + err = e.opts.Workspace.WriteFile(b, request.RootID, request.Path, r.Plan.ExpectedFile, []byte(content), func(old []byte) error { + if lease.Err() != nil { + return lease.Err() + } + err := e.opts.Journal.write(r.Summary.ID+".before", struct { + ID, Digest string + Data []byte + }{r.Summary.ID, r.Summary.Digest, old}) + if err != nil { + return err + } + return lease.Err() + }) + if err == nil { + exit = 0 + } + } else { + tool := e.runners[request.ToolID] + var result probe.TrustedProcessResult + err = e.opts.Workspace.WithDirectory(b, request.RootID, request.Directory, func(cwd string) error { + if lease.Err() != nil { + return lease.Err() + } + args := append([]string(nil), request.Args...) + work, er := os.MkdirTemp(e.opts.Journal.Path, "run-") + if er != nil { + return ErrStorage + } + defer os.RemoveAll(work) + if request.Kind == "script" { + var prefix []string + extension := ".txt" + switch tool.tool.ScriptType { + case "python": + extension = ".py" + case "node": + extension = ".js" + case "powershell": + extension = ".ps1" + prefix = []string{"-NoProfile", "-NonInteractive", "-File"} + case "cmd": + extension = ".cmd" + prefix = []string{"/d", "/s", "/c"} + default: + return ErrInvalid + } + path := filepath.Join(work, "approved"+extension) + if er = os.WriteFile(path, []byte(request.Script), 0600); er != nil { + return ErrStorage + } + args = append(append(prefix, path), args...) + } + env := append([]string(nil), tool.tool.Environment...) + env = append(env, "TEMP="+work, "TMP="+work) + result, er = probe.RunTrustedProcess(lease, probe.TrustedProcessSpec{Executable: tool.descriptor, SHA256: tool.tool.SHA256, Args: args, Directory: cwd, Environment: env, Timeout: time.Duration(request.TimeoutSeconds) * time.Second, OutputBytes: 64 << 10, AcquireLaunch: b.AcquireRevisionLease}) + return er + }) + stdout, stderr, exit = result.Stdout, result.Stderr, result.ExitCode + } + } + } + state, code := "succeeded", "" + if err != nil { + state, code = "failed", "execution_failed" + var probeError *probe.Error + if errors.As(err, &probeError) { + code = string(probeError.Code) + } + if errors.Is(err, rootfs.ErrDenied) { + code = "workspace_denied" + } + switch { + case errors.Is(err, probe.ErrCleanupUnconfirmed): + state, code = "unknown", "process_tree_cleanup_unconfirmed" + case errors.Is(err, context.Canceled), errors.Is(err, probe.ErrCancelled): + state, code = "cancelled", "cancelled" + case errors.Is(err, context.DeadlineExceeded), errors.Is(err, probe.ErrDeadlineExceeded): + code = "deadline_exceeded" + case errors.Is(err, rootfs.ErrWriteConflict): + code = "file_conflict" + case errors.Is(err, rootfs.ErrWriteUncertain): + state, code = "unknown", "write_uncertain" + case errors.Is(err, probe.ErrOutputLimit): + code = "output_limit" + case errors.Is(err, ErrDenied): + code = "authorization_changed" + } + } + e.mu.Lock() + defer e.mu.Unlock() + r.Stdout = stdout + r.Stderr = stderr + r.Summary.ExitCode = exit + r.Summary.StdoutBytes = len(stdout) + r.Summary.StderrBytes = len(stderr) + if e.transition(&r, state, code) == nil { + e.jobs[r.Summary.ID] = r + } + if errors.Is(err, probe.ErrCleanupUnconfirmed) { + e.failStorage() + } + delete(e.running, r.Summary.ID) + close(live.done) +} +func (e *Engine) Close() error { e.cancel(); <-e.done; e.wg.Wait(); return e.lock.file.Close() } diff --git a/internal/operations/engine_test.go b/internal/operations/engine_test.go new file mode 100644 index 0000000..37b092f --- /dev/null +++ b/internal/operations/engine_test.go @@ -0,0 +1,307 @@ +package operations + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/commandprofile" + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/policy" +) + +type countingWorkspace struct { + writes atomic.Int32 + directory string +} +type previewWorkspace struct { + *countingWorkspace + before []byte +} + +func (w previewWorkspace) FilePreview(policy.BoundScope, string, string) (string, []byte, error) { + return "existing", append([]byte(nil), w.before...), nil +} + +func (w *countingWorkspace) WithDirectory(_ policy.BoundScope, _, _ string, call func(string) error) error { + return call(w.directory) +} +func (w *countingWorkspace) FilePreview(policy.BoundScope, string, string) (string, []byte, error) { + return "absent", nil, nil +} +func (w *countingWorkspace) WriteFile(_ policy.BoundScope, _, _, _ string, _ []byte, backup func([]byte) error) error { + if err := backup(nil); err != nil { + return err + } + w.writes.Add(1) + return nil +} + +func testConfig(t *testing.T, workspace string) *config.Store { + t.Helper() + root, err := config.NewRoot("workspace", workspace, []string{"*.key"}) + if err != nil { + t.Fatal(err) + } + profile, err := config.NewProfile("profile", []string{"workspace"}, []string{"server_info", "read_file", "prepare_operation", "submit_operation", "operation_status", "operation_output", "cancel_operation", "prepare_file_change", "commit_file_change", "probe_tools"}, nil) + if err != nil { + t.Fatal(err) + } + profile = profile.WithWriteAccess() + c := config.NewConnection("connection", "test", profile.ID(), "credential", true) + c, err = c.WithPurpose(config.PurposeAgentRemote) + if err != nil { + t.Fatal(err) + } + c, err = c.WithExecutionPolicy(config.ExecutionTrustedHost) + if err != nil { + t.Fatal(err) + } + mode, err := commandprofile.NewDeveloperMode(true, []string{c.ID()}, commandprofile.ConfirmationPerCall, commandprofile.NetworkDeny) + if err != nil { + t.Fatal(err) + } + cfg, err := config.NewWithCommandProfiles(config.SchemaVersionV2, []config.Root{root}, []config.Profile{profile}, []config.Connection{c}, []config.CredentialRef{config.NewCredentialRef("credential", "runtime")}, nil, mode, nil) + if err != nil { + t.Fatal(err) + } + s, err := config.NewStore(cfg) + if err != nil { + t.Fatal(err) + } + return s +} +func newTestEngine(t *testing.T) (*Engine, *Journal, *countingWorkspace) { + t.Helper() + dir := t.TempDir() + workspace := &countingWorkspace{directory: filepath.Join(dir, "workspace")} + if err := os.Mkdir(workspace.directory, 0700); err != nil { + t.Fatal(err) + } + j, err := OpenJournal(filepath.Join(dir, "journal"), true) + if err != nil { + t.Fatal(err) + } + if err = j.Initialize(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { j.Close() }) + store := testConfig(t, workspace.directory) + manager, err := policy.NewManager(store) + if err != nil { + t.Fatal(err) + } + e, err := New(context.Background(), Options{Journal: j, Config: store, Manager: manager, Workspace: workspace, Catalog: Catalog{Version: Version}, Acquire: func(ctx context.Context, _ Subject) (context.Context, func(), error) { return ctx, func() {}, nil }}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { e.Close() }) + return e, j, workspace +} +func waitState(t *testing.T, e *Engine, s Subject, id string, want string) Summary { + t.Helper() + end := time.Now().Add(8 * time.Second) + for time.Now().Before(end) { + out, err := e.Status(s, id) + if err != nil { + t.Fatal(err) + } + if out.State == want { + return out + } + if terminal(out.State) { + output, _ := e.Output(s, id, "stderr", 0, 1024) + t.Fatalf("state=%s code=%s exit=%d stderr=%q, want %s", out.State, out.ErrorCode, out.ExitCode, output.Data, want) + } + time.Sleep(10 * time.Millisecond) + } + t.Fatal("operation did not reach expected state") + return Summary{} +} +func prepareFile(t *testing.T, e *Engine, s Subject, nonce string) Summary { + t.Helper() + r, err := e.Prepare(context.Background(), s, Request{Nonce: nonce, Kind: "file_write", RootID: "workspace", Path: "test.txt", Content: "approved"}) + if err != nil { + t.Fatal(err) + } + return r +} +func TestApprovalIdempotencyAndSubjectIsolation(t *testing.T) { + e, j, w := newTestEngine(t) + subject := Subject{"principal", "connection"} + p := prepareFile(t, e, subject, "once") + if _, err := e.Submit(subject, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + if w.writes.Load() != 0 { + t.Fatal("unapproved job wrote files") + } + if err := j.Decide(p.ID, strings.Repeat("0", 64), true, true); !errors.Is(err, ErrConflict) { + t.Fatalf("changed digest accepted: %v", err) + } + if err := j.Decide(p.ID, p.Digest, true, false); !errors.Is(err, ErrInvalid) { + t.Fatalf("missing trusted-host acknowledgement accepted: %v", err) + } + if _, err := e.Status(Subject{"different-principal", "connection"}, p.ID); !errors.Is(err, ErrDenied) { + t.Fatal("cross-principal status exposed") + } + if err := j.Decide(p.ID, p.Digest, true, true); err != nil { + t.Fatal(err) + } + waitState(t, e, subject, p.ID, "succeeded") + if _, err := e.Submit(subject, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + if w.writes.Load() != 1 { + t.Fatal("idempotent submission repeated side effects") + } + _, err := e.Prepare(context.Background(), subject, Request{Nonce: "once", Kind: "file_write", RootID: "workspace", Path: "test.txt", Content: "different"}) + if !errors.Is(err, ErrConflict) { + t.Fatal("same nonce accepted a different plan") + } + if err = j.Decide(p.ID, p.Digest, true, true); err == nil { + t.Fatal("terminal job was re-approved") + } +} +func TestRejectCancelAndPolicyChangeHaveNoEffects(t *testing.T) { + for _, action := range []string{"reject", "cancel", "policy"} { + t.Run(action, func(t *testing.T) { + e, j, w := newTestEngine(t) + s := Subject{"principal", "connection"} + p := prepareFile(t, e, s, action) + if _, err := e.Submit(s, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + state := "cancelled" + switch action { + case "reject": + state = "rejected" + if err := j.Decide(p.ID, p.Digest, false, false); err != nil { + t.Fatal(err) + } + case "cancel": + if _, err := e.Cancel(context.Background(), s, p.ID); err != nil { + t.Fatal(err) + } + case "policy": + if _, err := e.opts.Config.Replace(e.opts.Config.Snapshot().Config()); err != nil { + t.Fatal(err) + } + } + waitState(t, e, s, p.ID, state) + if w.writes.Load() != 0 { + t.Fatal("unapproved/revoked/cancelled operation executed") + } + }) + } +} +func TestJournalOwnershipCorruptionAndRestartRecovery(t *testing.T) { + e, j, w := newTestEngine(t) + s := Subject{"principal", "connection"} + p := prepareFile(t, e, s, "restart") + if _, err := New(context.Background(), e.opts); !errors.Is(err, ErrConflict) { + t.Fatalf("second engine obtained the same journal: %v", err) + } + if err := e.Close(); err != nil { + t.Fatal(err) + } + records, err := j.Records() + if err != nil { + t.Fatal(err) + } + r := records[p.ID] + r.Sequence++ + r.Summary.State = "running" + if err = j.save(r); err != nil { + t.Fatal(err) + } + restarted, err := New(context.Background(), e.opts) + if err != nil { + t.Fatal(err) + } + defer restarted.Close() + if out, err := restarted.Status(s, p.ID); err != nil || out.State != "unknown" { + t.Fatalf("restart incorrectly resolved an in-flight operation: %+v %v", out, err) + } + if w.writes.Load() != 0 { + t.Fatal("restart replayed uncertain side effect") + } + if err = os.WriteFile(filepath.Join(j.Path, p.ID+".000003.record"), []byte("broken"), 0600); err != nil { + t.Fatal(err) + } + if _, err = j.Records(); err == nil { + t.Fatal("corrupt persisted record was ignored") + } +} + +func TestJournalPublicationIsCompleteAndCannotReplace(t *testing.T) { + _, j, _ := newTestEngine(t) + name := "publication.bin" + body := strings.Repeat("test-payload-", 100000) + done := make(chan error, 1) + go func() { done <- j.write(name, struct{ Body string }{body}) }() + for { + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + var result struct{ Body string } + if j.read(name, &result) != nil || result.Body != body { + t.Fatal("published record corrupted") + } + if j.write(name, struct{ Body string }{"replaced"}) == nil { + t.Fatal("write-once record replaced") + } + return + default: + if _, err := j.root.Lstat(name); err == nil { + var result struct{ Body string } + if j.read(name, &result) != nil || result.Body != body { + t.Fatal("reader observed a partial published record") + } + } + time.Sleep(time.Millisecond) + } + } +} + +func TestEscapedPatchBudgetIsRejectedWithoutDisablingEngine(t *testing.T) { + e, _, w := newTestEngine(t) + old := strings.Repeat("\x01", MaxContent/2) + other := strings.Repeat("\x02", MaxContent/2) + e.opts.Workspace = previewWorkspace{w, []byte(old + other)} + _, err := e.Prepare(context.Background(), Subject{"principal", "connection"}, Request{Nonce: "oversize", Kind: "file_patch", RootID: "workspace", Path: "test.txt", Edits: []Edit{{Old: old, New: strings.Repeat("\x03", MaxContent/2)}}}) + if !errors.Is(err, ErrInvalid) || !e.Allows(Subject{"principal", "connection"}) { + t.Fatal("oversized serialized patch damaged operation admission") + } +} + +func TestReadOnlyProfileCannotEnableOperationTools(t *testing.T) { + e, _, _ := newTestEngine(t) + cfg := e.opts.Config.Snapshot().Config() + old, _ := cfg.Profile("profile") + readonly, err := config.NewProfile(old.ID(), old.RootIDs(), old.Tools(), old.DenyPatterns()) + if err != nil { + t.Fatal(err) + } + next, err := config.NewWithCommandProfiles(config.SchemaVersionV2, cfg.Roots(), []config.Profile{readonly}, cfg.Connections(), cfg.Credentials(), nil, cfg.DeveloperMode(), nil) + if err != nil { + t.Fatal(err) + } + if _, err = e.opts.Config.Replace(next); err != nil { + t.Fatal(err) + } + s := Subject{"principal", "connection"} + if e.Allows(s) { + t.Fatal("read-only profile exposed operation tools") + } + if _, err = e.Prepare(context.Background(), s, Request{Nonce: "read-only", Kind: "file_write", RootID: "workspace", Path: "test.txt", Content: "bad"}); !errors.Is(err, ErrDenied) { + t.Fatal("read-only profile admitted an operation") + } +} diff --git a/internal/operations/execution_windows_test.go b/internal/operations/execution_windows_test.go new file mode 100644 index 0000000..982888f --- /dev/null +++ b/internal/operations/execution_windows_test.go @@ -0,0 +1,454 @@ +package operations + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/commandprofile" + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/policy" + "github.com/LE-saber/Local-Probe/internal/rootfs" + "golang.org/x/sys/windows" +) + +func realEngine(t *testing.T, tools []Tool) (*Engine, *Journal, string) { + return realEngineConfigured(t, tools, nil) +} +func realEngineConfigured(t *testing.T, tools []Tool, configure func(*config.Store)) (*Engine, *Journal, string) { + t.Helper() + dir := t.TempDir() + workspace := filepath.Join(dir, "workspace") + if err := os.Mkdir(workspace, 0700); err != nil { + t.Fatal(err) + } + j, err := OpenJournal(filepath.Join(dir, "journal"), true) + if err != nil { + t.Fatal(err) + } + if err = j.Initialize(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { j.Close() }) + cfg := testConfig(t, workspace) + if configure != nil { + configure(cfg) + } + manager, err := policy.NewManager(cfg) + if err != nil { + t.Fatal(err) + } + source, err := rootfs.New(cfg) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { source.Close() }) + e, err := New(context.Background(), Options{Journal: j, Config: cfg, Manager: manager, Workspace: source, Catalog: Catalog{Version: Version, Tools: tools}, Acquire: func(ctx context.Context, _ Subject) (context.Context, func(), error) { return ctx, func() {}, nil }}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { e.Close() }) + return e, j, workspace +} +func approved(t *testing.T, e *Engine, j *Journal, r Request) Summary { + t.Helper() + s := Subject{"principal", "connection"} + p, err := e.Prepare(context.Background(), s, r) + if err != nil { + t.Fatal(err) + } + if _, err = e.Submit(s, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + if err = j.Decide(p.ID, p.Digest, true, true); err != nil { + t.Fatal(err) + } + return p +} +func helperTool(t *testing.T) Tool { + t.Helper() + exe := filepath.Join(t.TempDir(), "operation-helper.exe") + build := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go.exe"), "build", "-o", exe, "./testhelper") + build.Env = append(os.Environ(), "CGO_ENABLED=0") + if output, err := build.CombinedOutput(); err != nil { + t.Fatalf("build helper: %v %s", err, output) + } + hash, err := hashFile(exe) + if err != nil { + t.Fatal(err) + } + return Tool{ID: "helper", Executable: exe, SHA256: hash, Environment: []string{"LP_OPERATIONS_HELPER=1", "SystemRoot=" + os.Getenv("SystemRoot")}} +} +func TestRealCommandBuildTestCancelOutputAndEnvironment(t *testing.T) { + t.Setenv("LP_UNAPPROVED_SECRET", "must-not-be-inherited") + e, j, workspace := realEngine(t, []Tool{helperTool(t)}) + s := Subject{"principal", "connection"} + for _, kind := range []string{"command", "build", "test"} { + p := approved(t, e, j, Request{Nonce: kind, Kind: kind, RootID: "workspace", ToolID: "helper", Args: []string{"write"}}) + waitState(t, e, s, p.ID, "succeeded") + if _, err := e.Submit(s, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + } + b, err := os.ReadFile(filepath.Join(workspace, "count.txt")) + if err != nil || string(b) != "once\nonce\nonce\n" { + t.Fatalf("wrong actual side effect count: %q %v", b, err) + } + for _, action := range []string{"environment", "flood", "wait"} { + p := approved(t, e, j, Request{Nonce: action, Kind: "command", RootID: "workspace", ToolID: "helper", Args: []string{action}}) + switch action { + case "environment": + waitState(t, e, s, p.ID, "succeeded") + out, err := e.Output(s, p.ID, "stdout", 0, 1024) + if err != nil || strings.Contains(string(out.Data), "must-not-be-inherited") || !strings.Contains(string(out.Data), "secret=") { + t.Fatal("unapproved environment inherited") + } + case "flood": + result := waitState(t, e, s, p.ID, "failed") + if result.ErrorCode != "output_limit" || result.StdoutBytes > 64<<10 { + t.Fatalf("unbounded output: %+v", result) + } + case "wait": + end := time.Now().Add(5 * time.Second) + for { + if _, err = os.Stat(filepath.Join(workspace, "started.txt")); err == nil { + break + } + if time.Now().After(end) { + t.Fatal("real child did not start") + } + time.Sleep(10 * time.Millisecond) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + result, err := e.Cancel(ctx, s, p.ID) + cancel() + if err != nil || result.State != "cancelled" { + t.Fatalf("real process cancellation failed: %+v %v", result, err) + } + } + } +} + +func TestInstalledPythonNodePowerShellScriptsAndVersions(t *testing.T) { + if os.Getenv("LOCAL_PROBE_OPERATIONS_REAL_TOOLS") != "1" { + t.Skip("opt-in: explicitly selected installed runtimes") + } + for _, runtime := range []struct{ name, env, script string }{ + {"python", "LOCAL_PROBE_OPERATIONS_PYTHON", "from pathlib import Path\nPath('python.txt').write_text('python-ok')\nprint('python-ok')\n"}, + {"node", "LOCAL_PROBE_OPERATIONS_NODE", "require('fs').writeFileSync('node.txt','node-ok'); console.log('node-ok');\n"}, + {"powershell", "LOCAL_PROBE_OPERATIONS_POWERSHELL", "[IO.File]::WriteAllText((Join-Path (Get-Location) 'powershell.txt'),'powershell-ok'); Write-Output 'powershell-ok'\n"}, + {"cmd", "LOCAL_PROBE_OPERATIONS_CMD", "@echo off\r\n>cmd.txt echo cmd-ok\r\necho cmd-ok\r\n"}, + } { + t.Run(runtime.name, func(t *testing.T) { + path := os.Getenv(runtime.env) + if path == "" { + t.Fatal("explicit runtime path required") + } + path, err := filepath.EvalSymlinks(path) + if err != nil { + t.Fatal(err) + } + hash, err := hashFile(path) + if err != nil { + t.Fatal(err) + } + e, j, workspace := realEngine(t, []Tool{{ID: runtime.name, Executable: path, SHA256: hash, ScriptType: runtime.name, Environment: []string{"SystemRoot=" + os.Getenv("SystemRoot")}}}) + s := Subject{"principal", "connection"} + if runtime.name == "cmd" { + if _, err := e.Prepare(context.Background(), s, Request{Nonce: "cmd-args", Kind: "script", RootID: "workspace", ToolID: "cmd", Script: "echo safe", Args: []string{"&", "echo unexpected"}}); err != ErrInvalid { + t.Fatal("cmd script accepted shell arguments outside its approved body") + } + } + versionArgs := []string{"--version"} + if runtime.name == "cmd" { + versionArgs = []string{"/d", "/c", "ver"} + } + version := approved(t, e, j, Request{Nonce: "version", Kind: "version", RootID: "workspace", ToolID: runtime.name, Args: versionArgs}) + waitState(t, e, s, version.ID, "succeeded") + output, err := e.Output(s, version.ID, "stdout", 0, 2048) + if err != nil || len(bytes.TrimSpace(output.Data)) == 0 { + t.Fatal("actual runtime version missing") + } + t.Logf("verified runtime version: %s", strings.TrimSpace(string(output.Data))) + script := approved(t, e, j, Request{Nonce: "script", Kind: "script", RootID: "workspace", ToolID: runtime.name, Script: runtime.script}) + waitState(t, e, s, script.ID, "succeeded") + b, err := os.ReadFile(filepath.Join(workspace, runtime.name+".txt")) + if err != nil || strings.TrimSpace(string(b)) != runtime.name+"-ok" { + t.Fatal("approved runtime did not produce expected real file") + } + }) + } +} + +func TestRealGoBuildAndTestProject(t *testing.T) { + if os.Getenv("LOCAL_PROBE_OPERATIONS_REAL_TOOLS") != "1" { + t.Skip("opt-in: real installed Go compiler") + } + goexe := filepath.Join(runtime.GOROOT(), "bin", "go.exe") + hash, err := hashFile(goexe) + if err != nil { + t.Fatal(err) + } + cache := filepath.Join(t.TempDir(), "cache") + gopath := filepath.Join(t.TempDir(), "gopath") + tool := Tool{ID: "go", Executable: goexe, SHA256: hash, Environment: []string{"SystemRoot=" + os.Getenv("SystemRoot"), "GOROOT=" + runtime.GOROOT(), "GOCACHE=" + cache, "GOPATH=" + gopath, "GOPROXY=off", "GOSUMDB=off", "CGO_ENABLED=0", "GOFLAGS=-p=2", "GOMAXPROCS=2"}} + e, j, workspace := realEngine(t, []Tool{tool}) + s := Subject{"principal", "connection"} + for name, body := range map[string]string{"go.mod": "module local-probe-synthetic\n\ngo 1.25.0\n", "main.go": "package main\nfunc add(a,b int)int{return a+b}\nfunc main(){}\n", "main_test.go": "package main\nimport \"testing\"\nfunc TestAdd(t *testing.T){if add(2,3)!=5{t.Fatal(\"wrong result\")}}\n"} { + if err = os.WriteFile(filepath.Join(workspace, name), []byte(body), 0600); err != nil { + t.Fatal(err) + } + } + for _, job := range []struct { + kind string + args []string + }{{"build", []string{"build", "-o", "application.exe", "."}}, {"test", []string{"test", "-count=1", "."}}} { + p := approved(t, e, j, Request{Nonce: job.kind, Kind: job.kind, RootID: "workspace", ToolID: "go", Args: job.args, TimeoutSeconds: 180}) + end := time.Now().Add(180 * time.Second) + for { + out, err := e.Status(s, p.ID) + if err != nil { + t.Fatal(err) + } + if terminal(out.State) { + if out.State != "succeeded" { + stderr, _ := e.Output(s, p.ID, "stderr", 0, 8192) + t.Fatalf("real %s state=%s code=%s stderr=%q", job.kind, out.State, out.ErrorCode, stderr.Data) + } + break + } + if time.Now().After(end) { + t.Fatal("real build/test timed out") + } + time.Sleep(100 * time.Millisecond) + } + } + if info, err := os.Stat(filepath.Join(workspace, "application.exe")); err != nil || info.Size() == 0 { + t.Fatal("real compiler did not produce executable") + } +} + +func TestLocalCLIApprovalPublishesDurableDecision(t *testing.T) { + e, j, workspace := realEngine(t, nil) + s := Subject{"principal", "connection"} + cli := filepath.Join(t.TempDir(), "local-probe-operations.exe") + build := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go.exe"), "build", "-o", cli, "../../cmd/local-probe-operations") + build.Env = append(os.Environ(), "CGO_ENABLED=0") + if output, err := build.CombinedOutput(); err != nil { + t.Fatalf("build local control CLI: %v %s", err, output) + } + p, err := e.Prepare(context.Background(), s, Request{Nonce: "local-cli", Kind: "file_write", RootID: "workspace", Path: "approved.txt", Content: "local-cli-approved"}) + if err != nil { + t.Fatal(err) + } + if _, err = e.Submit(s, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + base := []string{"-journal", j.Path, "-id", p.ID, "-digest", p.Digest} + if err = exec.Command(cli, append(append([]string(nil), base...), "-action", "approve")...).Run(); err == nil { + t.Fatal("CLI accepted missing acknowledgement") + } + if _, err = os.Stat(filepath.Join(workspace, "approved.txt")); !os.IsNotExist(err) { + t.Fatal("file changed before explicit CLI approval") + } + if output, err := exec.Command(cli, append(append([]string(nil), base...), "-action", "inspect")...).CombinedOutput(); err != nil { + t.Fatalf("local inspection failed: %v %s", err, output) + } else { + var record Record + if json.Unmarshal(output, &record) != nil || record.Plan.Request.Content != "local-cli-approved" || record.Summary.Digest != p.Digest { + t.Fatal("CLI inspection did not show the exact approved plan") + } + } + if output, err := exec.Command(cli, append(append([]string(nil), base...), "-action", "approve", "-ack-trusted-host")...).CombinedOutput(); err != nil { + t.Fatalf("local approval failed: %v %s", err, output) + } + waitState(t, e, s, p.ID, "succeeded") + content, err := os.ReadFile(filepath.Join(workspace, "approved.txt")) + if err != nil || string(content) != "local-cli-approved" { + t.Fatal("local CLI approval did not dispatch actual write") + } + replayed, err := e.Prepare(context.Background(), s, Request{Nonce: "local-cli", Kind: "file_write", RootID: "workspace", Path: "approved.txt", Content: "local-cli-approved"}) + if err != nil || replayed.ID != p.ID || replayed.State != "succeeded" { + t.Fatal("retrying prepare after side effects did not return the existing operation") + } +} + +func TestExactTextPatchRequiresUniqueContextAndProtectsUserChanges(t *testing.T) { + e, j, workspace := realEngine(t, nil) + s := Subject{"principal", "connection"} + target := filepath.Join(workspace, "patch.txt") + if err := os.WriteFile(target, []byte("before old after\n"), 0600); err != nil { + t.Fatal(err) + } + request := Request{Nonce: "patch", Kind: "file_patch", RootID: "workspace", Path: "patch.txt", Edits: []Edit{{Old: "old", New: "new"}}} + p := approved(t, e, j, request) + waitState(t, e, s, p.ID, "succeeded") + b, err := os.ReadFile(target) + if err != nil || string(b) != "before new after\n" { + t.Fatal("exact patch not applied") + } + records, err := j.Records() + if err != nil || records[p.ID].Plan.Before != "before old after\n" || records[p.ID].Plan.PatchedContent != "before new after\n" { + t.Fatal("approval did not bind before/after patch contents") + } + if err = os.WriteFile(target, []byte("old old"), 0600); err != nil { + t.Fatal(err) + } + request.Nonce = "ambiguous" + if _, err = e.Prepare(context.Background(), s, request); err != ErrConflict { + t.Fatalf("ambiguous patch context accepted: %v", err) + } + if err = os.WriteFile(target, []byte("old"), 0600); err != nil { + t.Fatal(err) + } + request.Nonce = "conflict" + p, err = e.Prepare(context.Background(), s, request) + if err != nil { + t.Fatal(err) + } + if _, err = e.Submit(s, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(target, []byte("user edit"), 0600); err != nil { + t.Fatal(err) + } + if err = j.Decide(p.ID, p.Digest, true, true); err != nil { + t.Fatal(err) + } + result := waitState(t, e, s, p.ID, "failed") + if result.ErrorCode != "file_conflict" { + t.Fatalf("patch did not detect intervening edit: %+v", result) + } + b, _ = os.ReadFile(target) + if string(b) != "user edit" { + t.Fatal("patch overwrote user's intervening edit") + } +} + +func TestTwoConnectionsRunIndependentlyAndCancelOnlyOwnJob(t *testing.T) { + e, j, workspace := realEngineConfigured(t, []Tool{helperTool(t)}, func(store *config.Store) { + cfg := store.Snapshot().Config() + c := config.NewConnection("connection-two", "second", "profile", "credential-two", true) + var err error + c, err = c.WithPurpose(config.PurposeAgentRemote) + if err != nil { + t.Fatal(err) + } + c, err = c.WithExecutionPolicy(config.ExecutionTrustedHost) + if err != nil { + t.Fatal(err) + } + mode, err := commandprofile.NewDeveloperMode(true, []string{"connection", "connection-two"}, commandprofile.ConfirmationPerCall, commandprofile.NetworkDeny) + if err != nil { + t.Fatal(err) + } + next, err := config.NewWithCommandProfiles(config.SchemaVersionV2, cfg.Roots(), cfg.Profiles(), append(cfg.Connections(), c), append(cfg.Credentials(), config.NewCredentialRef("credential-two", "runtime")), nil, mode, nil) + if err != nil { + t.Fatal(err) + } + if _, err = store.Replace(next); err != nil { + t.Fatal(err) + } + }) + subjects := []Subject{{"one", "connection"}, {"two", "connection-two"}} + ids := make([]string, 2) + for i, s := range subjects { + action := "wait" + if i == 1 { + action = "wait-two" + } + p, err := e.Prepare(context.Background(), s, Request{Nonce: action, Kind: "command", RootID: "workspace", ToolID: "helper", Args: []string{action}}) + if err != nil { + t.Fatal(err) + } + if _, err = e.Submit(s, p.ID, p.Digest); err != nil { + t.Fatal(err) + } + if err = j.Decide(p.ID, p.Digest, true, true); err != nil { + t.Fatal(err) + } + ids[i] = p.ID + } + end := time.Now().Add(5 * time.Second) + for { + _, one := os.Stat(filepath.Join(workspace, "started.txt")) + _, two := os.Stat(filepath.Join(workspace, "started-two.txt")) + if one == nil && two == nil { + break + } + if time.Now().After(end) { + t.Fatal("both real connection processes did not start concurrently") + } + time.Sleep(10 * time.Millisecond) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := e.Cancel(ctx, subjects[0], ids[1]); err != ErrDenied { + t.Fatal("cross-connection cancellation was accepted") + } + if result, err := e.Cancel(ctx, subjects[0], ids[0]); err != nil || result.State != "cancelled" { + t.Fatal("first job cancellation failed") + } + if result, err := e.Status(subjects[1], ids[1]); err != nil || result.State != "running" { + t.Fatal("cancelling one connection stopped the other") + } + if result, err := e.Cancel(ctx, subjects[1], ids[1]); err != nil || result.State != "cancelled" { + t.Fatal("second job cleanup failed") + } +} + +func TestOwnerCanCancelRunningJobWithoutAgent(t *testing.T) { + e, j, workspace := realEngine(t, []Tool{helperTool(t)}) + s := Subject{"principal", "connection"} + p := approved(t, e, j, Request{Nonce: "owner-cancel", Kind: "command", RootID: "workspace", ToolID: "helper", Args: []string{"wait"}}) + end := time.Now().Add(5 * time.Second) + for { + if _, err := os.Stat(filepath.Join(workspace, "started.txt")); err == nil { + break + } + if time.Now().After(end) { + t.Fatal("real child did not start") + } + time.Sleep(10 * time.Millisecond) + } + if err := j.CancelLocal(p.ID, p.Digest); err != nil { + t.Fatal(err) + } + waitState(t, e, s, p.ID, "cancelled") +} + +func TestSuccessfulParentExitReapsChildWithoutOutputHandles(t *testing.T) { + e, j, workspace := realEngine(t, []Tool{helperTool(t)}) + s := Subject{"principal", "connection"} + p := approved(t, e, j, Request{Nonce: "descendant", Kind: "command", RootID: "workspace", ToolID: "helper", Args: []string{"spawn"}}) + waitState(t, e, s, p.ID, "succeeded") + b, err := os.ReadFile(filepath.Join(workspace, "child.pid")) + if err != nil { + t.Fatal(err) + } + pid, err := strconv.ParseUint(string(b), 10, 32) + if err != nil { + t.Fatal(err) + } + h, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid)) + if err != nil { + if errors.Is(err, windows.ERROR_INVALID_PARAMETER) { + return + } + t.Fatalf("cannot verify descendant termination: %v", err) + } + defer windows.CloseHandle(h) + state, err := windows.WaitForSingleObject(h, 0) + if err != nil || state != windows.WAIT_OBJECT_0 { + t.Fatal("job reported success while its output-detached child was still running") + } +} diff --git a/internal/operations/journal.go b/internal/operations/journal.go new file mode 100644 index 0000000..814cec7 --- /dev/null +++ b/internal/operations/journal.go @@ -0,0 +1,285 @@ +package operations + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" +) + +const maxRecord = 2 << 20 +const maxJournal = 64 << 20 + +// Journal is owner-private and write-once. Partial or malformed records are +// retained and fail closed. Only Engine owns state transitions; the local CLI +// may append a separate decision. Do not put this directory inside a workspace. +type Journal struct { + root *os.Root + Path string +} + +func OpenJournal(path string, create bool) (*Journal, error) { + if !filepath.IsAbs(path) { + return nil, ErrStorage + } + if create { + if err := os.Mkdir(path, 0700); err != nil { + return nil, ErrStorage + } + if err := protectJournal(path); err != nil { + return nil, ErrStorage + } + } + info, err := os.Lstat(path) + if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return nil, ErrStorage + } + if err = checkPrivateJournal(path, info); err != nil { + return nil, ErrStorage + } + r, err := os.OpenRoot(path) + if err != nil { + return nil, ErrStorage + } + return &Journal{r, path}, nil +} +func (j *Journal) Close() error { return j.root.Close() } +func (j *Journal) write(name string, v any) error { + b, e := json.Marshal(v) + if e != nil || len(b) > maxRecord { + return ErrStorage + } + defer clear(b) + b, e = sealJournal(b) + if e != nil { + return ErrStorage + } + entries, e := j.root.ReadFile("journal.version") + if name != "journal.version" && (e != nil || string(entries) != Version) { + return ErrStorage + } + if e = j.checkSize(len(b)); e != nil { + return e + } + var random [16]byte + if _, e = rand.Read(random[:]); e != nil { + return ErrStorage + } + pending := "pending-" + hex.EncodeToString(random[:]) + f, e := j.root.OpenFile(pending, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if e != nil { + return ErrStorage + } + _, we := f.Write(b) + se := f.Sync() + ce := f.Close() + if we != nil || se != nil || ce != nil { + return ErrStorage + } + // Link publishes a complete write-once record atomically and refuses to + // replace an existing decision. Readers never observe partial approvals. + if e = j.root.Link(pending, name); e != nil { + return ErrStorage + } + if e = j.root.Remove(pending); e != nil { + return ErrStorage + } + return nil +} + +func (j *Journal) BeforeImage(id, expected string) ([]byte, error) { + if !validID(id) || !validID(expected) { + return nil, ErrInvalid + } + var v struct { + ID, Digest string + Data []byte + } + if j.read(id+".before", &v) != nil || v.ID != id || v.Digest != expected { + return nil, ErrDenied + } + return v.Data, nil +} +func (j *Journal) checkSize(extra int) error { + d, e := j.root.Open(".") + if e != nil { + return ErrStorage + } + defer d.Close() + entries, e := d.ReadDir(-1) + if e != nil || len(entries) > 4096 { + return ErrCapacity + } + total := int64(extra) + for _, entry := range entries { + info, e := entry.Info() + if e != nil { + if errors.Is(e, os.ErrNotExist) && (strings.HasPrefix(entry.Name(), "pending-") || strings.HasPrefix(entry.Name(), "run-")) { + continue + } + return ErrStorage + } + if info.IsDir() && strings.HasPrefix(entry.Name(), "run-") { + total += MaxContent + continue + } + if !info.Mode().IsRegular() { + return ErrStorage + } + total += info.Size() + } + if total > maxJournal { + return ErrCapacity + } + return nil +} +func (j *Journal) read(name string, v any) error { + i, e := j.root.Lstat(name) + if e != nil || !i.Mode().IsRegular() || i.Size() > 2*maxRecord { + return ErrStorage + } + f, e := j.root.Open(name) + if e != nil { + return ErrStorage + } + defer f.Close() + b, e := io.ReadAll(io.LimitReader(f, 2*maxRecord+1)) + if e != nil || len(b) > 2*maxRecord { + return ErrStorage + } + b, e = unsealJournal(b) + if e != nil { + return ErrStorage + } + defer clear(b) + d := json.NewDecoder(bytes.NewReader(b)) + d.DisallowUnknownFields() + if d.Decode(v) != nil { + return ErrStorage + } + if d.Decode(new(any)) != io.EOF { + return ErrStorage + } + return nil +} +func (j *Journal) Initialize() error { + f, e := j.root.OpenFile("journal.version", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if e != nil { + return ErrStorage + } + _, we := f.WriteString(Version) + se := f.Sync() + ce := f.Close() + if we != nil || se != nil || ce != nil { + return ErrStorage + } + return nil +} +func (j *Journal) Records() (map[string]Record, error) { + b, e := j.root.ReadFile("journal.version") + if e != nil || string(b) != Version { + return nil, ErrStorage + } + d, e := j.root.Open(".") + if e != nil { + return nil, ErrStorage + } + defer d.Close() + names, e := d.Readdirnames(-1) + if e != nil || len(names) > 4096 { + return nil, ErrStorage + } + sort.Strings(names) + result := map[string]Record{} + for _, name := range names { + if !strings.HasSuffix(name, ".record") { + continue + } + var r Record + if j.read(name, &r) != nil { + return nil, ErrStorage + } + if !validID(r.Summary.ID) || r.Version != Version || r.Summary.Digest != digest(r.Plan) || name != recordName(r) { + return nil, ErrStorage + } + old, ok := result[r.Summary.ID] + if (!ok && r.Sequence != 1) || (ok && (r.Sequence != old.Sequence+1 || old.Summary.Digest != r.Summary.Digest || terminal(old.Summary.State))) { + return nil, ErrStorage + } + result[r.Summary.ID] = r + } + return result, nil +} +func recordName(r Record) string { return fmt.Sprintf("%s.%06d.record", r.Summary.ID, r.Sequence) } +func (j *Journal) save(r Record) error { return j.write(recordName(r), r) } +func (j *Journal) decision(id string) (Decision, bool, error) { + var d Decision + if !validID(id) { + return d, false, ErrInvalid + } + _, e := j.root.Lstat(id + ".decision") + if errors.Is(e, os.ErrNotExist) { + return d, false, nil + } + if e != nil { + return d, false, ErrStorage + } + if e = j.read(id+".decision", &d); e != nil { + return d, false, e + } + return d, true, nil +} + +// Decide is a LOCAL control API. It is deliberately absent from MCP tools. +func (j *Journal) Decide(id, expected string, approve, ack bool) error { + if !validID(id) || !validID(expected) || approve && !ack { + return ErrInvalid + } + records, e := j.Records() + if e != nil { + return e + } + r, ok := records[id] + if !ok || r.Summary.Digest != expected || r.Summary.State != "awaiting_approval" { + return ErrConflict + } + d := Decision{Version: Version, ID: id, Digest: expected, Approved: approve, TrustedHostAcknowledged: ack, Expires: r.Summary.Expires} + return j.write(id+".decision", d) +} + +func (j *Journal) CancelLocal(id, expected string) error { + if !validID(id) || !validID(expected) { + return ErrInvalid + } + records, err := j.Records() + if err != nil { + return err + } + r, ok := records[id] + if !ok || r.Summary.Digest != expected || terminal(r.Summary.State) { + return ErrConflict + } + return j.write(id+".cancel", struct{ Version, ID, Digest string }{Version, id, expected}) +} +func (j *Journal) localCancel(r Record) (bool, error) { + name := r.Summary.ID + ".cancel" + _, err := j.root.Lstat(name) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, ErrStorage + } + var v struct{ Version, ID, Digest string } + if j.read(name, &v) != nil || v.Version != Version || v.ID != r.Summary.ID || v.Digest != r.Summary.Digest { + return false, ErrStorage + } + return true, nil +} diff --git a/internal/operations/lock_windows.go b/internal/operations/lock_windows.go new file mode 100644 index 0000000..8cb1da3 --- /dev/null +++ b/internal/operations/lock_windows.go @@ -0,0 +1,11 @@ +package operations + +import ( + "golang.org/x/sys/windows" + "os" +) + +type fsLock struct { + file *os.File + overlap windows.Overlapped +} diff --git a/internal/operations/protect_other.go b/internal/operations/protect_other.go new file mode 100644 index 0000000..f652c6b --- /dev/null +++ b/internal/operations/protect_other.go @@ -0,0 +1,22 @@ +//go:build !windows + +package operations + +import ( + "golang.org/x/sys/unix" + "io/fs" + "os" +) + +type fsLock struct{ file *os.File } + +func protectJournal(path string) error { return os.Chmod(path, 0700) } +func checkPrivateJournal(_ string, i fs.FileInfo) error { + if i.Mode().Perm()&0077 != 0 { + return ErrStorage + } + return nil +} +func sealJournal(b []byte) ([]byte, error) { return append([]byte(nil), b...), nil } +func unsealJournal(b []byte) ([]byte, error) { return append([]byte(nil), b...), nil } +func lockEngine(f *fsLock) error { return unix.Flock(int(f.file.Fd()), unix.LOCK_EX|unix.LOCK_NB) } diff --git a/internal/operations/protect_windows.go b/internal/operations/protect_windows.go new file mode 100644 index 0000000..eef66fb --- /dev/null +++ b/internal/operations/protect_windows.go @@ -0,0 +1,107 @@ +package operations + +import ( + "io/fs" + "runtime" + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +func protectJournal(path string) error { + u, e := windows.GetCurrentProcessToken().GetTokenUser() + if e != nil { + return e + } + s, e := windows.SecurityDescriptorFromString("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;" + u.User.Sid.String() + ")") + if e != nil { + return e + } + a, _, e := s.DACL() + if e != nil { + return e + } + return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, a, nil) +} +func checkPrivateJournal(path string, info fs.FileInfo) error { + attrs, ok := info.Sys().(*syscall.Win32FileAttributeData) + if !ok || attrs.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return ErrStorage + } + user, err := windows.GetCurrentProcessToken().GetTokenUser() + if err != nil { + return ErrStorage + } + actual, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) + if err != nil { + return ErrStorage + } + control, _, err := actual.Control() + if err != nil || control&windows.SE_DACL_PROTECTED == 0 { + return ErrStorage + } + acl, _, err := actual.DACL() + if err != nil || acl == nil || acl.AceCount != 2 { + return ErrStorage + } + system, err := windows.StringToSid("S-1-5-18") + if err != nil { + return ErrStorage + } + ownerSeen, systemSeen := false, false + for i := uint32(0); i < uint32(acl.AceCount); i++ { + var ace *windows.ACCESS_ALLOWED_ACE + if windows.GetAce(acl, i, &ace) != nil || ace == nil || ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE || ace.Header.AceFlags&windows.INHERIT_ONLY_ACE != 0 || ace.Mask != 0x001f01ff { // FILE_ALL_ACCESS + return ErrStorage + } + sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) + switch { + case windows.EqualSid(sid, user.User.Sid): + ownerSeen = true + case windows.EqualSid(sid, system): + systemSeen = true + default: + return ErrStorage + } + } + if !ownerSeen || !systemSeen { + return ErrStorage + } + return nil +} +func sealJournal(b []byte) ([]byte, error) { + var out windows.DataBlob + in := windows.DataBlob{Size: uint32(len(b)), Data: &b[0]} + e := windows.CryptProtectData(&in, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &out) + runtime.KeepAlive(b) + if e != nil { + return nil, e + } + defer windows.LocalFree(windows.Handle(unsafe.Pointer(out.Data))) + if out.Size > 2*maxRecord { + return nil, ErrStorage + } + return append([]byte(nil), unsafe.Slice(out.Data, int(out.Size))...), nil +} +func unsealJournal(b []byte) ([]byte, error) { + if len(b) == 0 { + return nil, ErrStorage + } + var out windows.DataBlob + in := windows.DataBlob{Size: uint32(len(b)), Data: &b[0]} + e := windows.CryptUnprotectData(&in, nil, nil, 0, nil, windows.CRYPTPROTECT_UI_FORBIDDEN, &out) + runtime.KeepAlive(b) + if e != nil { + return nil, e + } + defer windows.LocalFree(windows.Handle(unsafe.Pointer(out.Data))) + if out.Size > maxRecord { + return nil, ErrStorage + } + return append([]byte(nil), unsafe.Slice(out.Data, int(out.Size))...), nil +} +func lockEngine(f *fsLock) error { + f.overlap = windows.Overlapped{} + return windows.LockFileEx(windows.Handle(f.file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &f.overlap) +} diff --git a/internal/operations/protect_windows_test.go b/internal/operations/protect_windows_test.go new file mode 100644 index 0000000..ef128d2 --- /dev/null +++ b/internal/operations/protect_windows_test.go @@ -0,0 +1,30 @@ +package operations + +import ( + "golang.org/x/sys/windows" + "os" + "path/filepath" + "testing" +) + +func TestJournalRejectsSharedApprovalDirectory(t *testing.T) { + dir := filepath.Join(t.TempDir(), "shared") + if err := os.Mkdir(dir, 0700); err != nil { + t.Fatal(err) + } + sd, err := windows.SecurityDescriptorFromString("D:P(A;OICI;FA;;;WD)") + if err != nil { + t.Fatal(err) + } + dacl, _, err := sd.DACL() + if err != nil { + t.Fatal(err) + } + if err = windows.SetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil); err != nil { + t.Fatal(err) + } + if journal, err := OpenJournal(dir, false); err == nil { + journal.Close() + t.Fatal("shared directory accepted as trusted local approval authority") + } +} diff --git a/internal/operations/testhelper/main.go b/internal/operations/testhelper/main.go new file mode 100644 index 0000000..689fe4d --- /dev/null +++ b/internal/operations/testhelper/main.go @@ -0,0 +1,74 @@ +// Test-only process fixture. No package in the product imports this program. +package main + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "strconv" + "time" +) + +func main() { + if os.Getenv("LP_OPERATIONS_HELPER") != "1" || len(os.Args) != 2 { + os.Exit(3) + } + switch os.Args[1] { + case "grandchild": + if os.WriteFile("child.pid", []byte(strconv.Itoa(os.Getpid())), 0600) != nil { + os.Exit(2) + } + for { + time.Sleep(time.Second) + } + case "spawn": + child := exec.Command(os.Args[0], "grandchild") + child.Env = os.Environ() + if child.Start() != nil { + os.Exit(2) + } + end := time.Now().Add(3 * time.Second) + for { + if _, err := os.Stat("child.pid"); err == nil { + break + } + if time.Now().After(end) { + os.Exit(2) + } + time.Sleep(time.Millisecond) + } + fmt.Println("spawned child without inherited output pipes") + case "write": + f, err := os.OpenFile("count.txt", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + os.Exit(2) + } + if _, err = f.WriteString("once\n"); err != nil { + os.Exit(2) + } + if err = f.Close(); err != nil { + os.Exit(2) + } + fmt.Println("done") + case "wait", "wait-two": + marker := "started.txt" + if os.Args[1] == "wait-two" { + marker = "started-two.txt" + } + if os.WriteFile(marker, []byte("started"), 0600) != nil { + os.Exit(2) + } + for { + time.Sleep(time.Second) + } + case "flood": + os.Stdout.Write(bytes.Repeat([]byte("x"), 256<<10)) + case "environment": + fmt.Printf("secret=%s\n", os.Getenv("LP_UNAPPROVED_SECRET")) + case "--version": + fmt.Println("test-tool 1.2.3") + default: + os.Exit(3) + } +} diff --git a/internal/operations/types.go b/internal/operations/types.go new file mode 100644 index 0000000..2187ef5 --- /dev/null +++ b/internal/operations/types.go @@ -0,0 +1,131 @@ +// Package operations owns explicitly approved trusted-host jobs. It never treats +// a remote boolean, a transport credential, or a tool annotation as approval. +package operations + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "time" + + "github.com/LE-saber/Local-Probe/internal/policy" +) + +var ( + ErrInvalid = errors.New("invalid_operation") + ErrDenied = errors.New("operation_denied") + ErrConflict = errors.New("operation_conflict") + ErrStorage = errors.New("operation_storage_unavailable") + ErrCapacity = errors.New("operation_capacity") +) + +const Version = "local-probe.operations.v1" +const MaxContent = 128 << 10 + +// Subject is supplied ONLY by an authenticated ingress, never JSON arguments. +type Subject struct{ Principal, Connection string } + +type Request struct { + Nonce string `json:"nonce"` + Kind string `json:"kind"` + ToolID string `json:"tool_id,omitempty"` + RootID string `json:"root_id"` + Directory string `json:"directory,omitempty"` + Args []string `json:"args,omitempty"` + Script string `json:"script,omitempty"` + Path string `json:"path,omitempty"` + Content string `json:"content,omitempty"` + Edits []Edit `json:"edits,omitempty"` + TimeoutSeconds int `json:"timeout_seconds,omitempty"` +} +type Edit struct { + Old string `json:"old"` + New string `json:"new"` +} + +// Tool is a locally configured runner, not an executable path chosen by MCP. +type Tool struct { + ID string `json:"id"` + Executable string `json:"executable"` + SHA256 string `json:"sha256"` + ScriptType string `json:"script_type,omitempty"` // python, node, powershell, cmd + Environment []string `json:"environment,omitempty"` +} +type Catalog struct { + Version string `json:"version"` + Tools []Tool `json:"tools"` +} + +type Plan struct { + Subject Subject `json:"subject"` + Request Request `json:"request"` + Epoch string `json:"epoch"` + ExpectedFile string `json:"expected_file,omitempty"` + Before string `json:"before,omitempty"` + PatchedContent string `json:"patched_content,omitempty"` + ExecutableHash string `json:"executable_hash,omitempty"` +} + +type Summary struct { + ID string `json:"id"` + Digest string `json:"digest"` + State string `json:"state"` + Kind string `json:"kind"` + RootID string `json:"root_id"` + ToolID string `json:"tool_id,omitempty"` + Created time.Time `json:"created"` + Updated time.Time `json:"updated"` + Expires time.Time `json:"expires"` + ExitCode int64 `json:"exit_code"` + ErrorCode string `json:"error_code,omitempty"` + StdoutBytes int `json:"stdout_bytes"` + StderrBytes int `json:"stderr_bytes"` +} +type Record struct { + Version string `json:"version"` + Summary Summary `json:"summary"` + Plan Plan `json:"plan"` + Sequence int `json:"sequence"` + Stdout []byte `json:"stdout,omitempty"` + Stderr []byte `json:"stderr,omitempty"` +} +type Decision struct { + Version string `json:"version"` + ID string `json:"id"` + Digest string `json:"digest"` + Approved bool `json:"approved"` + TrustedHostAcknowledged bool `json:"trusted_host_acknowledged"` + Expires time.Time `json:"expires"` +} +type Output struct { + Data []byte `json:"data_base64"` + NextOffset int `json:"next_offset"` + Total int `json:"total"` +} + +type Workspace interface { + WithDirectory(policy.BoundScope, string, string, func(string) error) error + FilePreview(policy.BoundScope, string, string) (string, []byte, error) + WriteFile(policy.BoundScope, string, string, string, []byte, func([]byte) error) error +} + +func digest(v any) string { + b, _ := json.Marshal(v) + h := sha256.Sum256(b) + return hex.EncodeToString(h[:]) +} +func validID(s string) bool { + if len(s) != 64 { + return false + } + _, e := hex.DecodeString(s) + return e == nil +} +func terminal(s string) bool { + switch s { + case "succeeded", "failed", "cancelled", "interrupted", "unknown", "rejected", "expired": + return true + } + return false +} diff --git a/internal/peertransport/client.go b/internal/peertransport/client.go new file mode 100644 index 0000000..eac283c --- /dev/null +++ b/internal/peertransport/client.go @@ -0,0 +1,88 @@ +package peertransport + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "net" + "net/http" + "net/url" + "time" + + "github.com/gorilla/websocket" +) + +// HTTPClient creates an HTTP/1.1 client whose connections always use the fixed +// WSS destination and inner TLS. It never falls back to plaintext or follows +// redirects. Headers contain outer admission credentials and stay in-process. +func HTTPClient(endpoint string, inner *tls.Config, headers http.Header) (*http.Client, func(), error) { + return HTTPClientWithRoots(endpoint, inner, headers, nil) +} + +// HTTPClientWithRoots supports an explicitly trusted private Relay/edge CA. +// Nil uses the normal OS trust store; hostname verification remains enabled. +func HTTPClientWithRoots(endpoint string, inner *tls.Config, headers http.Header, outerRoots *x509.CertPool) (*http.Client, func(), error) { + return newHTTPClient(endpoint, inner, headers, outerRoots, false) +} + +const RelayReadyMessage = "local-probe.relay.ready.v1" + +// RelayHTTPClient consumes the Relay's bounded rendezvous marker before inner +// TLS begins. The marker grants no identity or operation permission. +func RelayHTTPClient(endpoint string, inner *tls.Config, headers http.Header, outerRoots *x509.CertPool) (*http.Client, func(), error) { + return newHTTPClient(endpoint, inner, headers, outerRoots, true) +} + +func newHTTPClient(endpoint string, inner *tls.Config, headers http.Header, outerRoots *x509.CertPool, ready bool) (*http.Client, func(), error) { + u, err := url.Parse(endpoint) + if err != nil || u.Scheme != "wss" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || inner == nil || inner.InsecureSkipVerify || inner.MinVersion < tls.VersionTLS13 { + return nil, nil, errors.New("explicit WSS endpoint and verified inner TLS required") + } + inner = inner.Clone() + headers = headers.Clone() + transport := &http.Transport{MaxConnsPerHost: 4, MaxIdleConnsPerHost: 4, IdleConnTimeout: 60 * time.Second, ResponseHeaderTimeout: 15 * time.Second, ForceAttemptHTTP2: false} + transport.DialTLSContext = func(ctx context.Context, _, _ string) (net.Conn, error) { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + stream, err := dialStream(ctx, endpoint, headers, outerRoots, ready) + if err != nil { + return nil, err + } + conn := tls.Client(stream, inner) + if err := conn.HandshakeContext(ctx); err != nil { + _ = stream.Close() + return nil, errors.New("remote peer authentication failed") + } + return conn, nil + } + return &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect rejected") }}, transport.CloseIdleConnections, nil +} + +func dialStream(ctx context.Context, endpoint string, headers http.Header, outerRoots *x509.CertPool, ready bool) (net.Conn, error) { + outerTLS := &tls.Config{MinVersion: tls.VersionTLS12} + if outerRoots != nil { + outerTLS.RootCAs = outerRoots.Clone() + } + dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second, EnableCompression: false, TLSClientConfig: outerTLS} + ws, resp, err := dialer.DialContext(ctx, endpoint, headers) + if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + return nil, errors.New("remote channel unavailable") + } + if ready { + stop := context.AfterFunc(ctx, func() { _ = ws.Close() }) + ws.SetReadLimit(16 << 10) + _ = ws.SetReadDeadline(time.Now().Add(35 * time.Second)) + kind, data, err := ws.ReadMessage() + stop() + if err != nil || kind != websocket.TextMessage || string(data) != RelayReadyMessage { + _ = ws.Close() + return nil, errors.New("Relay rendezvous unavailable") + } + _ = ws.SetReadDeadline(time.Time{}) + } + return NewStream(ws), nil +} diff --git a/internal/peertransport/http.go b/internal/peertransport/http.go new file mode 100644 index 0000000..6b02e8f --- /dev/null +++ b/internal/peertransport/http.go @@ -0,0 +1,34 @@ +package peertransport + +import ( + "context" + "crypto/tls" + "net/http" +) + +type identityKey struct{} + +// Identity returns the peer authenticated by inner mTLS, never a JSON/header ID. +func Identity(ctx context.Context) (Pin, bool) { + pin, ok := ctx.Value(identityKey{}).(Pin) + return pin, ok +} + +// AuthorizeHTTP rechecks revocation for every request, including requests on a +// previously authenticated keep-alive connection. The caller must additionally +// bind this identity to a connection scope before calling any tool handler. +// Passing nil dependencies is denied rather than defaulting to public access. +func AuthorizeHTTP(authorize func(Pin) bool, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if authorize == nil || next == nil || r.TLS == nil || r.TLS.Version < tls.VersionTLS13 || len(r.TLS.VerifiedChains) == 0 || len(r.TLS.PeerCertificates) == 0 { + http.Error(w, "peer authentication required", http.StatusUnauthorized) + return + } + pin := PublicKeyPin(r.TLS.PeerCertificates[0]) + if !authorize(pin) { + http.Error(w, "peer authorization revoked", http.StatusForbidden) + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), identityKey{}, pin))) + }) +} diff --git a/internal/peertransport/reverse.go b/internal/peertransport/reverse.go new file mode 100644 index 0000000..25e3b24 --- /dev/null +++ b/internal/peertransport/reverse.go @@ -0,0 +1,59 @@ +package peertransport + +import ( + "context" + "crypto/x509" + "errors" + "math/rand/v2" + "net/http" + "net/url" + "sync" + "time" +) + +// ServeRelay maintains four outbound rendezvous streams for this target. The +// Relay's route/outer credentials are independent of inner peer authorization. +// Reconnecting restores transport only; it never replays a tool call or job. +func (e *Endpoint) ServeRelay(ctx context.Context, endpoint string, headers http.Header, outerRoots *x509.CertPool) error { + u, err := url.Parse(endpoint) + if err != nil || u.Scheme != "wss" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return errors.New("explicit WSS Relay target endpoint required") + } + headers = headers.Clone() + var workers sync.WaitGroup + for range 4 { + workers.Add(1) + go func() { + defer workers.Done() + delay := time.Second + for ctx.Err() == nil { + raw, err := dialStream(ctx, endpoint, headers, outerRoots, true) + if err == nil { + done := make(chan struct{}) + tracked := &trackedConn{Conn: raw, onClose: func() { close(done) }} + if err = e.AcceptStream(ctx, tracked); err == nil { + delay = time.Second + select { + case <-done: + case <-ctx.Done(): + _ = tracked.Close() + } + } + } + if ctx.Err() != nil { + return + } + timer := time.NewTimer(delay + time.Duration(rand.Int64N(int64(delay/2)+1))) + select { + case <-ctx.Done(): + timer.Stop() + return + case <-timer.C: + } + delay = min(delay*2, 30*time.Second) + } + }() + } + workers.Wait() + return nil +} diff --git a/internal/peertransport/roots.go b/internal/peertransport/roots.go new file mode 100644 index 0000000..ee803b6 --- /dev/null +++ b/internal/peertransport/roots.go @@ -0,0 +1,50 @@ +package peertransport + +import ( + "bytes" + "crypto/x509" + "encoding/pem" + "errors" + "io" + "os" + "path/filepath" +) + +// LoadPublicRoots loads an explicitly trusted private edge/Relay CA. Empty path +// uses OS trust. Only public CA certificate PEM is allowed, never private keys. +func LoadPublicRoots(path string) (*x509.CertPool, error) { + if path == "" { + return nil, nil + } + if !filepath.IsAbs(path) { + return nil, errors.New("absolute public CA path required") + } + file, err := os.Open(path) + if err != nil { + return nil, errors.New("public CA unavailable") + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, 64<<10+1)) + if err != nil || len(data) > 64<<10 { + return nil, errors.New("invalid public CA") + } + roots := x509.NewCertPool() + count := 0 + for len(bytes.TrimSpace(data)) > 0 { + block, rest := pem.Decode(data) + if block == nil || block.Type != "CERTIFICATE" { + return nil, errors.New("only public CA certificate PEM allowed") + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil || !cert.IsCA { + return nil, errors.New("invalid public CA") + } + roots.AddCert(cert) + count++ + data = rest + } + if count == 0 { + return nil, errors.New("public CA required") + } + return roots, nil +} diff --git a/internal/peertransport/server.go b/internal/peertransport/server.go new file mode 100644 index 0000000..79dee76 --- /dev/null +++ b/internal/peertransport/server.go @@ -0,0 +1,171 @@ +package peertransport + +import ( + "context" + "crypto/tls" + "errors" + "net" + "net/http" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +// Endpoint upgrades an admitted outer connection and feeds inner-mTLS HTTP to +// the target's handler. It owns no public listener. The caller supplies bounded +// outer admission; inner TLS and per-request scope remain independently required. +type Endpoint struct { + mu sync.Mutex + closed bool + connections map[net.Conn]struct{} + slots chan struct{} + inner *tls.Config + admit func(*http.Request) bool + server *http.Server + listener *virtualListener + done chan struct{} +} + +func NewEndpoint(inner *tls.Config, handler http.Handler, admit func(*http.Request) bool) (*Endpoint, error) { + if inner == nil || inner.MinVersion < tls.VersionTLS13 || inner.ClientAuth != tls.RequireAndVerifyClientCert || inner.VerifyConnection == nil || handler == nil || admit == nil { + return nil, errors.New("authenticated peer endpoint required") + } + l := &virtualListener{incoming: make(chan net.Conn), closed: make(chan struct{})} + e := &Endpoint{connections: make(map[net.Conn]struct{}), slots: make(chan struct{}, 16), inner: inner.Clone(), admit: admit, listener: l, done: make(chan struct{})} + e.server = &http.Server{Handler: handler, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} + go func() { defer close(e.done); _ = e.server.Serve(l) }() + return e, nil +} + +func (e *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !e.admit(r) { + http.Error(w, "channel admission denied", http.StatusUnauthorized) + return + } + select { + case e.slots <- struct{}{}: + default: + http.Error(w, "channel capacity reached", http.StatusServiceUnavailable) + return + } + owned := false + defer func() { + if !owned { + <-e.slots + } + }() + e.mu.Lock() + closed := e.closed + e.mu.Unlock() + if closed { + http.Error(w, "endpoint closed", http.StatusServiceUnavailable) + return + } + upgrader := websocket.Upgrader{HandshakeTimeout: 10 * time.Second, EnableCompression: false, CheckOrigin: func(r *http.Request) bool { return r.Header.Get("Origin") == "" }} + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + stream := NewStream(ws) + owned = true // acceptStream now owns this reserved slot, including failures. + _ = e.acceptStream(r.Context(), stream) +} + +// AcceptStream accepts an externally admitted Relay stream. It takes ownership +// even on failure; all application requests still pass through inner mTLS. +func (e *Endpoint) AcceptStream(ctx context.Context, stream net.Conn) error { + select { + case e.slots <- struct{}{}: + default: + _ = stream.Close() + return errors.New("endpoint capacity reached") + } + return e.acceptStream(ctx, stream) +} + +// acceptStream is called with one reserved capacity slot. +func (e *Endpoint) acceptStream(parent context.Context, stream net.Conn) error { + owned := false + defer func() { + if !owned { + _ = stream.Close() + <-e.slots + } + }() + tracked := &trackedConn{Conn: stream} + tracked.onClose = func() { e.mu.Lock(); delete(e.connections, tracked); e.mu.Unlock(); <-e.slots } + e.mu.Lock() + if e.closed { + e.mu.Unlock() + _ = stream.Close() + return net.ErrClosed + } + e.connections[tracked] = struct{}{} + e.mu.Unlock() + owned = true + conn := tls.Server(tracked, e.inner) + ctx, cancel := context.WithTimeout(parent, 10*time.Second) + defer cancel() + if err := conn.HandshakeContext(ctx); err != nil { + _ = tracked.Close() + return err + } + select { + case e.listener.incoming <- conn: + case <-e.listener.closed: + _ = tracked.Close() + case <-ctx.Done(): + _ = tracked.Close() + } + return nil +} +func (e *Endpoint) Close() error { + e.mu.Lock() + e.closed = true + conns := make([]net.Conn, 0, len(e.connections)) + for c := range e.connections { + conns = append(conns, c) + } + e.mu.Unlock() + for _, c := range conns { + _ = c.Close() + } + err := e.server.Close() + <-e.done + return err +} + +type trackedConn struct { + net.Conn + once sync.Once + onClose func() +} + +func (c *trackedConn) Close() error { + var err error + c.once.Do(func() { err = c.Conn.Close(); c.onClose() }) + return err +} + +type virtualListener struct { + incoming chan net.Conn + closed chan struct{} + once sync.Once +} + +func (l *virtualListener) Accept() (net.Conn, error) { + select { + case <-l.closed: + return nil, net.ErrClosed + case c := <-l.incoming: + return c, nil + } +} +func (l *virtualListener) Close() error { l.once.Do(func() { close(l.closed) }); return nil } +func (l *virtualListener) Addr() net.Addr { return virtualAddr("paired-peer-stream") } + +type virtualAddr string + +func (a virtualAddr) Network() string { return "peer" } +func (a virtualAddr) String() string { return string(a) } diff --git a/internal/peertransport/tls.go b/internal/peertransport/tls.go new file mode 100644 index 0000000..0dedb7a --- /dev/null +++ b/internal/peertransport/tls.go @@ -0,0 +1,63 @@ +// Package peertransport implements the encrypted endpoint stream. It does not +// grant filesystem or execution access. Callers must authorize every request. +package peertransport + +import ( + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "errors" +) + +var ErrIdentity = errors.New("peer identity rejected") + +// Pin is the SHA-256 digest of a paired leaf certificate's public key. +// Pairing must deliver this value over an independently trusted channel. +type Pin [sha256.Size]byte + +func PublicKeyPin(cert *x509.Certificate) Pin { + return sha256.Sum256(cert.RawSubjectPublicKeyInfo) +} + +// ServerTLS requires a trusted Agent certificate AND an online authorization +// decision. authorize must be concurrency safe and must not trust client names. +func ServerTLS(identity tls.Certificate, roots *x509.CertPool, authorize func(Pin) bool) (*tls.Config, error) { + if len(identity.Certificate) == 0 || identity.PrivateKey == nil || roots == nil || authorize == nil { + return nil, ErrIdentity + } + return &tls.Config{ + MinVersion: tls.VersionTLS13, + Certificates: []tls.Certificate{identity}, + ClientAuth: tls.RequireAndVerifyClientCert, + ClientCAs: roots.Clone(), + SessionTicketsDisabled: true, + NextProtos: []string{"http/1.1"}, + VerifyConnection: func(state tls.ConnectionState) error { + if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 || !authorize(PublicKeyPin(state.PeerCertificates[0])) { + return ErrIdentity + } + return nil + }, + }, nil +} + +// ClientTLS retains normal chain and hostname verification before checking the +// paired target key. A relay-issued certificate alone cannot impersonate it. +func ClientTLS(identity tls.Certificate, roots *x509.CertPool, serverName string, target Pin) (*tls.Config, error) { + if len(identity.Certificate) == 0 || identity.PrivateKey == nil || roots == nil || serverName == "" || target == (Pin{}) { + return nil, ErrIdentity + } + return &tls.Config{ + MinVersion: tls.VersionTLS13, + Certificates: []tls.Certificate{identity}, + RootCAs: roots.Clone(), + ServerName: serverName, + NextProtos: []string{"http/1.1"}, + VerifyConnection: func(state tls.ConnectionState) error { + if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 || PublicKeyPin(state.PeerCertificates[0]) != target { + return ErrIdentity + } + return nil + }, + }, nil +} diff --git a/internal/peertransport/transport_test.go b/internal/peertransport/transport_test.go new file mode 100644 index 0000000..46a022a --- /dev/null +++ b/internal/peertransport/transport_test.go @@ -0,0 +1,297 @@ +package peertransport + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "io" + "math/big" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +type testPKI struct { + roots *x509.CertPool + target, agent tls.Certificate + targetPin, agentPin Pin +} + +// Certificates are ephemeral test fixtures, never installed in OS trust stores. +func newPKI(t *testing.T) testPKI { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + now := time.Now() + ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-only"}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} + der, err := x509.CreateCertificate(rand.Reader, ca, ca, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + ca, err = x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + roots := x509.NewCertPool() + roots.AddCert(ca) + issue := func(serial int64, usage x509.ExtKeyUsage) (tls.Certificate, Pin) { + k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + leaf := &x509.Certificate{SerialNumber: big.NewInt(serial), DNSNames: []string{"target.test"}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{usage}} + b, err := x509.CreateCertificate(rand.Reader, leaf, ca, &k.PublicKey, key) + if err != nil { + t.Fatal(err) + } + priv, err := x509.MarshalPKCS8PrivateKey(k) + if err != nil { + t.Fatal(err) + } + pair, err := tls.X509KeyPair(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: priv})) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(b) + if err != nil { + t.Fatal(err) + } + return pair, PublicKeyPin(cert) + } + target, targetPin := issue(2, x509.ExtKeyUsageServerAuth) + agent, agentPin := issue(3, x509.ExtKeyUsageClientAuth) + return testPKI{roots, target, agent, targetPin, agentPin} +} + +func TestMutualTLSRejectsUnpairedAndRevokedPeers(t *testing.T) { + p := newPKI(t) + for _, tc := range []struct { + name string + pin Pin + allowed bool + }{ + {"paired", p.targetPin, true}, {"wrong-target", Pin{1}, true}, {"revoked-agent", p.targetPin, false}, + } { + t.Run(tc.name, func(t *testing.T) { + scfg, err := ServerTLS(p.target, p.roots, func(pin Pin) bool { return tc.allowed && pin == p.agentPin }) + if err != nil { + t.Fatal(err) + } + ccfg, err := ClientTLS(p.agent, p.roots, "target.test", tc.pin) + if err != nil { + t.Fatal(err) + } + a, b := net.Pipe() + defer a.Close() + defer b.Close() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { done <- tls.Server(a, scfg).HandshakeContext(ctx) }() + clientErr := tls.Client(b, ccfg).HandshakeContext(ctx) + serverErr := <-done + if tc.name == "paired" { + if clientErr != nil || serverErr != nil { + t.Fatalf("handshake: %v / %v", clientErr, serverErr) + } + } else if clientErr == nil && serverErr == nil { + t.Fatal("unpaired handshake accepted") + } + }) + } +} + +func TestHTTPAuthorizationRejectsPlaintextAndHeaderIdentity(t *testing.T) { + called := false + handler := AuthorizeHTTP(func(Pin) bool { return true }, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true })) + req := httptest.NewRequest(http.MethodPost, "https://127.0.0.1/mcp", nil) + req.Header.Set("X-Peer-Identity", "paired-agent") + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, req) + if recorder.Code != http.StatusUnauthorized || called { + t.Fatal("unauthenticated identity reached handler") + } +} + +func TestStreamRejectsTextAndOversizedMessages(t *testing.T) { + for _, kind := range []int{websocket.TextMessage, websocket.BinaryMessage} { + t.Run(map[int]string{websocket.TextMessage: "text", websocket.BinaryMessage: "oversized"}[kind], func(t *testing.T) { + upgrader := websocket.Upgrader{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + _ = conn.WriteMessage(kind, []byte(strings.Repeat("x", MaxMessageBytes+1))) + })) + defer srv.Close() + ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http"), nil) + if err != nil { + t.Fatal(err) + } + stream := NewStream(ws) + defer stream.Close() + _ = stream.SetReadDeadline(time.Now().Add(time.Second)) + if _, err = io.ReadAll(stream); err == nil { + t.Fatal("invalid message accepted") + } + // A failed stream must return its cached error rather than repeatedly + // calling Gorilla's NextReader until it panics. + for range 1100 { + if _, err = stream.Read(make([]byte, 1)); err == nil { + t.Fatal("failed stream recovered") + } + } + }) + } +} + +func TestReadDeadlineCanBeResetWithoutPoisoningWebSocket(t *testing.T) { + send := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upgrader := websocket.Upgrader{} + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer ws.Close() + <-send + _ = ws.WriteMessage(websocket.BinaryMessage, []byte("recovered")) + })) + defer srv.Close() + ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http"), nil) + if err != nil { + t.Fatal(err) + } + stream := NewStream(ws) + defer stream.Close() + _ = stream.SetReadDeadline(time.Now().Add(10 * time.Millisecond)) + if _, err = stream.Read(make([]byte, 1)); err == nil { + t.Fatal("read did not time out") + } else if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() { + t.Fatalf("wrong timeout: %v", err) + } + _ = stream.SetReadDeadline(time.Time{}) + close(send) + buffer := make([]byte, len("recovered")) + if _, err = io.ReadFull(stream, buffer); err != nil || string(buffer) != "recovered" { + t.Fatalf("deadline poisoned reader: %q / %v", buffer, err) + } +} + +// This exercises the official SDK through real outer WSS and inner mTLS, with +// no public listener and no changes to the user's running MCP service. +func TestOfficialMCPOverWSSWithInnerTLS(t *testing.T) { + p := newPKI(t) + var allowed atomic.Bool + allowed.Store(true) + scfg, err := ServerTLS(p.target, p.roots, func(pin Pin) bool { return allowed.Load() && pin == p.agentPin }) + if err != nil { + t.Fatal(err) + } + ccfg, err := ClientTLS(p.agent, p.roots, "target.test", p.targetPin) + if err != nil { + t.Fatal(err) + } + server := mcp.NewServer(&mcp.Implementation{Name: "encrypted-test", Version: "test"}, nil) + server.AddTool(&mcp.Tool{Name: "echo", InputSchema: map[string]any{"type": "object"}}, func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: strings.Repeat("x", MaxMessageBytes+7)}}}, nil + }) + mcpHandler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true}) + // Revocation must be enforced per request on an already established channel. + handler := AuthorizeHTTP(func(pin Pin) bool { return allowed.Load() && pin == p.agentPin }, mcpHandler) + httpServer := &http.Server{Handler: handler, ReadHeaderTimeout: time.Second, MaxHeaderBytes: 16 << 10} + defer httpServer.Close() + upgrader := websocket.Upgrader{EnableCompression: false} + outer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ws, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + stream := NewStream(ws) + conn := tls.Server(stream, scfg) + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := conn.HandshakeContext(ctx); err != nil { + _ = stream.Close() + return + } + // http.Server owns the accepted encrypted connection from here. + go func() { _ = httpServer.Serve(&oneConnListener{conn: conn, done: make(chan struct{})}) }() + })) + defer outer.Close() + transport := &http.Transport{ForceAttemptHTTP2: false, DialTLSContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + dialer := websocket.Dialer{TLSClientConfig: outer.Client().Transport.(*http.Transport).TLSClientConfig.Clone(), HandshakeTimeout: 2 * time.Second} + ws, _, err := dialer.DialContext(ctx, "wss"+strings.TrimPrefix(outer.URL, "https"), nil) + if err != nil { + return nil, err + } + stream := NewStream(ws) + conn := tls.Client(stream, ccfg) + if err := conn.HandshakeContext(ctx); err != nil { + _ = stream.Close() + return nil, err + } + return conn, nil + }} + defer transport.CloseIdleConnections() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client := mcp.NewClient(&mcp.Implementation{Name: "test-agent", Version: "test"}, nil) + session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: "https://127.0.0.1/mcp", HTTPClient: &http.Client{Transport: transport}, DisableStandaloneSSE: true, MaxRetries: -1}, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "echo", Arguments: map[string]any{}}) + if err != nil { + t.Fatal(err) + } + if result.IsError || len(result.Content) != 1 || len(result.Content[0].(*mcp.TextContent).Text) != MaxMessageBytes+7 { + t.Fatal("large result corrupted") + } + allowed.Store(false) + if _, err := session.ListTools(ctx, nil); err == nil { + t.Fatal("revoked peer retained access") + } +} + +// Test-only listener hands an established connection to net/http once. +type oneConnListener struct { + conn net.Conn + done chan struct{} + handed bool +} + +func (l *oneConnListener) Accept() (net.Conn, error) { + if !l.handed { + l.handed = true + return l.conn, nil + } + <-l.done + return nil, io.EOF +} +func (l *oneConnListener) Close() error { + select { + case <-l.done: + default: + close(l.done) + } + return l.conn.Close() +} +func (l *oneConnListener) Addr() net.Addr { return l.conn.LocalAddr() } diff --git a/internal/peertransport/websocket.go b/internal/peertransport/websocket.go new file mode 100644 index 0000000..9c77e7f --- /dev/null +++ b/internal/peertransport/websocket.go @@ -0,0 +1,174 @@ +package peertransport + +import ( + "errors" + "net" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +const MaxMessageBytes = 64 << 10 + +// Stream converts an already established, externally authenticated WebSocket +// into an ordered stream for inner TLS. Never serve plaintext MCP over Stream. +// Read deadlines are implemented above Gorilla: net/http deliberately uses a +// temporary read deadline to abort its background read between requests. Giving +// that deadline to Gorilla would permanently poison its reader. Write failures +// remain terminal for TLS and require reconnecting. +type Stream struct { + ws *websocket.Conn + readMu sync.Mutex + writeMu sync.Mutex + pending []byte + readErr error + reads chan streamRead + closed chan struct{} + closeOnce sync.Once + deadlineMu sync.Mutex + readDeadline time.Time + writeDeadline time.Time + deadlineChanged chan struct{} +} +type streamRead struct { + data []byte + err error +} +type deadlineError struct{} + +func (deadlineError) Error() string { return "peer stream deadline exceeded" } +func (deadlineError) Timeout() bool { return true } +func (deadlineError) Temporary() bool { return true } + +var _ net.Conn = (*Stream)(nil) + +// NewStream must be called before any concurrent WebSocket reads or writes. +// Compression must be disabled at both the dialer and upgrader. +func NewStream(ws *websocket.Conn) *Stream { + ws.SetReadLimit(MaxMessageBytes) + ws.EnableWriteCompression(false) + s := &Stream{ws: ws, reads: make(chan streamRead, 1), closed: make(chan struct{}), deadlineChanged: make(chan struct{})} + go s.readPump() + return s +} + +func (s *Stream) readPump() { + for { + kind, data, err := s.ws.ReadMessage() + if err == nil && kind != websocket.BinaryMessage { + err = errors.New("non-binary peer stream message") + } + select { + case s.reads <- streamRead{data, err}: + case <-s.closed: + return + } + if err != nil { + return + } + } +} + +func (s *Stream) Read(p []byte) (int, error) { + s.readMu.Lock() + defer s.readMu.Unlock() + if len(p) == 0 { + return 0, nil + } + if s.readErr != nil { + return 0, s.readErr + } + for { + s.deadlineMu.Lock() + deadline, changed := s.readDeadline, s.deadlineChanged + s.deadlineMu.Unlock() + if !deadline.IsZero() && !time.Now().Before(deadline) { + return 0, deadlineError{} + } + if len(s.pending) > 0 { + n := copy(p, s.pending) + s.pending = s.pending[n:] + return n, nil + } + var timer *time.Timer + var timeout <-chan time.Time + if !deadline.IsZero() { + timer = time.NewTimer(time.Until(deadline)) + timeout = timer.C + } + select { + case <-s.closed: + if timer != nil { + timer.Stop() + } + return 0, net.ErrClosed + case <-changed: + if timer != nil { + timer.Stop() + } + continue + case <-timeout: + return 0, deadlineError{} + case value := <-s.reads: + if timer != nil { + timer.Stop() + } + if value.err != nil { + s.readErr = value.err + return 0, value.err + } + s.pending = value.data + } + } +} + +func (s *Stream) Write(p []byte) (int, error) { + s.writeMu.Lock() + defer s.writeMu.Unlock() + written := 0 + for len(p) > 0 { + n := min(len(p), MaxMessageBytes) + s.deadlineMu.Lock() + deadline := s.writeDeadline + s.deadlineMu.Unlock() + if err := s.ws.SetWriteDeadline(deadline); err != nil { + return written, err + } + if err := s.ws.WriteMessage(websocket.BinaryMessage, p[:n]); err != nil { + return written, err + } + written += n + p = p[n:] + } + return written, nil +} + +func (s *Stream) Close() error { + var err error + s.closeOnce.Do(func() { close(s.closed); err = s.ws.Close() }) + return err +} +func (s *Stream) LocalAddr() net.Addr { return s.ws.LocalAddr() } +func (s *Stream) RemoteAddr() net.Addr { return s.ws.RemoteAddr() } + +func (s *Stream) SetDeadline(t time.Time) error { + if err := s.SetReadDeadline(t); err != nil { + return err + } + return s.SetWriteDeadline(t) +} +func (s *Stream) SetReadDeadline(t time.Time) error { + s.deadlineMu.Lock() + s.readDeadline = t + close(s.deadlineChanged) + s.deadlineChanged = make(chan struct{}) + s.deadlineMu.Unlock() + return nil +} +func (s *Stream) SetWriteDeadline(t time.Time) error { + s.deadlineMu.Lock() + s.writeDeadline = t + s.deadlineMu.Unlock() + return s.ws.UnderlyingConn().SetWriteDeadline(t) +} diff --git a/internal/policy/policy.go b/internal/policy/policy.go index ee48ba1..4a3d44d 100644 --- a/internal/policy/policy.go +++ b/internal/policy/policy.go @@ -1,5 +1,6 @@ -// Package policy binds authenticated connections to immutable, read-only -// configuration snapshots. It does not open files or authenticate transport. +// Package policy binds authenticated connections to immutable configuration +// snapshots. The readcore scope stays read-only; AllowsWrites is an independent +// explicit v2 grant. Policy does not open files or authenticate transport. package policy import ( @@ -42,6 +43,7 @@ type BoundScope struct { revision string tools map[string]struct{} roots map[string]rootPolicy + readOnly bool } type rootPolicy struct { @@ -62,7 +64,7 @@ func (m *Manager) BindAuthenticated(connectionID string) (BoundScope, error) { return BoundScope{}, fmt.Errorf("%w: connection unavailable", ErrDenied) } profile, ok := cfg.Profile(connection.ProfileID()) - if !ok || !profile.ReadOnly() { + if !ok || !profile.ReadOnly() && cfg.SchemaVersion() != config.SchemaVersionV2 { return BoundScope{}, fmt.Errorf("%w: profile unavailable", ErrDenied) } scope, err := readcore.NewScope(connection.ID(), snapshot.Revision(), profile.RootIDs()) @@ -95,6 +97,7 @@ func (m *Manager) BindAuthenticated(connectionID string) (BoundScope, error) { revision: snapshot.Revision(), tools: tools, roots: roots, + readOnly: profile.ReadOnly(), }, nil } @@ -113,6 +116,10 @@ func (m *Manager) Validate(bound BoundScope) error { if !ok || !connection.Enabled() || connection.ProfileID() != bound.profileID { return ErrRevoked } + profile, ok := cfg.Profile(bound.profileID) + if !ok || profile.ReadOnly() != bound.readOnly { + return ErrRevoked + } if bound.scope.ConnectionID() != bound.connectionID || bound.scope.ProfileRevision() != bound.revision { return ErrRevoked } @@ -144,6 +151,21 @@ func (b BoundScope) ProfileID() string { return b.profileID } func (b BoundScope) Revision() string { return b.revision } +func (b BoundScope) AllowsWrites() bool { return b.Validate() == nil && !b.readOnly } + +// AcquireRevisionLease is a short commit/launch guard, not a job-long lock. +// Callers must not recursively call scope methods while holding this lease. +func (b BoundScope) AcquireRevisionLease() (func(), error) { + if b.manager == nil || b.revision == "" { + return nil, ErrRevoked + } + release, ok := b.manager.store.AcquireRevisionLease(b.revision) + if !ok { + return nil, ErrRevoked + } + return release, nil +} + func (b BoundScope) AllowsTool(tool string) bool { if b.Validate() != nil { return false diff --git a/internal/probe/process.go b/internal/probe/process.go index bfdf3bf..08f71b9 100644 --- a/internal/probe/process.go +++ b/internal/probe/process.go @@ -9,6 +9,7 @@ type managedProcess struct { stderr ioReadCloser wait func() (int64, error) kill func() error + reap func() error close func() } diff --git a/internal/probe/process_windows.go b/internal/probe/process_windows.go index 27d0312..2a16684 100644 --- a/internal/probe/process_windows.go +++ b/internal/probe/process_windows.go @@ -9,6 +9,7 @@ import ( "sort" "strings" "sync" + "time" "unicode/utf16" "unsafe" @@ -29,6 +30,14 @@ type windowsProcess struct { } func startFixedProcess(ctx context.Context, path string, args []string, cwd string, env []string, expected fileIdentity, expectedSHA256 string) (*managedProcess, error) { + return startManagedProcess(ctx, path, args, cwd, env, expected, expectedSHA256, false) +} + +func startTrustedProcess(ctx context.Context, path string, args []string, cwd string, env []string, expected fileIdentity, expectedSHA256 string) (*managedProcess, error) { + return startManagedProcess(ctx, path, args, cwd, env, expected, expectedSHA256, true) +} + +func startManagedProcess(ctx context.Context, path string, args []string, cwd string, env []string, expected fileIdentity, expectedSHA256 string, trustedSubtree bool) (*managedProcess, error) { if path == "" || cwd == "" { return nil, ErrInvalidInput } @@ -61,10 +70,16 @@ func startFixedProcess(ctx context.Context, path string, args []string, cwd stri return nil, ErrUnavailable } state := &windowsProcess{job: job, process: windows.InvalidHandle, thread: windows.InvalidHandle} - if err := configureKillOnClose(job); err != nil { + if err := configureProcessJob(job, trustedSubtree); err != nil { state.close() return nil, ErrUnavailable } + if trustedSubtree { + if err := configureTrustedCPUTime(job, ctx); err != nil { + state.close() + return nil, ErrUnavailable + } + } stdinRead, stdinWrite, stdoutRead, stdoutWrite, stderrRead, stderrWrite, err := makeProbePipes() if err != nil { @@ -208,6 +223,7 @@ func startFixedProcess(ctx context.Context, path string, args []string, cwd stri stderr: stderr, wait: state.wait, kill: state.kill, + reap: state.reap, close: func() { // Closing the readers is safe after the capture goroutines have // completed and also makes the ownership explicit if a future @@ -250,9 +266,18 @@ func makeProbePipes() (stdinRead, stdinWrite, stdoutRead, stdoutWrite, stderrRea } func configureKillOnClose(job windows.Handle) error { + return configureProcessJob(job, false) +} + +func configureProcessJob(job windows.Handle, trustedSubtree bool) error { info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{} info.BasicLimitInformation.LimitFlags = windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | windows.JOB_OBJECT_LIMIT_ACTIVE_PROCESS info.BasicLimitInformation.ActiveProcessLimit = 1 + if trustedSubtree { + info.BasicLimitInformation.ActiveProcessLimit = 32 + info.BasicLimitInformation.LimitFlags |= windows.JOB_OBJECT_LIMIT_JOB_MEMORY + info.JobMemoryLimit = 1 << 30 + } _, err := windows.SetInformationJobObject( job, windows.JobObjectExtendedLimitInformation, @@ -262,6 +287,25 @@ func configureKillOnClose(job windows.Handle) error { return err } +func configureTrustedCPUTime(job windows.Handle, ctx context.Context) error { + deadline, ok := ctx.Deadline() + if !ok { + return ErrInvalidInput + } + remaining := time.Until(deadline) + if remaining <= 0 { + return ErrDeadlineExceeded + } + var info windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION + if err := windows.QueryInformationJobObject(job, windows.JobObjectExtendedLimitInformation, uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info)), nil); err != nil { + return err + } + info.BasicLimitInformation.LimitFlags |= windows.JOB_OBJECT_LIMIT_JOB_TIME + info.BasicLimitInformation.PerJobUserTimeLimit = int64(remaining / (100 * time.Nanosecond)) + _, err := windows.SetInformationJobObject(job, windows.JobObjectExtendedLimitInformation, uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info))) + return err +} + func (state *windowsProcess) wait() (int64, error) { state.mu.Lock() process := state.process @@ -304,6 +348,34 @@ func (state *windowsProcess) kill() error { return nil } +// TerminateJobObject is asynchronous. Confirm the bounded process list is +// actually empty before reporting a trusted job as fully cancelled/completed. +func (state *windowsProcess) reap() error { + deadline := time.Now().Add(5 * time.Second) + for { + var list struct { + Assigned, Count uint32 + IDs [32]uintptr + } + state.mu.Lock() + job := state.job + closed := state.closed + if closed || job == windows.InvalidHandle { + state.mu.Unlock() + return ErrUnavailable + } + err := windows.QueryInformationJobObject(job, windows.JobObjectBasicProcessIdList, uintptr(unsafe.Pointer(&list)), uint32(unsafe.Sizeof(list)), nil) + state.mu.Unlock() + if err == nil && list.Count == 0 && list.Assigned == 0 { + return nil + } + if err != nil || time.Now().After(deadline) { + return ErrUnavailable + } + time.Sleep(5 * time.Millisecond) + } +} + func (state *windowsProcess) terminateSetup() { state.mu.Lock() if state.closed { diff --git a/internal/probe/trusted.go b/internal/probe/trusted.go new file mode 100644 index 0000000..3bde752 --- /dev/null +++ b/internal/probe/trusted.go @@ -0,0 +1,125 @@ +package probe + +import ( + "context" + "encoding/hex" + "errors" + "path/filepath" + "strings" + "time" +) + +var ErrCleanupUnconfirmed = errors.New("process_tree_cleanup_unconfirmed") + +// TrustedProcessSpec is a LOCAL approved execution plan, not a model request. +// This mode has current-user OS access; it provides no filesystem/network sandbox. +// The caller owns approval, connection authorization, audit and revocation. +type TrustedProcessSpec struct { + Executable ExecutableDescriptor + SHA256 string + Args []string + Directory string + Environment []string + Timeout time.Duration + OutputBytes int + // AcquireLaunch is an optional local revision guard. It must not come from + // wire input, and is held only until the process is created and resumed. + AcquireLaunch func() (func(), error) +} + +type TrustedProcessResult struct { + Stdout, Stderr []byte + ExitCode int64 +} + +// RunTrustedProcess is separate from fixed probes so their original one-process, +// version-only contract stays intact. No MCP or GUI adapter exposes this API yet. +func RunTrustedProcess(ctx context.Context, spec TrustedProcessSpec) (TrustedProcessResult, error) { + result := TrustedProcessResult{ExitCode: -1} + if ctx == nil || validateDescriptor(spec.Executable) != nil || !filepath.IsAbs(spec.Directory) || strings.ContainsRune(spec.Directory, 0) || spec.Timeout <= 0 || spec.Timeout > 30*time.Minute || spec.OutputBytes <= 0 || spec.OutputBytes > 10<<20 || len(spec.Args) > 128 || len(spec.Environment) > 128 || len(spec.SHA256) != 64 { + return result, ErrInvalidInput + } + if _, err := hex.DecodeString(spec.SHA256); err != nil { + return result, ErrInvalidInput + } + for _, arg := range spec.Args { + if len(arg) > 4096 || strings.ContainsRune(arg, 0) { + return result, ErrInvalidInput + } + } + if !processExecutionSupported() { + return result, ErrUnsupported + } + ctx, cancel := context.WithTimeout(ctx, spec.Timeout) + defer cancel() + var release func() + if spec.AcquireLaunch != nil { + var err error + release, err = spec.AcquireLaunch() + if err != nil || release == nil { + return result, ErrCancelled + } + } + process, err := startTrustedProcess(ctx, spec.Executable.Path, append([]string(nil), spec.Args...), spec.Directory, append([]string(nil), spec.Environment...), spec.Executable.identity, spec.SHA256) + if release != nil { + release() + } + if err != nil { + return result, err + } + defer process.close() + out, stderr := make(chan streamResult, 1), make(chan streamResult, 1) + go captureStream(process.stdout, spec.OutputBytes, out) + go captureStream(process.stderr, spec.OutputBytes, stderr) + wait := make(chan processWaitResult, 1) + go func() { code, err := process.wait(); wait <- processWaitResult{code, err} }() + done := ctx.Done() + var firstErr error + stop := func(err error) { + if firstErr == nil { + firstErr = err + } + _ = process.kill() + } + for out != nil || stderr != nil || wait != nil { + select { + case value := <-out: + result.Stdout = value.data + out = nil + if value.err != nil { + stop(value.err) + } + case value := <-stderr: + result.Stderr = value.data + stderr = nil + if value.err != nil { + stop(value.err) + } + case value := <-wait: + result.ExitCode = value.exitCode + wait = nil + // Reap descendants even when the original process exits naturally. + if err := process.kill(); err != nil && firstErr == nil { + firstErr = ErrUnavailable + } + if value.err != nil && firstErr == nil { + firstErr = ErrUnavailable + } + case <-done: + stop(contextExecutionError(ctx)) + done = nil + } + } + if process.reap != nil { + if err := process.reap(); err != nil { + return result, ErrCleanupUnconfirmed + } + } + if firstErr != nil { + return result, firstErr + } + if result.ExitCode != 0 { + return result, ErrChildExit + } + return result, nil +} diff --git a/internal/probe/trusted_limits_windows_test.go b/internal/probe/trusted_limits_windows_test.go new file mode 100644 index 0000000..1244016 --- /dev/null +++ b/internal/probe/trusted_limits_windows_test.go @@ -0,0 +1,33 @@ +package probe + +import ( + "context" + "golang.org/x/sys/windows" + "testing" + "time" + "unsafe" +) + +func TestTrustedJobLimitsAreInstalledInKernel(t *testing.T) { + job, err := windows.CreateJobObject(nil, nil) + if err != nil { + t.Fatal(err) + } + defer windows.CloseHandle(job) + if err = configureProcessJob(job, true); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err = configureTrustedCPUTime(job, ctx); err != nil { + t.Fatal(err) + } + var actual windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION + if err = windows.QueryInformationJobObject(job, windows.JobObjectExtendedLimitInformation, uintptr(unsafe.Pointer(&actual)), uint32(unsafe.Sizeof(actual)), nil); err != nil { + t.Fatal(err) + } + flags := uint32(windows.JOB_OBJECT_LIMIT_JOB_MEMORY | windows.JOB_OBJECT_LIMIT_JOB_TIME | windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | windows.JOB_OBJECT_LIMIT_ACTIVE_PROCESS) + if actual.BasicLimitInformation.LimitFlags&flags != flags || actual.JobMemoryLimit != 1<<30 || actual.BasicLimitInformation.ActiveProcessLimit != 32 || actual.BasicLimitInformation.PerJobUserTimeLimit <= 0 || actual.BasicLimitInformation.PerJobUserTimeLimit > 3*10000000 { + t.Fatal("kernel job limits do not match the trusted-host contract") + } +} diff --git a/internal/probe/trusted_unsupported.go b/internal/probe/trusted_unsupported.go new file mode 100644 index 0000000..0e66772 --- /dev/null +++ b/internal/probe/trusted_unsupported.go @@ -0,0 +1,9 @@ +//go:build !windows + +package probe + +import "context" + +func startTrustedProcess(context.Context, string, []string, string, []string, fileIdentity, string) (*managedProcess, error) { + return nil, ErrUnsupported +} diff --git a/internal/probe/trusted_windows_test.go b/internal/probe/trusted_windows_test.go new file mode 100644 index 0000000..3f43a8e --- /dev/null +++ b/internal/probe/trusted_windows_test.go @@ -0,0 +1,50 @@ +//go:build windows + +package probe + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func TestTrustedHostRealExecution(t *testing.T) { + for _, action := range []string{"fake-node", "fake-timeout", "fake-overoutput"} { + t.Run(action, func(t *testing.T) { + exe := helperPath(action) + descriptor, err := AuditExecutable(ToolVersionGeneric, exe) + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(exe) + if err != nil { + t.Fatal(err) + } + hash := sha256.Sum256(data) + dir := t.TempDir() + spec := TrustedProcessSpec{Executable: descriptor, SHA256: hex.EncodeToString(hash[:]), Args: []string{"--version"}, Directory: dir, Environment: []string{"SystemRoot=" + filepath.Clean(os.Getenv("SystemRoot")), "TEMP=" + dir, "TMP=" + dir}, Timeout: 3 * time.Second, OutputBytes: 4096} + if action == "fake-timeout" { + spec.Timeout = 250 * time.Millisecond + } + result, err := RunTrustedProcess(context.Background(), spec) + if action == "fake-node" { + if err != nil || string(result.Stdout) != "v1.2.3\n" || result.ExitCode != 0 { + t.Fatalf("result=%+v err=%v", result, err) + } + } else { + want := ErrOutputLimit + if action == "fake-timeout" { + want = ErrDeadlineExceeded + } + if !errors.Is(err, want) { + t.Fatalf("%s error=%v, want %v", action, err, want) + } + } + }) + } +} diff --git a/internal/relay/cli_windows_test.go b/internal/relay/cli_windows_test.go new file mode 100644 index 0000000..2339b54 --- /dev/null +++ b/internal/relay/cli_windows_test.go @@ -0,0 +1,169 @@ +//go:build windows + +package relay + +import ( + "context" + "encoding/json" + "encoding/pem" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// Builds and launches the REAL target and Agent CLIs. The Agent is controlled +// through the official SDK's stdio CommandTransport, not an in-memory stand-in. +func TestWindowsRealCLIReadsFileThroughRelay(t *testing.T) { + base := t.TempDir() + binaries := map[string]string{} + for _, name := range []string{"local-probe-target", "local-probe-agent"} { + bin := filepath.Join(base, name+".exe") + command := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go.exe"), "build", "-o", bin, "../../cmd/"+name) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("build %s: %v: %s", name, err, output) + } + binaries[name] = bin + } + workspace := filepath.Join(base, "workspace") + if err := os.Mkdir(workspace, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, "evidence.txt"), []byte("real-cli-relay-evidence"), 0600); err != nil { + t.Fatal(err) + } + root, err := config.NewRoot("workspace", workspace, nil) + if err != nil { + t.Fatal(err) + } + profile, err := config.NewProfile("profile-a", []string{"workspace"}, []string{"server_info", "read_file"}, nil) + if err != nil { + t.Fatal(err) + } + connection, err := config.NewConnection("connection-a", "test", profile.ID(), "credential-a", true).WithPurpose(config.PurposeAgentRemote) + if err != nil { + t.Fatal(err) + } + cfg, err := config.New(config.SchemaVersionV2, []config.Root{root}, []config.Profile{profile}, []config.Connection{connection}, []config.CredentialRef{config.NewCredentialRef("credential-a", "runtime")}) + if err != nil { + t.Fatal(err) + } + configPath := filepath.Join(base, "config.json") + fileStore, err := config.NewFileStore(configPath) + if err != nil { + t.Fatal(err) + } + if _, err = fileStore.Save(cfg); err != nil { + t.Fatal(err) + } + targetPath, agentPath := filepath.Join(base, "target-identity"), filepath.Join(base, "agent-identity") + targetStore, err := deviceidentity.CreateStore(targetPath) + if err != nil { + t.Fatal(err) + } + defer targetStore.Close() + a, err := deviceidentity.NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = targetStore.SaveAuthority(a); err != nil { + t.Fatal(err) + } + agentStore, err := deviceidentity.CreateStore(agentPath) + if err != nil { + t.Fatal(err) + } + defer agentStore.Close() + agent, request, err := deviceidentity.NewAgent() + if err != nil { + t.Fatal(err) + } + if err = agentStore.SaveAgent(agent); err != nil { + t.Fatal(err) + } + fp, _ := request.Fingerprint() + g, err := targetStore.IssueGrant(request, fp, connection.ID(), time.Hour) + if err != nil { + t.Fatal(err) + } + bundle := a.Bundle() + bf, _ := bundle.Fingerprint() + if err = agentStore.InstallPairing(deviceidentity.Pairing{Version: deviceidentity.Version, Bundle: bundle, Grant: g, Fingerprint: bf}, bf); err != nil { + t.Fatal(err) + } + service, err := New([]Route{{bundle.DeviceID, targetToken, agentToken}}) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewTLSServer(service) + defer srv.Close() + defer service.Close() + wss := "wss" + strings.TrimPrefix(srv.URL, "https") + caFile := filepath.Join(base, "outer-ca.pem") + if err = os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + target := exec.CommandContext(ctx, binaries["local-probe-target"], "-store", targetPath, "-config", configPath, "-audit-dir", filepath.Join(base, "audit"), "-relay-endpoint", wss+"/v1/target", "-outer-ca-file", caFile) + target.Env = append(os.Environ(), "LOCAL_PROBE_RELAY_TARGET_TOKEN="+targetToken) + if err = target.Start(); err != nil { + t.Fatal(err) + } + targetDone := make(chan error, 1) + go func() { targetDone <- target.Wait() }() + defer func() { + cancel() + select { + case <-targetDone: + case <-time.After(2 * time.Second): + t.Error("target did not exit") + } + }() + registered := false + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + service.mu.Lock() + for _, slot := range service.routes[0].slots { + if slot.ws != nil { + registered = true + } + } + service.mu.Unlock() + if registered { + break + } + select { + case err := <-targetDone: + t.Fatalf("target exited: %v", err) + case <-time.After(10 * time.Millisecond): + } + } + if !registered { + t.Fatal("real target did not connect") + } + agentCommand := exec.CommandContext(ctx, binaries["local-probe-agent"], "-store", agentPath, "-transport", "relay", "-endpoint", wss+"/v1/agent", "-outer-ca-file", caFile) + agentCommand.Env = append(os.Environ(), "LOCAL_PROBE_AGENT_ACCESS_TOKEN="+agentToken) + client := mcp.NewClient(&mcp.Implementation{Name: "cli-test-native-agent", Version: "test"}, nil) + session, err := client.Connect(ctx, &mcp.CommandTransport{Command: agentCommand, TerminateDuration: time.Second}, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "read_file", Arguments: map[string]any{"root_id": "workspace", "path": "evidence.txt", "max_bytes": 64}}) + if err != nil || result.IsError { + t.Fatalf("real read failed: %v", err) + } + data, err := json.Marshal(result) + if err != nil || !strings.Contains(string(data), "real-cli-relay-evidence") { + t.Fatal("real file bytes missing") + } +} diff --git a/internal/relay/public_test.go b/internal/relay/public_test.go new file mode 100644 index 0000000..329d6b5 --- /dev/null +++ b/internal/relay/public_test.go @@ -0,0 +1,312 @@ +package relay + +import ( + "context" + "crypto/tls" + "encoding/json" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/agentbridge" + "github.com/LE-saber/Local-Probe/internal/config" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/mcpserver" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "github.com/LE-saber/Local-Probe/internal/policy" + "github.com/LE-saber/Local-Probe/internal/rootfs" + "github.com/gorilla/websocket" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// This opt-in test uses an already provisioned Relay. No deployment, SSH access, +// account creation, firewall edits or user filesystem access happens here. +func TestPublicRelayReadOnlyEndToEnd(t *testing.T) { + endpoint := os.Getenv("LOCAL_PROBE_PUBLIC_RELAY_URL") + if endpoint == "" { + t.Skip("opt-in: explicit deployed Relay URL and private test credentials required") + } + u, err := url.Parse(endpoint) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + t.Fatal("explicit HTTPS Relay origin required") + } + credentialsPath, caPath := os.Getenv("LOCAL_PROBE_PUBLIC_CREDENTIALS_FILE"), os.Getenv("LOCAL_PROBE_PUBLIC_CA_FILE") + if !filepath.IsAbs(credentialsPath) || !filepath.IsAbs(caPath) { + t.Fatal("absolute private credentials and public CA paths required") + } + file, err := os.Open(credentialsPath) + if err != nil { + t.Fatal("test credentials unavailable") + } + data, err := io.ReadAll(io.LimitReader(file, 65537)) + _ = file.Close() + if err != nil { + t.Fatal("test credentials unavailable") + } + var credentials struct { + DeviceID string `json:"device_id"` + TargetToken string `json:"target_token"` + AgentToken string `json:"agent_token"` + } + if deviceidentity.DecodePublic(data, &credentials) != nil || len(credentials.TargetToken) < 32 || len(credentials.AgentToken) < 32 { + t.Fatal("invalid private test credentials") + } + clear(data) + roots, err := peertransport.LoadPublicRoots(caPath) + if err != nil { + t.Fatal(err) + } + // Optional SSH diagnostic tunnel changes only TCP destination. The original + // URL hostname still controls TLS verification, and both TLS layers remain. + dial := (&net.Dialer{Timeout: 10 * time.Second}).DialContext + if connect := os.Getenv("LOCAL_PROBE_PUBLIC_CONNECT_ADDRESS"); connect != "" { + host, _, err := net.SplitHostPort(connect) + ip := net.ParseIP(host) + if err != nil || ip == nil || !ip.IsLoopback() { + t.Fatal("diagnostic connect address must be explicit loopback") + } + dial = func(ctx context.Context, network, _ string) (net.Conn, error) { + return (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, network, connect) + } + t.Log("transport=SSH-forwarded TCP; hostname verification and inner mTLS remain enabled; this is not direct public WSS evidence") + } else { + t.Log("transport=direct public WSS") + } + outerTransport := &http.Transport{Proxy: nil, DialContext: dial, TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS13}} + defer outerTransport.CloseIdleConnections() + outerClient := &http.Client{Transport: outerTransport, Timeout: 15 * time.Second} + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + response, err := outerClient.Get(strings.TrimSuffix(endpoint, "/") + "/healthz") + if err != nil { + t.Fatal("deployed HTTPS endpoint unavailable:", err) + } + _ = response.Body.Close() + if response.StatusCode != 204 { + t.Fatal("deployed HTTPS health failed") + } + for _, token := range []string{"invalid-public-test-credential", credentials.TargetToken} { + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(endpoint, "/")+"/v1/agent", nil) + req.Header.Set("Authorization", "Bearer "+token) + resp, err := outerClient.Do(req) + if err != nil { + t.Fatal("negative admission request failed") + } + _ = resp.Body.Close() + if resp.StatusCode != 401 { + t.Fatal("unauthorized or wrong-role caller accepted") + } + } + base := t.TempDir() + workspace := filepath.Join(base, "workspace") + if err = os.Mkdir(workspace, 0700); err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(workspace, "evidence.txt"), []byte("public-relay-read-evidence"), 0600); err != nil { + t.Fatal(err) + } + root, err := config.NewRoot("workspace", workspace, nil) + if err != nil { + t.Fatal(err) + } + profile, err := config.NewProfile("profile-a", []string{"workspace"}, []string{"server_info", "read_file"}, nil) + if err != nil { + t.Fatal(err) + } + connection, err := config.NewConnection("connection-a", "public test", profile.ID(), "credential-a", true).WithPurpose(config.PurposeAgentRemote) + if err != nil { + t.Fatal(err) + } + cfg, err := config.New(config.SchemaVersionV2, []config.Root{root}, []config.Profile{profile}, []config.Connection{connection}, []config.CredentialRef{config.NewCredentialRef("credential-a", "runtime")}) + if err != nil { + t.Fatal(err) + } + configStore, err := config.NewStore(cfg) + if err != nil { + t.Fatal(err) + } + manager, err := policy.NewManager(configStore) + if err != nil { + t.Fatal(err) + } + source, err := rootfs.New(configStore) + if err != nil { + t.Fatal(err) + } + defer source.Close() + store, err := deviceidentity.CreateStore(filepath.Join(base, "identity")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + a, err := deviceidentity.NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = store.SaveAuthority(a); err != nil { + t.Fatal(err) + } + agent, csr, err := deviceidentity.NewAgent() + if err != nil { + t.Fatal(err) + } + fp, _ := csr.Fingerprint() + grant, err := store.IssueGrant(csr, fp, connection.ID(), time.Hour) + if err != nil { + t.Fatal(err) + } + registry, err := deviceidentity.NewRegistry(store) + if err != nil { + t.Fatal(err) + } + server, err := mcpserver.New(mcpserver.Options{Manager: manager, Source: source, PeerRegistry: registry}) + if err != nil { + t.Fatal(err) + } + inner, err := registry.ServerTLS() + if err != nil { + t.Fatal(err) + } + target, err := peertransport.NewEndpoint(inner, server.Handler(), func(*http.Request) bool { return false }) + if err != nil { + t.Fatal(err) + } + defer target.Close() + wss := "wss" + strings.TrimPrefix(strings.TrimSuffix(endpoint, "/"), "https") + dialStream := func(ctx context.Context, role, token string, registered chan<- struct{}) (net.Conn, error) { + d := websocket.Dialer{NetDialContext: dial, HandshakeTimeout: 10 * time.Second, TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots}, EnableCompression: false} + ws, resp, err := d.DialContext(ctx, wss+"/v1/"+role, http.Header{"Authorization": []string{"Bearer " + token}}) + if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + return nil, err + } + if registered != nil { + registered <- struct{}{} + } + stop := context.AfterFunc(ctx, func() { _ = ws.Close() }) + ws.SetReadLimit(16 << 10) + _ = ws.SetReadDeadline(time.Now().Add(35 * time.Second)) + kind, b, err := ws.ReadMessage() + stop() + if err != nil || kind != websocket.TextMessage || string(b) != ReadyMessage { + _ = ws.Close() + return nil, io.ErrUnexpectedEOF + } + _ = ws.SetReadDeadline(time.Time{}) + return peertransport.NewStream(ws), nil + } + registered := make(chan struct{}, 4) + var workers sync.WaitGroup + for range 4 { + workers.Add(1) + go func() { + defer workers.Done() + raw, err := dialStream(ctx, "target", credentials.TargetToken, registered) + if err != nil { + return + } + stop := context.AfterFunc(ctx, func() { _ = raw.Close() }) + defer stop() + _ = target.AcceptStream(ctx, raw) + <-ctx.Done() + _ = raw.Close() + }() + } + defer func() { cancel(); workers.Wait() }() + select { + case <-registered: + case <-ctx.Done(): + t.Fatal("target outbound registration failed") + } + bundle := a.Bundle() + bf, _ := bundle.Fingerprint() + clientTLS, err := agent.ClientTLS(bundle, grant, bf) + if err != nil { + t.Fatal(err) + } + transport := &http.Transport{ForceAttemptHTTP2: false, DialTLSContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + raw, err := dialStream(ctx, "agent", credentials.AgentToken, nil) + if err != nil { + return nil, err + } + conn := tls.Client(raw, clientTLS) + if err = conn.HandshakeContext(ctx); err != nil { + _ = raw.Close() + return nil, err + } + return conn, nil + }} + defer transport.CloseIdleConnections() + bridge, remote, err := agentbridge.New(ctx, &http.Client{Transport: transport}) + if err != nil { + t.Fatal(err) + } + defer remote.Close() + left, right := mcp.NewInMemoryTransports() + ss, err := bridge.Connect(ctx, right, nil) + if err != nil { + t.Fatal(err) + } + defer ss.Close() + client := mcp.NewClient(&mcp.Implementation{Name: "public-relay-test-agent", Version: "test"}, nil) + session, err := client.Connect(ctx, left, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "read_file", Arguments: map[string]any{"root_id": "workspace", "path": "evidence.txt", "max_bytes": 64}}) + if err != nil { + t.Fatal(err) + } + encoded, _ := json.Marshal(result) + if result.IsError || !strings.Contains(string(encoded), "public-relay-read-evidence") { + t.Fatal("real file bytes missing") + } + denied, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "read_file", Arguments: map[string]any{"root_id": "outside", "path": "evidence.txt", "max_bytes": 64}}) + if err != nil { + t.Fatal(err) + } + encoded, _ = json.Marshal(denied) + if !strings.Contains(string(encoded), `"code":"denied"`) || strings.Contains(string(encoded), "public-relay-read-evidence") { + t.Fatal("scope denial failed") + } + unknown, unknownCSR, err := deviceidentity.NewAgent() + if err != nil { + t.Fatal(err) + } + ufp, _ := unknownCSR.Fingerprint() + unknownGrant, err := a.Issue(unknownCSR, ufp, connection.ID(), time.Hour) + if err != nil { + t.Fatal(err) + } + unknownTLS, err := unknown.ClientTLS(bundle, unknownGrant, bf) + if err != nil { + t.Fatal(err) + } + badRaw, err := dialStream(ctx, "agent", credentials.AgentToken, nil) + if err != nil { + t.Fatal(err) + } + bad := tls.Client(badRaw, unknownTLS) + defer badRaw.Close() + _ = bad.SetDeadline(time.Now().Add(10 * time.Second)) + if err = bad.HandshakeContext(ctx); err == nil { + _, writeErr := bad.Write([]byte("GET /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")) + if writeErr == nil { + buffer := make([]byte, 1) + if _, readErr := bad.Read(buffer); readErr == nil { + t.Fatal("unregistered Agent certificate accepted") + } + } + } + t.Log("PASS: TLS hostname validation, outer role rejection, inner mutual TLS, real scoped file read, cross-root denial, unregistered certificate rejection") +} diff --git a/internal/relay/relay.go b/internal/relay/relay.go new file mode 100644 index 0000000..67aaa7a --- /dev/null +++ b/internal/relay/relay.go @@ -0,0 +1,373 @@ +// Package relay pairs authenticated outbound WebSocket streams. It never +// terminates inner TLS, interprets MCP, or accepts arbitrary target addresses. +package relay + +import ( + "crypto/sha256" + "crypto/subtle" + "errors" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "net" + "net/http" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +// Route is loaded locally, with role-separated strong tokens. A route maps only +// two opaque outer identities. Target mTLS and local grants authorize operations. +type Route struct{ DeviceID, TargetToken, AgentToken string } +type route struct { + id string + target, agent [32]byte + slots []*slot +} +type slot struct { + ws *websocket.Conn + incoming chan []byte + reserved bool + paired chan struct{} + done chan struct{} + once sync.Once +} +type Service struct { + mu sync.Mutex + routes []*route + closed bool + total int + wait time.Duration + visitors map[string]visitor +} +type visitor struct { + at time.Time + credit float64 +} + +const ReadyMessage = peertransport.RelayReadyMessage + +func New(routes []Route) (*Service, error) { + if len(routes) == 0 || len(routes) > 64 { + return nil, errors.New("bounded Relay routes required") + } + s := &Service{wait: 30 * time.Second, visitors: make(map[string]visitor)} + seen := map[[32]byte]bool{} + ids := map[string]bool{} + for _, r := range routes { + if strings.ContainsAny(r.TargetToken+r.AgentToken, "\r\n") { + return nil, errors.New("invalid Relay credentials") + } + if len(r.DeviceID) == 0 || len(r.DeviceID) > 128 || ids[r.DeviceID] || len(r.TargetToken) < 32 || len(r.AgentToken) < 32 || len(r.TargetToken) > 4096 || len(r.AgentToken) > 4096 { + return nil, errors.New("invalid Relay route") + } + for _, c := range r.DeviceID { + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') { + return nil, errors.New("invalid Relay route") + } + } + target, agent := sha256.Sum256([]byte("Bearer "+r.TargetToken)), sha256.Sum256([]byte("Bearer "+r.AgentToken)) + if target == agent || seen[target] || seen[agent] { + return nil, errors.New("Relay credentials must be role separated") + } + seen[target] = true + seen[agent] = true + ids[r.DeviceID] = true + s.routes = append(s.routes, &route{id: r.DeviceID, target: target, agent: agent}) + } + return s, nil +} + +func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if !s.admitRate(r.RemoteAddr) { + http.Error(w, "rate limited", http.StatusTooManyRequests) + return + } + if r.URL.Path == "/healthz" && r.Method == http.MethodGet { + w.WriteHeader(http.StatusNoContent) + return + } + if r.Method != http.MethodGet || (r.URL.Path != "/v1/target" && r.URL.Path != "/v1/agent") || r.URL.RawQuery != "" { + http.NotFound(w, r) + return + } + values := r.Header.Values("Authorization") + if len(values) != 1 || len(values[0]) > 4103 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + hash := sha256.Sum256([]byte(values[0])) + isTarget := r.URL.Path == "/v1/target" + var selected *route + for _, route := range s.routes { + expected := route.agent + if isTarget { + expected = route.target + } + if subtle.ConstantTimeCompare(hash[:], expected[:]) == 1 { + selected = route + } + } + if selected == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if isTarget { + s.serveTarget(w, r, selected) + } else { + s.serveAgent(w, r, selected) + } +} + +// Ignore forwarded headers: only a trusted proxy integration may replace peer +// addresses. Behind a reverse proxy this intentionally applies a shared budget. +func (s *Service) admitRate(remote string) bool { + ip, _, err := net.SplitHostPort(remote) + if err != nil { + return false + } + now := time.Now() + s.mu.Lock() + defer s.mu.Unlock() + v, ok := s.visitors[ip] + if !ok { + if len(s.visitors) >= 1024 { + for key, item := range s.visitors { + if now.Sub(item.at) > time.Minute { + delete(s.visitors, key) + } + } + if len(s.visitors) >= 1024 { + return false + } + } + v = visitor{now, 20} + } + v.credit = min(20, v.credit+now.Sub(v.at).Seconds()*10) + v.at = now + allowed := v.credit >= 1 + if allowed { + v.credit-- + } + s.visitors[ip] = v + return allowed +} +func upgrade(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) { + u := websocket.Upgrader{HandshakeTimeout: 10 * time.Second, EnableCompression: false, CheckOrigin: func(r *http.Request) bool { return r.Header.Get("Origin") == "" }} + c, err := u.Upgrade(w, r, nil) + if err == nil { + c.SetReadLimit(64 << 10) + } + return c, err +} + +func (s *Service) serveTarget(w http.ResponseWriter, r *http.Request, route *route) { + s.mu.Lock() + if s.closed || s.total >= 128 || len(route.slots) >= 16 { + s.mu.Unlock() + http.Error(w, "capacity reached", http.StatusServiceUnavailable) + return + } + // Reserve capacity before upgrade so concurrent handshakes cannot overflow. + slot := &slot{paired: make(chan struct{}), done: make(chan struct{}), incoming: make(chan []byte, 2)} + route.slots = append(route.slots, slot) + s.total++ + s.mu.Unlock() + defer s.remove(route, slot) + conn, err := upgrade(w, r) + if err != nil { + return + } + s.mu.Lock() + if s.closed { + s.mu.Unlock() + _ = conn.Close() + return + } + slot.ws = conn + s.mu.Unlock() + defer conn.Close() + // Keep one reader from registration through forwarding. Without a reader, + // disconnected waiting targets remain selectable until the pairing timeout. + readDone := make(chan struct{}) + go func() { + defer close(readDone) + defer close(slot.incoming) + _ = conn.SetReadDeadline(time.Now().Add(60 * time.Second)) + conn.SetPongHandler(func(string) error { return conn.SetReadDeadline(time.Now().Add(60 * time.Second)) }) + for { + kind, data, err := conn.ReadMessage() + if err != nil || kind != websocket.BinaryMessage { + return + } + select { + case slot.incoming <- data: + case <-slot.done: + return + } + } + }() + defer func() { s.remove(route, slot); <-readDone }() + timer := time.NewTimer(s.wait) + defer timer.Stop() + select { + case <-slot.paired: + select { + case <-slot.done: + case <-r.Context().Done(): + case <-readDone: + } + case <-slot.done: + case <-readDone: + case <-timer.C: + case <-r.Context().Done(): + } +} +func (s *Service) serveAgent(w http.ResponseWriter, r *http.Request, route *route) { + s.mu.Lock() + var target *slot + if !s.closed { + for _, slot := range route.slots { + if slot.ws != nil && !slot.reserved { + slot.reserved = true + target = slot + break + } + } + } + s.mu.Unlock() + if target == nil { + http.Error(w, "target unavailable", http.StatusServiceUnavailable) + return + } + defer s.remove(route, target) + agent, err := upgrade(w, r) + if err != nil { + return + } + defer agent.Close() + s.mu.Lock() + closed := s.closed + peer := target.ws + s.mu.Unlock() + if closed || peer == nil { + return + } + _ = peer.SetWriteDeadline(time.Now().Add(10 * time.Second)) + _ = agent.SetWriteDeadline(time.Now().Add(10 * time.Second)) + if peer.WriteMessage(websocket.TextMessage, []byte(ReadyMessage)) != nil || agent.WriteMessage(websocket.TextMessage, []byte(ReadyMessage)) != nil { + return + } + _ = peer.SetWriteDeadline(time.Time{}) + _ = agent.SetWriteDeadline(time.Time{}) + close(target.paired) + // Each direction has one reader and one data writer; only TLS ciphertext + // binary messages are forwarded. Reads enforce aggregate message size. + done := make(chan struct{}, 2) + pump := func(src, dst *websocket.Conn, incoming <-chan []byte) { + defer func() { done <- struct{}{} }() + if incoming == nil { + _ = src.SetReadDeadline(time.Now().Add(60 * time.Second)) + src.SetPongHandler(func(string) error { return src.SetReadDeadline(time.Now().Add(60 * time.Second)) }) + } + for { + var data []byte + if incoming != nil { + select { + case next, ok := <-incoming: + if !ok { + return + } + data = next + case <-target.done: + return + } + } else { + kind, next, err := src.ReadMessage() + if err != nil || kind != websocket.BinaryMessage { + return + } + data = next + } + _ = dst.SetWriteDeadline(time.Now().Add(15 * time.Second)) + if dst.WriteMessage(websocket.BinaryMessage, data) != nil { + return + } + } + } + go pump(peer, agent, target.incoming) + go pump(agent, peer, nil) + heartbeatStop := make(chan struct{}) + heartbeatDone := make(chan struct{}) + go func() { + defer close(heartbeatDone) + ticker := time.NewTicker(20 * time.Second) + defer ticker.Stop() + for { + select { + case <-heartbeatStop: + return + case <-ticker.C: + if peer.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second)) != nil || agent.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second)) != nil { + _ = peer.Close() + _ = agent.Close() + return + } + } + } + }() + completed := 0 + select { + case <-done: + completed++ + case <-target.done: + case <-r.Context().Done(): + } + _ = peer.Close() + _ = agent.Close() + close(heartbeatStop) + <-heartbeatDone + // Both pumps always complete after Close, without leaving forwarding tasks. + // If one completed above, only one receive remains. + for completed < 2 { + <-done + completed++ + } +} +func (s *Service) remove(route *route, slot *slot) { + slot.once.Do(func() { + s.mu.Lock() + for i, candidate := range route.slots { + if candidate == slot { + route.slots = append(route.slots[:i], route.slots[i+1:]...) + s.total-- + break + } + } + conn := slot.ws + close(slot.done) + s.mu.Unlock() + if conn != nil { + _ = conn.Close() + } + }) +} +func (s *Service) Close() error { + s.mu.Lock() + s.closed = true + type entry struct { + r *route + s *slot + } + var all []entry + for _, r := range s.routes { + for _, slot := range r.slots { + all = append(all, entry{r, slot}) + } + } + s.mu.Unlock() + for _, e := range all { + s.remove(e.r, e.s) + } + return nil +} diff --git a/internal/relay/relay_test.go b/internal/relay/relay_test.go new file mode 100644 index 0000000..877d6c9 --- /dev/null +++ b/internal/relay/relay_test.go @@ -0,0 +1,230 @@ +package relay + +import ( + "context" + "crypto/x509" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/LE-saber/Local-Probe/internal/agentbridge" + "github.com/LE-saber/Local-Probe/internal/deviceidentity" + "github.com/LE-saber/Local-Probe/internal/peertransport" + "github.com/gorilla/websocket" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +const targetToken = "synthetic-target-admission-0123456789" +const agentToken = "synthetic-agent-admission-01234567890" + +func TestDisconnectedWaitingTargetIsRemovedBeforeNextPairing(t *testing.T) { + service, err := New([]Route{{"device-test", targetToken, agentToken}}) + if err != nil { + t.Fatal(err) + } + outer := httptest.NewServer(service) + defer outer.Close() + defer service.Close() + target, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(outer.URL, "http")+"/v1/target", http.Header{"Authorization": []string{"Bearer " + targetToken}}) + if err != nil { + t.Fatal(err) + } + _ = target.Close() + deadline := time.Now().Add(2 * time.Second) + for { + service.mu.Lock() + remaining := service.total + service.mu.Unlock() + if remaining == 0 { + break + } + if time.Now().After(deadline) { + t.Fatal("disconnected waiting target still consumes pairing capacity") + } + time.Sleep(time.Millisecond) + } + request, _ := http.NewRequest(http.MethodGet, outer.URL+"/v1/agent", nil) + request.Header.Set("Authorization", "Bearer "+agentToken) + response, err := outer.Client().Do(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if response.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("offline route returned %d instead of rejecting pairing", response.StatusCode) + } +} + +func TestRelayCarriesPairedMCPWithoutTerminatingInnerTLS(t *testing.T) { + service, err := New([]Route{{"device-test", targetToken, agentToken}}) + if err != nil { + t.Fatal(err) + } + outer := httptest.NewTLSServer(service) + defer outer.Close() + defer service.Close() + roots := x509.NewCertPool() + roots.AddCert(outer.Certificate()) + baseURL := "wss" + strings.TrimPrefix(outer.URL, "https") + store, err := deviceidentity.CreateStore(filepath.Join(t.TempDir(), "identity")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + a, err := deviceidentity.NewAuthority() + if err != nil { + t.Fatal(err) + } + if err = store.SaveAuthority(a); err != nil { + t.Fatal(err) + } + agent, request, err := deviceidentity.NewAgent() + if err != nil { + t.Fatal(err) + } + fp, _ := request.Fingerprint() + g, err := store.IssueGrant(request, fp, "connection-relay", time.Hour) + if err != nil { + t.Fatal(err) + } + registry, err := deviceidentity.NewRegistry(store) + if err != nil { + t.Fatal(err) + } + target := mcp.NewServer(&mcp.Implementation{Name: "relay-target", Version: "test"}, nil) + target.AddTool(&mcp.Tool{Name: "echo", InputSchema: map[string]any{"type": "object"}}, func(ctx context.Context, _ *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + grant, ok := deviceidentity.GrantFromContext(ctx) + if !ok { + t.Error("missing grant") + } + return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: grant.ConnectionID}}}, nil + }) + handler := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return target }, &mcp.StreamableHTTPOptions{Stateless: true}) + inner, err := registry.ServerTLS() + if err != nil { + t.Fatal(err) + } + endpoint, err := peertransport.NewEndpoint(inner, registry.Handler(handler), func(*http.Request) bool { return false }) + if err != nil { + t.Fatal(err) + } + defer endpoint.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + reverseDone := make(chan error, 1) + go func() { + reverseDone <- endpoint.ServeRelay(ctx, baseURL+"/v1/target", http.Header{"Authorization": []string{"Bearer " + targetToken}}, roots) + }() + // Wait for a real outgoing target registration; no arbitrary startup sleep. + deadline := time.Now().Add(3 * time.Second) + registered := false + for time.Now().Before(deadline) { + service.mu.Lock() + for _, slot := range service.routes[0].slots { + if slot.ws != nil { + registered = true + } + } + service.mu.Unlock() + if registered { + break + } + time.Sleep(5 * time.Millisecond) + } + if !registered { + t.Fatal("target did not register") + } + b := a.Bundle() + bf, _ := b.Fingerprint() + clientTLS, err := agent.ClientTLS(b, g, bf) + if err != nil { + t.Fatal(err) + } + hc, closeHTTP, err := peertransport.RelayHTTPClient(baseURL+"/v1/agent", clientTLS, http.Header{"Authorization": []string{"Bearer " + agentToken}}, roots) + if err != nil { + t.Fatal(err) + } + defer closeHTTP() + bridge, remote, err := agentbridge.New(ctx, hc) + if err != nil { + t.Fatal(err) + } + defer remote.Close() + left, right := mcp.NewInMemoryTransports() + ss, err := bridge.Connect(ctx, right, nil) + if err != nil { + t.Fatal(err) + } + defer ss.Close() + client := mcp.NewClient(&mcp.Implementation{Name: "agent", Version: "test"}, nil) + session, err := client.Connect(ctx, left, nil) + if err != nil { + t.Fatal(err) + } + defer session.Close() + result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "echo", Arguments: map[string]any{}}) + if err != nil { + t.Fatal(err) + } + if result.IsError || result.Content[0].(*mcp.TextContent).Text != "connection-relay" { + t.Fatal("inner MCP data corrupted") + } + cancel() + select { + case err := <-reverseDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("reverse workers did not stop") + } +} + +func TestRelayRejectsUnknownRoleOfflineRouteAndArbitraryDestination(t *testing.T) { + service, err := New([]Route{{"device-test", targetToken, agentToken}}) + if err != nil { + t.Fatal(err) + } + defer service.Close() + for _, tc := range []struct { + path, token string + status int + }{ + {"/v1/agent", targetToken, 401}, {"/v1/target", agentToken, 401}, {"/v1/agent", agentToken, 503}, {"/v1/agent?destination=http://internal", agentToken, 404}, + } { + req := httptest.NewRequest(http.MethodGet, tc.path, nil) + req.Header.Set("Authorization", "Bearer "+tc.token) + w := httptest.NewRecorder() + service.ServeHTTP(w, req) + if w.Code != tc.status { + t.Fatalf("path=%s status=%d want=%d", tc.path, w.Code, tc.status) + } + } + if _, err = New([]Route{{"device-test", agentToken, agentToken}}); err == nil { + t.Fatal("shared role credential accepted") + } +} + +func TestRelayBoundsWaitingTargetsAndShutdown(t *testing.T) { + service, err := New([]Route{{"device-test", targetToken, agentToken}}) + if err != nil { + t.Fatal(err) + } + service.wait = 50 * time.Millisecond + srv := httptest.NewTLSServer(service) + defer srv.Close() + defer service.Close() + dialer := websocket.Dialer{TLSClientConfig: srv.Client().Transport.(*http.Transport).TLSClientConfig.Clone()} + conn, _, err := dialer.Dial("wss"+strings.TrimPrefix(srv.URL, "https")+"/v1/target", http.Header{"Authorization": []string{"Bearer " + targetToken}}) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + _ = conn.SetReadDeadline(time.Now().Add(time.Second)) + if _, _, err = conn.ReadMessage(); err == nil { + t.Fatal("unpaired target did not expire") + } +} diff --git a/internal/rootfs/source.go b/internal/rootfs/source.go index a281425..a38c28f 100644 --- a/internal/rootfs/source.go +++ b/internal/rootfs/source.go @@ -1,4 +1,5 @@ -// Package rootfs provides the read-only filesystem boundary for readcore. +// Package rootfs provides the read-only filesystem boundary for readcore and +// a separately authorized, handle-bound Windows writer for explicit v2 grants. // // Source instances are built from one immutable config.Store snapshot. A // Source is used with a policy.BoundScope; the scope is deliberately retained diff --git a/internal/rootfs/write.go b/internal/rootfs/write.go new file mode 100644 index 0000000..23f2e63 --- /dev/null +++ b/internal/rootfs/write.go @@ -0,0 +1,8 @@ +package rootfs + +import "errors" + +var ( + ErrWriteConflict = errors.New("file version conflict") + ErrWriteUncertain = errors.New("file write outcome uncertain; retained private before image") +) diff --git a/internal/rootfs/write_other.go b/internal/rootfs/write_other.go new file mode 100644 index 0000000..325ed89 --- /dev/null +++ b/internal/rootfs/write_other.go @@ -0,0 +1,20 @@ +//go:build !windows + +package rootfs + +import "github.com/LE-saber/Local-Probe/internal/policy" + +// Non-Windows targets remain read-only until handle-bound write/exec support +// has its own real-platform tests. Linux Agents and Relays remain usable. +func (s *Source) WithDirectory(policy.BoundScope, string, string, func(string) error) error { + return ErrUnsupportedType +} +func (s *Source) FileVersion(policy.BoundScope, string, string) (string, error) { + return "", ErrUnsupportedType +} +func (s *Source) FilePreview(policy.BoundScope, string, string) (string, []byte, error) { + return "", nil, ErrUnsupportedType +} +func (s *Source) WriteFile(policy.BoundScope, string, string, string, []byte, func([]byte) error) error { + return ErrUnsupportedType +} diff --git a/internal/rootfs/write_windows.go b/internal/rootfs/write_windows.go new file mode 100644 index 0000000..7c2761e --- /dev/null +++ b/internal/rootfs/write_windows.go @@ -0,0 +1,245 @@ +package rootfs + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "os" + "path" + "path/filepath" + "strings" + + "github.com/LE-saber/Local-Probe/internal/policy" + "golang.org/x/sys/windows" +) + +const maxWriteBytes = 128 << 10 + +// WithDirectory pins a no-reparse, fixed-volume directory chain for the entire +// callback. The supplied name is presentation; handles anchor the actual root. +// Commands still have trusted-host permissions, not directory sandboxing. +func (s *Source) WithDirectory(b policy.BoundScope, id, relative string, call func(string) error) error { + if call == nil || !b.AllowsRoot(id) || !b.AllowsDirectory(id, relative) { + return ErrDenied + } + root, err := s.commandRoot(b, id) + if err != nil { + return ErrDenied + } + if err = rejectPresentedRoot(root); err != nil { + return ErrDenied + } + anchor, err := root.Open(".") + if err != nil { + return ErrDenied + } + defer anchor.Close() + identity, err := strongCommandIdentity(anchor, false) + if err != nil { + return ErrDenied + } + base, err := finalCommandPath(anchor) + if err != nil || requireFixedCommandVolume(base) != nil { + return ErrDenied + } + // OpenRoot follows links in its presented name. Reject an anchor that + // resolved elsewhere during Source construction, even if that name was + // restored before this operation. No pathname-only cwd/write fallback. + if !sameCommandPath(base, `\\?\`+filepath.Clean(root.Name())) { + return ErrDenied + } + full := base + if relative != "" { + full = joinCommandPath(base, relative) + } + // Pin every ancestor, including the configured root, against rename/delete. + var handles []*os.File + defer func() { + for i := len(handles) - 1; i >= 0; i-- { + handles[i].Close() + } + }() + current := full[:7] + parts := strings.Split(strings.Trim(full[7:], `\`), `\`) + names := []string{current} + for _, part := range parts { + if part != "" { + current = strings.TrimRight(current, `\`) + `\` + part + names = append(names, current) + } + } + matched := false + for _, name := range names { + p, er := windows.UTF16PtrFromString(name) + if er != nil { + return ErrDenied + } + h, er := windows.CreateFile(p, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) + if er != nil { + return ErrDenied + } + f := os.NewFile(uintptr(h), "") + handles = append(handles, f) + actual, er := strongCommandIdentity(f, false) + if er != nil { + return ErrDenied + } + final, er := finalCommandPath(f) + if er != nil || !sameCommandPath(final, name) { + return ErrDenied + } + if sameCommandPath(name, base) { + if actual.volume != identity.volume || actual.fileID != identity.fileID { + return ErrDenied + } + matched = true + } + } + if !matched || b.Validate() != nil { + return ErrDenied + } + return call(strings.TrimPrefix(full, `\\?\`)) +} + +func (s *Source) openWriteFile(b policy.BoundScope, id, relative string, write, create bool, call func(*os.File) error) error { + if !b.AllowsRoot(id) || !b.AllowsPath(id, relative) { + return ErrDenied + } + directory := path.Dir(relative) + if directory == "." { + directory = "" + } + return s.WithDirectory(b, id, directory, func(parent string) error { + name := strings.TrimRight(parent, `\`) + `\` + path.Base(relative) + p, err := windows.UTF16PtrFromString(name) + if err != nil { + return ErrDenied + } + access := uint32(windows.GENERIC_READ) + share := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE | windows.FILE_SHARE_DELETE) + mode := uint32(windows.OPEN_EXISTING) + if write { + access |= windows.GENERIC_WRITE + share = windows.FILE_SHARE_READ + } + if create { + mode = windows.CREATE_NEW + } + if create { + release, err := b.AcquireRevisionLease() + if err != nil { + return ErrDenied + } + defer release() + } + h, err := windows.CreateFile(p, access, share, nil, mode, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) + if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { + return os.ErrNotExist + } + if errors.Is(err, windows.ERROR_FILE_EXISTS) || errors.Is(err, windows.ERROR_ALREADY_EXISTS) { + return ErrWriteConflict + } + if err != nil { + return ErrDenied + } + f := os.NewFile(uintptr(h), "") + defer f.Close() + if _, err = strongCommandIdentity(f, true); err != nil { + return ErrDenied + } + actual, err := finalCommandPath(f) + if err != nil || !sameCommandPath(actual, `\\?\`+name) { + return ErrDenied + } + if !create && b.Validate() != nil { + return ErrDenied + } + return call(f) + }) +} +func writeVersion(f *os.File) (string, []byte, error) { + before, err := strongCommandIdentity(f, true) + if err != nil { + return "", nil, ErrDenied + } + data, err := io.ReadAll(io.LimitReader(f, maxWriteBytes+1)) + if err != nil || len(data) > maxWriteBytes { + return "", nil, ErrDenied + } + meta, err := f.Stat() + if err != nil || meta.Size() != int64(len(data)) { + return "", nil, ErrWriteConflict + } + h := sha256.Sum256(data) + encoded, _ := json.Marshal(struct { + Volume, ID uint64 + Hash string + }{before.volume, before.fileID, hex.EncodeToString(h[:])}) + v := sha256.Sum256(encoded) + return hex.EncodeToString(v[:]), data, nil +} +func (s *Source) FileVersion(b policy.BoundScope, id, relative string) (string, error) { + v, _, err := s.FilePreview(b, id, relative) + return v, err +} +func (s *Source) FilePreview(b policy.BoundScope, id, relative string) (string, []byte, error) { + var version string + var before []byte + err := s.openWriteFile(b, id, relative, false, false, func(f *os.File) error { v, old, err := writeVersion(f); version = v; before = old; return err }) + if errors.Is(err, os.ErrNotExist) { + return "absent", nil, nil + } + return version, before, err +} + +// WriteFile updates through a no-write/no-delete-sharing handle. Existing-file +// updates are NOT atomic replacements: a durable private before image is written +// first. A failed update is reported unknown, never silently retried/restored. +func (s *Source) WriteFile(b policy.BoundScope, id, relative, expected string, data []byte, backup func([]byte) error) error { + if !b.AllowsWrites() || backup == nil || len(data) > maxWriteBytes || expected == "" { + return ErrDenied + } + create := expected == "absent" + if create { + if err := backup(nil); err != nil { + return err + } + } + return s.openWriteFile(b, id, relative, true, create, func(f *os.File) error { + if !create { + v, old, err := writeVersion(f) + if err != nil { + return err + } + if v != expected { + return ErrWriteConflict + } + if err = backup(old); err != nil { + return err + } + } + if !create { + release, err := b.AcquireRevisionLease() + if err != nil { + return ErrDenied + } + defer release() + } + var err error + if _, err = f.Seek(0, 0); err != nil { + return ErrWriteUncertain + } + if _, err = f.Write(data); err != nil { + return ErrWriteUncertain + } + if err = f.Truncate(int64(len(data))); err != nil { + return ErrWriteUncertain + } + if err = f.Sync(); err != nil { + return ErrWriteUncertain + } + return nil + }) +} diff --git a/internal/rootfs/write_windows_test.go b/internal/rootfs/write_windows_test.go new file mode 100644 index 0000000..6a0e8a2 --- /dev/null +++ b/internal/rootfs/write_windows_test.go @@ -0,0 +1,133 @@ +package rootfs + +import ( + "errors" + "github.com/LE-saber/Local-Probe/internal/config" + "os" + "path/filepath" + "testing" +) + +func newWritableTestSource(t *testing.T, deny []string) testSource { + t.Helper() + f := newTestSource(t, deny) + cfg := f.store.Snapshot().Config() + profiles := cfg.Profiles() + for i := range profiles { + profiles[i] = profiles[i].WithWriteAccess() + } + next, err := config.New(config.SchemaVersionV2, cfg.Roots(), profiles, cfg.Connections(), cfg.Credentials()) + if err != nil { + t.Fatal(err) + } + if _, err = f.store.Replace(next); err != nil { + t.Fatal(err) + } + f.source.Close() + f.source, err = New(f.store) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { f.source.Close() }) + f.bound, err = f.manager.BindAuthenticated("connection") + if err != nil { + t.Fatal(err) + } + return f +} + +func TestWriteFileConflictBackupAndLinkedObjects(t *testing.T) { + f := newWritableTestSource(t, []string{"*.key"}) + target := filepath.Join(f.dir, "edit.txt") + if err := os.WriteFile(target, []byte("original"), 0600); err != nil { + t.Fatal(err) + } + v, err := f.source.FileVersion(f.bound, "workspace", "edit.txt") + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(target, []byte("user-edited"), 0600); err != nil { + t.Fatal(err) + } + backed := false + backup := func(b []byte) error { backed = true; return nil } + if err = f.source.WriteFile(f.bound, "workspace", "edit.txt", v, []byte("remote"), backup); !errors.Is(err, ErrWriteConflict) || backed { + t.Fatalf("conflict was not preserved: %v backup=%v", err, backed) + } + content, _ := os.ReadFile(target) + if string(content) != "user-edited" { + t.Fatal("conflict overwrote user's edits") + } + v, err = f.source.FileVersion(f.bound, "workspace", "edit.txt") + if err != nil { + t.Fatal(err) + } + if err = f.source.WriteFile(f.bound, "workspace", "edit.txt", v, []byte("updated"), func(b []byte) error { + if string(b) != "user-edited" { + t.Fatal("wrong before image") + } + return nil + }); err != nil { + t.Fatal(err) + } + content, _ = os.ReadFile(target) + if string(content) != "updated" { + t.Fatal("file was not written") + } + if err = f.source.WriteFile(f.bound, "workspace", "new.txt", "absent", []byte("new"), backup); err != nil { + t.Fatal(err) + } + if err = f.source.WriteFile(f.bound, "workspace", "new.txt", "absent", []byte("clobbered"), backup); !errors.Is(err, ErrWriteConflict) { + t.Fatal("exclusive creation clobbered existing file") + } + outside := filepath.Join(t.TempDir(), "outside.txt") + if err = os.WriteFile(outside, []byte("private"), 0600); err != nil { + t.Fatal(err) + } + if err = os.Link(outside, filepath.Join(f.dir, "linked.txt")); err != nil { + t.Fatal(err) + } + if _, err = f.source.FileVersion(f.bound, "workspace", "linked.txt"); err == nil { + t.Fatal("hard linked file accepted") + } + if err = f.source.WriteFile(f.bound, "workspace", "../outside.txt", "absent", []byte("escape"), backup); err == nil { + t.Fatal("traversal write accepted") + } + if err = f.source.WriteFile(f.bound, "workspace", "secret.key", "absent", []byte("escape"), backup); err == nil { + t.Fatal("deny rule bypassed") + } + content, _ = os.ReadFile(outside) + if string(content) != "private" { + t.Fatal("outside marker was modified") + } +} +func TestWriteFileBackupFailureDoesNotTouchFile(t *testing.T) { + f := newWritableTestSource(t, nil) + target := filepath.Join(f.dir, "file.txt") + if err := os.WriteFile(target, []byte("keep"), 0600); err != nil { + t.Fatal(err) + } + v, err := f.source.FileVersion(f.bound, "workspace", "file.txt") + if err != nil { + t.Fatal(err) + } + if err = f.source.WriteFile(f.bound, "workspace", "file.txt", v, []byte("changed"), func([]byte) error { return errors.New("backup unavailable") }); err == nil { + t.Fatal("failed backup did not stop write") + } + b, _ := os.ReadFile(target) + if string(b) != "keep" { + t.Fatal("failed backup still changed file") + } +} + +func TestReadOnlyScopeCannotWriteEvenThroughLocalCore(t *testing.T) { + f := newTestSource(t, nil) + called := false + err := f.source.WriteFile(f.bound, "workspace", "not-created.txt", "absent", []byte("bad"), func([]byte) error { called = true; return nil }) + if err == nil || called { + t.Fatal("read-only profile admitted a file write") + } + if _, err = os.Stat(filepath.Join(f.dir, "not-created.txt")); !os.IsNotExist(err) { + t.Fatal("read-only write created a file") + } +} diff --git a/internal/workspaceadmin/workspaceadmin_test.go b/internal/workspaceadmin/workspaceadmin_test.go index afbcf49..a7c1837 100644 --- a/internal/workspaceadmin/workspaceadmin_test.go +++ b/internal/workspaceadmin/workspaceadmin_test.go @@ -154,7 +154,7 @@ func TestUpdatePauseAndResumeAreProfileScoped(t *testing.T) { pausedValue := false paused, err := env.manager.Update(context.Background(), DefaultConnectionID, env.initial.Revision(), "shared", RootUpdate{Enabled: &pausedValue}) if err != nil { - t.Fatal(err) + t.Fatalf("pause failed: %v; storage detail: %v", err, errors.Unwrap(err)) } var shared WorkspaceRoot for _, root := range paused.Roots { @@ -185,7 +185,7 @@ func TestUpdatePauseAndResumeAreProfileScoped(t *testing.T) { resumedValue := true resumed, err := env.manager.Update(context.Background(), DefaultConnectionID, paused.Revision, "shared", RootUpdate{Enabled: &resumedValue}) if err != nil { - t.Fatal(err) + t.Fatalf("resume failed: %v; storage detail: %v", err, errors.Unwrap(err)) } profileA, _ = mustLoadConfig(t, env.store).Profile("profile-a") if !reflect.DeepEqual(profileA.RootIDs(), []string{"project", "shared"}) { diff --git a/third_party/gorilla-websocket/LICENSE b/third_party/gorilla-websocket/LICENSE new file mode 100644 index 0000000..9171c97 --- /dev/null +++ b/third_party/gorilla-websocket/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.