// Package policy validates navigation destinations. It is not an egress firewall. package policy import ( "context" "net" "net/url" "strings" "clusterflow.dev/cfbrowser/api" ) type Resolver interface { LookupIPAddr(context.Context, string) ([]net.IPAddr, error) } type URLPolicy struct { // AllowOrigins authorizes exact normalized origins, including private hosts. AllowOrigins []string Resolver Resolver } func origin(u *url.URL) string { port := u.Port() if port == "" { if u.Scheme == "https" { port = "443" } else { port = "80" } } return strings.ToLower(u.Scheme) + "://" + net.JoinHostPort(strings.ToLower(u.Hostname()), port) } func public(ip net.IP) bool { if ip == nil || !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() { return false } for _, cidr := range []string{"100.64.0.0/10", "198.18.0.0/15", "192.0.0.0/24", "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "2001:db8::/32"} { _, n, _ := net.ParseCIDR(cidr) if n.Contains(ip) { return false } } return true } func (p URLPolicy) Validate(ctx context.Context, raw string) (string, error) { u, err := url.Parse(strings.TrimSpace(raw)) if err != nil || u == nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.Opaque != "" { return "", api.Err("BROWSER_INVALID_URL", "an HTTP(S) URL without credentials is required") } if len(raw) > 8192 { return "", api.Err("BROWSER_INVALID_URL", "URL exceeds 8 KiB") } for _, a := range p.AllowOrigins { v, e := url.Parse(a) if e == nil && v.Host != "" && v.User == nil && origin(v) == origin(u) { return u.String(), nil } } if ip := net.ParseIP(u.Hostname()); ip != nil { if public(ip) { return u.String(), nil } return "", api.Err("BROWSER_NETWORK_BLOCKED", "destination is not public or explicitly allowed") } host := strings.ToLower(u.Hostname()) if host == "localhost" || strings.HasSuffix(host, ".localhost") { return "", api.Err("BROWSER_NETWORK_BLOCKED", "localhost requires an exact allowed origin") } resolver := p.Resolver if resolver == nil { resolver = net.DefaultResolver } ips, err := resolver.LookupIPAddr(ctx, host) if err != nil || len(ips) == 0 { return "", api.Err("BROWSER_DNS_FAILED", "destination did not resolve") } for _, ip := range ips { if !public(ip.IP) { return "", api.Err("BROWSER_NETWORK_BLOCKED", "destination resolves to a non-public address") } } return u.String(), nil }