feat(kit): central tools for harnesses through the egress proxy and gateway task-tool RPCs
This commit is contained in:
41 files changed
+2187
-189
No files matched your search
@@ -41,13 +41,16 @@ func TestCredentialPhaseEnforcement(t *testing.T) {
|
||||
{Service: "key", Phase: phases, APIKey: &spec.APIKey{Inject: []spec.Inject{{Domain: "api.example", Header: "X-Key"}}}},
|
||||
{Service: "oauth", Phase: phases, OAuth: &spec.OAuth{TokenEndpoint: &spec.TokenEndpoint{Host: "token.example", Path: "/token"}, ResourceHosts: []string{"api.example"}, Sentinels: &spec.Sentinels{AccessToken: "sentinel"}}},
|
||||
}
|
||||
proxy := NewProxy(nil, ProxyOptions{Resolver: ResolverFunc(func(context.Context, string, string) (string, error) {
|
||||
proxy := NewProxy(nil, ProxyOptions{Resolver: ResolverFunc(func(_ context.Context, credential, _ string) (string, error) {
|
||||
if credential != "host-run-grant" {
|
||||
t.Fatal("resolver received the container proxy password instead of the host grant")
|
||||
}
|
||||
if tc.revoked {
|
||||
return "", ErrUnbound
|
||||
}
|
||||
return "real-key", nil
|
||||
}), OAuthStore: phaseOAuthStore{}})
|
||||
session := &Session{token: "run", org: "org", injections: compileInjections(creds, nil), oauth: compileOAuthRules(creds, nil)}
|
||||
session := &Session{token: "proxy-password", runCredential: "host-run-grant", org: "org", injections: compileInjections(creds, nil), oauth: compileOAuthRules(creds, nil)}
|
||||
for _, runtime := range []bool{false, true} {
|
||||
session.atRun.Store(runtime)
|
||||
want := tc.install
|
||||
|
||||
@@ -97,7 +97,7 @@ func (p *Proxy) inject(ctx context.Context, s *Session, r *http.Request, host st
|
||||
}
|
||||
continue
|
||||
}
|
||||
secret, err := p.resolver.Resolve(ctx, s.token, rule.service)
|
||||
secret, err := p.resolver.Resolve(ctx, s.credential(), rule.service)
|
||||
switch {
|
||||
case errors.Is(err, ErrUnbound) && !rule.required:
|
||||
continue
|
||||
|
||||
@@ -110,7 +110,7 @@ func (p *Proxy) granted(ctx context.Context, s *Session, rule oauthRule) (bool,
|
||||
case p.resolver == nil:
|
||||
err = ErrUnbound
|
||||
default:
|
||||
_, err = p.resolver.Resolve(ctx, s.token, rule.service)
|
||||
_, err = p.resolver.Resolve(ctx, s.credential(), rule.service)
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
|
||||
@@ -2,9 +2,11 @@ package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
@@ -20,6 +22,7 @@ import (
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/access"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/tasktools"
|
||||
)
|
||||
|
||||
// proxyUser is the fixed user name in a sandbox's proxy URL; the session
|
||||
@@ -38,6 +41,9 @@ var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
|
||||
type Session struct {
|
||||
token string
|
||||
runCredential string
|
||||
gatewayToken string
|
||||
lifetime context.Context //nolint:containedctx // Session lifetime cancels active HTTP requests.
|
||||
cancel context.CancelFunc
|
||||
principal access.Principal
|
||||
org string
|
||||
install rules
|
||||
@@ -48,8 +54,7 @@ type Session struct {
|
||||
atRun atomic.Bool
|
||||
}
|
||||
|
||||
// Token is the secret the container presents as its proxy password: its run
|
||||
// credential.
|
||||
// Token is the proxy password the container may hold; it is not its task grant.
|
||||
func (s *Session) Token() string { return s.token }
|
||||
|
||||
// EnterRuntime switches the session from install-phase to runtime-phase
|
||||
@@ -82,14 +87,14 @@ type ProxyOptions struct {
|
||||
// OAuthStore holds the org token sets OAuth credentials use. Without
|
||||
// one, Register refuses a session with a required OAuth credential.
|
||||
OAuthStore OAuthStore
|
||||
TaskTools tasktools.Backend
|
||||
}
|
||||
|
||||
// SessionOptions describe one container's run: the run credential it acts
|
||||
// under, the org whose OAuth token sets it uses, and its Kit's network
|
||||
// policy and credential requests.
|
||||
type SessionOptions struct {
|
||||
// Token is the run credential: the container's proxy password, and what
|
||||
// the Resolver resolves the run from.
|
||||
// Token is the container's proxy password. RunCredential stays on the host.
|
||||
Token string
|
||||
// RunCredential scopes task OAuth operations; setup sessions forward Principal.
|
||||
RunCredential string
|
||||
@@ -116,6 +121,7 @@ type Proxy struct {
|
||||
transport *http.Transport
|
||||
resolver Resolver
|
||||
oauth OAuthStore
|
||||
taskTools tasktools.Backend
|
||||
|
||||
mu sync.RWMutex
|
||||
sessions map[string]*Session
|
||||
@@ -124,7 +130,7 @@ type Proxy struct {
|
||||
type sessionKey struct{}
|
||||
|
||||
func NewProxy(ca *CA, opts ProxyOptions) *Proxy {
|
||||
p := &Proxy{ca: ca, dial: opts.Dial, resolver: opts.Resolver, oauth: opts.OAuthStore, sessions: map[string]*Session{}}
|
||||
p := &Proxy{ca: ca, dial: opts.Dial, resolver: opts.Resolver, oauth: opts.OAuthStore, taskTools: opts.TaskTools, sessions: map[string]*Session{}}
|
||||
p.transport = &http.Transport{
|
||||
DialContext: p.dialUpstream,
|
||||
TLSClientConfig: &tls.Config{RootCAs: opts.UpstreamRoots, MinVersion: tls.VersionTLS12},
|
||||
@@ -145,6 +151,14 @@ func (p *Proxy) Register(opts SessionOptions) (*Session, error) {
|
||||
injections: compileInjections(opts.Credentials, opts.Bound), oauth: compileOAuthRules(opts.Credentials, opts.Bound),
|
||||
substitutions: compileSubstitutions(opts.Substitutions),
|
||||
}
|
||||
if opts.RunCredential != "" && p.taskTools != nil {
|
||||
var token [32]byte
|
||||
if _, err := rand.Read(token[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.gatewayToken = hex.EncodeToString(token[:])
|
||||
s.lifetime, s.cancel = context.WithCancel(context.Background())
|
||||
}
|
||||
for _, rule := range s.oauth {
|
||||
if rule.required && p.oauth == nil {
|
||||
return nil, fmt.Errorf("credential %q is OAuth-managed and no harness secret store is configured", rule.service)
|
||||
@@ -160,10 +174,17 @@ func (p *Proxy) Register(opts SessionOptions) (*Session, error) {
|
||||
}
|
||||
|
||||
// Revoke ends a session. Requests already forwarded finish; new ones fail.
|
||||
func (p *Proxy) Revoke(token string) {
|
||||
func (p *Proxy) Revoke(parent context.Context, token string) {
|
||||
p.mu.Lock()
|
||||
s := p.sessions[token]
|
||||
delete(p.sessions, token)
|
||||
p.mu.Unlock()
|
||||
if s != nil && s.cancel != nil {
|
||||
s.cancel()
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = p.taskTools.Close(ctx, s.runCredential)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Proxy) session(r *http.Request) *Session {
|
||||
@@ -191,6 +212,10 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "proxy authentication required", http.StatusProxyAuthRequired)
|
||||
return
|
||||
}
|
||||
if normalizeHost(r.URL.Hostname()) == "archie.tools" {
|
||||
p.serveTaskTools(r.Context(), w, r, s)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case r.Method == http.MethodConnect:
|
||||
p.serveConnect(w, r, s)
|
||||
@@ -435,3 +460,32 @@ func (c *closeNotifyConn) Close() error {
|
||||
c.once.Do(func() { close(c.done) })
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
func (p *Proxy) serveTaskTools(parent context.Context, w http.ResponseWriter, r *http.Request, s *Session) {
|
||||
if s.gatewayToken == "" || s.phase() != "runtime" || r.URL.String() != tasktools.Endpoint || r.Host != "archie.tools" {
|
||||
http.Error(w, "task tools are unavailable for this session or target", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer "+tasktools.Sentinel {
|
||||
http.Error(w, "task tools sentinel required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
// Only this authenticated proxy hop supplies the host-held gateway token.
|
||||
r = r.Clone(parent)
|
||||
r.Header.Set("Authorization", "Bearer "+s.gatewayToken)
|
||||
r.Header.Del("Proxy-Authorization")
|
||||
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
stop := context.AfterFunc(s.lifetime, cancel) //nolint:contextcheck // Session revocation is an additional cancellation source.
|
||||
defer stop()
|
||||
tasktools.ServeHTTP(ctx, w, r, p.taskTools, s.runCredential, s.gatewayToken)
|
||||
}
|
||||
|
||||
// credential is the host-held task grant, or a setup session's own grant.
|
||||
func (s *Session) credential() string {
|
||||
if s.runCredential != "" {
|
||||
return s.runCredential
|
||||
}
|
||||
return s.token
|
||||
}
|
||||
@@ -51,7 +51,7 @@ func (p *Proxy) substitute(ctx context.Context, s *Session, r *http.Request, hos
|
||||
if p.resolver == nil {
|
||||
return fmt.Errorf("credential %q has no resolver", sub.service)
|
||||
}
|
||||
secret, err := p.resolver.Resolve(ctx, s.token, sub.service)
|
||||
secret, err := p.resolver.Resolve(ctx, s.credential(), sub.service)
|
||||
if errors.Is(err, ErrUnbound) {
|
||||
return fmt.Errorf("credential %q is not bound for this run", sub.service)
|
||||
}
|
||||
|
||||
@@ -43,12 +43,18 @@ func TestSubstitutionReachesOnlyTheServiceHost(t *testing.T) {
|
||||
resolve = func() (string, error) { return "real-key", nil }
|
||||
}
|
||||
proxy := NewProxy(nil, ProxyOptions{
|
||||
Resolver: ResolverFunc(func(context.Context, string, string) (string, error) { return resolve() }),
|
||||
Resolver: ResolverFunc(func(_ context.Context, credential, _ string) (string, error) {
|
||||
if credential != "host-run-grant" {
|
||||
t.Error("resolver received the proxy password")
|
||||
return "", ErrUnbound
|
||||
}
|
||||
return resolve()
|
||||
}),
|
||||
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, "tcp", upstream.Listener.Addr().String())
|
||||
},
|
||||
})
|
||||
session := &Session{token: "run-token", substitutions: compileSubstitutions([]Substitution{{Service: "openai", Host: "api.openai.example"}})}
|
||||
session := &Session{token: "proxy-password", runCredential: "host-run-grant", substitutions: compileSubstitutions([]Substitution{{Service: "openai", Host: "api.openai.example"}})}
|
||||
|
||||
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "http://"+tc.host+tc.target, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+SentinelFor("openai"))
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/tasktools"
|
||||
)
|
||||
|
||||
type proxyTaskTools struct{ calls int }
|
||||
|
||||
func (b *proxyTaskTools) List(context.Context, string) ([]*mcp.Tool, error) {
|
||||
b.calls++
|
||||
return []*mcp.Tool{}, nil
|
||||
}
|
||||
|
||||
func (*proxyTaskTools) Call(context.Context, string, string, json.RawMessage) (*mcp.CallToolResult, error) {
|
||||
return &mcp.CallToolResult{}, nil
|
||||
}
|
||||
func (*proxyTaskTools) Close(context.Context, string) error { return nil }
|
||||
|
||||
func TestTaskToolsProxyConfinement(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, target, auth string
|
||||
task, runtime, revoked bool
|
||||
want int
|
||||
}{
|
||||
{name: "runtime", target: tasktools.Endpoint, auth: tasktools.Sentinel, task: true, runtime: true, want: http.StatusOK},
|
||||
{name: "install", target: tasktools.Endpoint, auth: tasktools.Sentinel, task: true, want: http.StatusForbidden},
|
||||
{name: "setup", target: tasktools.Endpoint, auth: tasktools.Sentinel, runtime: true, want: http.StatusForbidden},
|
||||
{name: "revoked", target: tasktools.Endpoint, auth: tasktools.Sentinel, task: true, runtime: true, revoked: true, want: http.StatusProxyAuthRequired},
|
||||
{name: "forged bearer", target: tasktools.Endpoint, auth: "forged", task: true, runtime: true, want: http.StatusUnauthorized},
|
||||
{name: "other path", target: "http://archie.tools/other", auth: tasktools.Sentinel, task: true, runtime: true, want: http.StatusForbidden},
|
||||
{name: "query", target: tasktools.Endpoint + "?target=victim", auth: tasktools.Sentinel, task: true, runtime: true, want: http.StatusForbidden},
|
||||
{name: "other port", target: "http://archie.tools:8080/mcp", auth: tasktools.Sentinel, task: true, runtime: true, want: http.StatusForbidden},
|
||||
{name: "other host", target: "http://attacker.example/mcp", auth: tasktools.Sentinel, task: true, runtime: true, want: http.StatusForbidden},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
backend := &proxyTaskTools{}
|
||||
proxy := NewProxy(nil, ProxyOptions{TaskTools: backend})
|
||||
opts := SessionOptions{Token: "proxy-password"}
|
||||
if tt.task {
|
||||
opts.RunCredential = "run-grant"
|
||||
}
|
||||
session, err := proxy.Register(opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tt.runtime {
|
||||
session.EnterRuntime()
|
||||
}
|
||||
if tt.revoked {
|
||||
proxy.Revoke(t.Context(), session.Token())
|
||||
}
|
||||
if session.gatewayToken != "" && (session.gatewayToken == session.Token() || session.gatewayToken == tasktools.Sentinel) {
|
||||
t.Fatal("gateway token is container-visible")
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, tt.target, strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}`))
|
||||
req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("archie:"+session.Token())))
|
||||
req.Header.Set("Authorization", "Bearer "+tt.auth)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
response := httptest.NewRecorder()
|
||||
proxy.ServeHTTP(response, req)
|
||||
if response.Code != tt.want {
|
||||
t.Fatalf("status %d, want %d: %s", response.Code, tt.want, response.Body.String())
|
||||
}
|
||||
if tt.want != http.StatusOK && backend.calls != 0 {
|
||||
t.Fatal("rejected request reached gateway")
|
||||
}
|
||||
if session.gatewayToken != "" && strings.Contains(response.Body.String(), session.gatewayToken) {
|
||||
t.Fatal("gateway token escaped in response")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,8 @@ type Request struct {
|
||||
// other.
|
||||
Org string
|
||||
GrantedServices []string
|
||||
// RunCredential is the run's credential: the container's proxy password.
|
||||
// RunCredential is the worker grant, retained only on the host and in the
|
||||
// worker environment. The harness gets a separate proxy password.
|
||||
RunCredential string
|
||||
}
|
||||
|
||||
@@ -180,13 +181,13 @@ func (l *Launcher) LaunchSetup(ctx context.Context, req SetupRequest) (*Run, err
|
||||
// harness environment.
|
||||
launch, err := kit.Assemble(k.plan, k.img, kit.LaunchParams{Execution: req.Session, ProxyToken: session.Token(), CAPath: caPath})
|
||||
if err != nil {
|
||||
l.release(run)
|
||||
l.release(ctx, run)
|
||||
return nil, err
|
||||
}
|
||||
run.Harness, run.Volumes = launch.Harness, launch.Volumes
|
||||
l.Grants.Grant(session.Token(), req.Org, services)
|
||||
if err := l.Networks.Create(ctx, run.network); err != nil {
|
||||
l.release(run)
|
||||
l.release(ctx, run)
|
||||
return nil, err
|
||||
}
|
||||
// The container runs archie's own agent as a keepalive rather than the
|
||||
@@ -207,7 +208,7 @@ func (l *Launcher) LaunchSetup(ctx context.Context, req SetupRequest) (*Run, err
|
||||
InstallDone: session.EnterRuntime,
|
||||
})
|
||||
if err != nil {
|
||||
l.release(run)
|
||||
l.release(ctx, run)
|
||||
return nil, errors.Join(err, l.Networks.Remove(context.WithoutCancel(ctx), run.network))
|
||||
}
|
||||
return run, nil
|
||||
@@ -235,8 +236,7 @@ func orgCredentialKinds(bindings []config.CredentialBinding, org string, creds [
|
||||
return kinds, services
|
||||
}
|
||||
|
||||
// newProxyToken mints a setup session's run credential. It is unguessable
|
||||
// because it is the container's proxy password.
|
||||
// newProxyToken mints a container proxy password, separate from worker grants.
|
||||
func newProxyToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
@@ -278,20 +278,21 @@ func (l *Launcher) Launch(ctx context.Context, req Request) (*Run, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
session, err := l.Proxy.Register(egress.SessionOptions{RunCredential: req.RunCredential, Token: req.RunCredential, Org: req.Org, Network: k.network, Credentials: k.creds, Bound: kinds})
|
||||
session, err := l.taskSession(req, k, kinds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
run := &Run{network: containerName, token: session.Token(), execution: execution}
|
||||
launch, err := kit.Assemble(k.plan, k.img, kit.LaunchParams{Execution: execution, ProxyToken: session.Token(), CAPath: caPath, Bound: kinds, OAuth: facts})
|
||||
if err != nil {
|
||||
l.release(run)
|
||||
l.release(ctx, run)
|
||||
return nil, err
|
||||
}
|
||||
launch.Harness.Adapter, launch.Harness.MCPConfig = req.Adapter, adapter.MCPConfig
|
||||
launch.Harness.CentralTools = len(adapter.MCPConfig) > 0
|
||||
run.Harness, run.Volumes = launch.Harness, launch.Volumes
|
||||
if err := l.Networks.Create(ctx, run.network); err != nil {
|
||||
l.release(run)
|
||||
l.release(ctx, run)
|
||||
return nil, err
|
||||
}
|
||||
run.Container, err = l.Pool.AcquireKit(ctx, container.KitSpec{
|
||||
@@ -309,7 +310,7 @@ func (l *Launcher) Launch(ctx context.Context, req Request) (*Run, error) {
|
||||
InstallDone: session.EnterRuntime,
|
||||
})
|
||||
if err != nil {
|
||||
l.release(run)
|
||||
l.release(ctx, run)
|
||||
return nil, errors.Join(err, l.Networks.Remove(context.WithoutCancel(ctx), run.network))
|
||||
}
|
||||
return run, nil
|
||||
@@ -374,8 +375,8 @@ func (l *Launcher) oauthFacts(ctx context.Context, org string, creds []spec.Cred
|
||||
// release undoes what Launch already did for run: its proxy session. Call sites past this point pass the network/container errors
|
||||
// through their own cleanup; release only ever needs to run once per Launch
|
||||
// failure, so it takes no error to join.
|
||||
func (l *Launcher) release(run *Run) {
|
||||
l.Proxy.Revoke(run.token)
|
||||
func (l *Launcher) release(ctx context.Context, run *Run) {
|
||||
l.Proxy.Revoke(ctx, run.token)
|
||||
if run.grants != nil {
|
||||
run.grants.Revoke(run.token)
|
||||
}
|
||||
@@ -443,7 +444,7 @@ func (l *Launcher) skillsDir() string {
|
||||
// them. A task run keeps its volumes for the life of its execution.
|
||||
func (l *Launcher) Release(ctx context.Context, run *Run) error {
|
||||
l.Pool.Release(ctx, run.Container)
|
||||
l.release(run)
|
||||
l.release(ctx, run)
|
||||
err := l.Networks.Remove(context.WithoutCancel(ctx), run.network)
|
||||
if run.ephemeral {
|
||||
err = errors.Join(err, l.RemoveVolumes(context.WithoutCancel(ctx), run.Volumes))
|
||||
@@ -510,3 +511,14 @@ func skillsBinds(asks []spec.AgentSkillsCapability, sharedDir string) []string {
|
||||
}
|
||||
return binds
|
||||
}
|
||||
|
||||
func (l *Launcher) taskSession(req Request, k kitNeeds, kinds map[string]egress.CredentialKind) (*egress.Session, error) {
|
||||
if req.RunCredential == "" {
|
||||
return nil, errors.New("kit tasks require a run credential")
|
||||
}
|
||||
token, err := newProxyToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return l.Proxy.Register(egress.SessionOptions{RunCredential: req.RunCredential, Token: token, Org: req.Org, Network: k.network, Credentials: k.creds, Bound: kinds})
|
||||
}
|
||||
@@ -3,12 +3,14 @@ package kitrun
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/docker/sandbox-kit-spec/v3/spec"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kit"
|
||||
"github.com/samcharles93/archie-core/internal/skill"
|
||||
)
|
||||
|
||||
@@ -103,3 +105,27 @@ func TestSharedSkillsDoNotMaskImageDiscovery(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHarnessProxyPasswordDoesNotExposeRunGrant(t *testing.T) {
|
||||
l := &Launcher{Proxy: egress.NewProxy(nil, egress.ProxyOptions{})}
|
||||
req := Request{RunCredential: "worker-state-store-grant", Org: "acme"}
|
||||
session, err := l.taskSession(req, kitNeeds{}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Proxy.Revoke(t.Context(), session.Token())
|
||||
if session.Token() == req.RunCredential {
|
||||
t.Fatal("harness proxy password exposes the worker's State Store grant")
|
||||
}
|
||||
launch, err := kit.Assemble(&kit.Plan{}, kit.ImageConfig{}, kit.LaunchParams{ProxyToken: session.Token()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env := strings.Join(launch.Harness.Env, "\n")
|
||||
if strings.Contains(env, req.RunCredential) {
|
||||
t.Fatal("worker grant entered the harness environment")
|
||||
}
|
||||
if !strings.Contains(env, session.Token()) {
|
||||
t.Fatal("harness has no proxy password")
|
||||
}
|
||||
}
|
||||
@@ -268,7 +268,7 @@ func (s *server) ResolveTaskGrant(ctx context.Context, r *pb.ResolveTaskGrantReq
|
||||
if principal == s.deps.RootIdentity {
|
||||
route = ""
|
||||
}
|
||||
return &pb.ResolveTaskGrantResponse{TaskId: id, ExecutionIdentity: route}, nil
|
||||
return &pb.ResolveTaskGrantResponse{TaskId: id, ExecutionIdentity: route, PrincipalId: string(principal)}, nil
|
||||
}
|
||||
|
||||
// RegisterTaskGrant creates fresh random material at the daemon and registers
|
||||
@@ -409,3 +409,13 @@ func (s *server) executionPrincipal(ctx context.Context, t *task.Task) (identity
|
||||
}
|
||||
return value.ID, nil
|
||||
}
|
||||
|
||||
// TaskPrincipalForCredential resolves the task and its canonical execution principal.
|
||||
func (c *Client) TaskPrincipalForCredential(ctx context.Context, token string) (*task.Task, identity.IdentityID, error) {
|
||||
r, err := c.client.ResolveTaskGrant(ctx, &pb.ResolveTaskGrantRequest{Token: token})
|
||||
if err != nil {
|
||||
return nil, "", unmapError(err)
|
||||
}
|
||||
t, err := c.TaskByID(ctx, r.TaskId)
|
||||
return t, identity.IdentityID(r.PrincipalId), err
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package taskmcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
toolprovider "github.com/samcharles93/archie-core/internal/tools/provider"
|
||||
mcptoolprovider "github.com/samcharles93/archie-core/internal/tools/provider/mcp"
|
||||
)
|
||||
|
||||
var errUnknownMCPTransport = errors.New("unknown MCP transport")
|
||||
|
||||
// Set holds the resources needed to clean up MCP providers.
|
||||
type Set struct {
|
||||
providers []toolprovider.Engine
|
||||
Registry *tools.Registry
|
||||
}
|
||||
|
||||
type mcpProviderBuilder func(config.MCPServer, mcp.SamplingHandler) (toolprovider.Engine, string, error)
|
||||
|
||||
// Start starts the configured MCP servers and registers their
|
||||
// tools. sampling answers sampling requests when non-nil. Returns nil with
|
||||
// no servers.
|
||||
func Start(
|
||||
ctx context.Context,
|
||||
servers []config.MCPServer,
|
||||
sampling mcp.SamplingHandler,
|
||||
log *slog.Logger,
|
||||
cacheDir string,
|
||||
) (*Set, error) {
|
||||
return startWith(ctx, servers, sampling, log, func(server config.MCPServer, sampling mcp.SamplingHandler) (toolprovider.Engine, string, error) {
|
||||
return NewProvider(server, sampling, cacheDir)
|
||||
})
|
||||
}
|
||||
|
||||
func startWith(
|
||||
ctx context.Context,
|
||||
servers []config.MCPServer,
|
||||
sampling mcp.SamplingHandler,
|
||||
log *slog.Logger,
|
||||
build mcpProviderBuilder,
|
||||
) (*Set, error) {
|
||||
if len(servers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
set := &Set{Registry: tools.NewRegistry()}
|
||||
var firstErr error
|
||||
for _, server := range servers {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
if name == "" {
|
||||
log.Warn("mcp server skipped: empty name")
|
||||
continue
|
||||
}
|
||||
|
||||
provider, transportType, err := build(server, sampling)
|
||||
if errors.Is(err, errUnknownMCPTransport) {
|
||||
log.Warn("mcp server skipped: unknown transport", "name", name, "transport", transportType)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
log.Warn("mcp server skipped", "name", name, "err", err)
|
||||
firstErr = retainFirstError(firstErr, err)
|
||||
continue
|
||||
}
|
||||
|
||||
toolCount, err := startMCPProvider(ctx, name, provider, set.Registry, log)
|
||||
if err != nil {
|
||||
firstErr = retainFirstError(firstErr, err)
|
||||
continue
|
||||
}
|
||||
|
||||
set.providers = append(set.providers, provider)
|
||||
log.Info("mcp provider started", "name", name, "transport", transportType, "tools", toolCount)
|
||||
}
|
||||
|
||||
if len(set.providers) == 0 {
|
||||
return nil, firstErr
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
// NewProvider builds the same transport and tool names for chat and tasks.
|
||||
func NewProvider(server config.MCPServer, sampling mcp.SamplingHandler, cacheDir string) (toolprovider.Engine, string, error) {
|
||||
name := strings.TrimSpace(server.Name)
|
||||
transportType := strings.ToLower(strings.TrimSpace(server.Transport))
|
||||
if transportType == "" {
|
||||
transportType = "stdio"
|
||||
}
|
||||
|
||||
if name == "" {
|
||||
return nil, transportType, fmt.Errorf("MCP server name is required")
|
||||
}
|
||||
transport, err := mcpTransportForServer(name, transportType, server, cacheDir)
|
||||
if err != nil {
|
||||
return nil, transportType, err
|
||||
}
|
||||
return mcptoolprovider.New(name, transport, server.ParallelToolCalls, mcptoolprovider.WithSamplingHandler(sampling)), transportType, nil
|
||||
}
|
||||
|
||||
func mcpTransportForServer(
|
||||
name string,
|
||||
transportType string,
|
||||
server config.MCPServer,
|
||||
cacheDir string,
|
||||
) (mcptoolprovider.LifecycleTransport, error) {
|
||||
switch transportType {
|
||||
case "stdio":
|
||||
command := strings.TrimSpace(server.Command)
|
||||
if command == "" {
|
||||
return nil, fmt.Errorf("MCP stdio server %q requires a command", name)
|
||||
}
|
||||
// Keep npx packages in the caller's cache.
|
||||
return mcp.NewStdioTransport(mcp.StdioTransportConfig{
|
||||
Command: command,
|
||||
Args: append([]string(nil), server.Args...),
|
||||
Dir: server.WorkDir,
|
||||
Env: mcp.NpmCacheEnv(command, cacheDir),
|
||||
}), nil
|
||||
case "http", "streamablehttp":
|
||||
url := strings.TrimSpace(server.URL)
|
||||
if url == "" {
|
||||
return nil, fmt.Errorf("MCP http server %q requires a url", name)
|
||||
}
|
||||
return mcp.NewHTTPTransport(mcp.HTTPTransportConfig{
|
||||
Endpoint: url,
|
||||
Headers: server.Headers,
|
||||
}), nil
|
||||
case "sse":
|
||||
sseEndpoint := strings.TrimSpace(server.SSEEndpoint)
|
||||
if sseEndpoint == "" {
|
||||
return nil, fmt.Errorf("MCP sse server %q requires an sse_endpoint", name)
|
||||
}
|
||||
return mcp.NewSSETransport(mcp.SSETransportConfig{
|
||||
SSEEndpoint: sseEndpoint,
|
||||
MessageEndpoint: strings.TrimSpace(server.MessageEndpoint),
|
||||
Headers: server.Headers,
|
||||
}), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errUnknownMCPTransport, transportType)
|
||||
}
|
||||
}
|
||||
|
||||
func startMCPProvider(
|
||||
ctx context.Context,
|
||||
name string,
|
||||
provider toolprovider.Engine,
|
||||
registry *tools.Registry,
|
||||
log *slog.Logger,
|
||||
) (int, error) {
|
||||
if err := provider.Start(ctx); err != nil {
|
||||
log.Warn("mcp provider start failed", "name", name, "err", err)
|
||||
return 0, err
|
||||
}
|
||||
|
||||
entries, err := provider.Discover(ctx)
|
||||
if err != nil {
|
||||
log.Warn("mcp tool discovery failed", "name", name, "err", err)
|
||||
_ = provider.Stop(ctx)
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if err := registry.Register(entry); err != nil {
|
||||
log.Warn("mcp tool registration failed", "tool", entry.Name, "err", err)
|
||||
}
|
||||
}
|
||||
return len(entries), nil
|
||||
}
|
||||
|
||||
func retainFirstError(firstErr, err error) error {
|
||||
if firstErr != nil {
|
||||
return firstErr
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Set) Close(ctx context.Context, log *slog.Logger) {
|
||||
for _, provider := range s.providers {
|
||||
if err := provider.Stop(ctx); err != nil {
|
||||
log.Warn("mcp provider stop failed", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package taskmcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/usage"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
// SamplingHandler answers MCP sampling requests with the task's model.
|
||||
// Without a runtime or model the request is refused. record receives each
|
||||
// call's model ref and token usage.
|
||||
func SamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig, record func(context.Context, string, chat.Usage)) mcp.SamplingHandler {
|
||||
return func(ctx context.Context, req mcp.SamplingRequest) (mcp.SamplingResult, error) {
|
||||
if llm == nil {
|
||||
return mcp.SamplingResult{}, errors.New("mcp sampling: no model runtime is configured")
|
||||
}
|
||||
model, err := config.ResolveModel(cfg.Models, "", config.PurposeAgent)
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
|
||||
}
|
||||
messages, err := modelloop.SamplingMessages(req)
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, err
|
||||
}
|
||||
limits := cfg.ModelLimits[model]
|
||||
options := core.GenerateOptions{
|
||||
Messages: messages,
|
||||
System: req.SystemPrompt,
|
||||
MaxSteps: 1,
|
||||
MaxTokens: modelloop.SamplingMaxTokens(req.MaxTokens, limits.MaxOutputTokens),
|
||||
}
|
||||
if req.Temperature != nil {
|
||||
options.Temperature = float32(*req.Temperature)
|
||||
}
|
||||
result, err := llm.Chat(ctx, model, options)
|
||||
record(ctx, model, result.TotalUsage)
|
||||
if err != nil {
|
||||
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
|
||||
}
|
||||
return mcp.SamplingResult{
|
||||
Model: model,
|
||||
Role: "assistant",
|
||||
Content: mcp.SamplingContent{Type: "text", Text: result.Text},
|
||||
StopReason: string(result.FinishReason),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// UsageRecorder records a task's MCP sampling calls against the task.
|
||||
// A failed write is logged, never fails the call.
|
||||
func UsageRecorder(store usage.Recorder, t *workflow.Task, log *slog.Logger) func(context.Context, string, chat.Usage) {
|
||||
return func(ctx context.Context, model string, used chat.Usage) {
|
||||
if store == nil || t == nil {
|
||||
return
|
||||
}
|
||||
record := usage.Record{
|
||||
Source: usage.SourceTask, TaskID: t.ID, Attempt: t.Attempt, Workflow: t.Workflow, Step: "mcp-sampling",
|
||||
InputTokens: int64(used.PromptTokens), OutputTokens: int64(used.CompletionTokens),
|
||||
CachedTokens: int64(used.CachedTokens), At: time.Now().UTC(),
|
||||
}.WithRef(model)
|
||||
if err := store.RecordUsage(ctx, record); err != nil && log != nil {
|
||||
log.Warn("record model usage failed", "model", model, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package taskmcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/chat"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/agentrun"
|
||||
protocol "github.com/samcharles93/archie-core/internal/tools/mcp"
|
||||
)
|
||||
|
||||
func TestSamplingKeepsTaskCredentialsAndUsage(t *testing.T) {
|
||||
t.Setenv("ARCHIE_SAMPLING_FIXTURE_KEY", "instance-key")
|
||||
for _, key := range []string{"org-a-key", "org-b-key"} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer "+key {
|
||||
t.Error("sampling used another org's key")
|
||||
}
|
||||
var input map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if input["model"] != "task-model" {
|
||||
t.Errorf("sampling model %v", input["model"])
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"sample","object":"chat.completion","model":"task-model","choices":[{"index":0,"message":{"role":"assistant","content":"sampled"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}`))
|
||||
}))
|
||||
defer upstream.Close()
|
||||
providers := map[string]agentrun.Provider{"fixture": {Class: "openai", BaseURL: upstream.URL + "/v1", APIKeyEnv: "ARCHIE_SAMPLING_FIXTURE_KEY"}}
|
||||
llm := modelloop.NewRuntimeWithKeys(providers, nil, map[string]string{"fixture": key})
|
||||
recorded := false
|
||||
sample := SamplingHandler(llm, config.TaskConfig{Models: map[string]string{"default": "fixture/task-model"}}, func(_ context.Context, model string, usage chat.Usage) {
|
||||
recorded = true
|
||||
if model != "fixture/task-model" || usage.TotalTokens != 5 {
|
||||
t.Errorf("usage attribution %s %+v", model, usage)
|
||||
}
|
||||
})
|
||||
result, err := sample(t.Context(), protocol.SamplingRequest{Messages: []protocol.SamplingMessage{{Role: "user", Content: protocol.SamplingContent{Type: "text", Text: "sample"}}}, MaxTokens: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if os.Getenv("ARCHIE_SAMPLING_FIXTURE_KEY") != "instance-key" {
|
||||
t.Fatal("sampling changed process-wide credentials")
|
||||
}
|
||||
if !recorded || result.Model != "fixture/task-model" || result.Content.Text != "sampled" {
|
||||
t.Fatalf("sampling result %+v, recorded %v", result, recorded)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Package tasktools adapts task-scoped central tools to the Gateway contract.
|
||||
package tasktools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/domain/presence"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/rpctls"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
)
|
||||
|
||||
// Client never accepts an identity, org or permission list from the harness.
|
||||
type Client struct{ rpc pb.TaskToolsServiceClient }
|
||||
|
||||
func NewClient(conn grpc.ClientConnInterface) *Client {
|
||||
return &Client{rpc: pb.NewTaskToolsServiceClient(conn)}
|
||||
}
|
||||
|
||||
func (c *Client) List(ctx context.Context, credential string) ([]*mcp.Tool, error) {
|
||||
r, err := c.rpc.ListTaskTools(ctx, &pb.ListTaskToolsRequest{RunCredential: credential})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var tools []*mcp.Tool
|
||||
err = json.Unmarshal(r.ToolsJson, &tools)
|
||||
return tools, err
|
||||
}
|
||||
|
||||
func (c *Client) Call(ctx context.Context, credential, name string, args json.RawMessage) (*mcp.CallToolResult, error) {
|
||||
r, err := c.rpc.CallTaskTool(ctx, &pb.CallTaskToolRequest{RunCredential: credential, Name: name, ArgumentsJson: args})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result mcp.CallToolResult
|
||||
err = json.Unmarshal(r.ResultJson, &result)
|
||||
return &result, err
|
||||
}
|
||||
|
||||
func (c *Client) Close(ctx context.Context, credential string) error {
|
||||
_, err := c.rpc.CloseTaskTools(ctx, &pb.CloseTaskToolsRequest{RunCredential: credential})
|
||||
return err
|
||||
}
|
||||
|
||||
// Dial opens the Gateway's task-tools contract as the authenticated daemon.
|
||||
func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
|
||||
creds, err := id.DialOption(target, presence.Gateway)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
conn, err := grpc.NewClient(target, creds, grpc.WithUnaryInterceptor(staterpc.UnaryClientCredentialInterceptor(presence.Daemon, "")), grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(messaging.MaxInboundAttachmentBytes+(1<<20))))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return NewClient(conn), func() { _ = conn.Close() }, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package tasktools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
)
|
||||
|
||||
const (
|
||||
Endpoint = "http://archie.tools/mcp"
|
||||
Sentinel = "archie-task-tools-sentinel"
|
||||
)
|
||||
|
||||
type Backend interface {
|
||||
List(context.Context, string) ([]*mcp.Tool, error)
|
||||
Call(context.Context, string, string, json.RawMessage) (*mcp.CallToolResult, error)
|
||||
Close(context.Context, string) error
|
||||
}
|
||||
|
||||
// ServeHTTP creates a fresh view so tool discovery never outlives permissions.
|
||||
func ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, backend Backend, credential, token string) {
|
||||
if token == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 {
|
||||
http.Error(w, "invalid gateway credential", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
tools, err := backend.List(ctx, credential)
|
||||
if err != nil {
|
||||
http.Error(w, "task tools unavailable", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "archie-central", Version: "1"}, nil)
|
||||
for _, tool := range tools {
|
||||
server.AddTool(tool, func(methodCtx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
// MCP handler contexts may outlive HTTP; proxy revocation must not.
|
||||
callCtx, cancel := context.WithCancel(methodCtx)
|
||||
defer cancel()
|
||||
stop := context.AfterFunc(ctx, cancel)
|
||||
defer stop()
|
||||
return backend.Call(callCtx, credential, req.Params.Name, req.Params.Arguments)
|
||||
})
|
||||
}
|
||||
// The proxy has already authenticated the session and confined Host and path.
|
||||
mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, DisableLocalhostProtection: true}).ServeHTTP(w, r.WithContext(ctx))
|
||||
}
|
||||
Reference in new issue
Block a user