Something went wrong. Try again.
A Kubernetes operator that gives a pod its own browser as an MCP server
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206// Package stateapi serves each profile's state and secrets to the// sidecars of the pods that may use it.//// GET /v1/namespaces/{namespace}/browserprofiles/{name}/state// PUT /v1/namespaces/{namespace}/browserprofiles/{name}/state// GET /v1/namespaces/{namespace}/browserprofiles/{name}/secrets//// The state is opaque here: the operator stores what a sidecar sends// and never reads it. Each version has an ETag, and a PUT must name the// version it replaces in If-Match, or say there is none with// If-None-Match: *. A PUT on any other version answers 412, and the// sidecar merges and writes again.package stateapi
import ( "context" "encoding/json" "errors" "fmt" "io" "log/slog" "net/http" "strconv" "strings" "time"
"github.com/liken-sh/liken/kubernetes/events" "github.com/prometheus/client_golang/prometheus"
"tangled.org/guid.foo/gofer/api/v1alpha1" "tangled.org/guid.foo/gofer/cluster" "tangled.org/guid.foo/gofer/seal" "tangled.org/guid.foo/gofer/store")
// maxState is the largest state a sidecar may save.const maxState = 16 << 20
// Server answers the state API.type Server struct { // image is the sidecar's image, which a caller's pod must run. image string cluster *cluster.Cluster store *store.Store log *slog.Logger events *events.Recorder now func() time.Time series}
// New answers a Server for the pods that run the sidecar's image, whose// series register on registerer.func New(image string, c *cluster.Cluster, s *store.Store, log *slog.Logger, registerer prometheus.Registerer, recorder *events.Recorder) *Server { return &Server{image: image, cluster: c, store: s, log: log, events: recorder, now: time.Now, series: newSeries(registerer)}}
// Handler answers the API's routes.func (s *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /v1/namespaces/{namespace}/browserprofiles/{name}/state", s.counted("get_state", s.getState)) mux.HandleFunc("PUT /v1/namespaces/{namespace}/browserprofiles/{name}/state", s.counted("put_state", s.putState)) mux.HandleFunc("GET /v1/namespaces/{namespace}/browserprofiles/{name}/secrets", s.counted("get_secrets", s.getSecrets)) return mux}
func identity(profile *v1alpha1.BrowserProfile) store.Profile { return store.Profile{Namespace: profile.Metadata.Namespace, Name: profile.Metadata.Name, UID: profile.Metadata.UID}}
func recordedVersion(profile *v1alpha1.BrowserProfile) int64 { if profile.Status.State == nil { return 0 } return profile.Status.State.Version}
func etag(version int64) string { return `"` + strconv.FormatInt(version, 10) + `"`}
func (s *Server) getState(w http.ResponseWriter, r *http.Request) { profile, err := s.authorize(r.Context(), r, r.PathValue("namespace"), r.PathValue("name")) if err != nil { s.refuse(w, r, err) return } state, version, err := s.store.Load(identity(profile), recordedVersion(profile)) if errors.Is(err, store.ErrNoState) { http.Error(w, "no state yet", http.StatusNotFound) return } if errors.Is(err, store.ErrRolledBack) { s.rollbacks.Inc() s.events.Warning(cluster.Reference(profile), v1alpha1.ReasonStateRolledBack, fmt.Sprintf("The stored state is older than version %d, which the status records, so no pod loads it.", recordedVersion(profile))) } if errors.Is(err, seal.ErrOpen) { s.unsealed.WithLabelValues("get_state").Inc() } if err != nil { s.fail(w, r, err) return } w.Header().Set("ETag", etag(version)) w.Header().Set("Content-Type", "application/json") w.Write(state)}
func (s *Server) putState(w http.ResponseWriter, r *http.Request) { profile, err := s.authorize(r.Context(), r, r.PathValue("namespace"), r.PathValue("name")) if err != nil { s.refuse(w, r, err) return } ifVersion, ok := precondition(r) if !ok { http.Error(w, "a write must name the version it replaces in If-Match, or If-None-Match: *", http.StatusPreconditionRequired) return } state, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxState)) if err != nil { http.Error(w, err.Error(), http.StatusRequestEntityTooLarge) return } version, size, err := s.store.Save(identity(profile), ifVersion, state) if errors.Is(err, store.ErrConflict) { s.conflicts.Inc() http.Error(w, err.Error(), http.StatusPreconditionFailed) return } if errors.Is(err, seal.ErrOpen) { s.unsealed.WithLabelValues("put_state").Inc() } if err != nil { s.fail(w, r, err) return } s.saves.Inc() w.Header().Set("ETag", etag(version)) w.WriteHeader(http.StatusNoContent) // The status records the version after the write lands, so a status // write that fails leaves the store ahead of the status, which Load // accepts, and never behind it. if err := s.recordSave(context.WithoutCancel(r.Context()), profile, version, size); err != nil { s.log.Error("recording a save on the profile's status", "profile", profile.Metadata.Namespace+"/"+profile.Metadata.Name, "version", version, "error", err) } s.log.Debug("saved state", "profile", profile.Metadata.Namespace+"/"+profile.Metadata.Name, "version", version, "size", size)}
// precondition reads the version a write replaces: the number in an// If-Match ETag, or 0 for If-None-Match: *.func precondition(r *http.Request) (int64, bool) { if r.Header.Get("If-None-Match") == "*" { return 0, true } match := strings.Trim(r.Header.Get("If-Match"), `"`) version, err := strconv.ParseInt(match, 10, 64) return version, err == nil && version > 0}
// recordSave writes the new version to the profile's status. A write// that meets another writer's change reads the profile again, and// writes only when the fresh copy records an older version.func (s *Server) recordSave(ctx context.Context, profile *v1alpha1.BrowserProfile, version, size int64) error { _, err := s.cluster.SettleStatus(ctx, cluster.WriterStateAPI, profile, func(p *v1alpha1.BrowserProfile) bool { if recordedVersion(p) >= version { return false } p.Status.State = &v1alpha1.StateStatus{Version: version, Size: size, SavedAt: s.now().UTC().Truncate(time.Second)} return true }) return err}
// Secret is one secret as the sidecar receives it.type Secret struct { Value string `json:"value"` Origins []string `json:"origins"`}
func (s *Server) getSecrets(w http.ResponseWriter, r *http.Request) { profile, err := s.authorize(r.Context(), r, r.PathValue("namespace"), r.PathValue("name")) if err != nil { s.refuse(w, r, err) return } secrets := map[string]Secret{} for _, secret := range profile.Spec.Secrets { value, err := s.cluster.SecretValue(r.Context(), profile.Metadata.Namespace, secret.SecretKeyRef.Name, secret.SecretKeyRef.Key) if err != nil { s.fail(w, r, fmt.Errorf("reading the secret %s: %w", secret.Name, err)) return } secrets[secret.Name] = Secret{Value: value, Origins: secret.Origins} } w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") json.NewEncoder(w).Encode(secrets) s.log.Info("served secrets", "profile", profile.Metadata.Namespace+"/"+profile.Metadata.Name, "count", len(secrets))}
func (s *Server) fail(w http.ResponseWriter, r *http.Request, err error) { s.log.Error("answering a request", "method", r.Method, "path", r.URL.Path, "error", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)}