oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "fmt"
5 "go/ast"
6 "go/importer"
7 "go/parser"
8 "go/token"
9 "go/types"
10 "io/fs"
11 "path/filepath"
12 "strconv"
13 "strings"
14 "testing"
15)
16
17func TestAPIErrorCopyKeys(t *testing.T) {
18 keys, err := scanAPIErrorCopy("..")
19 if err != nil {
20 t.Fatal(err)
21 }
22 for key := range keys {
23 if copyText(key) == "" || copyText(key) == key {
24 t.Errorf("API returns copy_key %s without text", key)
25 }
26 }
27}
28
29// Scan all internal packages, including wiring outside chat and personapi.
30// Follow string assignments to API error sinks, not unrelated tool-result codes.
31// Unknown expressions fail closed so a new helper needs explicit analysis.
32func scanAPIErrorCopy(root string) (map[string]bool, error) {
33 keys := map[string]bool{}
34 fset := token.NewFileSet()
35 imports := importer.Default()
36 err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
37 if walkErr != nil {
38 return walkErr
39 }
40 if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
41 return nil
42 }
43 file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
44 if err != nil {
45 return err
46 }
47 // Only error-writing files need lexical bindings. Other declarations in
48 // this single file may be unresolved; unknown sink values still fail below.
49 hasSink := false
50 ast.Inspect(file, func(n ast.Node) bool {
51 if call, ok := n.(*ast.CallExpr); ok && callName(call.Fun) == "WriteError" {
52 hasSink = true
53 }
54 if id, ok := n.(*ast.Ident); ok && id.Name == "CopyKey" {
55 hasSink = true
56 }
57 if literal, ok := n.(*ast.BasicLit); ok && literal.Kind == token.STRING {
58 value, _ := strconv.Unquote(literal.Value)
59 if value == "copy_key" {
60 hasSink = true
61 }
62 }
63 return true
64 })
65 if !hasSink {
66 return nil
67 }
68 info := &types.Info{Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}}
69 config := types.Config{Importer: imports, Error: func(error) {}}
70 _, _ = config.Check(file.Name.Name, fset, []*ast.File{file}, info)
71 object := func(id *ast.Ident) types.Object {
72 if value := info.Defs[id]; value != nil {
73 return value
74 }
75 return info.Uses[id]
76 }
77 assignments := map[types.Object][]ast.Expr{}
78 bind := func(id *ast.Ident, expr ast.Expr) {
79 if object(id) != nil {
80 assignments[object(id)] = append(assignments[object(id)], expr)
81 }
82 }
83 ast.Inspect(file, func(n ast.Node) bool {
84 switch v := n.(type) {
85 case *ast.AssignStmt:
86 if len(v.Lhs) == len(v.Rhs) {
87 for i, lhs := range v.Lhs {
88 if id, ok := lhs.(*ast.Ident); ok {
89 bind(id, v.Rhs[i])
90 }
91 }
92 }
93 case *ast.ValueSpec:
94 if len(v.Names) == len(v.Values) {
95 for i, id := range v.Names {
96 bind(id, v.Values[i])
97 }
98 }
99 }
100 return true
101 })
102 var values func(ast.Expr, map[types.Object]bool) ([]string, error)
103 values = func(expr ast.Expr, seen map[types.Object]bool) ([]string, error) {
104 switch v := expr.(type) {
105 case *ast.BasicLit:
106 if v.Kind == token.STRING {
107 s, e := strconv.Unquote(v.Value)
108 return []string{s}, e
109 }
110 case *ast.ParenExpr:
111 return values(v.X, seen)
112 case *ast.Ident:
113 if object(v) != nil && !seen[object(v)] && len(assignments[object(v)]) > 0 {
114 seen[object(v)] = true
115 defer delete(seen, object(v))
116 var out []string
117 for _, expr := range assignments[object(v)] {
118 parts, e := values(expr, seen)
119 if e != nil {
120 return nil, e
121 }
122 out = append(out, parts...)
123 }
124 return out, nil
125 }
126 case *ast.BinaryExpr:
127 if v.Op == token.ADD {
128 left, e := values(v.X, seen)
129 if e != nil {
130 return nil, e
131 }
132 right, e := values(v.Y, seen)
133 if e != nil {
134 return nil, e
135 }
136 var out []string
137 for _, a := range left {
138 for _, b := range right {
139 out = append(out, a+b)
140 }
141 }
142 return out, nil
143 }
144 }
145 return nil, fmt.Errorf("unresolved API error expression at %s", fset.Position(expr.Pos()))
146 }
147 var failure error
148 ast.Inspect(file, func(n ast.Node) bool {
149 if failure != nil {
150 return false
151 }
152 if call, ok := n.(*ast.CallExpr); ok && callName(call.Fun) == "WriteError" {
153 if len(call.Args) != 5 {
154 failure = fmt.Errorf("unrecognised WriteError at %s", fset.Position(call.Pos()))
155 return false
156 }
157 codes, e := values(call.Args[3], map[types.Object]bool{})
158 if e != nil {
159 failure = e
160 return false
161 }
162 for _, code := range codes {
163 if code == "subscription_expired" {
164 keys["notifications."+code] = true
165 } else {
166 keys["api."+code] = true
167 }
168 // These are the additional scopes of personapi.errorCopyKey. Their
169 // dispatch is exercised by the person API's error response tests.
170 if code == "cursor_expired" {
171 keys["notifications."+code] = true
172 }
173 if code == "invalid_input" || code == "forbidden" || code == "revision_conflict" {
174 keys["roster."+code] = true
175 keys["budgets."+code] = true
176 }
177 }
178 }
179 if literal, ok := n.(*ast.CompositeLit); ok {
180 hasCode := false
181 for _, element := range literal.Elts {
182 if kv, ok := element.(*ast.KeyValueExpr); ok {
183 if id, ok := kv.Key.(*ast.Ident); ok && id.Name == "Code" {
184 hasCode = true
185 }
186 }
187 }
188 for _, element := range literal.Elts {
189 kv, ok := element.(*ast.KeyValueExpr)
190 if !ok {
191 continue
192 }
193 id, namedField := kv.Key.(*ast.Ident)
194 structCopyKey := namedField && id.Name == "CopyKey"
195 rawMapCopyKey := false
196 if names, err := values(kv.Key, map[types.Object]bool{}); err == nil {
197 for _, name := range names {
198 if name == "copy_key" {
199 rawMapCopyKey = true
200 }
201 }
202 }
203 if !structCopyKey && !rawMapCopyKey {
204 continue
205 }
206 // WriteError's computed copy key is covered through every call above.
207 if call, ok := kv.Value.(*ast.CallExpr); ok && callName(call.Fun) == "errorCopyKey" {
208 continue
209 }
210 apiLiteral := false
211 ast.Inspect(kv.Value, func(n ast.Node) bool {
212 if s, ok := n.(*ast.BasicLit); ok && s.Kind == token.STRING {
213 v, _ := strconv.Unquote(s.Value)
214 apiLiteral = apiLiteral || strings.HasPrefix(v, "api.")
215 }
216 return true
217 })
218 errorType := strings.HasSuffix(callName(literal.Type), "Error") || strings.HasSuffix(callName(literal.Type), "Conflict")
219 if !hasCode && !apiLiteral && !errorType && !rawMapCopyKey {
220 continue
221 }
222 texts, e := values(kv.Value, map[types.Object]bool{})
223 if e != nil {
224 failure = e
225 return false
226 }
227 for _, text := range texts {
228 keys[text] = true
229 }
230 }
231 }
232 return true
233 })
234 return failure
235 })
236 return keys, err
237}
238
239func callName(expr ast.Expr) string {
240 switch v := expr.(type) {
241 case *ast.Ident:
242 return v.Name
243 case *ast.SelectorExpr:
244 return v.Sel.Name
245 }
246 return ""
247}
248