| 1 | // Package webread is Research's fetch phase (spec §3): no model, only the |
| 2 | // step's approved sources and their deterministic expansion, fetched one |
| 3 | // at a time under fixed bounds, into a bundle of extracted text and |
| 4 | // re-encoded images. It runs as its own process (Main, Launch); the |
| 5 | // runner reads what it wrote with ReadBundle. |
| 6 | package webread |
| 7 | |
| 8 | import ( |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net/netip" |
| 14 | "regexp" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/websource" |
| 19 | ) |
| 20 | |
| 21 | // Bounds (spec §3.4). |
| 22 | const ( |
| 23 | MaxRequests = 30 |
| 24 | MaxBytes = 20 << 20 |
| 25 | ConnectTimeout = 5 * time.Second |
| 26 | FirstByteTimeout = 10 * time.Second |
| 27 | RequestTimeout = 15 * time.Second |
| 28 | OverallTimeout = 3 * time.Minute |
| 29 | MaxHeaderBytes = 32 << 10 |
| 30 | MaxTextBytes = 2 << 20 |
| 31 | MaxImageBytes = 8 << 20 |
| 32 | MaxRedirects = 5 |
| 33 | MaxLinks = 500 |
| 34 | MaxPageText = 100 << 10 |
| 35 | MaxTotalText = 300 << 10 |
| 36 | MaxPixels = 16_000_000 |
| 37 | MaxEdge = 2048 |
| 38 | // MaxImageFile bounds one re-encoded image, MaxImageTotal all of them. |
| 39 | MaxImageFile = 8 << 20 |
| 40 | MaxImageTotal = 40 << 20 |
| 41 | // MaxSources bounds a plan's approved sources, MaxInventory its prefixes. |
| 42 | MaxSources = MaxRequests |
| 43 | MaxInventory = 256 |
| 44 | // MaxPlanBytes bounds the plan the fetcher reads on stdin. |
| 45 | MaxPlanBytes = 1 << 20 |
| 46 | // MaxLogEntries and MaxManifestBytes bound the manifest. |
| 47 | MaxLogEntries = 1024 |
| 48 | MaxManifestBytes = 4 << 20 |
| 49 | ) |
| 50 | |
| 51 | // The fixed request headers. |
| 52 | const ( |
| 53 | UserAgent = "Equipo-Research/1" |
| 54 | 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" |
| 55 | ) |
| 56 | |
| 57 | // Origins. |
| 58 | const ( |
| 59 | OriginPaul = "paul" |
| 60 | OriginProposed = "proposed" |
| 61 | OriginExpanded = "expanded" |
| 62 | ) |
| 63 | |
| 64 | // Reason codes in the log, stable on the wire. websource's refusals |
| 65 | // (ip_literal, host_refused, port_refused, ...) appear as they are. |
| 66 | const ( |
| 67 | ReasonNotPublic = "not_public" |
| 68 | ReasonInventory = "inventory" |
| 69 | ReasonHostRefused = "host_refused" |
| 70 | ReasonDowngrade = "downgrade" |
| 71 | ReasonTooLarge = "too_large" |
| 72 | ReasonPixels = "too_many_pixels" |
| 73 | ReasonType = "type_refused" |
| 74 | ReasonEncoding = "encoding_refused" |
| 75 | ReasonBudget = "budget" |
| 76 | ReasonTextBudget = "text_budget" |
| 77 | ReasonTimeout = "timeout" |
| 78 | ReasonRedirects = "too_many_redirects" |
| 79 | ReasonBadRedirect = "bad_redirect" |
| 80 | ReasonStatus = "http_status" |
| 81 | ReasonLookup = "lookup_failed" |
| 82 | ReasonConnect = "connect_failed" |
| 83 | ReasonRequest = "request_failed" |
| 84 | ReasonImageInvalid = "image_invalid" |
| 85 | ) |
| 86 | |
| 87 | // ReasonFamilyUnknown: the address's family (IPv4 or IPv6) has no public |
| 88 | // prefix in the confirmed inventory, so this site's egress in that family |
| 89 | // is unknown and a hairpin back into it cannot be ruled out. Fail closed. |
| 90 | const ReasonFamilyUnknown = "family_unknown" |
| 91 | |
| 92 | // Source is one approved URL. |
| 93 | type Source struct { |
| 94 | ID string `json:"id"` |
| 95 | URL websource.URL `json:"url"` |
| 96 | Origin string `json:"origin"` |
| 97 | } |
| 98 | |
| 99 | // Plan is everything the fetch phase acts on. Instance and Forge are |
| 100 | // hosts never requested: the instance's origin and the forge. |
| 101 | type Plan struct { |
| 102 | Sources []Source `json:"sources"` |
| 103 | Inventory []netip.Prefix `json:"inventory"` |
| 104 | Instance string `json:"instance,omitempty"` |
| 105 | Forge string `json:"forge,omitempty"` |
| 106 | // Spent is what earlier passes of the same step used: the runner's |
| 107 | // retries share one budget and one phase deadline (nil: a first pass). |
| 108 | Spent *Spent `json:"spent,omitempty"` |
| 109 | } |
| 110 | |
| 111 | // Spent is a step's fetch phase so far: requests reserved, bytes read and |
| 112 | // time taken, over every pass. |
| 113 | type Spent struct { |
| 114 | Requests int `json:"requests"` |
| 115 | Bytes int64 `json:"bytes"` |
| 116 | Millis int64 `json:"millis"` |
| 117 | } |
| 118 | |
| 119 | // ErrPlan refuses a plan the fetch phase will not act on. |
| 120 | var ErrPlan = errors.New("webread: plan refused") |
| 121 | |
| 122 | var sourceID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,32}$`) |
| 123 | |
| 124 | // Validate checks a plan as the fetcher receives it: every source a |
| 125 | // canonical URL under the contract (and a proposal under the proposal |
| 126 | // rules), ids unique, origins known, the inventory well formed. |
| 127 | func (p Plan) Validate() error { |
| 128 | if len(p.Sources) == 0 || len(p.Sources) > MaxSources || len(p.Inventory) > MaxInventory { |
| 129 | return fmt.Errorf("%w: %d sources, %d prefixes", ErrPlan, len(p.Sources), len(p.Inventory)) |
| 130 | } |
| 131 | ids := map[string]bool{} |
| 132 | for _, s := range p.Sources { |
| 133 | if !sourceID.MatchString(s.ID) || ids[s.ID] { |
| 134 | return fmt.Errorf("%w: source id %q", ErrPlan, s.ID) |
| 135 | } |
| 136 | ids[s.ID] = true |
| 137 | check := websource.Parse |
| 138 | switch s.Origin { |
| 139 | case OriginPaul: |
| 140 | case OriginProposed: |
| 141 | check = websource.Proposal |
| 142 | default: |
| 143 | return fmt.Errorf("%w: origin %q", ErrPlan, s.Origin) |
| 144 | } |
| 145 | if u, err := check(s.URL.String()); err != nil || u != s.URL { |
| 146 | return fmt.Errorf("%w: source %s: %s", ErrPlan, s.ID, websource.Reason(err)) |
| 147 | } |
| 148 | } |
| 149 | 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()) { |
| 150 | return fmt.Errorf("%w: spent %+v", ErrPlan, *s) |
| 151 | } |
| 152 | for _, pr := range p.Inventory { |
| 153 | if !pr.IsValid() || pr != pr.Masked() || pr.Addr().Zone() != "" { |
| 154 | return fmt.Errorf("%w: inventory prefix", ErrPlan) |
| 155 | } |
| 156 | } |
| 157 | for _, h := range []string{p.Instance, p.Forge} { |
| 158 | if h != strings.ToLower(h) || strings.ContainsAny(h, "/:@ ") || strings.HasSuffix(h, ".") { |
| 159 | return fmt.Errorf("%w: refused host %q", ErrPlan, h) |
| 160 | } |
| 161 | } |
| 162 | return nil |
| 163 | } |
| 164 | |
| 165 | // DecodePlan reads one plan, at most MaxPlanBytes, with no unknown fields. |
| 166 | func DecodePlan(r io.Reader) (Plan, error) { |
| 167 | b, err := io.ReadAll(io.LimitReader(r, MaxPlanBytes+1)) |
| 168 | if err != nil { |
| 169 | return Plan{}, err |
| 170 | } |
| 171 | if len(b) > MaxPlanBytes { |
| 172 | return Plan{}, fmt.Errorf("%w: too large", ErrPlan) |
| 173 | } |
| 174 | d := json.NewDecoder(strings.NewReader(string(b))) |
| 175 | d.DisallowUnknownFields() |
| 176 | var p Plan |
| 177 | if err = d.Decode(&p); err != nil { |
| 178 | return Plan{}, fmt.Errorf("%w: %v", ErrPlan, err) |
| 179 | } |
| 180 | if d.More() { |
| 181 | return Plan{}, fmt.Errorf("%w: trailing data", ErrPlan) |
| 182 | } |
| 183 | return p, p.Validate() |
| 184 | } |
| 185 | |
| 186 | // Hop is one request: the URL, the address connected and the status. |
| 187 | // A redirect target refused before any request is a hop with no address. |
| 188 | type Hop struct { |
| 189 | URL string `json:"url"` |
| 190 | Address string `json:"address,omitempty"` |
| 191 | Status int `json:"status,omitempty"` |
| 192 | } |
| 193 | |
| 194 | // Entry is the log's record of one source: fetched, failed or refused. |
| 195 | type Entry struct { |
| 196 | Source string `json:"source"` |
| 197 | Origin string `json:"origin"` |
| 198 | Parent string `json:"parent,omitempty"` |
| 199 | URL string `json:"url"` |
| 200 | Hops []Hop `json:"hops,omitempty"` |
| 201 | Address string `json:"address,omitempty"` |
| 202 | Status int `json:"status,omitempty"` |
| 203 | Type string `json:"type,omitempty"` |
| 204 | Bytes int64 `json:"bytes"` |
| 205 | SHA256 string `json:"sha256,omitempty"` |
| 206 | Millis int64 `json:"ms"` |
| 207 | Reason string `json:"reason,omitempty"` |
| 208 | File string `json:"file,omitempty"` |
| 209 | } |
| 210 | |
| 211 | // File kinds. |
| 212 | const ( |
| 213 | KindText = "text" |
| 214 | KindImage = "image" |
| 215 | ) |
| 216 | |
| 217 | // File is one bundle file as the manifest lists it. |
| 218 | type File struct { |
| 219 | Name string `json:"name"` |
| 220 | Source string `json:"source"` |
| 221 | Kind string `json:"kind"` |
| 222 | Type string `json:"type"` |
| 223 | Size int64 `json:"size"` |
| 224 | SHA256 string `json:"sha256"` |
| 225 | Width int `json:"width,omitempty"` |
| 226 | Height int `json:"height,omitempty"` |
| 227 | } |
| 228 | |
| 229 | // Manifest is manifest.json: the files and the log. |
| 230 | type Manifest struct { |
| 231 | Version int `json:"version"` |
| 232 | Files []File `json:"files"` |
| 233 | Log []Entry `json:"log"` |
| 234 | // Used is what the step has spent, this pass and the ones before. |
| 235 | Used Spent `json:"used"` |
| 236 | } |
| 237 | |
| 238 | // ManifestName is the manifest's file name in the bundle directory. |
| 239 | const ManifestName = "manifest.json" |
| 240 | |
| 241 | var fileName = regexp.MustCompile(`^s[0-9]{3}\.(txt|png)$`) |
| 242 | |