// Package webread is Research's fetch phase (spec §3): no model, only the // step's approved sources and their deterministic expansion, fetched one // at a time under fixed bounds, into a bundle of extracted text and // re-encoded images. It runs as its own process (Main, Launch); the // runner reads what it wrote with ReadBundle. package webread import ( "encoding/json" "errors" "fmt" "io" "net/netip" "regexp" "strings" "time" "amadan.net/oficina/equipo/internal/websource" ) // Bounds (spec §3.4). const ( MaxRequests = 30 MaxBytes = 20 << 20 ConnectTimeout = 5 * time.Second FirstByteTimeout = 10 * time.Second RequestTimeout = 15 * time.Second OverallTimeout = 3 * time.Minute MaxHeaderBytes = 32 << 10 MaxTextBytes = 2 << 20 MaxImageBytes = 8 << 20 MaxRedirects = 5 MaxLinks = 500 MaxPageText = 100 << 10 MaxTotalText = 300 << 10 MaxPixels = 16_000_000 MaxEdge = 2048 // MaxImageFile bounds one re-encoded image, MaxImageTotal all of them. MaxImageFile = 8 << 20 MaxImageTotal = 40 << 20 // MaxSources bounds a plan's approved sources, MaxInventory its prefixes. MaxSources = MaxRequests MaxInventory = 256 // MaxPlanBytes bounds the plan the fetcher reads on stdin. MaxPlanBytes = 1 << 20 // MaxLogEntries and MaxManifestBytes bound the manifest. MaxLogEntries = 1024 MaxManifestBytes = 4 << 20 ) // The fixed request headers. const ( UserAgent = "Equipo-Research/1" accept = "text/html,text/plain,text/css,text/markdown,application/json,image/svg+xml,image/png,image/jpeg,image/gif;q=0.9,*/*;q=0.1" ) // Origins. const ( OriginPaul = "paul" OriginProposed = "proposed" OriginExpanded = "expanded" ) // Reason codes in the log, stable on the wire. websource's refusals // (ip_literal, host_refused, port_refused, ...) appear as they are. const ( ReasonNotPublic = "not_public" ReasonInventory = "inventory" ReasonHostRefused = "host_refused" ReasonDowngrade = "downgrade" ReasonTooLarge = "too_large" ReasonPixels = "too_many_pixels" ReasonType = "type_refused" ReasonEncoding = "encoding_refused" ReasonBudget = "budget" ReasonTextBudget = "text_budget" ReasonTimeout = "timeout" ReasonRedirects = "too_many_redirects" ReasonBadRedirect = "bad_redirect" ReasonStatus = "http_status" ReasonLookup = "lookup_failed" ReasonConnect = "connect_failed" ReasonRequest = "request_failed" ReasonImageInvalid = "image_invalid" ) // ReasonFamilyUnknown: the address's family (IPv4 or IPv6) has no public // prefix in the confirmed inventory, so this site's egress in that family // is unknown and a hairpin back into it cannot be ruled out. Fail closed. const ReasonFamilyUnknown = "family_unknown" // Source is one approved URL. type Source struct { ID string `json:"id"` URL websource.URL `json:"url"` Origin string `json:"origin"` } // Plan is everything the fetch phase acts on. Instance and Forge are // hosts never requested: the instance's origin and the forge. type Plan struct { Sources []Source `json:"sources"` Inventory []netip.Prefix `json:"inventory"` Instance string `json:"instance,omitempty"` Forge string `json:"forge,omitempty"` // Spent is what earlier passes of the same step used: the runner's // retries share one budget and one phase deadline (nil: a first pass). Spent *Spent `json:"spent,omitempty"` } // Spent is a step's fetch phase so far: requests reserved, bytes read and // time taken, over every pass. type Spent struct { Requests int `json:"requests"` Bytes int64 `json:"bytes"` Millis int64 `json:"millis"` } // ErrPlan refuses a plan the fetch phase will not act on. var ErrPlan = errors.New("webread: plan refused") var sourceID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,32}$`) // Validate checks a plan as the fetcher receives it: every source a // canonical URL under the contract (and a proposal under the proposal // rules), ids unique, origins known, the inventory well formed. func (p Plan) Validate() error { if len(p.Sources) == 0 || len(p.Sources) > MaxSources || len(p.Inventory) > MaxInventory { return fmt.Errorf("%w: %d sources, %d prefixes", ErrPlan, len(p.Sources), len(p.Inventory)) } ids := map[string]bool{} for _, s := range p.Sources { if !sourceID.MatchString(s.ID) || ids[s.ID] { return fmt.Errorf("%w: source id %q", ErrPlan, s.ID) } ids[s.ID] = true check := websource.Parse switch s.Origin { case OriginPaul: case OriginProposed: check = websource.Proposal default: return fmt.Errorf("%w: origin %q", ErrPlan, s.Origin) } if u, err := check(s.URL.String()); err != nil || u != s.URL { return fmt.Errorf("%w: source %s: %s", ErrPlan, s.ID, websource.Reason(err)) } } if s := p.Spent; s != nil && (s.Requests < 0 || s.Requests > MaxRequests || s.Bytes < 0 || s.Bytes > MaxBytes || s.Millis < 0 || s.Millis > OverallTimeout.Milliseconds()) { return fmt.Errorf("%w: spent %+v", ErrPlan, *s) } for _, pr := range p.Inventory { if !pr.IsValid() || pr != pr.Masked() || pr.Addr().Zone() != "" { return fmt.Errorf("%w: inventory prefix", ErrPlan) } } for _, h := range []string{p.Instance, p.Forge} { if h != strings.ToLower(h) || strings.ContainsAny(h, "/:@ ") || strings.HasSuffix(h, ".") { return fmt.Errorf("%w: refused host %q", ErrPlan, h) } } return nil } // DecodePlan reads one plan, at most MaxPlanBytes, with no unknown fields. func DecodePlan(r io.Reader) (Plan, error) { b, err := io.ReadAll(io.LimitReader(r, MaxPlanBytes+1)) if err != nil { return Plan{}, err } if len(b) > MaxPlanBytes { return Plan{}, fmt.Errorf("%w: too large", ErrPlan) } d := json.NewDecoder(strings.NewReader(string(b))) d.DisallowUnknownFields() var p Plan if err = d.Decode(&p); err != nil { return Plan{}, fmt.Errorf("%w: %v", ErrPlan, err) } if d.More() { return Plan{}, fmt.Errorf("%w: trailing data", ErrPlan) } return p, p.Validate() } // Hop is one request: the URL, the address connected and the status. // A redirect target refused before any request is a hop with no address. type Hop struct { URL string `json:"url"` Address string `json:"address,omitempty"` Status int `json:"status,omitempty"` } // Entry is the log's record of one source: fetched, failed or refused. type Entry struct { Source string `json:"source"` Origin string `json:"origin"` Parent string `json:"parent,omitempty"` URL string `json:"url"` Hops []Hop `json:"hops,omitempty"` Address string `json:"address,omitempty"` Status int `json:"status,omitempty"` Type string `json:"type,omitempty"` Bytes int64 `json:"bytes"` SHA256 string `json:"sha256,omitempty"` Millis int64 `json:"ms"` Reason string `json:"reason,omitempty"` File string `json:"file,omitempty"` } // File kinds. const ( KindText = "text" KindImage = "image" ) // File is one bundle file as the manifest lists it. type File struct { Name string `json:"name"` Source string `json:"source"` Kind string `json:"kind"` Type string `json:"type"` Size int64 `json:"size"` SHA256 string `json:"sha256"` Width int `json:"width,omitempty"` Height int `json:"height,omitempty"` } // Manifest is manifest.json: the files and the log. type Manifest struct { Version int `json:"version"` Files []File `json:"files"` Log []Entry `json:"log"` // Used is what the step has spent, this pass and the ones before. Used Spent `json:"used"` } // ManifestName is the manifest's file name in the bundle directory. const ManifestName = "manifest.json" var fileName = regexp.MustCompile(`^s[0-9]{3}\.(txt|png)$`)