141 lines
4 KiB
Go
141 lines
4 KiB
Go
// devbox-mcpd-plugin is metadata-only request audit middleware for Mozilla mcpd.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/url"
|
|
"os"
|
|
"os/signal"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
|
|
mcpdpluginsv1 "github.com/mozilla-ai/mcpd-plugins-sdk-go/pkg/plugins/v1"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
)
|
|
|
|
var version = "dev"
|
|
|
|
// Only canonical, bounded tool identifiers may enter the audit stream.
|
|
var toolName = regexp.MustCompile(`^devbox_[a-z][a-z0-9_]{0,63}$`)
|
|
|
|
type auditPlugin struct {
|
|
mcpdpluginsv1.BasePlugin
|
|
version string
|
|
output io.Writer
|
|
mu sync.Mutex
|
|
stop context.CancelFunc
|
|
}
|
|
|
|
func (p *auditPlugin) GetMetadata(context.Context, *emptypb.Empty) (*mcpdpluginsv1.Metadata, error) {
|
|
return &mcpdpluginsv1.Metadata{Name: "devbox-mcpd-plugin", Version: p.version, Description: "Metadata-only audit telemetry for devbox tool requests"}, nil
|
|
}
|
|
func (p *auditPlugin) GetCapabilities(context.Context, *emptypb.Empty) (*mcpdpluginsv1.Capabilities, error) {
|
|
return &mcpdpluginsv1.Capabilities{Flows: []mcpdpluginsv1.Flow{mcpdpluginsv1.FlowRequest}}, nil
|
|
}
|
|
func (p *auditPlugin) Stop(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
|
|
if p.stop != nil {
|
|
p.stop()
|
|
}
|
|
return &emptypb.Empty{}, nil
|
|
}
|
|
|
|
func requestTool(req *mcpdpluginsv1.HTTPRequest) string {
|
|
if req.GetMethod() != "POST" {
|
|
return ""
|
|
}
|
|
const prefix = "/api/v1/servers/devbox/tools/"
|
|
path := req.GetPath()
|
|
if !strings.HasPrefix(path, prefix) {
|
|
return ""
|
|
}
|
|
tool := strings.TrimPrefix(path, prefix)
|
|
if !toolName.MatchString(tool) {
|
|
return ""
|
|
}
|
|
// Path is decoded by HTTP servers. Check the wire representations too, so
|
|
// percent-encoded separators or identifiers cannot masquerade as canonical paths.
|
|
for _, raw := range []string{req.GetUrl(), req.GetRequestUri()} {
|
|
if raw == "" {
|
|
continue
|
|
}
|
|
u, err := url.ParseRequestURI(raw)
|
|
if err != nil || u.EscapedPath() != path || u.Fragment != "" {
|
|
return ""
|
|
}
|
|
}
|
|
return tool
|
|
}
|
|
|
|
func (p *auditPlugin) HandleRequest(ctx context.Context, req *mcpdpluginsv1.HTTPRequest) (*mcpdpluginsv1.HTTPResponse, error) {
|
|
if tool := requestTool(req); tool != "" {
|
|
event := struct {
|
|
Event string `json:"event"`
|
|
Version string `json:"version"`
|
|
Method string `json:"method"`
|
|
Tool string `json:"tool"`
|
|
}{"devbox.tool.request", p.version, "POST", tool}
|
|
p.mu.Lock()
|
|
// Telemetry failures must never block or change a tool request's policy.
|
|
_ = json.NewEncoder(p.output).Encode(event)
|
|
p.mu.Unlock()
|
|
}
|
|
return p.BasePlugin.HandleRequest(ctx, req)
|
|
}
|
|
|
|
func run(args []string, stdout, stderr io.Writer) error {
|
|
flags := flag.NewFlagSet("devbox-mcpd-plugin", flag.ContinueOnError)
|
|
flags.SetOutput(stderr)
|
|
address := flags.String("address", "", "gRPC address (socket path for unix, host:port for tcp)")
|
|
network := flags.String("network", "unix", "Network type (unix or tcp)")
|
|
showVersion := flags.Bool("version", false, "Print version and exit")
|
|
if err := flags.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
if *showVersion {
|
|
_, err := fmt.Fprintln(stdout, "devbox-mcpd-plugin", version)
|
|
return err
|
|
}
|
|
if flags.NArg() != 0 || *address == "" || (*network != "unix" && *network != "tcp") {
|
|
return fmt.Errorf("--address and --network unix|tcp are required")
|
|
}
|
|
lis, err := net.Listen(*network, *address)
|
|
if err != nil {
|
|
return fmt.Errorf("plugin listener failed")
|
|
}
|
|
defer lis.Close()
|
|
if *network == "unix" {
|
|
defer os.Remove(*address)
|
|
}
|
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer cancel()
|
|
server := grpc.NewServer()
|
|
mcpdpluginsv1.RegisterPluginServer(server, &auditPlugin{version: version, output: stderr, stop: cancel})
|
|
done := make(chan struct{})
|
|
go func() {
|
|
select {
|
|
case <-ctx.Done():
|
|
server.GracefulStop()
|
|
case <-done:
|
|
}
|
|
}()
|
|
err = server.Serve(lis)
|
|
close(done)
|
|
if err != nil {
|
|
return fmt.Errorf("plugin server failed")
|
|
}
|
|
return nil
|
|
}
|
|
func main() {
|
|
if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
}
|