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
- Variables
- func AnthropicHosts() []string
- func Canonical(u *url.URL) bool
- func CarrierHeaders() []string
- func CheckGraphQLDocument(doc string) error
- func CheckGraphQLRequest(body []byte) error
- func FilterCookies(values []string) []string
- func InfraCookies() []string
- func InterceptedHosts() []string
- func IsInfraCookie(name string) bool
- func NormalizeHost(h string) string
- type Access
- type Action
- type Class
- type Code
- type CookieRule
- type Decision
- type DenyClass
- type DenyRange
- type Egress
- type EgressError
- type GitHubDecision
- type GitHubRequest
- type Response
- type Target
Constants ¶
const ( ModeDefault = "default" // every host passes the host check ModeDenyByDefault = "deny-by-default" // only AllowHosts pass )
The egress modes (#100's environment.egress.mode).
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.
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.
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: " )
const GraphQLPath = "/graphql"
GraphQLPath is api.github.com's GraphQL endpoint.
const InfraCookiePrefix = "cf_chl_"
InfraCookiePrefix starts the names of Cloudflare's challenge cookies, which pass too.
const MaxGraphQLBody = 1 << 20
MaxGraphQLBody bounds a POST /graphql body the gateway reads to check it.
Variables ¶
var ErrEgress = errors.New("invalid egress policy")
ErrEgress is wrapped by every *EgressError.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
IsInfraCookie reports whether name, compared exactly (cookie names are case-sensitive), is an infrastructure cookie.
func NormalizeHost ¶
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.
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.
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 ¶
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 ¶
Intercepted reports whether a CONNECT to the class is TLS-intercepted (on InterceptPort).
func (Class) StripsCarriers ¶
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 ¶
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 DecideDispatcher ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
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.
type DenyRange ¶
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 ¶
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 ¶
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 "".
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) 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 ¶
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 ¶
ParseConnectTarget parses a CONNECT's target, host:port with the port required.
func ParseHostPort ¶
ParseHostPort parses an absolute-form URL's host, [host]:port or host, with defaultPort when it has none.