api

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2026 License: Apache-2.0 Imports: 42 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package api serves the local UI and the read API behind it.

A local HTTP server holding live cluster credentials is a real attack surface, so it is treated as one. Three defences, all enforced here rather than assumed:

  • The listener binds 127.0.0.1 only, never 0.0.0.0.
  • Every request carries a per-session token generated at startup. The browser gets it once, in the URL kubeside opens.
  • Origin and Host are checked, so a page on another site cannot drive this server through the user's browser.

The browser never talks to an apiserver. It talks to this, and this holds the kubeconfig credentials.

Index

Constants

View Source
const (
	ViewApps = "apps"
	ViewLogs = "logs"
)

Views the stream can serve. Anything else is refused by name rather than silently ignored, so a client bug surfaces as an error instead of a screen that never updates.

View Source
const (
	// DefaultPollInterval is how often a watched view is re-read.
	DefaultPollInterval = 5 * time.Second
)

Variables

This section is empty.

Functions

func Listen

func Listen(port int) (net.Listener, error)

Listen binds a loopback listener.

The address is hardcoded to 127.0.0.1. Binding 0.0.0.0 would expose cluster credentials to the local network, so it is not configurable.

Types

type API

type API interface {
	Contexts() []ContextView
	Apps(context string) (AppsView, error)
	// LogSource opens the log side of one workload. It is separate from Apps
	// because a log stream outlives a single read: the transport keeps it for
	// as long as a window is watching.
	LogSource(contextName, namespace, workload string) (logs.Source, error)
	// Timeline reconstructs one workload's history from the cluster, on demand.
	Timeline(contextName, namespace, workload string) (TimelineView, error)
	// AppDetail is one workload's current state, pods, and history in one read.
	AppDetail(contextName, namespace, workload string) (AppDetailView, error)
	// Config resolves what one container actually received.
	Config(contextName, namespace, workload string) (ConfigView, error)
	// RevealSecret fetches one key of one Secret, gated and recorded.
	RevealSecret(contextName, namespace, secret, key, workload string) (RevealView, error)
	// Diff compares one app's configuration across two environments.
	Diff(req DiffRequest) (DiffView, error)
	// StartForward opens a port-forward, Forwards lists them, StopForward
	// closes one.
	StartForward(req ForwardRequest) (forward.Forward, error)
	Forwards() []forward.Forward
	StopForward(id string) error
	// Promotion compares every app across every environment.
	Promotion() PromotionView
	// Capabilities resolves what this reader may do in one namespace, so every
	// control renders disabled-with-a-reason rather than hidden.
	Capabilities(contextName, namespace string) CapabilitiesView
	// Gate answers what ceremony an action needs, and whether the cluster
	// would permit it at all.
	Gate(req GateRequest) (GateView, error)
	// StartExec opens an interactive shell, after both gates agree.
	StartExec(ctx context.Context, req ExecRequest, onOutput func([]byte)) (*exec.Session, <-chan error, error)
	// Observed reports a row that changed between two reads, which is how the
	// timeline extends forward while kubeside runs.
	Observed(contextName string, before, after AppView)
}

API is what the server exposes. Keeping it an interface lets the transport be tested without a cluster manager behind it.

The return types are concrete rather than any, because the delta path has to diff two views to compute a patch and cannot do that through an interface value.

type AppDetailView

type AppDetailView struct {
	Context   string `json:"context"`
	Namespace string `json:"namespace"`
	Workload  string `json:"workload"`
	Kind      string `json:"kind"`

	Health string `json:"health"`
	Reason string `json:"reason,omitempty"`
	Detail string `json:"detail,omitempty"`
	Ready  string `json:"ready,omitempty"`

	// Image and RevisionAt come from the newest reconstructed rollout, which is
	// the only place the running version is recoverable without a second read.
	Image      string `json:"image,omitempty"`
	RevisionAt string `json:"revisionAt,omitempty"`

	Restarts int32        `json:"restarts"`
	Pods     []PodView    `json:"pods"`
	Timeline TimelineView `json:"timeline"`
}

AppDetailView is everything Screen 2 renders: the app's current state, the pods behind it, and its history. One read, because a screen that arrives in four pieces flickers through four wrong answers first.

type AppView

type AppView struct {
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
	Kind      string `json:"kind"`
	Health    string `json:"health"`
	Reason    string `json:"reason"`
	Detail    string `json:"detail"`
	GroupedBy string `json:"groupedBy"`
	ManagedBy string `json:"managedBy,omitempty"`
	Ready     string `json:"ready"` // "5/6" or "" when not applicable
	Objects   int    `json:"objects"`
}

AppView is one row.

type AppsMeta

type AppsMeta struct {
	State   string      `json:"state"`
	Scope   string      `json:"scope"`
	Reason  string      `json:"reason,omitempty"`
	Partial []string    `json:"partial,omitempty"`
	Error   string      `json:"error,omitempty"`
	Metrics MetricsInfo `json:"metrics"`
}

AppsMeta is the view-level truth: what scope was readable, what state the connection is in, what could not be read. It travels only when it changes, but it must travel, because a cluster going stale changes what the screen is allowed to claim.

type AppsPatch

type AppsPatch struct {
	Meta    *AppsMeta `json:"meta,omitempty"`
	Added   []AppView `json:"added,omitempty"`
	Changed []AppView `json:"changed,omitempty"`
	Removed []string  `json:"removed,omitempty"`
}

AppsPatch carries only what moved. Absent fields mean unchanged, never empty: an omitted Removed is not "everything was deleted".

type AppsView

type AppsView struct {
	Context string      `json:"context"`
	State   string      `json:"state"`
	Scope   string      `json:"scope"`
	Reason  string      `json:"reason,omitempty"`
	Partial []string    `json:"partial,omitempty"`
	Apps    []AppView   `json:"apps"`
	Error   string      `json:"error,omitempty"`
	Metrics MetricsInfo `json:"metrics"`
}

AppsView is one context's grouped app list plus the honesty metadata the UI needs: what scope was readable and which kinds were not.

func AppsFromSnapshot

func AppsFromSnapshot(snap clusters.Snapshot, state string, metrics MetricsInfo) AppsView

AppsFromSnapshot renders a snapshot into the wire view. The health verdict is computed here, once, so every consumer sees the same derivation.

type CapabilitiesView

type CapabilitiesView struct {
	Context   string                     `json:"context"`
	Namespace string                     `json:"namespace"`
	Can       map[string]rbac.Permission `json:"can"`
}

CapabilitiesView is what this reader may do in one namespace of one context.

The UI asks once per screen and renders every control accordingly: visible, disabled where refused, and naming the verb it needs. Nothing is ever hidden for lack of permission.

type ClientMessage

type ClientMessage struct {
	Type    string `json:"type"`
	View    string `json:"view"`
	Context string `json:"context"`

	Namespace string `json:"namespace,omitempty"`
	Workload  string `json:"workload,omitempty"`

	Pods            []string `json:"pods,omitempty"`
	Containers      []string `json:"containers,omitempty"`
	IncludeSidecars bool     `json:"includeSidecars,omitempty"`
	IncludeInit     bool     `json:"includeInit,omitempty"`
	Previous        bool     `json:"previous,omitempty"`
	Tail            int64    `json:"tail,omitempty"`
}

ClientMessage is what the browser sends. Type, View, and Context are always required; the rest identify and shape a logs subscription.

Every field that changes what a subscription reads is part of its identity, so one window revealing sidecars cannot change what another window sees.

type ConfigView

type ConfigView struct {
	Context    string               `json:"context"`
	Namespace  string               `json:"namespace"`
	Workload   string               `json:"workload"`
	Pod        string               `json:"pod"`
	Containers []resolved.Container `json:"containers"`
	Caveat     string               `json:"caveat,omitempty"`
	// ComparedTo names the revision the diff column compares against.
	ComparedTo string `json:"comparedTo,omitempty"`
}

ConfigView is the configuration one container actually received, one table per container.

type ContextView

type ContextView struct {
	Name    string `json:"name"`
	Current bool   `json:"current"`
	State   string `json:"state"`   // never-connected, connecting, live, stale, unreachable, unauthorized
	HasData bool   `json:"hasData"` // false means never render an app list; nothing is known
	AgeSec  int64  `json:"ageSec,omitempty"`
	Error   string `json:"error,omitempty"`

	// The environment this context belongs to, resolved from the config file
	// when one binds it and from the context name otherwise. Risk drives the
	// colour and the hazard hatch, so the browser never re-guesses what an
	// environment is from its name.
	Environment string `json:"environment"`
	Risk        string `json:"risk"`   // low, medium, high
	Color       string `json:"color"`  // green, amber, red, violet, or whatever the file named
	Hazard      bool   `json:"hazard"` // hatch the edge: high risk only
	Write       string `json:"write"`  // allow, confirm, deny, break-glass
}

ContextView is one kubeconfig context and its live connection state.

type DiffRequest

type DiffRequest struct {
	Context        string
	Namespace      string
	Workload       string
	Other          string
	OtherNamespace string
	OtherWorkload  string
	Container      string
}

DiffRequest names the two sides of a comparison. The right side defaults to the same namespace and workload, since the common case is the same app in another environment.

type DiffSide

type DiffSide struct {
	Context   string       `json:"context"`
	Namespace string       `json:"namespace"`
	Workload  string       `json:"workload"`
	Pod       string       `json:"pod,omitempty"`
	Env       resolved.Env `json:"env"`
}

DiffSide is one environment in a comparison.

type DiffView

type DiffView struct {
	Left      DiffSide            `json:"left"`
	Right     DiffSide            `json:"right"`
	Container string              `json:"container"`
	Rows      []resolved.CrossRow `json:"rows"`
	Summary   resolved.Summary    `json:"summary"`
}

DiffView is one app's configuration compared across two environments.

type ExecRequest

type ExecRequest struct {
	Context   string
	Namespace string
	Pod       string
	Container string
	Workload  string
	// Confirm is what the developer typed. The guard says what it has to
	// match, and the server compares it: a confirmation the server does not
	// check is a dialog, not a control.
	Confirm string
}

ExecRequest names one container to open a shell in.

type ForbiddenError

type ForbiddenError struct{ Reason string }

ForbiddenError is a refusal the transport turns into a 403 with the verb named, rather than a generic failure.

func (*ForbiddenError) Error

func (e *ForbiddenError) Error() string

type ForwardRequest

type ForwardRequest struct {
	Context    string `json:"context"`
	Namespace  string `json:"namespace"`
	Workload   string `json:"workload"`
	Pod        string `json:"pod,omitempty"`
	RemotePort int    `json:"remotePort"`
	LocalPort  int    `json:"localPort,omitempty"`
	// Confirm is what the developer typed, when the environment asks for it.
	Confirm string `json:"confirm,omitempty"`
}

ForwardRequest asks for one port-forward.

type GateRequest

type GateRequest struct {
	Context   string `json:"context"`
	Namespace string `json:"namespace"`
	Verb      string `json:"verb"`
	Resource  string `json:"resource"`
	Name      string `json:"name"`
	// Unlock, when set, arms the environment with this reason before answering.
	Unlock string `json:"unlock,omitempty"`
}

GateRequest asks what ceremony an action needs in one environment.

type GateView

type GateView struct {
	Gate       guard.Gate      `json:"gate"`
	Permission rbac.Permission `json:"permission"`
}

GateView is the answer, with everything a confirmation dialog must show: which environment, what it touches, and the equivalent command.

type LogEdge

type LogEdge struct {
	Kind      string `json:"kind"` // horizon, restart, gone, error, ended
	Pod       string `json:"pod,omitempty"`
	Container string `json:"container,omitempty"`
	Time      string `json:"time,omitempty"`
	Reason    string `json:"reason"`
}

LogEdge is a boundary in what the cluster can still tell us.

type LogLine

type LogLine struct {
	Seq       int64  `json:"seq"`
	Time      string `json:"time,omitempty"`
	Pod       string `json:"pod"`
	Container string `json:"container"`
	Text      string `json:"text"`
	Previous  bool   `json:"previous,omitempty"`
	Truncated bool   `json:"truncated,omitempty"`
	Late      bool   `json:"late,omitempty"`
}

LogLine is one merged line. Time is RFC3339Nano, or empty when the kubelet did not stamp it.

type LogsBatch

type LogsBatch struct {
	Lines []LogLine `json:"lines,omitempty"`
	Edges []LogEdge `json:"edges,omitempty"`
	// Dropped is how many lines the server-side ring has discarded. A buffer
	// that quietly loses lines makes a chatty workload look calm.
	Dropped int `json:"dropped,omitempty"`
	// Reset marks the batch that replaces the view, which is what a fresh
	// subscription and a reconnect both send.
	Reset bool `json:"reset,omitempty"`
}

LogsBatch is a slice of merged output. Lines are batched rather than sent one per frame: a workload emitting thousands of lines a second would otherwise spend the tab's whole budget on framing.

type MetricsInfo

type MetricsInfo struct {
	Source    string `json:"source"`
	Available bool   `json:"available"`
	Reason    string `json:"reason,omitempty"`
}

MetricsInfo tells the UI whether to render usage columns at all. A source that is unavailable yields no columns, never zeroes.

type Option

type Option func(*Server)

Option configures a Server.

func WithPollInterval

func WithPollInterval(d time.Duration) Option

WithPollInterval sets how often a watched view is re-read. Tests use a short interval; nothing else needs to set it.

type PodView

type PodView struct {
	Name     string `json:"name"`
	Phase    string `json:"phase,omitempty"`
	Health   string `json:"health"`
	Ready    bool   `json:"ready"`
	Restarts int32  `json:"restarts"`
	AgeSec   int64  `json:"ageSec,omitempty"`
	Reason   string `json:"reason,omitempty"`
}

PodView is one replica.

func PodsOf

func PodsOf(a apps.App, now time.Time) []PodView

PodsOf renders an app's pods, worst first: the replica that needs a human should not be somewhere in the middle of six.

type PromotionView

type PromotionView struct {
	Envs    []promotion.Env   `json:"envs"`
	Rows    []promotion.Row   `json:"rows"`
	Summary promotion.Summary `json:"summary"`
	// Unreachable names the environments that could not be read at all, so an
	// empty column reads as "not connected" rather than as "nothing deployed".
	Unreachable []string `json:"unreachable,omitempty"`
}

PromotionView is the matrix: one row per app, one column per environment.

type RevealView

type RevealView struct {
	Secret string `json:"secret"`
	Key    string `json:"key"`
	Value  string `json:"value,omitempty"`
	// Binary marks data that is not text. Rendering bytes as characters would
	// produce garbage and hide what the value actually is.
	Binary bool   `json:"binary,omitempty"`
	Note   string `json:"note,omitempty"`
}

RevealView is one secret key, fetched on demand. It carries exactly the key that was asked for and nothing else from the object.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is the local HTTP server.

func New

func New(a API, ui http.Handler, opts ...Option) (*Server, error)

New builds a server with a freshly generated session token.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler is the fully wrapped handler, security included. There is no way to obtain the bare mux, so the checks cannot be bypassed by accident.

func (*Server) Handoff

func (s *Server) Handoff() string

Handoff is the single-use code the opened URL carries.

func (*Server) Token

func (s *Server) Token() string

Token is the session token. It is never put in a URL.

func (*Server) URL

func (s *Server) URL(l net.Listener) string

URL is the address to open.

It carries a code that is spent the moment the browser presents it, not the session token. The URL becomes an argv another local user can read, and the browser writes it to its history; both survive long enough to matter, and neither should hold a credential that stays valid.

type ServerMessage

type ServerMessage struct {
	Type    string `json:"type"`
	View    string `json:"view"`
	Context string `json:"context"`
	// Key echoes the subscription this message belongs to, so a tab holding
	// two subscriptions on one context routes by identity rather than by
	// guessing from the view name.
	Key string `json:"key,omitempty"`
	// Seq increments per subscription, starting at the snapshot. A client that
	// sees a gap knows it missed a patch and must resubscribe.
	Seq      int64      `json:"seq"`
	Snapshot *AppsView  `json:"snapshot,omitempty"`
	Patch    *AppsPatch `json:"patch,omitempty"`
	Logs     *LogsBatch `json:"logs,omitempty"`
	Message  string     `json:"message,omitempty"`
}

ServerMessage is what the browser receives. Exactly one payload field is populated, chosen by Type.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service implements API over the cluster manager. It connects lazily and fetches on demand, holding nothing on disk.

func NewService

func NewService(cfg *kubeconfig.Config, mgr *clusters.Manager, opts kubeconfig.Options, conf *config.Config, timeout time.Duration) *Service

NewService builds the API backend. conf may be nil, which is the zero-config first run: environments are then inferred from context names.

func (*Service) AppDetail

func (s *Service) AppDetail(contextName, namespace, workload string) (AppDetailView, error)

AppDetail is everything Screen 2 needs in one read.

The current state comes from the grouping engine, the history from reconstruction, and the running image from the newest rollout, which is the only place it survives without a second read.

func (*Service) Apps

func (s *Service) Apps(name string) (AppsView, error)

Apps connects the named context if needed, fetches, and renders the view.

An unreached context returns its state and no app list, never an empty one: absence of knowledge and absence of apps are different facts.

func (*Service) Can

func (s *Service) Can(contextName string, action rbac.Action) rbac.Permission

Can answers one permission question for the UI, which is how a control knows whether to render itself disabled and what verb to name.

func (*Service) Capabilities

func (s *Service) Capabilities(contextName, namespace string) CapabilitiesView

Capabilities resolves every control's permission for one namespace at once.

func (*Service) Close

func (s *Service) Close()

Close releases everything the service holds. No tunnel outlives the process that opened it.

func (*Service) Config

func (s *Service) Config(contextName, namespace, workload string) (ConfigView, error)

Config resolves what one container actually received.

The reading comes from a running pod rather than the workload's template, because the template is what was asked for and the pod is what happened. A rollout that has not finished makes those different, and the difference is the thing worth seeing.

func (*Service) Contexts

func (s *Service) Contexts() []ContextView

Contexts returns every context with its live connection state, in connect order so the current context leads.

func (*Service) Diff

func (s *Service) Diff(req DiffRequest) (DiffView, error)

Diff compares one app's configuration across two environments.

Both sides are resolved the same way the configuration screen resolves one, then classified. Secret values are hashed inside this process and never returned: the answer says two credentials differ without either appearing on a screen.

func (*Service) Forwards

func (s *Service) Forwards() []forward.Forward

Forwards lists every live tunnel.

func (*Service) Gate

func (s *Service) Gate(req GateRequest) (GateView, error)

Gate answers what an action costs in one environment, and whether the cluster would allow it at all.

Both halves travel together on purpose. The guardrail is ergonomics against acting in the wrong window; the permission is the security boundary. A UI that shows one without the other teaches the wrong lesson about which is which.

func (*Service) LogSource

func (s *Service) LogSource(contextName, namespace, workload string) (logs.Source, error)

LogSource opens the log side of one workload.

The pod set comes from the grouping engine, not a label selector: the engine already decided which pods are this app, and a selector would be a second answer that disagrees on exactly the workloads that need it most.

func (*Service) Observed

func (s *Service) Observed(contextName string, before, after AppView)

Observed records a row that changed between two reads.

Only health transitions are kept. Replica counts churn through every rollout and a timeline of them buries the one line that matters, which is the moment an app stopped being healthy.

func (*Service) Promotion

func (s *Service) Promotion() PromotionView

Promotion compares every app across every environment.

Opening this view is what connects the environments: the matrix cannot answer "is the fix in prod yet" without reading prod. An environment that will not connect becomes a column of unreadable cells naming the reason, never an empty column that reads as "nothing is deployed there".

func (*Service) Reap

func (s *Service) Reap() []string

Reap drops connections nobody has looked at, which is the idle tier.

The connection goes; the snapshot stays. A context that has been idle for fifteen minutes renders its last known answer labelled with its age, which is a different thing from a context nothing is known about.

func (*Service) RevealSecret

func (s *Service) RevealSecret(contextName, namespace, secret, key, workload string) (RevealView, error)

RevealSecret fetches one key of one Secret, on demand.

Three things make this safe enough to exist. The permission is checked against the specific Secret, not inferred. Only the requested key is returned, never the whole object. And every reveal is written to the session timeline, so reading a production credential leaves a trace in the same place every other change does.

func (*Service) StartExec

func (s *Service) StartExec(ctx context.Context, req ExecRequest, onOutput func([]byte)) (*exec.Session, <-chan error, error)

StartExec opens an interactive session, after both gates agree.

The order matters and is not an accident. The cluster is asked first, because RBAC is the boundary; the write policy is checked second, because it is ergonomics on top. A session that opens leaves a record on the timeline: a shell in production is an event.

func (*Service) StartForward

func (s *Service) StartForward(req ForwardRequest) (forward.Forward, error)

StartForward opens a port-forward into one workload.

The pod is chosen the same way the configuration screen chooses one: a ready replica, because forwarding into a crash-looping pod produces a tunnel that closes as fast as it opens.

func (*Service) StartJanitor

func (s *Service) StartJanitor(ctx context.Context)

StartJanitor reaps idle connections until ctx is cancelled. Nothing else in the process is on a timer: attention drives everything, and this is what notices the absence of attention.

func (*Service) StopForward

func (s *Service) StopForward(id string) error

StopForward closes one tunnel.

func (*Service) Timeline

func (s *Service) Timeline(contextName, namespace, workload string) (TimelineView, error)

Timeline reconstructs one workload's history from the cluster.

Nothing here was recorded by kubeside: every entry is assembled on demand from what Kubernetes still holds, which is why two developers opening the same app see the same history.

type TimelineView

type TimelineView struct {
	Context   string             `json:"context"`
	Namespace string             `json:"namespace"`
	Workload  string             `json:"workload"`
	Entries   []timeline.Entry   `json:"entries"`
	Horizons  []timeline.Horizon `json:"horizons,omitempty"`
	Gaps      []timeline.Gap     `json:"gaps,omitempty"`
}

TimelineView is one app's reconstructed history, plus the honesty metadata: where each source ran out and which could not be read at all.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL