oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/github"
5 "amadan.net/rastrillo/rastrillo"
6 "bytes"
7 "crypto/x509"
8 "encoding/base64"
9 "encoding/json"
10 "html"
11 "io"
12 "log/slog"
13 "net/http"
14 "net/http/httptest"
15 "net/url"
16 "reflect"
17 "regexp"
18 "strconv"
19 "strings"
20 "testing"
21 "time"
22
23 "amadan.net/oficina/equipo/internal/equipo"
24 "amadan.net/oficina/equipo/internal/runner/forge/forgetest"
25)
26
27type githubAuthFixture struct {
28 authFixture
29 logs *bytes.Buffer
30}
31
32func githubFixture(t *testing.T, enabled bool, observe ...func(*http.Request)) (githubAuthFixture, *forgetest.GitHub) {
33 t.Helper()
34 d, _ := foundationDB(t)
35 logs := new(bytes.Buffer)
36 logger := slog.New(slog.NewTextHandler(logs, nil))
37 mail := &capturingMailer{}
38 g := forgetest.NewGitHub(t)
39 cfg := testConfig(testOrigin)
40 cfg.GitHubEnabled = enabled
41 cfg.GitHubTransport = g.Transport()
42 if len(observe) > 0 {
43 base := cfg.GitHubTransport
44 cfg.GitHubTransport = githubHTTPTransportFunc(func(r *http.Request) (*http.Response, error) {
45 response, err := base.RoundTrip(r)
46 if err == nil {
47 observe[0](r)
48 }
49 return response, err
50 })
51 }
52 router, err := equipo.Router(d, cfg, mail, logger)
53 if err != nil {
54 t.Fatal(err)
55 }
56 handler, closeHandler, err := rastrillo.Handler(rastrillo.Options{Mux: equipo.Mux(router), Logger: logger})
57 if err != nil {
58 t.Fatal(err)
59 }
60 t.Cleanup(func() { _ = closeHandler() })
61 server := httptest.NewServer(handler)
62 t.Cleanup(server.Close)
63 return githubAuthFixture{authFixture{d, equipo.NewStore(d), mail, server}, logs}, g
64}
65func githubBody(t *testing.T, response *http.Response) string {
66 t.Helper()
67 defer response.Body.Close()
68 raw, err := io.ReadAll(response.Body)
69 if err != nil {
70 t.Fatal(err)
71 }
72 return string(raw)
73}
74func TestGitHubOwnerSettings(t *testing.T) {
75 for _, enabled := range []bool{false, true} {
76 t.Run(map[bool]string{false: "off", true: "on"}[enabled], func(t *testing.T) {
77 f, g := githubFixture(t, enabled)
78 client := signinClient(t, f.server.URL)
79 signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress)
80 page := clientGet(t, client, f.server.URL+"/conversation/settings/github")
81 if enabled && page.StatusCode != 200 {
82 t.Fatalf("owner page status %d", page.StatusCode)
83 }
84 if !enabled && page.StatusCode != 404 {
85 t.Fatalf("flag-off page status %d", page.StatusCode)
86 }
87 body := githubBody(t, page)
88 if enabled && !strings.Contains(body, "Connect GitHub") {
89 t.Fatal("owner setup missing")
90 }
91 request := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}})
92 if enabled && request.StatusCode != 200 {
93 t.Fatalf("manifest page status %d", request.StatusCode)
94 }
95 if !enabled && request.StatusCode != 404 {
96 t.Fatalf("flag-off start status %d", request.StatusCode)
97 }
98 body = githubBody(t, request)
99 if enabled && (!strings.Contains(body, "https://github.com/organizations/") || !strings.Contains(body, "name=\"manifest\"")) {
100 t.Fatal("manifest form absent")
101 }
102 })
103 }
104}
105
106func githubManifestForm(t *testing.T, body string) (string, string, string) {
107 t.Helper()
108 match := regexp.MustCompile(`action="(https://github.com/[^\"]+)"`).FindStringSubmatch(body)
109 if len(match) != 2 {
110 t.Fatal("missing external manifest form")
111 }
112 action := html.UnescapeString(match[1])
113 fields := formFields(t, body, action)
114 parsed := mustURL(t, action)
115 return action, fields.Get("manifest"), parsed.Query().Get("state")
116}
117
118func TestGitHubHTTPFlowAndValues(t *testing.T) {
119 f, g := githubFixture(t, true)
120 client := signinClient(t, f.server.URL)
121 signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress)
122 start := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}})
123 if start.StatusCode != 200 {
124 t.Fatalf("start %d", start.StatusCode)
125 }
126 if !strings.Contains(start.Header.Get("Content-Security-Policy"), "form-action 'self' https://github.com") {
127 t.Fatal("manifest CSP absent")
128 }
129 _, manifest, state := githubManifestForm(t, githubBody(t, start))
130 var m map[string]any
131 if err := json.Unmarshal([]byte(manifest), &m); err != nil {
132 t.Fatal(err)
133 }
134 if m["public"] != false || m["request_oauth_on_install"] != false || len(m["default_events"].([]any)) != 0 || m["redirect_url"] != testOrigin+"/github/connect/manifest" || m["setup_url"] != testOrigin+"/github/connect/installation" {
135 t.Fatal("manifest authority or callbacks changed")
136 }
137 want := map[string]any{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"}
138 if !reflect.DeepEqual(m["default_permissions"], want) || m["hook_attributes"].(map[string]any)["active"] != false {
139 t.Fatal("manifest permissions or webhook widened")
140 }
141 // Every sink is labelled so a leak names where it escaped, never the value.
142 seen := map[string]string{}
143 sink := func(label, value string) { seen[label+" "+strconv.Itoa(len(seen))] = value }
144 dump := func(phase string) {
145 t.Helper()
146 var tables []string
147 if err := f.db.G.Raw("SELECT name FROM sqlite_master WHERE type='table'").Scan(&tables).Error; err != nil {
148 t.Fatal(err)
149 }
150 for _, table := range tables {
151 var rows []map[string]any
152 if err := f.db.G.Table(table).Find(&rows).Error; err != nil {
153 t.Fatal(err)
154 }
155 // json.Marshal would base64 a BLOB and hide a stored key from the search.
156 for _, row := range rows {
157 for column, value := range row {
158 if blob, ok := value.([]byte); ok {
159 row[column] = string(blob)
160 }
161 }
162 }
163 raw, err := json.Marshal(rows)
164 if err != nil {
165 t.Fatal(err)
166 }
167 sink("table "+table+" "+phase, string(raw))
168 }
169 }
170 clean := func(response *http.Response) string {
171 t.Helper()
172 if response.StatusCode != 303 {
173 t.Fatalf("callback status %d", response.StatusCode)
174 }
175 location := response.Header.Get("Location")
176 if !strings.HasPrefix(location, "/conversation/settings/github") || strings.Contains(location, "state=") || strings.Contains(location, "code=") {
177 t.Fatal("callback URL not clean")
178 }
179 if response.Header.Get("Cache-Control") != "no-store" || response.Header.Get("Referrer-Policy") != "no-referrer" {
180 t.Fatal("callback caching or referrer")
181 }
182 sink("location", location)
183 sink("callback body", githubBody(t, response))
184 return location
185 }
186 callback := f.server.URL + "/github/connect/manifest?" + url.Values{"state": {state}, "code": {g.Code}}.Encode()
187 location := clean(clientGet(t, client, callback))
188 dump("after conversion")
189 var connections []github.Connection
190 if err := f.db.G.Find(&connections).Error; err != nil {
191 t.Fatal(err)
192 }
193 if len(connections) != 1 || connections[0].Confirmed || connections[0].SealedKey == "" {
194 t.Fatal("conversion activated or failed to seal")
195 }
196 install := clientGet(t, client, f.server.URL+location)
197 if install.StatusCode != 303 {
198 t.Fatalf("install handoff %d", install.StatusCode)
199 }
200 installURL := mustURL(t, install.Header.Get("Location"))
201 githubBody(t, install)
202 installState := installURL.Query().Get("state")
203 if installURL.Host != "github.com" || installState == "" || installState == state {
204 t.Fatal("invalid installation handoff")
205 }
206 clean(clientGet(t, client, f.server.URL+"/github/connect/installation?"+url.Values{"state": {installState}, "installation_id": {"999999"}}.Encode()))
207 page := clientGet(t, client, f.server.URL+"/conversation/settings/github")
208 if strings.Contains(page.Header.Get("Content-Security-Policy"), "github.com") {
209 t.Fatal("CSP exception spread")
210 }
211 body := githubBody(t, page)
212 sink("page", body)
213 if !strings.Contains(body, "Repositories: 2") || !strings.Contains(body, `action="/github/connect/confirm"`) {
214 t.Fatal("verified installation confirmation absent")
215 }
216 id := connections[0].ID
217 clean(clientPost(t, client, f.server.URL+"/github/connect/confirm", testOrigin, url.Values{"id": {id}}))
218 page = clientGet(t, client, f.server.URL+"/conversation/settings/github")
219 body = githubBody(t, page)
220 sink("page", body)
221 if !strings.Contains(body, "GitHub is connected") {
222 t.Fatal("Connect not reflected")
223 }
224 dump("after connect")
225 clean(clientGet(t, client, callback))
226 if g.Calls("POST", "/app-manifests/"+g.Code+"/conversions") != 1 {
227 t.Fatal("callback replay converted again")
228 }
229 clean(clientPost(t, client, f.server.URL+"/github/connect/disconnect", testOrigin, url.Values{"id": {id}}))
230 page = clientGet(t, client, f.server.URL+"/conversation/settings/github")
231 sink("page", githubBody(t, page))
232 // Search every application table, including audits, reports, frames and prompts.
233 // Credential boundaries above are the only permitted code/state surfaces.
234 dump("after disconnect")
235 sink("log", f.logs.String())
236 githubValueSearch(t, seen, g, state, installState)
237}
238
239// githubValueSearch looks for single-line key fragments, which survive JSON,
240// log and HTML escaping, as well as the other credential values. The raw PEM
241// spans lines, so a dump that escapes its newlines would hide it.
242func githubValueSearch(t *testing.T, seen map[string]string, g *forgetest.GitHub, state, installState string) {
243 t.Helper()
244 lines := strings.Split(strings.TrimSpace(g.PEM), "\n")
245 if len(lines) < 4 {
246 t.Fatal("generated PEM too short")
247 }
248 forbidden := map[string]string{
249 "PEM body line": lines[len(lines)/2], "DER base64": base64.StdEncoding.EncodeToString(x509.MarshalPKCS1PrivateKey(g.Key)),
250 "client secret": g.ClientSecret, "webhook secret": g.WebhookSecret, "token": g.Token, "code": g.Code, "state": state, "installation state": installState,
251 }
252 for name, secret := range forbidden {
253 if len(secret) < 16 {
254 t.Fatal("weak value-search fixture:", name)
255 }
256 for label, value := range seen {
257 if strings.Contains(value, secret) || strings.Contains(html.UnescapeString(value), secret) {
258 t.Errorf("%s escaped into %s", name, label)
259 }
260 }
261 }
262}
263
264func TestGitHubHTTPAuthority(t *testing.T) {
265 f, g := githubFixture(t, true)
266 client := signinClient(t, f.server.URL)
267 signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress)
268 fields := url.Values{"account": {g.Login}, "account_type": {g.AccountType}}
269 for _, origin := range []string{"", "https://evil.example"} {
270 response := clientPost(t, client, f.server.URL+"/github/connect/start", origin, fields)
271 if response.StatusCode != 403 {
272 t.Fatalf("CSRF status %d", response.StatusCode)
273 }
274 githubBody(t, response)
275 }
276 if err := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("role", equipo.RoleMember).Error; err != nil {
277 t.Fatal(err)
278 }
279 for _, path := range []string{"start", "check", "confirm", "disconnect"} {
280 response := clientPost(t, client, f.server.URL+"/github/connect/"+path, testOrigin, fields)
281 if response.StatusCode != 403 {
282 t.Fatalf("member %s status %d", path, response.StatusCode)
283 }
284 githubBody(t, response)
285 }
286 page := clientGet(t, client, f.server.URL+"/conversation/settings/github")
287 if page.StatusCode != 403 {
288 t.Fatal("member setup visible")
289 }
290 githubBody(t, page)
291 var n int64
292 f.db.G.Model(&github.Connection{}).Count(&n)
293 if n != 0 {
294 t.Fatal("forbidden Start wrote")
295 }
296}
297
298func TestGitHubInvalidCallbackCleanURL(t *testing.T) {
299 f, _ := githubFixture(t, true)
300 client := signinClient(t, f.server.URL)
301 for _, path := range []string{"manifest", "installation"} {
302 response := clientGet(t, client, f.server.URL+"/github/connect/"+path+"?state=unknown-state&code=unknown-code")
303 if response.StatusCode != 303 || response.Header.Get("Location") != "/conversation/settings/github?failed=1" {
304 t.Fatalf("unauthenticated callback not cleaned: status %d", response.StatusCode)
305 }
306 githubBody(t, response)
307 }
308}
309
310type githubHTTPTransportFunc func(*http.Request) (*http.Response, error)
311
312func (f githubHTTPTransportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
313func TestGitHubCallbackSessionRevokedDuringConversion(t *testing.T) {
314 var f githubAuthFixture
315 f, g := githubFixture(t, true, func(r *http.Request) {
316 if strings.HasSuffix(r.URL.Path, "/conversions") {
317 if e := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("session_epoch", time.Now().Add(time.Minute).Unix()).Error; e != nil {
318 t.Error(e)
319 }
320 }
321 })
322 client := signinClient(t, f.server.URL)
323 signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress)
324 response := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}})
325 _, _, state := githubManifestForm(t, githubBody(t, response))
326 response = clientGet(t, client, f.server.URL+"/github/connect/manifest?"+url.Values{"state": {state}, "code": {g.Code}}.Encode())
327 githubBody(t, response)
328 var rows []github.Connection
329 if e := f.db.G.Find(&rows).Error; e != nil {
330 t.Fatal(e)
331 }
332 if len(rows) != 1 || rows[0].SealedKey != "" {
333 t.Fatal("revoked browser session saved an App key")
334 }
335}
336
337func TestGitHubInventorySessionRevoked(t *testing.T) {
338 for _, action := range []string{"check", "confirm"} {
339 t.Run(action, func(t *testing.T) {
340 var f githubAuthFixture
341 f, g := githubFixture(t, true, func(r *http.Request) {
342 if r.URL.Path == "/installation/repositories" {
343 if e := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("session_epoch", time.Now().Add(time.Minute).Unix()).Error; e != nil {
344 t.Error(e)
345 }
346 }
347 })
348 client := signinClient(t, f.server.URL)
349 signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress)
350 response := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}})
351 _, _, state := githubManifestForm(t, githubBody(t, response))
352 response = clientGet(t, client, f.server.URL+"/github/connect/manifest?"+url.Values{"state": {state}, "code": {g.Code}}.Encode())
353 githubBody(t, response)
354 var c github.Connection
355 if e := f.db.G.First(&c).Error; e != nil {
356 t.Fatal(e)
357 }
358 response = clientPost(t, client, f.server.URL+"/github/connect/"+action, testOrigin, url.Values{"id": {c.ID}})
359 githubBody(t, response)
360 if e := f.db.G.First(&c).Error; e != nil {
361 t.Fatal(e)
362 }
363 if c.CountKnown || c.Confirmed {
364 t.Fatal("revoked browser session committed inventory")
365 }
366 if g.Calls("DELETE", "/installation/token") != 1 {
367 t.Fatal("refused inventory retained metadata token")
368 }
369 })
370 }
371}
372