proxy

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 33 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 proxy is kojo-proxy: the egress proxy every sandbox must go through.

It denies every destination that is not on the sandbox's allowlist and sets real credentials on requests to allowlisted hosts, so a sandbox only ever holds placeholders. It runs inside the kojo process (single VM installs) or as its own deployment of one or several replicas (`kojo proxy`, Kubernetes), driven through the Controller interface either way.

Index

Constants

View Source
const (
	ReadyBody    = "kojo-proxy ready\n"
	NotReadyBody = "kojo-proxy is waiting for a kōjō server to send it the sandbox policies\n"
)

ReadyBody and NotReadyBody are the bodies of GET /readyz on the admin listener.

View Source
const (
	DefaultListen      = ":3128"
	DefaultAdminListen = ":3129"
	// DefaultSyncSettle is the SyncSettle of `kojo proxy`: longer than a
	// Client takes to find a new replica (DefaultResolveInterval) and check
	// it (DefaultCheckInterval).
	DefaultSyncSettle = 10 * time.Second
)

Defaults for Options.

View Source
const (
	// ReasonAllowed: the host is on the sandbox's allowlist.
	ReasonAllowed = "allowed"
	// ReasonDeniedHost: the host is not on the allowlist (HTTP 403).
	ReasonDeniedHost = "denied_host"
	// ReasonUnauthenticated: no or wrong proxy credentials (HTTP 407).
	ReasonUnauthenticated = "unauthenticated"
	// ReasonBlockedAddress: the host is allowlisted but resolves to a
	// non-public address (HTTP 403).
	ReasonBlockedAddress = "blocked_address"
)

Reasons a Decision carries. They are also the values of the decision label of kojo_proxy_requests_total.

View Source
const DefaultCheckInterval = 2 * time.Second

DefaultCheckInterval is how often a Client asks each proxy replica for its status: whether it restarted, and whether it holds what it should.

View Source
const DefaultResolveInterval = 5 * time.Second

DefaultResolveInterval is how often a Client that discovers replicas through DNS resolves their name again.

View Source
const HealthBody = "kojo-proxy ok\n"

HealthBody is the body of GET /healthz on the proxy and admin listeners.

View Source
const InstanceHeader = "Kojo-Proxy-Instance"

InstanceHeader is set on every authenticated admin API answer to the proxy's Instance, so a client notices a restart on any call.

Variables

View Source
var ErrBlockedAddress = errors.New("proxy: destination address is not public")

ErrBlockedAddress marks a destination the proxy refuses to dial because it resolves to a loopback, link-local, private or otherwise non-public address. It stops a sandbox from using an allowlisted name to reach the cloud metadata service, the host, or the network kojo itself runs in.

View Source
var ErrNoAdminToken = errors.New("proxy: the admin API needs an admin token")

ErrNoAdminToken is returned when the admin API is asked for without an admin token. The API hands out and replaces credentials, so it never runs open.

Functions

This section is empty.

Types

type CA

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

CA is the certificate authority kojo-proxy signs leaf certificates with.

The proxy terminates TLS only for hosts it injects a credential on, and a sandbox trusts this CA so those connections verify. The CA key never leaves the proxy process: sandboxes get the certificate only.

func LoadOrCreateCA

func LoadOrCreateCA(certFile, keyFile string) (*CA, error)

LoadOrCreateCA returns the CA stored in certFile and keyFile (PEM).

With both paths empty the CA lives in memory only and is new on every start, so sandboxes created earlier must have their policy applied again to trust it. With both paths set, the files are loaded when they exist and generated when both are missing: the certificate with mode 0644 and the key with mode 0600. The key is ECDSA P-256.

func (*CA) CertPEM

func (c *CA) CertPEM() []byte

CertPEM returns the CA certificate, PEM encoded. It is what a sandbox adds to its trust store.

func (*CA) Certificate

func (c *CA) Certificate() *x509.Certificate

Certificate returns the CA certificate.

func (*CA) Leaf

func (c *CA) Leaf(host string) (*tls.Certificate, error)

Leaf returns a certificate for host signed by the CA, valid for a week. Leaves are cached per host and replaced a day before they expire.

type Client

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

Client drives a remote kojo-proxy through its admin API, one replica or several. It implements Controller, so a driver does not care whether the proxy is embedded or remote.

Each replica keeps policies in memory and loses them when it restarts. The Client sends every Set and Delete to every replica it knows, and remembers the last policy it set for each sandbox, in memory, until it deletes that sandbox. Run keeps the replicas in line with it: a replica that restarted, that appeared, or that missed a Set gets the policies it lacks (credentials resolved again through Policy.Refresh, or the ones the Client has that have not expired), one that missed a Delete gets it again, and once a replica holds everything the Client tells it so, which is what makes a new replica ready.

The admin API carries real credentials in policies. Run it on a network only the core can reach, or behind TLS.

func NewClient

func NewClient(o ClientOptions) (*Client, error)

NewClient returns a Client for the admin APIs o names.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, sandboxID string) error

Delete forgets a sandbox, here and on every replica. A replica the delete does not reach gets it again from Run until it lands, or until the replica restarts (and so holds nothing) or is gone. Delete returns an error when no replica took it or one refused it.

func (*Client) Endpoint

func (c *Client) Endpoint(ctx context.Context) (Endpoint, error)

Endpoint returns the address and CA the replicas advertise. Replicas that advertise different ones are an error: a sandbox trusts one CA, and its requests land on any replica.

func (*Client) Report

func (c *Client) Report(ctx context.Context) (ReplicaReport, error)

Report asks every known replica, after resolving them again, for its status and CA. kojo doctor reads it.

func (*Client) Run

func (c *Client) Run(ctx context.Context) error

Run keeps the replicas in line with what the Client remembers, until ctx ends. Every CheckInterval, and at once when an answer names an instance it has not seen or a call missed a replica, it asks each replica for its status, sends it the deletes and policies it lacks, and then tells it it is synced. With DNS discovery it resolves the replicas every ResolveInterval. It returns nil when ctx ends.

func (*Client) Set

func (c *Client) Set(ctx context.Context, p Policy) error

Set creates or replaces the policy of p.SandboxID on every replica and remembers it.

It calls the replicas that answered at their last contact (all of them when none did) and succeeds when at least one took the policy and none refused it. A replica that could not be reached is behind: Run sends it the policy as soon as it answers, and until then it holds what it had. Failing the call instead would not undo the policy on the replicas that took it, and would make one replica that is down, or rolling, fail every sandbox.

type ClientOptions

type ClientOptions struct {
	// URL is the base of the remote proxy's admin API: http://kojo-proxy:3129.
	// Without DiscoverDNS it is one replica.
	URL string
	// URLs are the admin APIs of several replicas, instead of URL.
	URLs []string
	// DiscoverDNS treats every address the host of URL resolves to as one
	// replica, with URL's scheme, port and path, and resolves it again every
	// ResolveInterval: a Kubernetes headless Service that publishes replicas
	// before they are ready.
	DiscoverDNS bool
	// ResolveInterval is how often Run resolves the replicas again. Default
	// DefaultResolveInterval.
	ResolveInterval time.Duration
	// LookupHost resolves a host name for DiscoverDNS. Default:
	// net.DefaultResolver.LookupHost.
	LookupHost func(ctx context.Context, host string) ([]string, error)
	// Token is the remote proxy's admin token.
	Token string
	// HTTPClient makes the requests. Default: a client with a 15s timeout
	// that ignores the environment's proxy settings and, with DiscoverDNS on
	// https, checks each replica's certificate against the host of URL.
	HTTPClient *http.Client
	// CheckInterval is how often Run asks each replica for its status.
	// Default DefaultCheckInterval.
	CheckInterval time.Duration
	// Logger receives restarts of replicas, replicas found and gone, and
	// policies that could not be sent. Credential values are never logged.
	// Default: discard.
	Logger *slog.Logger
	// Registerer receives kojo_proxy_policies_resent_total{replica}. Nil
	// means no metrics.
	Registerer prometheus.Registerer
}

ClientOptions configure a Client.

type Controller

type Controller interface {
	// Set creates or replaces the policy of p.SandboxID.
	Set(ctx context.Context, p Policy) error
	// Delete forgets a sandbox. Deleting an unknown one is not an error.
	Delete(ctx context.Context, sandboxID string) error
	// Endpoint returns the address and CA sandboxes use.
	Endpoint(ctx context.Context) (Endpoint, error)
}

Controller manages sandbox policies on a proxy. *Server implements it in process; *Client implements it against a remote kojo-proxy's admin API.

type Decision

type Decision struct {
	Time time.Time
	// SandboxID is the proxy username. For ReasonUnauthenticated it is the
	// name the client claimed, which nothing has verified.
	SandboxID string
	// Method is the HTTP method, CONNECT for a tunnel.
	Method string
	// Host is the destination hostname, lower-cased, without a port.
	Host    string
	Allowed bool
	// Reason is one of the Reason constants.
	Reason string
	// Injected lists the names of the credentials set on the request.
	Injected []string
	// Intercepted reports whether the proxy terminated TLS for the request.
	Intercepted bool
}

Decision is what the proxy decided about one request. OnDecision receives one per plain-HTTP request, per request inside an intercepted TLS connection, and per CONNECT that is denied or tunneled blindly. It never carries a header value or a token.

type Endpoint

type Endpoint struct {
	// URL is the proxy address as the sandbox sees it, without userinfo:
	// http://host:port.
	URL string `json:"url"`
	// CACertPEM is the CA the sandbox must trust: the proxy terminates TLS
	// for hosts it injects credentials on.
	CACertPEM []byte `json:"ca_cert_pem"`
}

Endpoint is how a sandbox reaches the proxy.

type Options

type Options struct {
	// Listen is the address Run serves the proxy on. Default ":3128".
	Listen string
	// AdminListen is the address Run serves the admin API on. Empty means
	// Run starts no admin listener (the embedded mode, where the core calls
	// the Server directly).
	AdminListen string
	// AdvertiseURL is the proxy address as sandboxes see it: http://host:port
	// without userinfo. Endpoint returns it. When empty, it is derived from
	// the listener, which is only right when sandboxes share the proxy's
	// network namespace.
	AdvertiseURL string
	// CA signs the certificates of intercepted hosts. A nil CA is generated
	// in memory.
	CA *CA
	// AdminToken is the bearer token of the admin API. The admin API does not
	// start without one.
	AdminToken string
	// Logger receives one line per decision at debug level and errors at
	// warn level. Header values and tokens are never logged. Default: discard.
	Logger *slog.Logger
	// AllowPrivate lets the proxy connect to loopback, link-local and private
	// addresses. It disables the SSRF guard and exists for tests and for a
	// forge that lives on a private network.
	AllowPrivate bool
	// OnDecision is called for every decision, from the goroutine serving the
	// request. It feeds the audit log and must not block.
	OnDecision func(Decision)
	// Registerer receives kojo_proxy_requests_total{decision}. Nil means no
	// metrics.
	Registerer prometheus.Registerer
	// Resolver replaces the system DNS resolver for upstream hosts. The
	// addresses it returns go through the same SSRF guard.
	Resolver Resolver
	// UpstreamRoots are the roots upstream certificates are verified against
	// on intercepted connections. Nil means the system roots. Set it for a
	// forge with a private CA.
	UpstreamRoots *x509.CertPool
	// DialTimeout bounds one upstream connection attempt. Default 15s.
	DialTimeout time.Duration
	// SyncTimeout is how long a new proxy waits for a kōjō server to send
	// it the sandbox policies before Ready reports it ready anyway. Until
	// then a replica of a remote proxy takes no sandbox traffic. Zero means
	// ready at once, which is what an embedded proxy wants.
	SyncTimeout time.Duration
	// SyncSettle is how long Ready still waits after the first kōjō server
	// said it had sent everything (MarkSynced), so that the other kōjō
	// servers, which find a new replica within seconds of each other, send
	// theirs too.
	SyncSettle time.Duration
}

Options configure a Server.

type Policy

type Policy struct {
	// SandboxID is the proxy username the sandbox authenticates with.
	SandboxID string `json:"sandbox_id"`
	// Token is the proxy password of this sandbox. It is not a credential
	// for anything else: it only selects this policy.
	Token string `json:"token"`
	// EgressAllow lists hostnames; "*.example.com" matches subdomains.
	EgressAllow []string `json:"egress_allow"`
	// Credentials are set on requests to their host.
	Credentials []sandbox.HostCredential `json:"credentials,omitempty"`
	// Refresh resolves Credentials again. A Client calls it before it sends
	// the policy again after the proxy restarted, so that short-lived values
	// are fresh; it gets a context that carries the values of the one Set
	// was called with. It returns sandbox.ErrNotFound when the sandbox is
	// gone, and the Client then forgets the policy. Nil means the Client
	// sends the credentials it has, without the ones that have expired. It
	// never leaves the process.
	Refresh func(ctx context.Context) ([]sandbox.HostCredential, error) `json:"-"`
}

Policy is what one sandbox may reach and which credentials are injected.

type ReplicaReport

type ReplicaReport struct {
	// Remembered is how many sandbox policies this Client remembers.
	Remembered int
	// Replicas are the known replicas, by address.
	Replicas []ReplicaStatus
}

ReplicaReport is what Report found.

type ReplicaStatus

type ReplicaStatus struct {
	// Address is the replica's admin address, host:port.
	Address string
	// Err is set when the replica did not answer; the other fields but
	// PendingDeletes are then empty.
	Err error
	// Instance is the replica's instance.
	Instance string
	// Ready is the replica's own readiness: whether it takes sandbox
	// traffic.
	Ready bool
	// Synced reports whether a kōjō server told this instance that it holds
	// everything that server remembers.
	Synced bool
	// Policies is how many sandbox policies the replica holds, from every
	// kōjō server.
	Policies int
	// Missing is how many of the policies this Client remembers the
	// replica's instance is not known to hold.
	Missing int
	// PendingDeletes is how many deletes have not reached the replica yet.
	PendingDeletes int
	// CA is the SHA-256 of the CA certificate the replica advertises, in hex.
	CA string
	// Shared reports that the address has answered for more than one
	// replica: it is a load balancer, and the replicas behind it are not
	// each kept in line.
	Shared bool
}

ReplicaStatus is one kojo-proxy replica as a Client sees it.

type Resolver

type Resolver func(ctx context.Context, host string) ([]net.IP, error)

Resolver looks up the addresses of a host. Options.Resolver replaces the system resolver with one.

type Server

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

Server is kojo-proxy: an HTTP forward proxy that only lets a sandbox reach the hosts on its allowlist and sets real credentials on those requests.

It is the single point where secrets meet untrusted traffic. A sandbox authenticates with its ID and token, which select its Policy and nothing else. Everything not allowlisted is refused, including every request without a policy. For hosts that have a credential the proxy terminates TLS with a certificate signed by its CA and rewrites the credential header; every other allowlisted host gets a blind tunnel the proxy cannot read.

A Server is safe for concurrent use. Close releases what it holds.

func New

func New(opts Options) (*Server, error)

New builds a Server. It does not listen: call Run, Serve, or mount Handler.

func (*Server) AdminHandler

func (s *Server) AdminHandler() (http.Handler, error)

AdminHandler returns the admin API a remote core drives the proxy with:

PUT    /v1/policies/{sandboxID}   body: Policy (JSON); 204
PUT    /v1/policies/{sandboxID}?set_at=<RFC 3339 time>
                                  the same, recording when the client
                                  set it, for later restores
PUT    /v1/policies/{sandboxID}?restore=<RFC 3339 time>
                                  Restore; 204, or 409 when a newer
                                  policy is held
DELETE /v1/policies/{sandboxID}   204, also for an unknown sandbox
GET    /v1/endpoint               200, Endpoint (JSON)
GET    /v1/instance               200, {"instance": "<Instance>"}
GET    /v1/status                 200, Status (JSON)
POST   /v1/synced                 body: {"instance": "<Instance>"};
                                  MarkSynced; 204, or 409 for another
                                  instance
GET    /healthz                   200, no authentication
GET    /readyz                    200 when Ready, else 503; no
                                  authentication

Every route except /healthz and /readyz needs "Authorization: Bearer <AdminToken>", and every answer to an authenticated request carries InstanceHeader. Policies carry real credentials: serve this handler on a network only the core reaches. It returns ErrNoAdminToken when Options.AdminToken is empty.

func (*Server) CA

func (s *Server) CA() *CA

CA returns the authority that signs intercepted hosts.

func (*Server) Close

func (s *Server) Close() error

Close ends open tunnels and intercepted connections and releases idle upstream connections. A server that only mounts Handler calls it when it is done; Run and Serve call it themselves.

func (*Server) Delete

func (s *Server) Delete(_ context.Context, sandboxID string) error

Delete forgets a sandbox: its next request gets 407. Deleting an unknown sandbox is not an error.

func (*Server) Endpoint

func (s *Server) Endpoint(context.Context) (Endpoint, error)

Endpoint returns the address and CA sandboxes use.

func (*Server) Handler

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

Handler returns the proxy itself: absolute-URI requests and CONNECT. It also answers GET /healthz, so a driver can check that a sandbox reaches the proxy. A server that mounts it must support http.Hijacker, as net/http's HTTP/1 server and httptest do.

func (*Server) Instance

func (s *Server) Instance() string

Instance identifies this run of the proxy. It is random and new on every start, so a client that sees it change knows the proxy has lost the policies it was given.

func (*Server) MarkSynced

func (s *Server) MarkSynced(instance string) error

MarkSynced records that a kōjō server has sent this proxy every policy it remembers. instance is the instance the server sent them to: a proxy that restarted in between is not synced by it, and MarkSynced returns an error.

func (*Server) Ready

func (s *Server) Ready() bool

Ready reports whether this proxy should take sandbox traffic: with Options.SyncTimeout set, once a kōjō server has marked it synced and Options.SyncSettle has passed since, or once SyncTimeout has passed since it started, whichever comes first. A proxy no kōjō server reached by then holds no policy, so all it can do is refuse.

func (*Server) Restore

func (s *Server) Restore(_ context.Context, p Policy, setAt time.Time) (bool, error)

Restore is Set for a policy a client sends again, which it set at setAt: after this proxy started, or because this replica missed the Set. It applies the policy only when the proxy holds none for the sandbox, or holds one set at an earlier or the same setAt, and reports whether it did. A policy set without a time (Set) is never replaced. Two kōjō replicas that both remember a sandbox (its session moved) therefore end with the policy the later one set, whichever arrives first, and a replica that missed a Set takes it late without undoing a newer one.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run listens on Options.Listen, and on Options.AdminListen when it is set, and serves until ctx ends.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, proxyLn, adminLn net.Listener) error

Serve serves the proxy on proxyLn and, when adminLn is not nil, the admin API on adminLn, until ctx ends. It closes both listeners and the Server. It returns nil when ctx ended and the error of the listener that failed otherwise.

func (*Server) Set

func (s *Server) Set(_ context.Context, p Policy) error

Set creates or replaces the policy of p.SandboxID. It takes effect on the next request, also on connections that are already open. No Restore replaces a policy set this way.

func (*Server) Status

func (s *Server) Status() Status

Status returns the proxy's instance, readiness and policy count.

type Status

type Status struct {
	// Instance is the proxy's Instance.
	Instance string `json:"instance"`
	// Ready is the proxy's Ready.
	Ready bool `json:"ready"`
	// Synced reports whether a kōjō server has marked this instance synced.
	Synced bool `json:"synced"`
	// Policies is how many sandbox policies the proxy holds, from every
	// kōjō server.
	Policies int `json:"policies"`
}

Status is what the admin API's GET /v1/status answers.

Jump to

Keyboard shortcuts

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