// Package websource is the one URL contract for Research's web sources // (spec §3.1). A URL is parsed and made canonical once, and that form is // what a card shows, what the runner requests and what the logs record. // The instance and the runner share it. Pure and stdlib only: no lookup, // no network. package websource import ( "errors" "net/netip" "net/url" "strings" ) // Bounds. const ( // MaxURL bounds a URL, raw or canonical, in bytes. MaxURL = 2048 // MaxProposalPath bounds a coordinator proposal's escaped path. MaxProposalPath = 100 ) // Refusal is a stable reason code. It is the error's whole text, so it is // safe to log and to send on the wire. type Refusal string func (r Refusal) Error() string { return string(r) } // Refusals. const ( ErrBadURL Refusal = "bad_url" ErrTooLong Refusal = "url_too_long" ErrScheme Refusal = "scheme_refused" ErrUserinfo Refusal = "userinfo_refused" ErrPort Refusal = "port_refused" ErrHost Refusal = "host_refused" ErrIPLiteral Refusal = "ip_literal" ErrNonASCII Refusal = "non_ascii_host" ErrQuery Refusal = "query_refused" ErrPathTooLong Refusal = "path_too_long" ErrSecret Refusal = "secret_refused" ) // Reason is err's reason code: "" for nil, bad_url for an error that is // not a Refusal. func Reason(err error) string { if err == nil { return "" } var r Refusal if errors.As(err, &r) { return string(r) } return string(ErrBadURL) } // URL is a canonical web address: scheme https or http, a lower-case ASCII // host with no trailing dot, the scheme's own port (443 or 80, nothing // else), the escaped path ("/" when empty) and the raw query, kept as // they arrived. No userinfo, no fragment. type URL struct { Scheme string `json:"scheme"` Host string `json:"host"` Port int `json:"port"` EscapedPath string `json:"path"` RawQuery string `json:"query,omitempty"` } // String is the canonical form. Parse(u.String()) == u for every URL // Parse returned. func (u URL) String() string { s := u.Scheme + "://" + u.Host + u.EscapedPath if u.RawQuery != "" { s += "?" + u.RawQuery } return s } // IsZero reports the zero URL. func (u URL) IsZero() bool { return u == URL{} } // Parse makes raw canonical, or refuses it with a Refusal. func Parse(raw string) (URL, error) { if raw == "" { return URL{}, ErrBadURL } if len(raw) > MaxURL { return URL{}, ErrTooLong } p, err := url.Parse(raw) if err != nil { return URL{}, ErrBadURL } return fromParsed(raw, p) } func fromParsed(raw string, p *url.URL) (URL, error) { if p.Scheme != "https" && p.Scheme != "http" { return URL{}, ErrScheme } if p.Opaque != "" || p.Host == "" { return URL{}, ErrBadURL } if p.User != nil { return URL{}, ErrUserinfo } if strings.HasPrefix(p.Host, "[") { return URL{}, ErrIPLiteral } host := p.Hostname() for i := 0; i < len(host); i++ { if host[i] >= 0x80 { return URL{}, ErrNonASCII } } // Spaces, control bytes, non-ASCII and backslashes are refused // anywhere: a browser and Go read them differently. for i := 0; i < len(raw); i++ { if c := raw[i]; c <= 0x20 || c >= 0x7f || c == '\\' { return URL{}, ErrBadURL } } host = strings.ToLower(host) host = strings.TrimSuffix(host, ".") if err := checkHost(host); err != nil { return URL{}, err } u := URL{Scheme: p.Scheme, Host: host, Port: 443} if p.Scheme == "http" { u.Port = 80 } if port := p.Port(); port != "" && port != map[string]string{"https": "443", "http": "80"}[p.Scheme] { return URL{}, ErrPort } u.EscapedPath = p.EscapedPath() if u.EscapedPath == "" { u.EscapedPath = "/" } if !strings.HasPrefix(u.EscapedPath, "/") { return URL{}, ErrBadURL } u.RawQuery = p.RawQuery if len(u.String()) > MaxURL { return URL{}, ErrTooLong } return u, nil } // refusedSuffixes are names that never leave the machine or the site. var refusedSuffixes = []string{".localhost", ".local", ".internal", ".lan", ".home.arpa", ".arpa", ".ts.net", ".onion", ".test", ".invalid", ".example"} // CheckHost applies §3.1's host rules to a lower-case host with its // trailing dot gone: a registered name whose last label has a letter, no // IP literal in any form, and none of the names that never leave the // machine or the site. The guarded client applies it to every hop. func CheckHost(host string) error { return checkHost(host) } // checkHost is CheckHost. func checkHost(host string) error { labels := strings.Split(host, ".") numeric := true for _, l := range labels { if !numericLabel(l) { numeric = false break } } // 127.1, 2130706433, 0177.0.0.1, 0x7f.0.0.1, 1.0x7f: inet_aton reads // every one as an address. if numeric { return ErrIPLiteral } if host == "localhost" { return ErrHost } for _, s := range refusedSuffixes { if strings.HasSuffix(host, s) || host == s[1:] { return ErrHost } } last := labels[len(labels)-1] if !Hostname(host) || numericLabel(last) || !strings.ContainsAny(last, "abcdefghijklmnopqrstuvwxyz") { return ErrHost } return nil } // numericLabel is a label inet_aton could read as a number: decimal, // octal or 0x hex. func numericLabel(l string) bool { if l == "" { return false } if strings.HasPrefix(l, "0x") { for _, c := range l[2:] { if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { return false } } return true } for _, c := range l { if c < '0' || c > '9' { return false } } return true } // Hostname is the egress relay's host rule: a lower-case DNS name of at // least two labels, each 1 to 63 of a-z, 0-9 and an inner hyphen, at most // 253 bytes, and not an IP address. func Hostname(s string) bool { if len(s) > 253 || !strings.Contains(s, ".") || s != strings.ToLower(s) { return false } for _, label := range strings.Split(s, ".") { if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' { return false } for _, c := range label { if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { return false } } } _, err := netip.ParseAddr(s) return err != nil } // Resolve is ref, a link on the page at base, as a canonical URL. func Resolve(base URL, ref string) (URL, error) { if len(ref) > MaxURL { return URL{}, ErrTooLong } r, err := url.Parse(ref) if err != nil { return URL{}, ErrBadURL } if r.Scheme != "" && r.Scheme != "https" && r.Scheme != "http" { return URL{}, ErrScheme } b, err := url.Parse(base.String()) if err != nil { return URL{}, ErrBadURL } abs := b.ResolveReference(r) abs.Fragment, abs.RawFragment = "", "" return Parse(abs.String()) } // Proposal is Parse plus the rules for a URL the coordinator proposes: // no query, an escaped path of at most MaxProposalPath bytes, and nothing // that looks like a secret. func Proposal(raw string) (URL, error) { u, err := Parse(raw) if err != nil { return URL{}, err } if u.RawQuery != "" || strings.Contains(raw, "?") { return URL{}, ErrQuery } if len(u.EscapedPath) > MaxProposalPath { return URL{}, ErrPathTooLong } if LooksSecret(u.String()) { return URL{}, ErrSecret } return u, nil }