From 35e4dff92f7b7826651b2a22438ccc21832007da Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Fri, 30 Oct 2026 09:41:58 -0400 Subject: [PATCH] add a background OpenAI-compatible proxy command with its own key --- cli/internal/app/proxy.go | 55 ++++++++ cli/internal/cli/proxy.go | 191 +++++++++++++++++++++++++ cli/internal/cli/proxy_background.go | 167 ++++++++++++++++++++++ cli/internal/cli/root.go | 2 +- cli/internal/daemon/proxy.go | 27 ++++ cli/internal/proxyserver/log.go | 33 +++++ cli/internal/proxyserver/server.go | 196 ++++++++++++++++++++++++++ cli/test/e2e/proxy_test.go | 200 +++++++++++++++++++++++++++ robot-docs/proxy.md | 25 ++++ 9 files changed, 895 insertions(+), 1 deletion(-) create mode 100644 cli/internal/app/proxy.go create mode 100644 cli/internal/cli/proxy.go create mode 100644 cli/internal/cli/proxy_background.go create mode 100644 cli/internal/daemon/proxy.go create mode 100644 cli/internal/proxyserver/log.go create mode 100644 cli/internal/proxyserver/server.go create mode 100644 cli/test/e2e/proxy_test.go diff --git a/cli/internal/app/proxy.go b/cli/internal/app/proxy.go new file mode 100644 index 000000000..77bf4aa28 --- /dev/null +++ b/cli/internal/app/proxy.go @@ -0,0 +1,55 @@ +package app + +import ( + "cmp" + "context" + "slices" + + "albedo/cli/internal/daemon" +) + +type ProxyProvider struct { + Name string + Models []string +} + +type PreparedProxy struct { + Connection *daemon.Connection + Enabled bool + Providers []ProxyProvider + Unavailable []string +} + +// PrepareProxy reads the global extension choice and its advertised models. +func (s *Service) PrepareProxy(ctx context.Context) (PreparedProxy, error) { + conn, err := s.Connect(ctx) + if err != nil { + return PreparedProxy{}, err + } + settings, err := daemon.GetSettings(ctx, conn) + if err != nil { + return PreparedProxy{}, err + } + prepared := PreparedProxy{Connection: conn, Enabled: settings.Extensions["proxy"]} + if !prepared.Enabled { + return prepared, nil + } + catalog, err := daemon.ListProxyModels(ctx, conn) + if err != nil { + return PreparedProxy{}, err + } + groups := map[string][]string{} + for _, model := range catalog.Data { + groups[model.Provider] = append(groups[model.Provider], model.ID) + } + for name, models := range groups { + slices.Sort(models) + prepared.Providers = append(prepared.Providers, ProxyProvider{Name: name, Models: slices.Compact(models)}) + } + slices.SortFunc(prepared.Providers, func(a, b ProxyProvider) int { return cmp.Compare(a.Name, b.Name) }) + for _, failure := range catalog.Errors { + prepared.Unavailable = append(prepared.Unavailable, failure.Profile) + } + slices.Sort(prepared.Unavailable) + return prepared, nil +} diff --git a/cli/internal/cli/proxy.go b/cli/internal/cli/proxy.go new file mode 100644 index 000000000..f2760cd70 --- /dev/null +++ b/cli/internal/cli/proxy.go @@ -0,0 +1,191 @@ +package cli + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "os/signal" + "slices" + "strconv" + "strings" + "syscall" + "time" + + "albedo/cli/internal/proxyserver" + "albedo/cli/internal/webui" + "github.com/spf13/cobra" +) + +func newProxy(deps Dependencies) *cobra.Command { + var port int + var allow []string + var publicURL string + var quiet, newKey, tailnetHTTPS, foreground, serve, stopServer bool + command := &cobra.Command{Use: "proxy", Short: "serve your model providers through an OpenAI-compatible endpoint", Args: cobra.NoArgs, Long: `Serve the enabled proxy extension in the background; --stop stops it. +Use --foreground to serve in this terminal until Ctrl-C. +The daemon is found or started as for the terminal client. The API key printed +here grants access only to proxy models and chat completions, not the daemon. + +It serves this machine only unless --allow opens a network (same syntax as +albedo web). --allow 100.64.0.0/10 shares your tailnet; --tailnet-https also +publishes it through tailscale serve. --public-url names an existing reverse +proxy's origin. Keep the printed key private.`, RunE: func(cmd *cobra.Command, _ []string) error { + if port < 0 || port > 65535 { + return errors.New("port must be between 0 and 65535") + } + var networks []*net.IPNet + for _, text := range allow { + network, err := webui.ParseNetwork(text) + if err != nil { + return err + } + networks = append(networks, network) + } + var public string + if publicURL != "" { + origin, err := webui.ParseOrigin(publicURL) + if err != nil { + return err + } + public = origin.String() + } + if !foreground && !serve { + return backgroundProxy(cmd, deps, webui.Options{Port: port, Allow: allow, Public: public, TailnetHTTPS: tailnetHTTPS}, quiet, newKey, stopServer) + } + if current, err := readProxyManifest(); err == nil && webui.ManifestAlive(current.Manifest) { + return errors.New("albedo proxy is already running; run albedo proxy --stop first") + } + prepared, err := deps.Application.PrepareProxy(cmd.Context()) + if err != nil { + return err + } + if !prepared.Enabled { + _, err := fmt.Fprintln(cmd.OutOrStdout(), "the proxy extension is off. turn it on in /extensions, then run albedo proxy again.") + return err + } + key, err := proxyserver.LoadKey(newKey) + if err != nil { + return err + } + var logs io.Writer + if !quiet { + logs = cmd.ErrOrStderr() + if serve { + output, err := proxyserver.OpenLog() + if err != nil { + return err + } + defer output.Close() + logs = output + } + } + server := proxyserver.New(prepared.Connection, logs) + bind := "127.0.0.1" + var addresses, names []string + tailnet, onTailnet := webui.Tailnet{}, false + if len(networks) > 0 || tailnetHTTPS { + tailnet, onTailnet = webui.CurrentTailnet(cmd.Context()) + } + if len(networks) > 0 { + machine, err := webui.NetworkAddresses() + if err != nil { + return err + } + addresses = server.Share(networks, machine) + if len(addresses) == 0 { + return fmt.Errorf("this machine has no address in %s", strings.Join(allow, ", ")) + } + bind = "0.0.0.0" + if onTailnet && slices.ContainsFunc(addresses, func(a string) bool { return webui.TailscaleNetwork.Contains(net.ParseIP(a)) }) { + names = tailnet.Names + server.Answer(names...) + } + } + if bind != "127.0.0.1" && port != 0 { + probe, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port))) + if err != nil { + return fmt.Errorf("cannot listen on 127.0.0.1:%d (use --port to pick another): %w", port, err) + } + probe.Close() + } + listener, err := net.Listen("tcp", net.JoinHostPort(bind, strconv.Itoa(port))) + if err != nil { + return fmt.Errorf("cannot listen on %s:%d (use --port to pick another): %w", bind, port, err) + } + defer listener.Close() + port = listener.Addr().(*net.TCPAddr).Port + if tailnetHTTPS { + claim, err := tailnet.ServeHTTPS(port) + if err != nil { + return err + } + origin, err := claim.Claim(cmd.Context()) + if err != nil { + return err + } + public = origin.String() + defer releaseTailnet(cmd, port) + } + if public != "" { + origin, err := webui.ParseOrigin(public) + if err != nil { + return err + } + server.Publish(origin) + } + manifest := proxyManifest{ + Manifest: webui.Manifest{Options: webui.Options{Port: port, Allow: allow, Public: public, TailnetHTTPS: tailnetHTTPS}, Names: names, Addresses: addresses, PID: os.Getpid(), URL: webui.Loopback(port).String()}, + Started: time.Now().UTC(), Quiet: quiet, Providers: prepared.Providers, Unavailable: prepared.Unavailable, + } + if err := writeProxyManifest(manifest); err != nil { + return err + } + defer func() { + if current, err := readProxyManifest(); err == nil && current.PID == os.Getpid() { + _ = os.Remove(proxyManifestPath()) + } + }() + if !serve { + printProxySummary(cmd.OutOrStdout(), key, manifest) + fmt.Fprintln(cmd.OutOrStdout(), "\nserving until ctrl-c") + } + ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM) + defer stop() + httpServer := &http.Server{Handler: server, ReadHeaderTimeout: 10 * time.Second} + finished := make(chan struct{}) + go func() { + defer close(finished) + <-ctx.Done() + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if httpServer.Shutdown(shutdown) != nil { + httpServer.Close() + } + }() + err = httpServer.Serve(listener) + stop() + <-finished + if !errors.Is(err, http.ErrServerClosed) { + return err + } + return nil + }} + command.Flags().BoolVar(&foreground, "foreground", false, "serve in this terminal until interrupted") + command.Flags().BoolVar(&serve, "serve", false, "background proxy server") + _ = command.Flags().MarkHidden("serve") + command.Flags().BoolVar(&stopServer, "stop", false, "stop the background proxy server") + command.MarkFlagsMutuallyExclusive("foreground", "serve", "stop") + command.Flags().IntVar(&port, "port", 4318, "port to serve on; 0 picks a free one") + command.Flags().StringArrayVar(&allow, "allow", nil, "serve devices on this network (CIDR, or 10.0.0.0 for 10.0.0.0/8); repeatable") + command.Flags().StringVar(&publicURL, "public-url", "", "origin a proxy in front serves this through (https://host), for links and requests") + command.Flags().BoolVar(&tailnetHTTPS, "tailnet-https", false, "serve https on your tailnet through tailscale serve, printing its https link") + command.MarkFlagsMutuallyExclusive("public-url", "tailnet-https") + command.Flags().BoolVar(&quiet, "quiet", false, "omit per-request logs") + command.Flags().BoolVar(&newKey, "new-key", false, "replace the proxy API key, revoking the previous key") + command.MarkFlagsMutuallyExclusive("stop", "new-key") + return command +} diff --git a/cli/internal/cli/proxy_background.go b/cli/internal/cli/proxy_background.go new file mode 100644 index 000000000..035155385 --- /dev/null +++ b/cli/internal/cli/proxy_background.go @@ -0,0 +1,167 @@ +package cli + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "albedo/cli/internal/app" + "albedo/cli/internal/config" + "albedo/cli/internal/proxyserver" + "albedo/cli/internal/webui" + "github.com/spf13/cobra" +) + +type proxyManifest struct { + webui.Manifest + Started time.Time `json:"started"` + Quiet bool `json:"quiet,omitempty"` + Providers []app.ProxyProvider `json:"providers"` + Unavailable []string `json:"unavailable,omitempty"` +} + +func proxyManifestPath() string { return filepath.Join(config.HomeDir(), "proxy.json") } + +func readProxyManifest() (proxyManifest, error) { + data, err := os.ReadFile(proxyManifestPath()) + if err != nil { + return proxyManifest{}, err + } + var manifest proxyManifest + err = json.Unmarshal(data, &manifest) + return manifest, err +} + +func writeProxyManifest(manifest proxyManifest) error { + data, err := json.Marshal(manifest) + if err != nil { + return err + } + file, err := os.CreateTemp(config.HomeDir(), ".proxy.json-*") + if err != nil { + return err + } + defer os.Remove(file.Name()) + _, err = file.Write(data) + if err = errors.Join(err, file.Close()); err != nil { + return err + } + return os.Rename(file.Name(), proxyManifestPath()) +} + +func backgroundProxy(cmd *cobra.Command, deps Dependencies, options webui.Options, quiet, rotate, stop bool) error { + if err := os.MkdirAll(config.HomeDir(), 0o700); err != nil { + return err + } + manifest, readErr := readProxyManifest() + alive := readErr == nil && webui.ManifestAlive(manifest.Manifest) + out := cmd.OutOrStdout() + if stop { + if !alive { + if manifest.TailnetHTTPS { + releaseTailnet(cmd, manifest.Port) + } + _, err := fmt.Fprintln(out, "albedo proxy is not running.") + return err + } + if err := stopDetached(manifest.PID); err != nil { + return err + } + _, err := fmt.Fprintf(out, "stopped albedo proxy on %s/v1.\n", manifest.URL) + return err + } + if alive { + if cmd.Flags().Changed("port") && options.Port != manifest.Port || + cmd.Flags().Changed("allow") && !options.SameAllow(manifest.Options) || + cmd.Flags().Changed("public-url") && options.Public != manifest.Public || + cmd.Flags().Changed("tailnet-https") && options.TailnetHTTPS != manifest.TailnetHTTPS || + cmd.Flags().Changed("quiet") && quiet != manifest.Quiet { + return errors.New("albedo proxy is already serving with different options; run albedo proxy --stop first") + } + } + prepared, err := deps.Application.PrepareProxy(cmd.Context()) + if err != nil { + return err + } + if !prepared.Enabled { + _, err := fmt.Fprintln(out, "the proxy extension is off. turn it on in /extensions, then run albedo proxy again.") + return err + } + key, err := proxyserver.LoadKey(rotate) + if err != nil { + return err + } + if !alive { + args := []string{"proxy", "--serve", "--port", strconv.Itoa(options.Port)} + for _, network := range options.Allow { + args = append(args, "--allow", network) + } + if quiet { + args = append(args, "--quiet") + } + if options.TailnetHTTPS { + args = append(args, "--tailnet-https") + } else if options.Public != "" { + args = append(args, "--public-url", options.Public) + } + if err := startDetached(cmd.Context(), args, filepath.Join(config.HomeDir(), "proxy.log"), func(pid int) bool { + manifest, _ = readProxyManifest() + return manifest.PID == pid && webui.ManifestAlive(manifest.Manifest) + }); err != nil { + return err + } + fmt.Fprintf(out, "albedo proxy is running in the background on %s/v1.\n", manifest.URL) + } else { + fmt.Fprintf(out, "albedo proxy was already running since %s on %s/v1.\n", proxyStarted(manifest.Started), manifest.URL) + } + fmt.Fprint(out, "stop it with: albedo proxy --stop\n\n") + manifest.Providers, manifest.Unavailable = prepared.Providers, prepared.Unavailable + printProxySummary(out, key, manifest) + return nil +} + +func proxyStarted(started time.Time) string { + local, now := started.Local(), time.Now() + layout := "3:04 pm" + if local.Year() != now.Year() { + layout = "2 Jan 2006 at 3:04 pm" + } else if local.YearDay() != now.YearDay() { + layout = "2 Jan at 3:04 pm" + } + return strings.ToLower(local.Format(layout)) +} + +func printProxySummary(out io.Writer, key string, manifest proxyManifest) { + fmt.Fprintf(out, "base url: %s/v1\n", manifest.URL) + for _, address := range append(manifest.Names, manifest.Addresses...) { + fmt.Fprintf(out, " http://%s/v1\n", net.JoinHostPort(address, strconv.Itoa(manifest.Port))) + } + if manifest.Public != "" { + fmt.Fprintf(out, " %s/v1\n", manifest.Public) + } + fmt.Fprintf(out, "api key: %s\n\nproviders:\n", key) + for _, provider := range manifest.Providers { + name := provider.Name + if name == "openai" { + name = "openai-compatible" + } + unit := "models" + if len(provider.Models) == 1 { + unit = "model" + } + fmt.Fprintf(out, " %s: %d %s — %s\n", name, len(provider.Models), unit, strings.Join(provider.Models[:min(3, len(provider.Models))], ", ")) + } + if len(manifest.Providers) == 0 { + fmt.Fprintln(out, " none configured; run albedo login to add one") + } + for _, profile := range manifest.Unavailable { + fmt.Fprintf(out, " %s: unavailable (check its provider settings)\n", profile) + } +} diff --git a/cli/internal/cli/root.go b/cli/internal/cli/root.go index 307cd4e3c..883e55887 100644 --- a/cli/internal/cli/root.go +++ b/cli/internal/cli/root.go @@ -134,7 +134,7 @@ func NewRoot(deps Dependencies) *cobra.Command { _, err = fmt.Fprintln(cmd.OutOrStdout(), result.Answer) return err } - root.AddCommand(newOpen(deps), newResume(deps), newSessions(deps), newModels(deps), newSend(deps), newStop(deps), newDaemon(deps), newStorage(deps), newLogin(deps), newWeb(deps)) + root.AddCommand(newOpen(deps), newResume(deps), newSessions(deps), newModels(deps), newSend(deps), newStop(deps), newDaemon(deps), newStorage(deps), newLogin(deps), newWeb(deps), newProxy(deps)) return root } func open(cmd *cobra.Command, deps Dependencies, options app.OpenOptions) error { diff --git a/cli/internal/daemon/proxy.go b/cli/internal/daemon/proxy.go new file mode 100644 index 000000000..15fb3d6ef --- /dev/null +++ b/cli/internal/daemon/proxy.go @@ -0,0 +1,27 @@ +package daemon + +import ( + "context" + "io" + "net/http" +) + +// ProxyCatalog is the model list advertised by the proxy extension. +type ProxyCatalog struct { + Data []struct { + ID string `json:"id"` + Provider string `json:"owned_by"` + } `json:"data"` + Errors []struct { + Profile string `json:"profile"` + Message string `json:"message"` + } `json:"errors"` +} + +func ListProxyModels(ctx context.Context, conn *Connection) (ProxyCatalog, error) { + var catalog ProxyCatalog + err := executeRead(ctx, conn, operation{Name: "list proxy models", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { + return http.NewRequest(http.MethodGet, base+"extensions/proxy/v1/models", nil) + }, Policy: readRecovery}, func(data []byte) error { return decodeRequired(data, &catalog) }) + return catalog, err +} diff --git a/cli/internal/proxyserver/log.go b/cli/internal/proxyserver/log.go new file mode 100644 index 000000000..04b1a9d0a --- /dev/null +++ b/cli/internal/proxyserver/log.go @@ -0,0 +1,33 @@ +package proxyserver + +import ( + "os" + "path/filepath" + + "albedo/cli/internal/config" +) + +// RequestLog replaces older request lines once proxy.log reaches 8 MiB. +// log.Logger serializes calls to Write. +type RequestLog struct{ *os.File } + +func OpenLog() (*RequestLog, error) { + file, err := os.OpenFile(filepath.Join(config.HomeDir(), "proxy.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) + if err != nil { + return nil, err + } + return &RequestLog{file}, nil +} + +func (l *RequestLog) Write(data []byte) (int, error) { + info, err := l.Stat() + if err != nil { + return 0, err + } + if info.Size()+int64(len(data)) > 8<<20 { + if err := l.Truncate(0); err != nil { + return 0, err + } + } + return l.File.Write(data) +} diff --git a/cli/internal/proxyserver/server.go b/cli/internal/proxyserver/server.go new file mode 100644 index 000000000..d626a8674 --- /dev/null +++ b/cli/internal/proxyserver/server.go @@ -0,0 +1,196 @@ +// Package proxyserver forwards only the proxy extension's two public routes. +package proxyserver + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/http/httputil" + "os" + "path/filepath" + "time" + + "albedo/cli/internal/config" + "albedo/cli/internal/webui" +) + +func KeyPath() string { return filepath.Join(config.HomeDir(), "proxy-key") } + +// LoadKey creates or reads the home's private proxy key; rotate replaces it atomically. +func LoadKey(rotate bool) (string, error) { + path := KeyPath() + if !rotate { + key, err := readKey() + if err == nil { + return key, os.Chmod(path, 0o600) + } + if !errors.Is(err, os.ErrNotExist) { + return "", err + } + } + raw := make([]byte, 24) + if _, err := rand.Read(raw); err != nil { + return "", err + } + key := hex.EncodeToString(raw) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return "", err + } + if !rotate { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if errors.Is(err, os.ErrExist) { + return readKey() + } + if err != nil { + return "", err + } + _, err = f.WriteString(key) + return key, errors.Join(err, f.Close()) + } + f, err := os.CreateTemp(filepath.Dir(path), ".proxy-key-*") + if err != nil { + return "", err + } + defer os.Remove(f.Name()) + _, err = f.WriteString(key) + if err = errors.Join(err, f.Close()); err != nil { + return "", err + } + return key, os.Rename(f.Name(), path) +} + +func readKey() (string, error) { + raw, err := os.ReadFile(KeyPath()) + if err != nil { + return "", err + } + key := string(raw) + if _, err := hex.DecodeString(key); err != nil || len(key) != 48 { + return "", fmt.Errorf("invalid proxy key in %s; use albedo proxy --new-key", KeyPath()) + } + return key, nil +} + +type Server struct { + *webui.Access + upstream webui.Upstream + proxy *httputil.ReverseProxy + logger *log.Logger +} + +func New(upstream webui.Upstream, output io.Writer) *Server { + s := &Server{Access: webui.NewAccess(), upstream: upstream} + if output != nil { + s.logger = log.New(output, "", 0) + } + s.proxy = &httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + endpoint := s.upstream.Snapshot() + pr.SetURL(webui.Loopback(endpoint.Port)) + pr.Out.Host = pr.Out.URL.Host + pr.Out.URL.Path = "/extensions/proxy" + pr.In.URL.Path + pr.Out.URL.RawPath = "" + for _, header := range []string{"Origin", "Cookie", "Referer", "Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto"} { + pr.Out.Header.Del(header) + } + pr.Out.Header.Set("Authorization", "Bearer "+endpoint.Token) + }, + FlushInterval: -1, + ModifyResponse: func(response *http.Response) error { + response.Header.Del("Set-Cookie") + response.Header.Del("Authorization") + if response.StatusCode == http.StatusUnauthorized { + return errors.New("daemon endpoint changed") + } + return nil + }, + ErrorHandler: func(w http.ResponseWriter, r *http.Request, _ error) { + if r.Context().Err() != nil { + return + } + s.refresh() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusServiceUnavailable) + _ = json.NewEncoder(w).Encode(map[string]map[string]string{"error": {"message": "the albedo daemon isn't running on this machine. start it by running albedo there, then retry.", "type": "service_unavailable"}}) + }, + } + return s +} + +func (s *Server) refresh() { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = s.upstream.Refresh(ctx) +} + +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + started := time.Now() + response := &statusWriter{ResponseWriter: w, status: http.StatusOK} + model := "-" + if s.logger != nil { + defer func() { + s.logger.Printf("%q %d %s", model, response.status, time.Since(started).Round(time.Millisecond)) + }() + } + if !s.Accept(r) { + http.Error(response, "host, origin or network is not allowed", http.StatusForbidden) + return + } + if r.URL.EscapedPath() != r.URL.Path || (r.URL.Path != "/v1/models" && r.URL.Path != "/v1/chat/completions") { + http.NotFound(response, r) + return + } + method := http.MethodGet + if r.URL.Path == "/v1/chat/completions" { + method = http.MethodPost + } + if r.Method != method { + response.Header().Set("Allow", method) + response.WriteHeader(http.StatusMethodNotAllowed) + return + } + key, err := readKey() + if err != nil || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+key)) != 1 { + response.Header().Set("WWW-Authenticate", "Bearer") + http.Error(response, "proxy API key required", http.StatusUnauthorized) + return + } + if r.Method == http.MethodPost && s.logger != nil { + body, err := io.ReadAll(http.MaxBytesReader(response, r.Body, 32_000_000)) + if err != nil { + code := http.StatusBadRequest + if _, oversized := errors.AsType[*http.MaxBytesError](err); oversized { + code = http.StatusRequestEntityTooLarge + } + http.Error(response, "could not read request body", code) + return + } + var request struct { + Model string `json:"model"` + } + if json.Unmarshal(body, &request) == nil { + model = request.Model[:min(len(request.Model), 256)] + } + r.Body = io.NopCloser(bytes.NewReader(body)) + } + s.proxy.ServeHTTP(response, r) +} + +type statusWriter struct { + http.ResponseWriter + status int +} + +func (w *statusWriter) WriteHeader(status int) { + w.status = status + w.ResponseWriter.WriteHeader(status) +} +func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } diff --git a/cli/test/e2e/proxy_test.go b/cli/test/e2e/proxy_test.go new file mode 100644 index 000000000..dfa8b0d81 --- /dev/null +++ b/cli/test/e2e/proxy_test.go @@ -0,0 +1,200 @@ +//go:build unix + +// These scenarios drive the detached CLI and a real daemon: a unit handler test +// cannot catch leaked daemon keys, wrong child argv, or stale restart discovery. +package e2e + +import ( + "context" + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "albedo/cli/internal/daemon" + "albedo/cli/internal/webui" +) + +func proxyExtension(t *testing.T, session string, enabled bool) { + t.Helper() + settings, err := daemon.GetSettings(context.Background(), conn(t)) + if err != nil { + t.Fatal(err) + } + if _, err := daemon.SelectExtension(context.Background(), conn(t), session, daemon.ExtensionSelectionRequest{Name: "proxy", Scope: "global", ETag: settings.ETags["extensions"], Enabled: &enabled}); err != nil { + t.Fatal(err) + } +} + +func proxyCall(t *testing.T, base, method, path, key, body string) (int, string) { + t.Helper() + request, err := http.NewRequestWithContext(t.Context(), method, base+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if key != "" { + request.Header.Set("Authorization", "Bearer "+key) + } + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + client := &http.Client{Timeout: 15 * time.Second} + response, err := client.Do(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + raw, err := io.ReadAll(response.Body) + if err != nil { + t.Fatal(err) + } + return response.StatusCode, string(raw) +} + +func proxyRecord(t *testing.T) webui.Manifest { + t.Helper() + raw, err := os.ReadFile(filepath.Join(suite.home, "proxy.json")) + if err != nil { + t.Fatal(err) + } + var record webui.Manifest + if err := json.Unmarshal(raw, &record); err != nil { + t.Fatal(err) + } + return record +} + +func TestProxyBackgroundScopesKeyAndRecoversAfterDaemonRestart(t *testing.T) { + profile := providerRoute(t, echoReply) + session := newSession(t, t.TempDir()) + proxyExtension(t, session, false) + off := cli(t, "proxy") + if off != "the proxy extension is off. turn it on in /extensions, then run albedo proxy again.\n" { + t.Fatalf("off: %q", off) + } + if _, err := os.Stat(filepath.Join(suite.home, "proxy-key")); !os.IsNotExist(err) { + t.Fatalf("disabled proxy created key: %v", err) + } + proxyExtension(t, session, true) + t.Cleanup(func() { + cli(t, "proxy", "--stop") + proxyExtension(t, session, false) + }) + started := cli(t, "proxy", "--port", "0") + record := proxyRecord(t) + keyPath := filepath.Join(suite.home, "proxy-key") + rawKey, err := os.ReadFile(keyPath) + if err != nil { + t.Fatal(err) + } + key := string(rawKey) + if info, err := os.Stat(keyPath); err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("key permissions: %v %v", info, err) + } + for _, text := range []string{"running in the background", "stop it with: albedo proxy --stop", record.URL + "/v1", key, "openai-compatible", "/fixture-model"} { + if !strings.Contains(started, text) { + t.Fatalf("summary missing %q: %s", text, started) + } + } + if strings.Contains(started, conn(t).Snapshot().Token) { + t.Fatal("summary leaked daemon token") + } + if _, _, err := runCLI("proxy", "--port", "1"); err == nil { + t.Fatal("running proxy accepted changed listen options") + } + repeated := cli(t, "proxy") + if !strings.Contains(repeated, "was already running since") || proxyRecord(t).PID != record.PID { + t.Fatalf("repeat replaced server: %s", repeated) + } + for _, candidate := range []string{"", "wrong", conn(t).Snapshot().Token} { + if code, _ := proxyCall(t, record.URL, "GET", "/v1/models", candidate, ""); code != 401 { + t.Errorf("key %q accepted: %d", candidate, code) + } + } + if code, body := proxyCall(t, record.URL, "GET", "/v1/models", key, ""); code != 200 || !strings.Contains(body, profile+"/fixture-model") { + t.Fatalf("models: %d %s", code, body) + } + for _, path := range []string{"/server", "/api/settings", "/extensions/proxy/v1/models", "/v1/models/../settings", "/v1/%6dodels"} { + if code, _ := proxyCall(t, record.URL, "GET", path, key, ""); code != 404 { + t.Errorf("non-proxy route %s: %d", path, code) + } + } + if code, _ := proxyCall(t, record.URL, "POST", "/v1/models", key, "{}"); code != 405 { + t.Fatalf("models accepted wrong method: %d", code) + } + body := `{"model":"` + profile + `/fixture-model","messages":[{"role":"user","content":"proxy test"}]}` + if code, reply := proxyCall(t, record.URL, "POST", "/v1/chat/completions", key, body); code != 200 || !strings.Contains(reply, "echo: proxy test") { + t.Fatalf("completion: %d %s", code, reply) + } + streaming := strings.Replace(body, `"messages":`, `"stream":true,"messages":`, 1) + if code, reply := proxyCall(t, record.URL, "POST", "/v1/chat/completions", key, streaming); code != 200 || !strings.Contains(reply, "data: [DONE]") { + t.Fatalf("stream: %d %s", code, reply) + } + // Rotation revokes the old key without replacing the listener. + rotated := cli(t, "proxy", "--new-key") + newRaw, err := os.ReadFile(keyPath) + if err != nil { + t.Fatal(err) + } + newKey := string(newRaw) + if newKey == key || !strings.Contains(rotated, newKey) || proxyRecord(t).PID != record.PID { + t.Fatal("rotation did not keep listener and replace key") + } + if code, _ := proxyCall(t, record.URL, "GET", "/v1/models", key, ""); code != 401 { + t.Fatalf("old key accepted: %d", code) + } + if code, _ := proxyCall(t, record.URL, "GET", "/v1/models", newKey, ""); code != 200 { + t.Fatalf("new key refused: %d", code) + } + // The forwarder stays up while the daemon is down and never restarts it. + oldPID := suite.daemonPID + if err := daemon.StopDaemon(context.Background(), conn(t), false); err != nil { + t.Fatal(err) + } + if !awaitExit(oldPID, 15*time.Second) { + t.Fatal("daemon did not stop") + } + if code, reply := proxyCall(t, record.URL, "GET", "/v1/models", newKey, ""); code != 503 || !strings.Contains(reply, "the albedo daemon isn't running on this machine") { + t.Fatalf("daemon down: %d %s", code, reply) + } + cli(t, "sessions") + snapshot, err := awaitDaemon(suite.home) + if err != nil { + t.Fatal(err) + } + suite.daemonPID = snapshot.Pid + if err := conn(t).Refresh(t.Context()); err != nil { + t.Fatal(err) + } + // One request may discover the new endpoint; it is not replayed automatically. + proxyCall(t, record.URL, "GET", "/v1/models", newKey, "") + if code, reply := proxyCall(t, record.URL, "POST", "/v1/chat/completions", newKey, body); code != 200 || !strings.Contains(reply, "echo: proxy test") { + t.Fatalf("restart: %d %s", code, reply) + } + log, err := os.ReadFile(filepath.Join(suite.home, "proxy.log")) + if err != nil || !strings.Contains(string(log), profile+"/fixture-model") || strings.Contains(string(log), key) || strings.Contains(string(log), snapshot.Token) { + t.Fatalf("request log missing or leaked key: %v", err) + } + stopped := cli(t, "proxy", "--stop") + if !strings.Contains(stopped, "stopped albedo proxy on "+record.URL+"/v1") { + t.Fatalf("stop: %s", stopped) + } + if got := cli(t, "proxy", "--stop"); got != "albedo proxy is not running.\n" { + t.Fatalf("second stop: %s", got) + } + // A normal restart preserves the client key. + cli(t, "proxy", "--port", "0", "--quiet") + persisted, err := os.ReadFile(keyPath) + if err != nil || string(persisted) != newKey { + t.Fatal("restart changed key") + } + quietRecord := proxyRecord(t) + proxyCall(t, quietRecord.URL, "GET", "/v1/models", newKey, "") + if log, err := os.ReadFile(filepath.Join(suite.home, "proxy.log")); err != nil || len(log) != 0 { + t.Fatalf("quiet request logged: %q %v", log, err) + } +} diff --git a/robot-docs/proxy.md b/robot-docs/proxy.md index 89de32295..24369fd84 100644 --- a/robot-docs/proxy.md +++ b/robot-docs/proxy.md @@ -2,6 +2,31 @@ The `proxy` extension serves an OpenAI-compatible Chat Completions endpoint for every saved provider profile, so other tools can use albedo's providers (Codex, Antigravity, OpenAI-compatible endpoints) through one base url. It is installed and disabled; enable it globally in `/extensions` or with `{"enabled": {"proxy": true}}` in `$ALBEDO_HOME/extensions.json`. The change applies to the next request. +## albedo proxy + +`albedo proxy` finds or starts the daemon, then starts a detached forwarder on `http://127.0.0.1:4318/v1` (`--port`, 0 for a free port). It prints the base URLs, its API key, and the providers grouped by extension, with model counts and up to three example `/` IDs per group. The proxy extension must be on globally; otherwise the command prints how to turn it on and exits without creating a key or listener. It never enables the extension itself. + +The forwarder keeps running after the command returns, until `albedo proxy --stop`. Running `albedo proxy` again reuses it and prints its start time and the full summary. Different listen options require `--stop` first. `--foreground` serves in the calling terminal until Ctrl-C instead. The detached process is not supervised and does not restart after a crash or reboot. + +Clients use the printed proxy key, not the daemon token. It lives at `$ALBEDO_HOME/proxy-key`, mode `0600`, and survives stops and restarts. `albedo proxy --new-key` replaces it atomically and revokes the previous key, including on an already-running forwarder. Every forwarded request requires `Authorization: Bearer `, even when the daemon allows anonymous loopback proxy access. The forwarder accepts only `GET /v1/models` and `POST /v1/chat/completions`; it adds the daemon token server-side. Other paths return 404 and other methods return 405. Streaming replies pass through without buffering. Chat request bodies are limited to 32,000,000 bytes. + +For example, configure an OpenAI-compatible client with: + +```sh +export OPENAI_BASE_URL=http://127.0.0.1:4318/v1 +export OPENAI_API_KEY='the printed proxy key' +``` + +It listens on loopback only by default, unlike `albedo web`'s automatic tailnet sharing. To share explicitly, use the web command's `--allow ` syntax (repeatable; CIDR or an IPv4 address with trailing zero octets, such as `10.0.0.0` for `/8`). `--allow 100.64.0.0/10` shares the tailnet; the summary includes this machine's matching addresses and detected MagicDNS names. Only loopback clients and clients in an allowed network may connect; the proxy key is still required. Other hostnames and foreign browser origins are refused. These settings are separate from `ui.web_allow` and never change web sharing. + +`--public-url https://proxy.example` prints and accepts the origin of an existing reverse proxy. `--tailnet-https` claims the machine's Tailscale HTTPS root through the same guarded `tailscale serve` machinery as `albedo web`, and releases its own handler when stopped. It refuses a root already serving something else (including albedo web) or one opened through Funnel. The two flags are exclusive. Neither flag silently opens a LAN listener. + +Each request logs its model, HTTP status and duration to `$ALBEDO_HOME/proxy.log` in background mode, or stderr with `--foreground`. `--quiet` disables request logs. No prompt, response, or key is logged. The log is replaced on each background start and discards older lines when it reaches 8 MiB. `$ALBEDO_HOME/proxy.json` records the listener PID, start time, options and summary; it contains no keys and is removed on a clean stop. + +If the daemon stops, the forwarder stays up and answers 503 with a message explaining how to start it again. A failed connection or daemon 401 refreshes the saved daemon endpoint, so a subsequent request reaches the replacement. A chat POST is never replayed automatically: retry it explicitly. Stopping the forwarder does not stop the daemon, and stopping it does not require a running daemon. + +Ownership: `cli/internal/app/proxy.go` reads the extension choice and model catalog; `cli/internal/proxyserver` owns keys, authentication and forwarding; `cli/internal/cli/proxy*.go` owns command rendering and lifecycle. The listener reuses `webui.Access`, network parsing, tailnet discovery and HTTPS claims, and the CLI's shared detached-process helpers. + ## endpoint The proxy is a [service](extensions.md) mounted at `http://127.0.0.1:/extensions/proxy/v1`. Set `ALBEDO_PORT` in the daemon's environment to keep the port stable; otherwise it changes each time the daemon starts (see `$ALBEDO_HOME/daemon.json`). -- knotmirror 0.0.1