policy

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package policy holds the workspace gateway's decisions as data (gateway.md): the host classes and what a CONNECT or a plain HTTP request to each gets, the egress check (the task's mode and allow list, the deny table, the open addresses), the github.com, api.github.com (with the GraphQL read check), dispatcher and model host (methods and path lists) request rules, the refusal codes and bodies, and the cookie filter of the model hosts.

It is pure, like internal/rules: no network, no I/O, no clock and no goroutines. The gateway package resolves names, reads the agent host's interface addresses and dials; this package only decides.

Index

Constants

View Source
const (
	ModeDefault       = "default"         // every host passes the host check
	ModeDenyByDefault = "deny-by-default" // only AllowHosts pass
)

The egress modes (#100's environment.egress.mode).

View Source
const (
	// GitHost is the git host: the only host whose git credentials the gateway uses, and the
	// one the CA's name constraints list.
	GitHost = "github.com"
	// GitHubAPIHost gets the task token on GET and HEAD.
	GitHubAPIHost = "api.github.com"
	// ChatGPTHost gets the ChatGPT login (codex).
	ChatGPTHost = "chatgpt.com"
	// AuthOpenAIHost is refused: the gateway owns the ChatGPT refresh.
	AuthOpenAIHost = "auth.openai.com"
	// DispatcherHost is runbundle.DefaultDispatcherURL's host: the dispatcher as the VM sees it.
	DispatcherHost = "dispatcher.factory.internal"
)

The hosts the gateway serves itself. Names are compared lower-cased and without a trailing dot, exactly: a name under one of them (downloads.claude.ai) is an ordinary host.

View Source
const (
	InterceptPort  = 443 // the intercepted hosts' CONNECT port
	DispatcherPort = 80  // the dispatcher's plain HTTP port

)

The ports the gateway's own routes are served on.

View Source
const (
	// RefusalHeader carries the code on every answer the gateway makes itself.
	RefusalHeader = "X-Factory-Gateway-Refusal"
	// ContentType is the type of every answer the gateway makes itself.
	ContentType = "text/plain; charset=utf-8"
	// BodyPrefix starts every refusal body.
	BodyPrefix = "factory gateway: "
)
View Source
const GraphQLPath = "/graphql"

GraphQLPath is api.github.com's GraphQL endpoint.

View Source
const InfraCookiePrefix = "cf_chl_"

InfraCookiePrefix starts the names of Cloudflare's challenge cookies, which pass too.

View Source
const MaxGraphQLBody = 1 << 20

MaxGraphQLBody bounds a POST /graphql body the gateway reads to check it.

Variables

View Source
var ErrEgress = errors.New("invalid egress policy")

ErrEgress is wrapped by every *EgressError.

View Source
var ErrGraphQLNotRead = errors.New("the GraphQL request is not a query")

ErrGraphQLNotRead is a POST /graphql body that isn't provably a read: not a single JSON object with only query, variables and operationName, or a document with anything but queries and fragments at its top level, or one that doesn't lex.

Functions

func AnthropicHosts

func AnthropicHosts() []string

AnthropicHosts returns the hosts that get the Anthropic credential, sorted.

func Canonical

func Canonical(u *url.URL) bool

Canonical reports whether u's path is the one that is matched: not encoded another way (RawPath empty) and clean, so /a/../b, //a and /a/ never reach a path rule.

func CarrierHeaders

func CarrierHeaders() []string

CarrierHeaders returns the request headers that can carry a credential. URL user info is a carrier too.

func CheckGraphQLDocument

func CheckGraphQLDocument(doc string) error

CheckGraphQLDocument reports whether a GraphQL document only reads. It lexes the document (skipping comments, strings and block strings) and checks its top level, outside every bracket: each definition starts with '{' (an anonymous query), query or fragment; no top-level name is mutation or subscription in any case (so an operation named mutation is refused too); and between definitions only names, '@', '(' and '{' appear. A lexical error, an unbalanced bracket, an unterminated definition or an empty document is ErrGraphQLNotRead.

func CheckGraphQLRequest

func CheckGraphQLRequest(body []byte) error

CheckGraphQLRequest reports whether body, a POST /graphql request body, only reads: one JSON object (no batch array, no trailing data, valid UTF-8, no key twice under any case) whose keys are query (a non-empty string), variables and operationName, and whose query document passes CheckGraphQLDocument. Anything else is ErrGraphQLNotRead. It fails closed: a body another parser might read differently is refused.

func FilterCookies

func FilterCookies(values []string) []string

FilterCookies applies CookiesInfraOnly to a request's Cookie header values: it keeps the name=value pairs whose name IsInfraCookie, in order and as they were sent, joined into one value with "; ". It drops every other cookie, and any pair that isn't name=value or whose value isn't an RFC 6265 cookie-value (no space, comma, backslash or control character, quotes only around it), so a lenient upstream parser can't read another cookie out of a kept one. It returns nil when nothing is left, so the caller removes the header.

func InfraCookies

func InfraCookies() []string

InfraCookies returns the cookie names the model hosts keep (CookiesInfraOnly), besides any name that starts with InfraCookiePrefix.

func InterceptedHosts

func InterceptedHosts() []string

InterceptedHosts returns every host the gateway TLS-intercepts, sorted: the Anthropic hosts, chatgpt.com, github.com and api.github.com. The CA's name constraints list exactly these.

func IsInfraCookie

func IsInfraCookie(name string) bool

IsInfraCookie reports whether name, compared exactly (cookie names are case-sensitive), is an infrastructure cookie.

func NormalizeHost

func NormalizeHost(h string) string

NormalizeHost lower-cases an ASCII host name and removes one trailing dot. Non-ASCII bytes are kept as they are, so a name that only folds to a known host under Unicode rules (conſole.anthropic.com, with a long s, which strings.EqualFold matches) never matches one.

Types

type Access

type Access uint8

Access is a repo's access for the task (gateway.md, github.com): rw for the task repo whose credential writes contents, read for the task repo otherwise and for every read credential's repos, unknown for any other repo.

const (
	AccessUnknown Access = iota
	AccessRead
	AccessRW
)

The accesses.

type Action

type Action uint8

Action is what the gateway does with a CONNECT or a plain HTTP request.

const (
	Refuse       Action = iota // answer Decision.Refusal (and close a CONNECT)
	Intercept                  // CONNECT: TLS-terminate and apply the class's request rules
	Tunnel                     // CONNECT: resolve, check every address (Egress.CheckResolved), tunnel
	Forward                    // plain HTTP: resolve, check every address, forward
	ToDispatcher               // plain HTTP to the dispatcher: its route rule, then Config.Dispatcher
)

The actions.

func (Action) String

func (a Action) String() string

type Class

type Class uint8

Class is a host's row in the host table.

const (
	Ordinary   Class = iota // every other host: a tunnel or plain forwarding, after the egress check
	Anthropic               // the Anthropic hosts: intercepted, the Anthropic credential
	ChatGPT                 // chatgpt.com: intercepted, the ChatGPT login
	AuthOpenAI              // auth.openai.com: refused
	GitHub                  // github.com: intercepted, git credentials by repo
	GitHubAPI               // api.github.com: intercepted, the task token on GET and HEAD
	Dispatcher              // the dispatcher: plain HTTP only, the run token
)

The host classes.

func ClassOf

func ClassOf(host string) Class

ClassOf is host's class. host is normalised first (NormalizeHost); an IP literal is Ordinary.

func (Class) Cookies

func (c Class) Cookies() CookieRule

Cookies is the class's cookie rule: the model hosts keep only the infrastructure cookies, github.com, api.github.com and the dispatcher lose the header, and ordinary hosts keep it.

func (Class) Intercepted

func (c Class) Intercepted() bool

Intercepted reports whether a CONNECT to the class is TLS-intercepted (on InterceptPort).

func (Class) String

func (c Class) String() string

func (Class) StripsCarriers

func (c Class) StripsCarriers() bool

StripsCarriers reports whether the class's routes remove every credential carrier (CarrierHeaders and URL user info) before setting the gateway's credential, so the VM's placeholder is replaced and never compared. An ordinary host keeps them, except Proxy-Authorization, which the gateway always drops.

type Code

type Code string

Code is a refusal: why the gateway answered a request itself, or closed a connection, instead of forwarding it. It is the X-Factory-Gateway-Refusal header's value and an egress record's "refusal".

const (
	CodeNotProxy         Code = "not-proxy"
	CodeBadPath          Code = "bad-path"
	CodeHostMismatch     Code = "host-mismatch"
	CodeBadTarget        Code = "bad-target"
	CodePort             Code = "port"
	CodePlainHTTP        Code = "plain-http"
	CodePlainOnly        Code = "plain-only"
	CodeAuthHost         Code = "auth-host"
	CodePushRefused      Code = "push-refused"
	CodeWebWrite         Code = "web-write"
	CodeAPIWrite         Code = "api-write"
	CodeDispatcherRoute  Code = "dispatcher-route"
	CodeModelPath        Code = "model-path"
	CodeEgressNotAllowed Code = "egress-not-allowed"
	CodeEgressDenied     Code = "egress-denied"
	CodeResolve          Code = "resolve"
	CodeUpstream         Code = "upstream"
	CodeTimeout          Code = "timeout"
	CodeClosing          Code = "closing"
	CodeNoLogin          Code = "no-login"
	// CodeSNIMismatch, CodeNotTLS and CodePeer close the connection without an answer.
	CodeSNIMismatch Code = "sni-mismatch"
	CodeNotTLS      Code = "not-tls"
	CodePeer        Code = "peer"
)

The refusal codes (gateway.md, "Refusals and errors").

func CheckHost

func CheckHost(hostHeader, connectHost string) Code

CheckHost checks the Host header of a request inside an intercepted tunnel against the CONNECT's host: both normalised, and the header's port, when it has one, removed only when it is 443. It returns "" when they match, else CodeHostMismatch (another name, or another port).

func Codes

func Codes() []Code

Codes returns every refusal code, in the LLD's table order.

func DecideDispatcher

func DecideDispatcher(method string, u *url.URL, taskID string) Code

DecideDispatcher applies the dispatcher's only route to a request: POST /api/v1/tasks/<taskID>/effects, compared segment by segment after the canonical-path check (bad-path), with any query; every other request is dispatcher-route. taskID must not be empty.

func DecideGitHubAPI

func DecideGitHubAPI(method string, u *url.URL) (graphql bool, refusal Code)

DecideGitHubAPI applies the api.github.com rule: GET and HEAD on any path are reads (the path isn't matched, so encoded branch names pass), except on the GraphQL endpoint in any spelling, which can't be checked there; POST /graphql, exactly and without a query, is a read only when its body is (graphql true: the caller checks it with CheckGraphQLRequest); every other request is api-write.

func DecideModel

func DecideModel(host, method string, u *url.URL, carrier bool) Code

DecideModel applies a model host's method and path rule to a request inside its tunnel, before the login is read: any method outside the model set is api-write. A request that gets the owner's login (every chatgpt.com request, whose account id is set while a login exists; an Anthropic request that carried a carrier, Authorization or X-Api-Key, whatever its value) must then have a canonical path (else bad-path) on its host's list, compared case-sensitively with any query (else model-path). An Anthropic request without a carrier goes on without a credential, its path unchecked. host is the CONNECT's normalised host.

func (Code) Response

func (c Code) Response(class DenyClass) (r Response, ok bool)

Response builds the answer for c. class is used only by egress-denied, whose body names it; it must then be one of the DenyClasses. ok is false for a code without an answer (sni-mismatch, not-tls, peer), an unknown code, and egress-denied with a class outside the set.

func (Code) Status

func (c Code) Status() int

Status is the HTTP status the gateway answers c with; 0 for a code it answers by closing the connection (sni-mismatch, not-tls, peer) and for an unknown code.

type CookieRule

type CookieRule uint8

CookieRule is what the gateway does with a request's Cookie header.

const (
	CookiesUntouched CookieRule = iota // tunnels and plain forwarding carry no credential
	CookiesInfraOnly                   // only InfraCookies pass (FilterCookies)
	CookiesStripped                    // the header is removed
)

The cookie rules.

type Decision

type Decision struct {
	Action  Action
	Refusal Code // set exactly when Action is Refuse
	Class   Class
	Target  Target // the zero Target when the target didn't parse
}

Decision is the host table's answer for one CONNECT or plain HTTP request.

func DecideConnect

func DecideConnect(target string, e Egress) Decision

DecideConnect applies the host table to a CONNECT's target (host:port): bad-target when it doesn't parse; auth.openai.com refused (auth-host); the dispatcher refused (plain-only); an intercepted host intercepted on 443 and refused on any other port (port); any other host tunnelled when e's host check allows it, else egress-not-allowed. The intercepted hosts and the dispatcher are the gateway's own routes, so the egress mode never applies to them.

func DecidePlain

func DecidePlain(scheme, hostport string, e Egress) Decision

DecidePlain applies the host table to an absolute-form request's URL scheme and host (port 80 when it has none): not-proxy for a scheme other than http or a host that doesn't parse (an origin-form request has neither); auth.openai.com refused (auth-host); an intercepted host refused (plain-http); the dispatcher on port 80 only, else dispatcher-route; any other host forwarded when e's host check allows it, else egress-not-allowed.

type DenyClass

type DenyClass string

DenyClass names why an address is denied: the egress-denied body says it.

const (
	DenyUnspecified   DenyClass = "unspecified"
	DenyLoopback      DenyClass = "loopback"
	DenyPrivate       DenyClass = "private"
	DenyCGNAT         DenyClass = "cgnat"
	DenyLinkLocal     DenyClass = "link-local"
	DenyULA           DenyClass = "ula"
	DenyMulticast     DenyClass = "multicast"
	DenyReserved      DenyClass = "reserved"
	DenyDocumentation DenyClass = "documentation"
	DenyAgentHost     DenyClass = "agent-host" // the agent host's own addresses and on-link prefixes
	DenyExtra         DenyClass = "extra"      // Egress.Deny
)

The deny classes.

func DenyClasses

func DenyClasses() []DenyClass

DenyClasses returns every deny class.

func (DenyClass) Valid

func (c DenyClass) Valid() bool

Valid reports whether c is one of the DenyClasses.

type DenyRange

type DenyRange struct {
	Prefix netip.Prefix
	Class  DenyClass
}

DenyRange is one row of the default deny table.

func DefaultDeny

func DefaultDeny() []DenyRange

DefaultDeny returns the default deny table. An address takes the class of the most specific range that contains it (::1 is loopback, not reserved).

type Egress

type Egress struct {
	// Mode is ModeDefault, ModeDenyByDefault, or "" for ModeDefault. Any other value fails
	// closed: the host check then allows only AllowHosts.
	Mode string
	// AllowHosts are #100's environment.egress.allow entries, which v1alpha1.ValidateHost
	// accepts: a name or *.domain, either with :port.
	AllowHosts []string
	// Deny are prefixes denied on top of the default deny table and the agent host's own
	// prefixes (class extra).
	Deny []netip.Prefix
	// OpenAddrs are exact exceptions to every deny rule except a zone.
	OpenAddrs []netip.AddrPort
}

Egress is a task's egress policy: the host check's mode and allow list, and the address check's extra denied prefixes and exact exceptions. The zero Egress is ModeDefault with only the default deny table.

func (Egress) AllowsHost

func (e Egress) AllowsHost(t Target) bool

AllowsHost is the host check for an ordinary host. ModeDefault allows every target. Otherwise the target must match an AllowHosts entry: an exact entry matches that name only, *.example.com any name under example.com at any depth but not example.com itself, an entry with a port only that port and one without every port. An IP literal never matches.

func (Egress) CheckAddr

func (e Egress) CheckAddr(ap netip.AddrPort, hostPrefixes []netip.Prefix) DenyClass

CheckAddr is the address check for one destination: "" when it may be dialled, else the class that denies it. hostPrefixes are the agent host's own addresses and on-link prefixes, which the caller reads (class agent-host).

In order: an invalid address is unspecified; an address with a zone is always denied (its table class, else link-local); an IPv4-mapped address is unmapped; an exact OpenAddrs match is allowed; then the default table's most specific range, a NAT64 (64:ff9b::/96) or 6to4 (2002::/16) address whose embedded IPv4 address is denied (that address's class), hostPrefixes (agent-host) and Egress.Deny (extra).

func (Egress) CheckResolved

func (e Egress) CheckResolved(addrs []netip.Addr, port uint16, hostPrefixes []netip.Prefix) (Code, DenyClass)

CheckResolved is the address check for every address a destination resolved to, on one port: CodeResolve when there is none, CodeEgressDenied with the first denied address's class when any is denied (a name with mixed public and private answers is refused, not filtered), else "" and "".

func (Egress) Validate

func (e Egress) Validate() error

Validate checks the mode, each AllowHosts entry (v1alpha1.ValidateHost), each Deny prefix and each OpenAddrs entry (a valid address with a non-zero port), returning an *EgressError.

type EgressError

type EgressError struct {
	Field string // Mode, AllowHosts[i], Deny[i] or OpenAddrs[i]
	// Err is a v1alpha1.ErrHost* sentinel for an AllowHosts entry, else nil.
	Err error
}

EgressError is a field of an Egress that Validate refuses. It never carries the value.

func (*EgressError) Error

func (e *EgressError) Error() string

func (*EgressError) Is

func (e *EgressError) Is(target error) bool

Is matches ErrEgress.

func (*EgressError) Unwrap

func (e *EgressError) Unwrap() error

type GitHubDecision

type GitHubDecision struct {
	GitHubRequest
	// Access is the repo's, from the access function; AccessUnknown for a path without a repo.
	Access Access
	// Refusal is set when the request is refused; "" to forward it.
	Refusal Code
}

GitHubDecision is the github.com rule's answer for one request inside the tunnel.

func DecideGitHub

func DecideGitHub(method string, u *url.URL, access func(repo string) Access) GitHubDecision

DecideGitHub applies gateway.md's github.com table to a request inside the tunnel: bad-path for a path that isn't canonical; a web request forwarded on GET and HEAD, else web-write; a git request for an rw repo forwarded whatever it is, and for a read or unknown repo only the two exact fetch forms (GET info/refs with the raw query service=git-upload-pack, and POST git-upload-pack without a query), else push-refused. access gives a repo's access; it is called only for a git request that names a repo.

func (GitHubDecision) Credentialed

func (d GitHubDecision) Credentialed() bool

Credentialed reports whether the repo's token goes with the request: a git request that is forwarded, for a repo that is rw or read. Web requests and unknown repos go anonymously.

type GitHubRequest

type GitHubRequest struct {
	// Repo is the path's owner/repo, lower-cased without .git; "" when the path names none.
	Repo string
	// Git is whether it is a git request: the repo segment ends in .git (any case), or the rest
	// of the path, lower-cased, is info/refs, git-upload-pack or git-receive-pack. Every other
	// request is a web request.
	Git bool
	// contains filtered or unexported fields
}

GitHubRequest is a github.com request's repo and kind.

func ParseGitHubPath

func ParseGitHubPath(p string) GitHubRequest

ParseGitHubPath splits a canonical github.com path, /<owner>/<repo>[.git]/<rest>.

type Response

type Response struct {
	Status int
	Header http.Header // Content-Type and RefusalHeader
	Body   string      // BodyPrefix, the code's text and a newline
}

Response is an answer the gateway makes itself. Nothing in it is chosen by the VM: the body never names a credential, an address or a host.

type Target

type Target struct {
	// Host is the name, lower-cased without a trailing dot, or the IP literal's canonical form
	// (netip.Addr.String, without brackets).
	Host string
	// Addr is the IP literal; the zero Addr for a name.
	Addr netip.Addr
	Port uint16
}

Target is a destination the VM named: a normalised host name, or an IP literal, and a port.

func ParseConnectTarget

func ParseConnectTarget(s string) (Target, bool)

ParseConnectTarget parses a CONNECT's target, host:port with the port required.

func ParseHostPort

func ParseHostPort(s string, defaultPort uint16) (Target, bool)

ParseHostPort parses an absolute-form URL's host, [host]:port or host, with defaultPort when it has none.

func (Target) IsIP

func (t Target) IsIP() bool

IsIP reports whether the target is an IP literal.

func (Target) String

func (t Target) String() string

String is the target as host:port, an IPv6 literal in brackets.

Jump to

Keyboard shortcuts

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