Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/outpost-host/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
48 changes: 43 additions & 5 deletions internal/e2e/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -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))

Expand All @@ -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)
Expand Down
118 changes: 118 additions & 0 deletions internal/host/peer/grant_requests.go
Original file line number Diff line number Diff line change
@@ -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
}
40 changes: 40 additions & 0 deletions internal/host/peer/grant_requests_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
65 changes: 50 additions & 15 deletions internal/host/peer/grants.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package peer
import (
"encoding/hex"
"encoding/json"
"errors"
"slices"
"time"

Expand All @@ -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}

Expand All @@ -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"`
Expand All @@ -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"`
Expand Down Expand Up @@ -120,21 +155,21 @@ 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]
}
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,
Expand Down
Loading
Loading