diff --git a/cmd/outpost-host/main.go b/cmd/outpost-host/main.go index eae8b98..f2f904a 100644 --- a/cmd/outpost-host/main.go +++ b/cmd/outpost-host/main.go @@ -357,7 +357,7 @@ func cmdRun(args []string) error { if err != nil { return err } - peers := &peer.Table{HostID: dev.DeviceID, Static: static, Store: store, Router: a.Router, + peers := &peer.Table{MCPURL: mcpURL, HostID: dev.DeviceID, Static: static, Store: store, Router: a.Router, Info: func() any { return a.Hello() }, Logf: log.Printf} if tokens != nil { // A browser is trusted when its owner proves, with a token from the identity provider, diff --git a/docs/mcp.md b/docs/mcp.md index 54c4d2c..cf2e138 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -76,6 +76,10 @@ bounded the same way on every machine: ## Asking for approval +Open **Preferences → Pending access requests** to review or dismiss a request from any online machine your browser can administer. Each row names the connection, machine and requested access. Review opens the same form as the chat link. The trusted browser sets the scope and time limits and grants access on that machine. A steering tool called through a view-only connection also raises a request. + +Each machine keeps pending requests in its local peer store for 24 hours. An MCP retry reuses the same row. A new request arrives over an encrypted channel that proves possession of the requesting key. For first-time connections, the host confirms that key belongs to its enrolled account with the Outpost MCP endpoint configured on the machine. Older hosts and self-hosted machines without a configured MCP endpoint can still approve via a link. + When no machine a tool asked has approved the connection, the service asks the client to send the person to the approval page itself (elicitation in `url` mode), so the link reaches the person without passing through the model. Only clients that declare `elicitation.url` are asked: diff --git a/internal/e2e/mcp_test.go b/internal/e2e/mcp_test.go index dbc5455..ad6f06f 100644 --- a/internal/e2e/mcp_test.go +++ b/internal/e2e/mcp_test.go @@ -71,6 +71,7 @@ func TestTheMCPServiceNeedsABrowsersGrant(t *testing.T) { defer hs.Close() endpoint := hs.URL + mcpserver.Path + r.table.MCPURL = endpoint // No token, no MCP; the challenge points at the metadata and names the scope to ask for. resp, err := http.Post(endpoint, "application/json", strings.NewReader(`{}`)) must(t, err) @@ -104,16 +105,38 @@ func TestTheMCPServiceNeedsABrowsersGrant(t *testing.T) { t.Fatalf("machines before the grant: %+v", ms) } + b, err := r.dial(browser, "KK") + must(t, err) + defer b.Close() + pending := func() []peer.GrantRequest { + t.Helper() + var res struct{ Requests []peer.GrantRequest } + must(t, b.Call(r.ctx, peer.MethodGrantsList, nil, &res)) + return res.Requests + } + // Only the enrolled account can establish a service identity for this inbox. + foreignKey, err := keys.For("another-account", "claude-dcr", "sid-claude") + must(t, err) + foreign, err := r.dial(foreignKey, "IK") + must(t, err) + if err := foreign.Call(r.ctx, peer.MethodGrantRequest, map[string]string{"id": "sid-claude", "client": "claude-dcr", "scope": peer.ScopeSteer}, nil); err == nil { + t.Fatal("machine accepted a request for another account") + } + foreign.Close() + if requests := pending(); len(requests) != 1 || requests[0].Scope != peer.ScopeView || requests[0].ClientID != who.KeyID { + t.Fatalf("new connection missing from Preferences: %+v", requests) + } + steerURL := who.ApproveURL + "&machine=" + r.hostID + "&scope=steer" input := mcpserver.AgentCreateInput{Machine: r.hostID, Name: "Navi", Job: "Release coordinator", Harness: "codex", Prompt: " " + canary + "\n"} wakeInput := mcpserver.AgentWakeInput{Machine: r.hostID, Session: "not-created-yet", At: time.Now().Add(time.Hour).Format(time.RFC3339Nano)} needsGrant := func() { t.Helper() wake := callTool[mcpserver.AgentWakeResult](t, r.ctx, cs, "agent_wake", wakeInput) - if wake.Access != mcpserver.AccessNeedsApproval || wake.ApproveURL != who.ApproveURL { + if wake.Access != mcpserver.AccessNeedsApproval || wake.ApproveURL != steerURL { t.Fatalf("scheduling without steer: %+v", wake) } out := callTool[mcpserver.AgentCreated](t, r.ctx, cs, "agent_create", input) - if out.Access != mcpserver.AccessNeedsApproval || out.ApproveURL != who.ApproveURL || out.SessionID != "" { + if out.Access != mcpserver.AccessNeedsApproval || out.ApproveURL != steerURL || out.SessionID != "" { t.Fatalf("creating an agent without steer: %+v", out) } } @@ -125,9 +148,6 @@ func TestTheMCPServiceNeedsABrowsersGrant(t *testing.T) { if who.KeyID != mcpserver.ClientID(key) || !strings.Contains(who.ApproveURL, hex.EncodeToString(key.Public)) { t.Fatalf("the approval link names another key: %+v", who) } - b, err := r.dial(browser, "KK") - must(t, err) - defer b.Close() must(t, b.Call(r.ctx, peer.MethodGrantsAdd, peer.GrantParams{PublicKey: hex.EncodeToString(key.Public), ID: who.GrantID, Name: "Claude (MCP)", Scopes: []string{peer.ScopeView}, LifetimeSeconds: 3600, IdleSeconds: 3600}, nil)) @@ -143,9 +163,27 @@ func TestTheMCPServiceNeedsABrowsersGrant(t *testing.T) { t.Fatal("an unknown machine was not an error") } + sent := callTool[mcpserver.SessionRead](t, r.ctx, cs, "session_send", map[string]string{"machine": r.hostID, "session": "navi", "text": "check the release"}) + if sent.Access != mcpserver.AccessNeedsApproval || sent.ApproveURL != steerURL { + t.Fatalf("steering did not offer approval: %+v", sent) + } + requests := pending() + if len(requests) != 1 || requests[0].Scope != peer.ScopeSteer { + t.Fatalf("expected one upgrade: %+v", requests) + } + must(t, b.Call(r.ctx, peer.MethodGrantDismiss, requests[0], nil)) + if len(pending()) != 0 { + t.Fatal("dismissed request remained") + } + if err := b.Call(r.ctx, peer.MethodGrantsAdd, peer.GrantParams{PublicKey: requests[0].PublicKey, ID: who.GrantID, Name: requests[0].Name, Scopes: []string{peer.ScopeView, peer.ScopeSteer}, LifetimeSeconds: 3600, IdleSeconds: 3600, RequestedAt: &requests[0].RequestedAt}, nil); err == nil { + t.Fatal("dismissed request was approved from a stale tab") + } needsGrant() // the view-only grant cannot create one must(t, b.Call(r.ctx, peer.MethodGrantsAdd, peer.GrantParams{PublicKey: hex.EncodeToString(key.Public), ID: who.GrantID, Name: "Claude (MCP)", Scopes: []string{peer.ScopeView, peer.ScopeSteer}, LifetimeSeconds: 3600, IdleSeconds: 3600}, nil)) + if len(pending()) != 0 { + t.Fatal("approved request remained") + } created := callTool[mcpserver.AgentCreated](t, r.ctx, cs, "agent_create", input) if created.SessionID == "" || created.MachineID != r.hostID || created.Name != input.Name || created.ChatURL != "https://outpost.test/agents/"+r.hostID+"/"+created.SessionID { t.Fatalf("created agent: %+v", created) diff --git a/internal/host/peer/grant_requests.go b/internal/host/peer/grant_requests.go new file mode 100644 index 0000000..35101fc --- /dev/null +++ b/internal/host/peer/grant_requests.go @@ -0,0 +1,118 @@ +package peer + +import ( + "bytes" + "context" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "slices" + "strings" + "time" + + "github.com/andyjmorgan/outpost/internal/host/wire" +) + +// A pending request records interest only. Trusted browsers still use grants.add. +type GrantRequest struct { + ClientID string `json:"clientId"` + PublicKey string `json:"publicKey"` + ID string `json:"id"` + Name string `json:"name"` + Scope string `json:"scope"` + RequestedAt time.Time `json:"requestedAt"` +} + +const requestLifetime = 24 * time.Hour + +func (st *state) pruneRequests(now time.Time) { + st.Requests = slices.DeleteFunc(st.Requests, func(r GrantRequest) bool { return !r.RequestedAt.Add(requestLifetime).After(now) }) +} + +func (s *Store) requestGrant(req GrantRequest) error { + return s.update(func(st *state) error { + st.pruneRequests(req.RequestedAt) + for _, rec := range st.Peers { + if rec.ClientID == req.ClientID && rec.Active(req.RequestedAt) && (rec.Grant == nil || rec.Has(req.Scope)) { + return nil + } + } + for i, old := range st.Requests { + if old.ClientID == req.ClientID { + if req.Scope == ScopeSteer && old.Scope == ScopeView { + st.Requests[i] = req + } + return nil + } + } + if len(st.Requests) >= 100 { + return errors.New("too many pending requests") + } + st.Requests = append(st.Requests, req) + return nil + }) +} + +// GrantIdentity is checked with the machine's configured Outpost MCP service. The +// machine supplies its enrolled owner and the key proven by the encrypted channel. +type GrantIdentity struct { + Owner string `json:"owner"` + Client string `json:"client"` + ID string `json:"id"` + PublicKey string `json:"publicKey"` +} + +func (p *Peer) requestGrant(msg *wire.Message) { + var in struct { + Client string `json:"client"` + ID string `json:"id"` + Scope string `json:"scope"` + } + if json.Unmarshal(msg.Params, &in) != nil || in.Client == "" || len(in.Client) > 256 || in.ID == "" || len(in.ID) > 200 || !slices.Contains(GrantableScopes, in.Scope) { + p.ep.Answer(msg, nil, wire.Errorf(codeInvalidParams, "invalid grant request")) + return + } + pub := hex.EncodeToString(p.pub) + name := "" + if rec := p.rec.Load(); rec != nil && rec.Grant != nil && rec.Grant.ID == in.ID { + name = rec.Name + } else if p.t.Owner != "" && p.t.MCPURL != "" { + ctx, cancel := context.WithTimeout(p.ctx, 3*time.Second) + defer cancel() + name = grantServiceName(ctx, p.t.MCPURL, GrantIdentity{Owner: p.t.Owner, Client: in.Client, ID: in.ID, PublicKey: pub}) + } + if name == "" { + p.ep.Answer(msg, nil, wire.Errorf(CodeForbidden, "unrecognized Outpost MCP connection")) + return + } + err := p.t.Store.requestGrant(GrantRequest{ClientID: p.clientID, PublicKey: pub, ID: in.ID, Name: name, Scope: in.Scope, RequestedAt: time.Now().UTC()}) + if err != nil { + p.ep.Answer(msg, nil, wire.Errorf(codeInternal, "%s", err.Error())) + return + } + p.ep.Answer(msg, map[string]any{}, nil) +} + +func grantServiceName(ctx context.Context, endpoint string, id GrantIdentity) string { + data, _ := json.Marshal(id) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(endpoint, "/")+"/grant-identity", bytes.NewReader(data)) + if err != nil { + return "" + } + req.Header.Set("Content-Type", "application/json") + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + res, err := client.Do(req) + if err != nil { + return "" + } + defer res.Body.Close() + var out struct { + Name string `json:"name"` + } + if res.StatusCode != http.StatusOK || json.NewDecoder(io.LimitReader(res.Body, 1024)).Decode(&out) != nil || len(out.Name) > 80 { + return "" + } + return out.Name +} diff --git a/internal/host/peer/grant_requests_test.go b/internal/host/peer/grant_requests_test.go new file mode 100644 index 0000000..56fc618 --- /dev/null +++ b/internal/host/peer/grant_requests_test.go @@ -0,0 +1,40 @@ +package peer + +import ( + "testing" + "time" +) + +func TestPendingRequestSurvivesRestartUntilItsDeadline(t *testing.T) { + store := &Store{Dir: t.TempDir()} + now := time.Now().UTC() + request := GrantRequest{ClientID: "example", Scope: ScopeSteer, RequestedAt: now} + if err := store.requestGrant(request); err != nil { + t.Fatal(err) + } + later := &Store{Dir: store.Dir} + retry := request + retry.Scope, retry.RequestedAt = ScopeView, now.Add(time.Hour) + if err := later.requestGrant(retry); err != nil { + t.Fatal(err) + } + err := later.update(func(st *state) error { + if len(st.Requests) != 1 || st.Requests[0] != request { + t.Fatalf("duplicate changed the pending request: %+v", st.Requests) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + later.Expire(now.Add(requestLifetime)) + err = later.update(func(st *state) error { + if len(st.Requests) != 0 || len(st.Peers) != 0 { + t.Fatal("expired request left a request or a grant") + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/host/peer/grants.go b/internal/host/peer/grants.go index 9332154..10a9262 100644 --- a/internal/host/peer/grants.go +++ b/internal/host/peer/grants.go @@ -3,6 +3,7 @@ package peer import ( "encoding/hex" "encoding/json" + "errors" "slices" "time" @@ -24,6 +25,11 @@ const ( codeInternal = -32603 ) +var ( + errRequestGone = errors.New("this access request is no longer pending") + errBrowserGrant = errors.New("that key is a browser's, not a service's") +) + // GrantableScopes are the scopes a grant may carry. var GrantableScopes = []string{ScopeView, ScopeSteer} @@ -48,10 +54,11 @@ var GrantMethods = map[string]bool{ // GrantParams is grants.add's request. type GrantParams struct { - PublicKey string `json:"publicKey"` // hex X25519 - ID string `json:"id"` - Name string `json:"name"` - Scopes []string `json:"scopes"` + RequestedAt *time.Time `json:"requestedAt,omitempty"` // set when approving a specific pending request + PublicKey string `json:"publicKey"` // hex X25519 + ID string `json:"id"` + Name string `json:"name"` + Scopes []string `json:"scopes"` // LifetimeSeconds is the hard limit from now, on the machine's clock: a deadline from the // browser would be off by the two clocks' difference. LifetimeSeconds int64 `json:"lifetimeSeconds"` @@ -70,12 +77,40 @@ func (p *Peer) grants(msg *wire.Message) { switch msg.Method { case MethodGrantsList: out := []Record{} - for _, r := range t.Store.List() { - if r.Grant != nil && r.Active(time.Now()) { - out = append(out, r) + var pending []GrantRequest + err := t.Store.update(func(st *state) error { + now := time.Now() + st.pruneRequests(now) + pending = slices.Clone(st.Requests) + for _, r := range st.Peers { + if r.Grant != nil && r.Active(now) { + out = append(out, *r.clone()) + } } + return nil + }) + if err != nil { + p.ep.Answer(msg, nil, wire.Errorf(codeInternal, "%s", err.Error())) + return + } + p.ep.Answer(msg, map[string]any{"grants": out, "requests": pending}, nil) + case MethodGrantDismiss: + var in struct { + ClientID string `json:"clientId"` + RequestedAt time.Time `json:"requestedAt"` + } + if json.Unmarshal(msg.Params, &in) != nil || in.ClientID == "" || in.RequestedAt.IsZero() { + p.ep.Answer(msg, nil, wire.Errorf(codeInvalidParams, "invalid request")) + return } - p.ep.Answer(msg, map[string]any{"grants": out}, nil) + if err := t.Store.update(func(st *state) error { + st.Requests = slices.DeleteFunc(st.Requests, func(r GrantRequest) bool { return r.ClientID == in.ClientID && r.RequestedAt.Equal(in.RequestedAt) }) + return nil + }); err != nil { + p.ep.Answer(msg, nil, wire.Errorf(codeInternal, "%s", err.Error())) + return + } + p.ep.Answer(msg, map[string]any{}, nil) case MethodGrantsRevoke: var params struct { ClientID string `json:"clientId"` @@ -120,10 +155,6 @@ func (p *Peer) grants(msg *wire.Message) { return } clientID := sc.ClientID(pub) - if existing := t.Store.Lookup(clientID); existing != nil && existing.Grant == nil { - p.ep.Answer(msg, nil, wire.Errorf(codeInvalidParams, "that key is a browser's, not a service's")) - return - } name := params.Name if len(name) > 80 { name = name[:80] @@ -131,10 +162,14 @@ func (p *Peer) grants(msg *wire.Message) { if name == "" { name = "Delegated key" } - r, err := t.Store.AddGrant(clientID, pub, name, slices.Clone(params.Scopes), Grant{ - ID: params.ID, ExpiresAt: now.Add(lifetime).UTC(), IdleSeconds: params.IdleSeconds, By: rec.ClientID}) + r, err := t.Store.addGrant(clientID, pub, name, slices.Clone(params.Scopes), Grant{ + ID: params.ID, ExpiresAt: now.Add(lifetime).UTC(), IdleSeconds: params.IdleSeconds, By: rec.ClientID}, params.RequestedAt) if err != nil { - p.ep.Answer(msg, nil, wire.Errorf(codeInternal, "%s", err.Error())) + code := codeInternal + if errors.Is(err, errRequestGone) || errors.Is(err, errBrowserGrant) { + code = codeInvalidParams + } + p.ep.Answer(msg, nil, wire.Errorf(code, "%s", err.Error())) return } // A replaced grant may carry less than before: channels opened under the old one end, diff --git a/internal/host/peer/store.go b/internal/host/peer/store.go index 4d5f97c..0772d74 100644 --- a/internal/host/peer/store.go +++ b/internal/host/peer/store.go @@ -92,7 +92,8 @@ func (r *Record) Active(now time.Time) bool { } type state struct { - Peers []*Record `json:"peers"` + Peers []*Record `json:"peers"` + Requests []GrantRequest `json:"requests,omitempty"` } // Store keeps the host key and the approved keys under Dir (peers.json and noise.json, both @@ -263,10 +264,26 @@ func (s *Store) Add(clientID string, pub []byte, name string, scopes []string) ( // AddGrant trusts a delegated key until its grant runs out (again replaces the earlier record). func (s *Store) AddGrant(clientID string, pub []byte, name string, scopes []string, g Grant) (*Record, error) { + return s.addGrant(clientID, pub, name, scopes, g, nil) +} + +func (s *Store) addGrant(clientID string, pub []byte, name string, scopes []string, g Grant, requestedAt *time.Time) (*Record, error) { var rec Record err := s.update(func(st *state) error { - st.Peers = slices.DeleteFunc(st.Peers, func(r *Record) bool { return r.ClientID == clientID }) now := time.Now().UTC() + st.pruneRequests(now) + if requestedAt != nil && !slices.ContainsFunc(st.Requests, func(r GrantRequest) bool { + return r.ClientID == clientID && r.ID == g.ID && r.RequestedAt.Equal(*requestedAt) + }) { + return errRequestGone + } + if slices.ContainsFunc(st.Peers, func(r *Record) bool { return r.ClientID == clientID && r.Grant == nil }) { + return errBrowserGrant + } + st.Peers = slices.DeleteFunc(st.Peers, func(r *Record) bool { return r.ClientID == clientID }) + st.Requests = slices.DeleteFunc(st.Requests, func(r GrantRequest) bool { + return r.ClientID == clientID && (requestedAt != nil || slices.Contains(scopes, r.Scope)) + }) g.LastUsed = now r := &Record{ClientID: clientID, PublicKey: hex.EncodeToString(pub), Name: name, Scopes: scopes, AddedAt: now, Grant: &g} st.Peers = append(st.Peers, r) @@ -305,6 +322,7 @@ func (s *Store) Use(clientID string, now time.Time) *Record { // returns their client ids. func (s *Store) Expire(now time.Time) (gone []string) { _ = s.update(func(st *state) error { + st.pruneRequests(now) st.Peers = slices.DeleteFunc(st.Peers, func(r *Record) bool { if r.Active(now) { return false @@ -324,6 +342,7 @@ func (s *Store) Revoke(clientID string) (bool, error) { err := s.update(func(st *state) error { n := len(st.Peers) st.Peers = slices.DeleteFunc(st.Peers, func(r *Record) bool { return r.ClientID == clientID }) + st.Requests = slices.DeleteFunc(st.Requests, func(r GrantRequest) bool { return r.ClientID == clientID }) found = len(st.Peers) != n return nil }) diff --git a/internal/host/peer/table.go b/internal/host/peer/table.go index 960d49a..946dc3a 100644 --- a/internal/host/peer/table.go +++ b/internal/host/peer/table.go @@ -24,8 +24,7 @@ import ( // Methods a channel answers itself, before the router. const ( - // MethodAuthToken presents the owner's identity token: the only call an untrusted key may - // make. + // MethodAuthToken presents the owner's identity token. MethodAuthToken = "auth.token" // MethodHostKey is the notification that tells the control plane this machine's public // key, for browsers to open a channel with. @@ -33,6 +32,8 @@ const ( // MethodHostInfo tells a trusted client who it is talking to and what it may do. MethodHostInfo = "host.info" // Grants: a trusted browser hands a time-boxed key to a service (grants.go). + MethodGrantRequest = "grants.request" + MethodGrantDismiss = "grants.dismiss" MethodGrantsAdd = "grants.add" MethodGrantsList = "grants.list" MethodGrantsRevoke = "grants.revoke" @@ -57,6 +58,8 @@ type Table struct { Router *rpc.Router // Owner is the account this machine was enrolled to (the identity provider's subject). Owner string + // MCPURL is the configured Outpost MCP endpoint for verifying new connection requests. + MCPURL string // Verifier checks identity tokens. Without one, or without an Owner, no new key is trusted. Verifier Verifier // Info is the host description host.info returns. @@ -381,7 +384,7 @@ func (p *Peer) run(open []byte) string { p.rec.Store(known) } // Otherwise this is an authenticated key the machine has not seen. It may present its - // owner's identity token and nothing else. + // owner's identity token or record an access request. msg2, cs1, cs2, err := hs.WriteMessage(nil, nil) if err != nil || cs1 == nil { return sc.ReasonHandshakeFailed @@ -439,7 +442,7 @@ func (p *Peer) run(open []byte) string { if json.Unmarshal(raw, &msg) != nil || msg.JSONRPC != wire.Version { return sc.ReasonProtocolError } - if p.rec.Load() == nil && msg.Method != MethodAuthToken { + if p.rec.Load() == nil && msg.Method != MethodAuthToken && msg.Method != MethodGrantRequest { return sc.ReasonApprovalRequired } p.ep.Dispatch(&msg) @@ -473,7 +476,10 @@ func (p *Peer) local(msg *wire.Message) bool { return true } switch msg.Method { - case MethodGrantsAdd, MethodGrantsList, MethodGrantsRevoke: + case MethodGrantRequest: + p.requestGrant(msg) + return true + case MethodGrantsAdd, MethodGrantsList, MethodGrantsRevoke, MethodGrantDismiss: p.grants(msg) return true case MethodAuthToken: diff --git a/internal/mcpserver/agents.go b/internal/mcpserver/agents.go index 9eab837..399dfae 100644 --- a/internal/mcpserver/agents.go +++ b/internal/mcpserver/agents.go @@ -51,7 +51,7 @@ func (s *Server) agentCreate(ctx context.Context, req *mcp.CallToolRequest, in A // Creating also fetches the shared Outpost prompt, with its own 15-second deadline. ctx, cancel := context.WithTimeout(ctx, perHost+20*time.Second) defer cancel() - c, h, ask, early, err := s.reach(ctx, req, u, in.Machine) + c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeSteer) if c == nil { var out AgentCreated if early != nil { @@ -68,15 +68,10 @@ func (s *Server) agentCreate(ctx context.Context, req *mcp.CallToolRequest, in A var rpcErr *wire.Error if errors.As(err, &rpcErr) { switch { - case rpcErr.Code == peer.CodeForbidden && strings.Contains(rpcErr.Message, `"steer" scope`): - if ask, err := s.approval(u, req); ask != nil || err != nil { - return ask, AgentCreated{}, err - } - key, err := s.key(u) - if err != nil { - return nil, AgentCreated{}, err - } - return nil, AgentCreated{MachineID: h.ID, Access: AccessNeedsApproval, ApproveURL: s.approveURL(u, key), Error: "Choose View and steer sessions for this machine to create an agent."}, nil + case needsSteer(err): + recordGrantRequest(ctx, c, u, peer.ScopeSteer) + ask, approval, err := s.machineApproval(u, req, h, peer.ScopeSteer) + return ask, AgentCreated{MachineID: h.ID, Access: approval.Access, ApproveURL: approval.ApproveURL, Error: "Choose View and steer sessions for this machine to create an agent."}, err case rpcErr.Code == wire.CodeMethodNotFound || (rpcErr.Code == peer.CodeForbidden && strings.Contains(rpcErr.Message, `"admin" scope`)): return nil, AgentCreated{}, fmt.Errorf("update Outpost on %s to a version that supports agent_create", h.Name) } diff --git a/internal/mcpserver/grant_requests.go b/internal/mcpserver/grant_requests.go new file mode 100644 index 0000000..cba7105 --- /dev/null +++ b/internal/mcpserver/grant_requests.go @@ -0,0 +1,63 @@ +package mcpserver + +import ( + "context" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/url" + "strings" + "time" + + "github.com/andyjmorgan/outpost/internal/client" + "github.com/andyjmorgan/outpost/internal/host/peer" + "github.com/andyjmorgan/outpost/internal/host/wire" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// A host checks its own account and the public key proven by the requesting channel. +// This endpoint only confirms a match. It never gives a caller a key or a grant. +func (s *Server) grantIdentity(w http.ResponseWriter, r *http.Request) { + var id peer.GrantIdentity + if json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&id) != nil { + http.Error(w, "invalid grant identity", http.StatusBadRequest) + return + } + pub, err := hex.DecodeString(id.PublicKey) + if err != nil || len(pub) != 32 || id.ID == "" || id.Owner == "" { + http.Error(w, "invalid grant identity", http.StatusBadRequest) + return + } + key, err := s.cfg.Keys.For(id.Owner, id.Client, id.ID) + if err != nil || subtle.ConstantTimeCompare(key.Public, pub) != 1 { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"name": s.cfg.GrantName}) +} + +func recordGrantRequest(ctx context.Context, c *client.Conn, u user, scope string) { + // Older hosts only have the approval link. A failure to save the request + // must leave both the link and URL elicitation available. + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + _ = c.Call(ctx, peer.MethodGrantRequest, map[string]string{"id": u.grantID(), "client": u.Client, "scope": scope}, nil) +} + +func needsSteer(err error) bool { + var rpcErr *wire.Error + return errors.As(err, &rpcErr) && rpcErr.Code == peer.CodeForbidden && strings.Contains(rpcErr.Message, `"steer" scope`) +} + +func (s *Server) machineApproval(u user, req *mcp.CallToolRequest, h relayHost, scope string) (*mcp.CallToolResult, SessionRead, error) { + key, err := s.key(u) + if err != nil { + return nil, SessionRead{}, err + } + link := s.approveURL(u, key) + "&machine=" + url.QueryEscape(h.ID) + "&scope=" + url.QueryEscape(scope) + ask, err := s.elicitApproval(u, req, link, ClientID(key)) + return ask, SessionRead{Access: AccessNeedsApproval, ApproveURL: link, Entries: []SessionEntry{}}, err +} diff --git a/internal/mcpserver/server.go b/internal/mcpserver/server.go index b0270a1..7f630c3 100644 --- a/internal/mcpserver/server.go +++ b/internal/mcpserver/server.go @@ -127,6 +127,14 @@ const currentProtocol = "2026-07-28" // when the call is already the one asked again: a person who came back without approving is // not sent round a second time. func (s *Server) approval(u user, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) { + key, err := s.key(u) + if err != nil { + return nil, err + } + return s.elicitApproval(u, req, s.approveURL(u, key), ClientID(key)) +} + +func (s *Server) elicitApproval(u user, req *mcp.CallToolRequest, link, keyID string) (*mcp.CallToolResult, error) { // A newer client states what it can do with each request; an older one said so once, when // it opened. takes, current := false, false @@ -149,15 +157,11 @@ func (s *Server) approval(u user, req *mcp.CallToolRequest) (*mcp.CallToolResult if !takes { return nil, nil } - key, err := s.key(u) - if err != nil { - return nil, nil - } ask := &mcp.ElicitParams{ Mode: "url", Message: "Choose which of your machines " + s.cfg.GrantName + " may reach, and for how long.", - URL: s.approveURL(u, key), - ElicitationID: "outpost-grant-" + ClientID(key), + URL: link, + ElicitationID: "outpost-grant-" + keyID, } if current { return &mcp.CallToolResult{InputRequests: mcp.InputRequestMap{approvalKey: ask}}, nil @@ -263,6 +267,7 @@ const Path = "/mcp" func (s *Server) Handler() http.Handler { h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return s.mcp() }, &mcp.StreamableHTTPOptions{Stateless: true}) mux := http.NewServeMux() + mux.HandleFunc("POST "+Path+"/grant-identity", s.grantIdentity) ok := func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "ok") } mux.HandleFunc("GET /livez", ok) mux.HandleFunc("GET /readyz", ok) @@ -459,7 +464,7 @@ const ( ) // dial opens a channel to one machine with this sign-in's key. -func (s *Server) dial(ctx context.Context, u user, h relayHost) (*client.Conn, string, error) { +func (s *Server) dial(ctx context.Context, u user, h relayHost, scope string) (*client.Conn, string, error) { if !h.Online { return nil, AccessOffline, nil } @@ -473,9 +478,15 @@ func (s *Server) dial(ctx context.Context, u user, h relayHost) (*client.Conn, s } ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() - c, err := client.Dial(ctx, client.Options{Server: s.cfg.Outpost, Token: u.Token, HostID: h.ID, HostKey: hostKey, Static: key, Pattern: "KK"}) + opts := client.Options{Server: s.cfg.Outpost, Token: u.Token, HostID: h.ID, HostKey: hostKey, Static: key, Pattern: "KK"} + c, err := client.Dial(ctx, opts) var ce *client.CloseError if errors.As(err, &ce) && (ce.Reason == sc.ReasonUnknownClient || ce.Reason == sc.ReasonGrantExpired || ce.Reason == sc.ReasonRevoked) { + opts.Pattern = "IK" + if pending, err := client.Dial(ctx, opts); err == nil { + recordGrantRequest(ctx, pending, u, scope) + pending.Close() + } return nil, AccessNeedsApproval, nil } if err != nil { @@ -530,7 +541,7 @@ func (s *Server) machinesList(ctx context.Context, req *mcp.CallToolRequest, _ a ctx, cancel := context.WithTimeout(ctx, perHost) defer cancel() m := Machine{ID: h.ID, Name: h.Name, OS: h.OS, AgentVersion: h.AgentVersion, Online: h.Online} - c, access, err := s.dial(ctx, u, h) + c, access, err := s.dial(ctx, u, h, peer.ScopeView) m.Access = access if err != nil { m.Error = err.Error() @@ -667,7 +678,7 @@ func (s *Server) sessionsList(ctx context.Context, req *mcp.CallToolRequest, in results := each(hosts, func(h relayHost) result { ctx, cancel := context.WithTimeout(ctx, perHost) defer cancel() - c, access, err := s.dial(ctx, u, h) + c, access, err := s.dial(ctx, u, h, peer.ScopeView) if c == nil { m := &Machine{ID: h.ID, Name: h.Name, Online: h.Online, Access: access} if err != nil { @@ -789,7 +800,7 @@ func sessionRow(h relayHost, hs hostSession) Session { // reach opens a channel to the machine a session is on. When the machine does not answer, the // channel is nil and what to tell the client comes back instead: a question that sends the // person to approve, or an answer saying why. -func (s *Server) reach(ctx context.Context, req *mcp.CallToolRequest, u user, machine string) (*client.Conn, relayHost, *mcp.CallToolResult, *SessionRead, error) { +func (s *Server) reach(ctx context.Context, req *mcp.CallToolRequest, u user, machine, scope string) (*client.Conn, relayHost, *mcp.CallToolResult, *SessionRead, error) { hosts, err := s.hosts(ctx, u) if err != nil { return nil, relayHost{}, nil, nil, err @@ -798,17 +809,14 @@ func (s *Server) reach(ctx context.Context, req *mcp.CallToolRequest, u user, ma if err != nil { return nil, relayHost{}, nil, nil, err } - c, access, err := s.dial(ctx, u, h) + c, access, err := s.dial(ctx, u, h, scope) if c != nil { return c, h, nil, nil, nil } out := &SessionRead{Entries: []SessionEntry{}, Access: access} if access == AccessNeedsApproval { - if ask, err := s.approval(u, req); ask != nil || err != nil { - return nil, h, ask, nil, err - } - key, _ := s.key(u) - out.ApproveURL = s.approveURL(u, key) + ask, result, err := s.machineApproval(u, req, h, scope) + return nil, h, ask, &result, err } else if err != nil { out.Error = err.Error() } @@ -855,7 +863,7 @@ func (s *Server) sessionRead(ctx context.Context, req *mcp.CallToolRequest, in S } ctx, cancel := context.WithTimeout(ctx, perHost) defer cancel() - c, h, ask, early, err := s.reach(ctx, req, u, in.Machine) + c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeView) if c == nil { if early == nil { early = &SessionRead{} @@ -881,7 +889,7 @@ func (s *Server) steer(ctx context.Context, req *mcp.CallToolRequest, machine, s } ctx, cancel := context.WithTimeout(ctx, perHost) defer cancel() - c, h, ask, early, err := s.reach(ctx, req, u, machine) + c, h, ask, early, err := s.reach(ctx, req, u, machine, peer.ScopeSteer) if c == nil { if early == nil { early = &SessionRead{} @@ -891,8 +899,9 @@ func (s *Server) steer(ctx context.Context, req *mcp.CallToolRequest, machine, s defer c.Close() cmd := map[string]any{"id": "mcp-" + hex.EncodeToString(randomBytes(12)), "sessionId": session, "op": op, "args": args} if err := c.Call(ctx, "command", cmd, nil); err != nil { - if strings.Contains(err.Error(), "scope") { - return nil, SessionRead{}, fmt.Errorf("this connection may only look at %s; steering it needs the steer access the user did not grant", h.Name) + if needsSteer(err) { + recordGrantRequest(ctx, c, u, peer.ScopeSteer) + return s.machineApproval(u, req, h, peer.ScopeSteer) } return nil, SessionRead{}, err } @@ -1009,7 +1018,7 @@ func (s *Server) foldersList(ctx context.Context, req *mcp.CallToolRequest, in F results := each(hosts, func(h relayHost) result { ctx, cancel := context.WithTimeout(ctx, perHost) defer cancel() - c, access, err := s.dial(ctx, u, h) + c, access, err := s.dial(ctx, u, h, peer.ScopeView) if c == nil { m := &Machine{ID: h.ID, Name: h.Name, Online: h.Online, Access: access} if err != nil { @@ -1116,7 +1125,7 @@ func (s *Server) sessionStart(ctx context.Context, req *mcp.CallToolRequest, in } ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) // a worktree of a large repository takes a while defer cancel() - c, h, ask, early, err := s.reach(ctx, req, u, in.Machine) + c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeSteer) if c == nil { if early == nil { early = &SessionRead{} @@ -1141,8 +1150,9 @@ func (s *Server) sessionStart(ctx context.Context, req *mcp.CallToolRequest, in } cmd := map[string]any{"id": "mcp-" + hex.EncodeToString(randomBytes(12)), "op": "session.start", "args": args} if err := c.Call(ctx, "command", cmd, nil); err != nil { - if strings.Contains(err.Error(), "scope") { - return nil, SessionRead{}, fmt.Errorf("this connection may only look at %s; starting a session needs the steer access the user did not grant", h.Name) + if needsSteer(err) { + recordGrantRequest(ctx, c, u, peer.ScopeSteer) + return s.machineApproval(u, req, h, peer.ScopeSteer) } return nil, SessionRead{}, err } diff --git a/internal/mcpserver/wake.go b/internal/mcpserver/wake.go index e9e303d..f61fcfe 100644 --- a/internal/mcpserver/wake.go +++ b/internal/mcpserver/wake.go @@ -47,7 +47,7 @@ func (s *Server) agentWake(ctx context.Context, req *mcp.CallToolRequest, in Age } ctx, cancel := context.WithTimeout(ctx, perHost+15*time.Second) defer cancel() - c, h, ask, early, err := s.reach(ctx, req, u, in.Machine) + c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeSteer) if c == nil { if early != nil { result.Access, result.ApproveURL, result.Error = early.Access, early.ApproveURL, early.Error @@ -58,17 +58,10 @@ func (s *Server) agentWake(ctx context.Context, req *mcp.CallToolRequest, in Age err = c.Call(ctx, "agents.setWake", map[string]any{"sessionId": in.Session, "at": at, "cancel": in.Cancel}, &result) if err != nil { var rpcErr *wire.Error - if errors.As(err, &rpcErr) && rpcErr.Code == peer.CodeForbidden && strings.Contains(rpcErr.Message, `"steer" scope`) { - if ask, err := s.approval(u, req); ask != nil || err != nil { - return ask, result, err - } - key, err := s.key(u) - if err != nil { - return nil, result, err - } - result.Access, result.ApproveURL = AccessNeedsApproval, s.approveURL(u, key) - result.Error = "Choose View and steer sessions for this machine to schedule a wake." - return nil, result, nil + if needsSteer(err) { + recordGrantRequest(ctx, c, u, peer.ScopeSteer) + ask, approval, err := s.machineApproval(u, req, h, peer.ScopeSteer) + return ask, AgentWakeResult{Access: approval.Access, ApproveURL: approval.ApproveURL, Error: "Choose View and steer sessions for this machine to schedule a wake."}, err } if errors.As(err, &rpcErr) && (rpcErr.Code == wire.CodeMethodNotFound || (rpcErr.Code == peer.CodeForbidden && (strings.Contains(rpcErr.Message, `"admin" scope`) || strings.Contains(rpcErr.Message, "may only reach sessions")))) { return nil, result, fmt.Errorf("update Outpost on %s to schedule named-agent wakes", h.Name) diff --git a/web/src/pages/Connections.tsx b/web/src/pages/Connections.tsx index 2c0a174..9c9758f 100644 --- a/web/src/pages/Connections.tsx +++ b/web/src/pages/Connections.tsx @@ -1,5 +1,5 @@ -import { useEffect, useMemo, useRef, useState } from 'react' -import { useLocation } from 'react-router-dom' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { Link, useLocation } from 'react-router-dom' import { KeyRound, Server } from 'lucide-react' import { FormSection } from '../components/FormField' import { Callout } from '../components/Callout' @@ -18,11 +18,28 @@ import { absoluteTime, cn } from '../lib' // service's key, for a while and for a little. The machine enforces both limits itself. interface Ask { + machine: string | null + scope: string | null + requestedAt: string | null key: string id: string name: string } +interface PendingRequest { + clientId: string + publicKey: string + id: string + name: string + scope: 'view' | 'steer' + requestedAt: string +} + +interface ConnectionsOnMachine { + grants: Grant[] + requests?: PendingRequest[] | null +} + interface Grant { clientId: string name: string @@ -51,7 +68,7 @@ function readAsk(hash: string): Ask | null { const key = q.get('key') ?? '' const id = q.get('id') ?? '' if (!/^[0-9a-f]{64}$/.test(key) || !id) return null - return { key, id, name: (q.get('name') || 'A service').slice(0, 80) } + return { key, id, name: (q.get('name') || 'A service').slice(0, 80), machine: q.get('machine'), scope: q.get('scope'), requestedAt: q.get('requestedAt') } } const label = (h: RelayHost) => h.name || h.hostId @@ -66,6 +83,10 @@ export function useAsk(): { ask: Ask | null; hash: string } { export function Connections() { const { ask, hash } = useAsk() + return +} + +function ConnectionSettings({ ask, hash }: { ask: Ask | null; hash: string }) { const askRef = useRef(null) useEffect(() => { if (ask) askRef.current?.scrollIntoView({ block: 'start' }) @@ -73,39 +94,57 @@ export function Connections() { const [keyId, setKeyId] = useState('') const [hosts, setHosts] = useState(null) const [picked, setPicked] = useState>(new Set()) - const [steer, setSteer] = useState(false) + const [steer, setSteer] = useState(ask?.scope === 'steer') const [idle, setIdle] = useState(String(8 * HOUR)) const [limit, setLimit] = useState(String(30 * DAY)) const [busy, setBusy] = useState(false) const [results, setResults] = useState>({}) - const [grants, setGrants] = useState>({}) + const [connections, setConnections] = useState>({}) + const [actionError, setActionError] = useState('') const [loadError, setLoadError] = useState('') // Machines whose grants could not be listed (offline, an older agent, a refusal): the list // cannot speak for them, so it says so rather than claim nothing reaches them. const [unchecked, setUnchecked] = useState | null>(null) - const loadGrants = async (list: RelayHost[]) => { - const out: Record = {} - const missed: Record = {} - await Promise.all( - list.map(async (h) => { + const loadVersion = useRef(0) + const initialized = useRef(false) + const refreshing = useRef(false) + const refresh = useCallback(async () => { + refreshing.current = true + const version = ++loadVersion.current + try { + const list = await listRelayHosts() + if (version !== loadVersion.current) return + setHosts(list) + setLoadError('') + if (!initialized.current) { + initialized.current = true + setPicked(new Set(list.filter((h) => h.online && (!ask?.machine || ask.machine === h.hostId)).map((h) => h.hostId))) + } + const out: Record = {} + const missed: Record = {} + await Promise.all(list.map(async (h) => { if (!h.online) { missed[h.hostId] = 'offline' return } try { const conn = await connect(h.hostId) - out[h.hostId] = (await conn.call<{ grants: Grant[] }>('grants.list')).grants + out[h.hostId] = await conn.call('grants.list') } catch (e) { missed[h.hostId] = refusal(e) } - }), - ) - setGrants(out) - setUnchecked(missed) - } - + })) + if (version !== loadVersion.current) return + setConnections(out) + setUnchecked(missed) + } catch (e) { + if (version === loadVersion.current) setLoadError((e as Error).message) + } finally { + if (version === loadVersion.current) refreshing.current = false + } + }, [ask]) // An approval is for the request and settings it was made with: any change asks again, and an // approval still in flight for the old ones is not reported against the new. const generation = useRef(0) @@ -115,16 +154,17 @@ export function Connections() { }, [ask, steer, idle, limit, picked]) useEffect(() => { - setKeyId('') if (ask) void clientIdOf(unhex(ask.key)).then(setKeyId) - listRelayHosts() - .then((list) => { - setHosts(list) - setPicked(new Set(list.filter((h) => h.online).map((h) => h.hostId))) - void loadGrants(list) - }) - .catch((e) => setLoadError((e as Error).message)) - }, [ask]) + void refresh() + const refreshVisible = () => { if (!document.hidden && !refreshing.current) void refresh() } + const timer = window.setInterval(refreshVisible, 15000) + window.addEventListener('focus', refreshVisible) + return () => { + loadVersion.current++ + clearInterval(timer) + window.removeEventListener('focus', refreshVisible) + } + }, [ask, refresh]) const approve = async () => { if (!ask || !hosts) return @@ -139,6 +179,7 @@ export function Connections() { publicKey: ask.key, id: ask.id, name: ask.name, + requestedAt: ask.requestedAt ?? undefined, scopes: steer ? ['view', 'steer'] : ['view'], lifetimeSeconds: Number(limit), idleSeconds: Number(idle), @@ -151,7 +192,7 @@ export function Connections() { ) if (gen === generation.current) setResults(next) setBusy(false) - void loadGrants(hosts) + void refresh() } const revoke = async (hostId: string, clientId: string) => { @@ -168,22 +209,33 @@ export function Connections() { } catch (e) { setResults((r) => ({ ...r, [hostId]: refusal(e) })) } - if (hosts) void loadGrants(hosts) + void refresh() + } + + const dismiss = async (hostId: string, request: PendingRequest) => { + setActionError('') + try { + const conn = await connect(hostId) + await conn.call('grants.dismiss', { clientId: request.clientId, requestedAt: request.requestedAt }) + } catch (e) { + setActionError(refusal(e)) + } + void refresh() } + const pending = hosts?.flatMap((host) => (connections[host.hostId]?.requests ?? []).map((request) => ({ host, request }))) ?? [] const approvedAll = ask && Object.keys(results).length > 0 && Object.values(results).every((r) => r === 'ok') - const existing = hosts?.flatMap((h) => (grants[h.hostId] ?? []).map((g) => ({ host: h, g }))) ?? [] + const existing = hosts?.flatMap((h) => (connections[h.hostId]?.grants ?? []).map((g) => ({ host: h, g }))) ?? [] return ( <> {ask && ( - // Approvals sit below the preferences; a link that carries a request scrolls to it.

Allow {ask.name}?

{ask.name} will be able to {steer ? 'read and steer' : 'read'} sessions on the machines you pick, until it is idle for{' '} {idleOptions.find(([v]) => v === idle)?.[1]} or {limitOptions.find(([v]) => v === limit)?.[1]} pass. Its key is held by the service, so the - service sees what it reads. {steer && 'Steer access also lets the service create named agents with permanent chats. '}Only approve a link you just asked for. + service sees what it reads. {steer && 'Steer access also lets the service create named agents with permanent chats. '}Approve requests you recognize.
@@ -205,8 +257,9 @@ export function Connections() {
{loadError &&

Your machines could not be loaded: {loadError}

} {!hosts && !loadError &&

Loading machines…

} - {hosts?.length === 0 &&

No machines yet.

} - {hosts?.map((h) => ( + {ask.machine && hosts && !hosts.some((h) => h.hostId === ask.machine) &&

The requested machine is unavailable.

} + {!ask.machine && hosts?.length === 0 &&

No machines yet.

} + {hosts?.filter((h) => !ask.machine || h.hostId === ask.machine).map((h) => (