package wire import ( "encoding/json" "fmt" "net/netip" "regexp" "unicode/utf8" "amadan.net/oficina/equipo/internal/websource" ) // What a Research step returns (Research spec §4 and §5, slice R3), the // site inventory it needs (R4 decision), and what Engineering and Review // are handed (slice R4). Both ends validate with the same functions. // CardResearchInventory asks an owner to confirm the addresses the // primary fetches from ("Research fetches from these addresses"); only // ChoiceConfirm (api.go) is offered. A Research step waits until every // address currently detected is inside a confirmed set. const CardResearchInventory = "research_inventory" // CardInstanceInventory asks an owner to confirm the network the instance // itself is on (its prefixes and the addresses it saw), before anything // reaches the public web from it. Its view is Inventory, prefixes first. const CardInstanceInventory = "instance_inventory" // Bounds of a Research result. const ( MaxFindingsBytes = 8 << 10 MaxFindingsSummary = 1000 MaxFactLabel = 100 MaxFactValue = 300 MaxFactSources = 10 MaxFindingsFacts = 60 MaxFindingsGaps = 20 MaxFindingsGap = 200 MaxKeptImages = 8 MaxKeptDescription = 200 MaxKeptImageBytes = 8 << 20 MaxResearchFetches = 64 MaxResearchHops = 5 MaxResearchAddresses = 32 MaxResearchFileChunks = MaxKeptImageBytes/ResearchFileChunk + 1 // ResearchFileChunk is one research_file frame's share of an image; // base64 in JSON stays well under MaxFrameBytes. ResearchFileChunk = 128 << 10 ) // Kept image roles. const ( ImageRoleLogo = "logo" ImageRolePhoto = "photo" ImageRoleIcon = "icon" ImageRoleOther = "other" ) // ResearchCapability is the primary's detected addresses (canonical // netip strings, global unicast only). type ResearchCapability struct { Addresses []string `json:"addresses"` } // ResearchFindings is submit_findings' argument and the stored findings. type ResearchFindings struct { Summary string `json:"summary"` Facts []ResearchFact `json:"facts"` Images []string `json:"images"` Gaps []string `json:"gaps"` } // ResearchFact is one extracted fact and the source ids it came from. type ResearchFact struct { Label string `json:"label"` Value string `json:"value"` Sources []string `json:"sources"` } // ResearchFetch is one line of a Research step's fetch log: a request or // a refusal. SourceID is the bundle's id (approved sources keep the // dispatch's id; expanded ones get new ids with Parent set). URL is the // source's canonical URL, or, for a refused target that fails the URL // contract (an IP literal, say), bounded escaped audit text with the // refusal in Reason. Hops are the redirects followed from URL, in order, // at most MaxResearchHops; Address and Status are the last request's. type ResearchFetch struct { SourceID string `json:"source_id"` Origin string `json:"origin"` Parent string `json:"parent,omitempty"` URL string `json:"url"` Hops []ResearchHop `json:"hops,omitempty"` Address string `json:"address,omitempty"` Status int `json:"status,omitempty"` Type string `json:"type,omitempty"` Bytes int64 `json:"bytes,omitempty"` SHA256 string `json:"sha256,omitempty"` Millis int64 `json:"millis"` Reason string `json:"reason,omitempty"` } // ResearchHop is one redirect of a fetch: the target, and the address // connected and the status answered when it was requested (none when the // target was refused; its URL is then audit text when it fails the URL // contract). type ResearchHop struct { URL string `json:"url"` Address string `json:"address,omitempty"` Status int `json:"status,omitempty"` } // ResearchImage is an image a Research step kept: normalised PNG. type ResearchImage struct { ID string `json:"id"` SourceID string `json:"source_id"` Role string `json:"role"` Description string `json:"description"` SHA256 string `json:"sha256"` Size int64 `json:"size"` Width int `json:"width"` Height int `json:"height"` } // ResearchResult is a Research step's report payload (protocol 13). // Findings is a ResearchFindings document. type ResearchResult struct { Findings json.RawMessage `json:"findings"` Fetches []ResearchFetch `json:"fetches"` Images []ResearchImage `json:"images"` } // ResearchFile is one chunk of a kept image, runner to instance, sent // before the step's final report. Index counts from 0 to Total-1; SHA256 // and Size are the whole file's. type ResearchFile struct { TaskID string `json:"task_id"` StepID string `json:"step_id"` Attempt int64 `json:"attempt"` ImageID string `json:"image_id"` Index int `json:"index"` Total int `json:"total"` Size int64 `json:"size"` SHA256 string `json:"sha256"` Data string `json:"data"` } // ResearchHandoff is the task's latest Research findings as handed to // Engineering and Review (protocol 13): the findings document, the // sources it cites (so Review knows which hosts the findings came from), // and the kept images the runner places read-only at /research/. type ResearchHandoff struct { Findings json.RawMessage `json:"findings"` Sources []ResearchSource `json:"sources"` Images []ResearchImage `json:"images"` } var ( imageIDPattern = regexp.MustCompile(`^img[0-9]{1,2}$`) sourceIDPattern = regexp.MustCompile(`^[a-z][a-z0-9]{0,15}$`) sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`) ) // ValidImageID and ValidSourceID are the id shapes the runner issues. func ValidImageID(id string) bool { return imageIDPattern.MatchString(id) } func ValidSourceID(id string) bool { return sourceIDPattern.MatchString(id) } // DecodeFindings strictly decodes and bounds a findings document. sources // is the set of source ids in this attempt's fetch log and kept the ids // of its kept images; every fact source and listed image must be in them. func DecodeFindings(raw json.RawMessage, sources, kept map[string]bool) (ResearchFindings, error) { var f ResearchFindings if len(raw) == 0 || len(raw) > MaxFindingsBytes { return f, fmt.Errorf("%w: findings size", ErrStrict) } if err := Strict(raw, &f); err != nil { return f, err } if !text(f.Summary, MaxFindingsSummary) || len(f.Facts) > MaxFindingsFacts || len(f.Gaps) > MaxFindingsGaps || len(f.Images) > MaxKeptImages { return f, fmt.Errorf("%w: findings bounds", ErrStrict) } for _, c := range f.Facts { if c.Label == "" || !text(c.Label, MaxFactLabel) || c.Value == "" || !text(c.Value, MaxFactValue) || len(c.Sources) == 0 || len(c.Sources) > MaxFactSources { return f, fmt.Errorf("%w: fact", ErrStrict) } for _, s := range c.Sources { if !sources[s] { return f, fmt.Errorf("%w: fact source %q not in this attempt's log", ErrStrict, s) } } } seen := map[string]bool{} for _, id := range f.Images { if !kept[id] || seen[id] { return f, fmt.Errorf("%w: image %q not kept in this attempt", ErrStrict, id) } seen[id] = true } for _, g := range f.Gaps { if g == "" || !text(g, MaxFindingsGap) { return f, fmt.Errorf("%w: gap", ErrStrict) } } return f, nil } // ValidResearchImage bounds a kept image's record. func ValidResearchImage(m ResearchImage) bool { switch m.Role { case ImageRoleLogo, ImageRolePhoto, ImageRoleIcon, ImageRoleOther: default: return false } return ValidImageID(m.ID) && ValidSourceID(m.SourceID) && text(m.Description, MaxKeptDescription) && sha256Pattern.MatchString(m.SHA256) && m.Size > 0 && m.Size <= MaxKeptImageBytes && m.Width > 0 && m.Height > 0 && m.Width <= 2048 && m.Height <= 2048 } // ValidResearchAddress is a canonical public address: one the egress // relay and the fetcher would dial (websource.PublicAddress, the same // list), so a tailnet, CGNAT, private, documentation or other // non-public address never counts as the site's egress. func ValidResearchAddress(s string) bool { a, err := netip.ParseAddr(s) return err == nil && a.String() == s && a.Zone() == "" && !a.Is4In6() && websource.PublicAddress(a) } // text: valid UTF-8, at most n bytes. func text(s string, n int) bool { return len(s) <= n && utf8.ValidString(s) }