oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package wire
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/netip"
7 "regexp"
8 "unicode/utf8"
9
10 "amadan.net/oficina/equipo/internal/websource"
11)
12
13// What a Research step returns (Research spec §4 and §5, slice R3), the
14// site inventory it needs (R4 decision), and what Engineering and Review
15// are handed (slice R4). Both ends validate with the same functions.
16
17// CardResearchInventory asks an owner to confirm the addresses the
18// primary fetches from ("Research fetches from these addresses"); only
19// ChoiceConfirm (api.go) is offered. A Research step waits until every
20// address currently detected is inside a confirmed set.
21const CardResearchInventory = "research_inventory"
22
23// CardInstanceInventory asks an owner to confirm the network the instance
24// itself is on (its prefixes and the addresses it saw), before anything
25// reaches the public web from it. Its view is Inventory, prefixes first.
26const CardInstanceInventory = "instance_inventory"
27
28// Bounds of a Research result.
29const (
30 MaxFindingsBytes = 8 << 10
31 MaxFindingsSummary = 1000
32 MaxFactLabel = 100
33 MaxFactValue = 300
34 MaxFactSources = 10
35 MaxFindingsFacts = 60
36 MaxFindingsGaps = 20
37 MaxFindingsGap = 200
38 MaxKeptImages = 8
39 MaxKeptDescription = 200
40 MaxKeptImageBytes = 8 << 20
41 MaxResearchFetches = 64
42 MaxResearchHops = 5
43 MaxResearchAddresses = 32
44 MaxResearchFileChunks = MaxKeptImageBytes/ResearchFileChunk + 1
45 // ResearchFileChunk is one research_file frame's share of an image;
46 // base64 in JSON stays well under MaxFrameBytes.
47 ResearchFileChunk = 128 << 10
48)
49
50// Kept image roles.
51const (
52 ImageRoleLogo = "logo"
53 ImageRolePhoto = "photo"
54 ImageRoleIcon = "icon"
55 ImageRoleOther = "other"
56)
57
58// ResearchCapability is the primary's detected addresses (canonical
59// netip strings, global unicast only).
60type ResearchCapability struct {
61 Addresses []string `json:"addresses"`
62}
63
64// ResearchFindings is submit_findings' argument and the stored findings.
65type ResearchFindings struct {
66 Summary string `json:"summary"`
67 Facts []ResearchFact `json:"facts"`
68 Images []string `json:"images"`
69 Gaps []string `json:"gaps"`
70}
71
72// ResearchFact is one extracted fact and the source ids it came from.
73type ResearchFact struct {
74 Label string `json:"label"`
75 Value string `json:"value"`
76 Sources []string `json:"sources"`
77}
78
79// ResearchFetch is one line of a Research step's fetch log: a request or
80// a refusal. SourceID is the bundle's id (approved sources keep the
81// dispatch's id; expanded ones get new ids with Parent set). URL is the
82// source's canonical URL, or, for a refused target that fails the URL
83// contract (an IP literal, say), bounded escaped audit text with the
84// refusal in Reason. Hops are the redirects followed from URL, in order,
85// at most MaxResearchHops; Address and Status are the last request's.
86type ResearchFetch struct {
87 SourceID string `json:"source_id"`
88 Origin string `json:"origin"`
89 Parent string `json:"parent,omitempty"`
90 URL string `json:"url"`
91 Hops []ResearchHop `json:"hops,omitempty"`
92 Address string `json:"address,omitempty"`
93 Status int `json:"status,omitempty"`
94 Type string `json:"type,omitempty"`
95 Bytes int64 `json:"bytes,omitempty"`
96 SHA256 string `json:"sha256,omitempty"`
97 Millis int64 `json:"millis"`
98 Reason string `json:"reason,omitempty"`
99}
100
101// ResearchHop is one redirect of a fetch: the target, and the address
102// connected and the status answered when it was requested (none when the
103// target was refused; its URL is then audit text when it fails the URL
104// contract).
105type ResearchHop struct {
106 URL string `json:"url"`
107 Address string `json:"address,omitempty"`
108 Status int `json:"status,omitempty"`
109}
110
111// ResearchImage is an image a Research step kept: normalised PNG.
112type ResearchImage struct {
113 ID string `json:"id"`
114 SourceID string `json:"source_id"`
115 Role string `json:"role"`
116 Description string `json:"description"`
117 SHA256 string `json:"sha256"`
118 Size int64 `json:"size"`
119 Width int `json:"width"`
120 Height int `json:"height"`
121}
122
123// ResearchResult is a Research step's report payload (protocol 13).
124// Findings is a ResearchFindings document.
125type ResearchResult struct {
126 Findings json.RawMessage `json:"findings"`
127 Fetches []ResearchFetch `json:"fetches"`
128 Images []ResearchImage `json:"images"`
129}
130
131// ResearchFile is one chunk of a kept image, runner to instance, sent
132// before the step's final report. Index counts from 0 to Total-1; SHA256
133// and Size are the whole file's.
134type ResearchFile struct {
135 TaskID string `json:"task_id"`
136 StepID string `json:"step_id"`
137 Attempt int64 `json:"attempt"`
138 ImageID string `json:"image_id"`
139 Index int `json:"index"`
140 Total int `json:"total"`
141 Size int64 `json:"size"`
142 SHA256 string `json:"sha256"`
143 Data string `json:"data"`
144}
145
146// ResearchHandoff is the task's latest Research findings as handed to
147// Engineering and Review (protocol 13): the findings document, the
148// sources it cites (so Review knows which hosts the findings came from),
149// and the kept images the runner places read-only at /research/.
150type ResearchHandoff struct {
151 Findings json.RawMessage `json:"findings"`
152 Sources []ResearchSource `json:"sources"`
153 Images []ResearchImage `json:"images"`
154}
155
156var (
157 imageIDPattern = regexp.MustCompile(`^img[0-9]{1,2}$`)
158 sourceIDPattern = regexp.MustCompile(`^[a-z][a-z0-9]{0,15}$`)
159 sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
160)
161
162// ValidImageID and ValidSourceID are the id shapes the runner issues.
163func ValidImageID(id string) bool { return imageIDPattern.MatchString(id) }
164func ValidSourceID(id string) bool { return sourceIDPattern.MatchString(id) }
165
166// DecodeFindings strictly decodes and bounds a findings document. sources
167// is the set of source ids in this attempt's fetch log and kept the ids
168// of its kept images; every fact source and listed image must be in them.
169func DecodeFindings(raw json.RawMessage, sources, kept map[string]bool) (ResearchFindings, error) {
170 var f ResearchFindings
171 if len(raw) == 0 || len(raw) > MaxFindingsBytes {
172 return f, fmt.Errorf("%w: findings size", ErrStrict)
173 }
174 if err := Strict(raw, &f); err != nil {
175 return f, err
176 }
177 if !text(f.Summary, MaxFindingsSummary) || len(f.Facts) > MaxFindingsFacts || len(f.Gaps) > MaxFindingsGaps || len(f.Images) > MaxKeptImages {
178 return f, fmt.Errorf("%w: findings bounds", ErrStrict)
179 }
180 for _, c := range f.Facts {
181 if c.Label == "" || !text(c.Label, MaxFactLabel) || c.Value == "" || !text(c.Value, MaxFactValue) || len(c.Sources) == 0 || len(c.Sources) > MaxFactSources {
182 return f, fmt.Errorf("%w: fact", ErrStrict)
183 }
184 for _, s := range c.Sources {
185 if !sources[s] {
186 return f, fmt.Errorf("%w: fact source %q not in this attempt's log", ErrStrict, s)
187 }
188 }
189 }
190 seen := map[string]bool{}
191 for _, id := range f.Images {
192 if !kept[id] || seen[id] {
193 return f, fmt.Errorf("%w: image %q not kept in this attempt", ErrStrict, id)
194 }
195 seen[id] = true
196 }
197 for _, g := range f.Gaps {
198 if g == "" || !text(g, MaxFindingsGap) {
199 return f, fmt.Errorf("%w: gap", ErrStrict)
200 }
201 }
202 return f, nil
203}
204
205// ValidResearchImage bounds a kept image's record.
206func ValidResearchImage(m ResearchImage) bool {
207 switch m.Role {
208 case ImageRoleLogo, ImageRolePhoto, ImageRoleIcon, ImageRoleOther:
209 default:
210 return false
211 }
212 return ValidImageID(m.ID) && ValidSourceID(m.SourceID) && text(m.Description, MaxKeptDescription) &&
213 sha256Pattern.MatchString(m.SHA256) && m.Size > 0 && m.Size <= MaxKeptImageBytes &&
214 m.Width > 0 && m.Height > 0 && m.Width <= 2048 && m.Height <= 2048
215}
216
217// ValidResearchAddress is a canonical public address: one the egress
218// relay and the fetcher would dial (websource.PublicAddress, the same
219// list), so a tailnet, CGNAT, private, documentation or other
220// non-public address never counts as the site's egress.
221func ValidResearchAddress(s string) bool {
222 a, err := netip.ParseAddr(s)
223 return err == nil && a.String() == s && a.Zone() == "" && !a.Is4In6() && websource.PublicAddress(a)
224}
225
226// text: valid UTF-8, at most n bytes.
227func text(s string, n int) bool { return len(s) <= n && utf8.ValidString(s) }
228