package equipotest import ( "amadan.net/oficina/equipo/internal/equipo/github" "amadan.net/rastrillo/rastrillo" "bytes" "crypto/x509" "encoding/base64" "encoding/json" "html" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "reflect" "regexp" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/runner/forge/forgetest" ) type githubAuthFixture struct { authFixture logs *bytes.Buffer } func githubFixture(t *testing.T, enabled bool, observe ...func(*http.Request)) (githubAuthFixture, *forgetest.GitHub) { t.Helper() d, _ := foundationDB(t) logs := new(bytes.Buffer) logger := slog.New(slog.NewTextHandler(logs, nil)) mail := &capturingMailer{} g := forgetest.NewGitHub(t) cfg := testConfig(testOrigin) cfg.GitHubEnabled = enabled cfg.GitHubTransport = g.Transport() if len(observe) > 0 { base := cfg.GitHubTransport cfg.GitHubTransport = githubHTTPTransportFunc(func(r *http.Request) (*http.Response, error) { response, err := base.RoundTrip(r) if err == nil { observe[0](r) } return response, err }) } router, err := equipo.Router(d, cfg, mail, logger) if err != nil { t.Fatal(err) } handler, closeHandler, err := rastrillo.Handler(rastrillo.Options{Mux: equipo.Mux(router), Logger: logger}) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = closeHandler() }) server := httptest.NewServer(handler) t.Cleanup(server.Close) return githubAuthFixture{authFixture{d, equipo.NewStore(d), mail, server}, logs}, g } func githubBody(t *testing.T, response *http.Response) string { t.Helper() defer response.Body.Close() raw, err := io.ReadAll(response.Body) if err != nil { t.Fatal(err) } return string(raw) } func TestGitHubOwnerSettings(t *testing.T) { for _, enabled := range []bool{false, true} { t.Run(map[bool]string{false: "off", true: "on"}[enabled], func(t *testing.T) { f, g := githubFixture(t, enabled) client := signinClient(t, f.server.URL) signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) page := clientGet(t, client, f.server.URL+"/conversation/settings/github") if enabled && page.StatusCode != 200 { t.Fatalf("owner page status %d", page.StatusCode) } if !enabled && page.StatusCode != 404 { t.Fatalf("flag-off page status %d", page.StatusCode) } body := githubBody(t, page) if enabled && !strings.Contains(body, "Connect GitHub") { t.Fatal("owner setup missing") } request := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) if enabled && request.StatusCode != 200 { t.Fatalf("manifest page status %d", request.StatusCode) } if !enabled && request.StatusCode != 404 { t.Fatalf("flag-off start status %d", request.StatusCode) } body = githubBody(t, request) if enabled && (!strings.Contains(body, "https://github.com/organizations/") || !strings.Contains(body, "name=\"manifest\"")) { t.Fatal("manifest form absent") } }) } } func githubManifestForm(t *testing.T, body string) (string, string, string) { t.Helper() match := regexp.MustCompile(`action="(https://github.com/[^\"]+)"`).FindStringSubmatch(body) if len(match) != 2 { t.Fatal("missing external manifest form") } action := html.UnescapeString(match[1]) fields := formFields(t, body, action) parsed := mustURL(t, action) return action, fields.Get("manifest"), parsed.Query().Get("state") } func TestGitHubHTTPFlowAndValues(t *testing.T) { f, g := githubFixture(t, true) client := signinClient(t, f.server.URL) signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) start := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) if start.StatusCode != 200 { t.Fatalf("start %d", start.StatusCode) } if !strings.Contains(start.Header.Get("Content-Security-Policy"), "form-action 'self' https://github.com") { t.Fatal("manifest CSP absent") } _, manifest, state := githubManifestForm(t, githubBody(t, start)) var m map[string]any if err := json.Unmarshal([]byte(manifest), &m); err != nil { t.Fatal(err) } 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" { t.Fatal("manifest authority or callbacks changed") } want := map[string]any{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"} if !reflect.DeepEqual(m["default_permissions"], want) || m["hook_attributes"].(map[string]any)["active"] != false { t.Fatal("manifest permissions or webhook widened") } // Every sink is labelled so a leak names where it escaped, never the value. seen := map[string]string{} sink := func(label, value string) { seen[label+" "+strconv.Itoa(len(seen))] = value } dump := func(phase string) { t.Helper() var tables []string if err := f.db.G.Raw("SELECT name FROM sqlite_master WHERE type='table'").Scan(&tables).Error; err != nil { t.Fatal(err) } for _, table := range tables { var rows []map[string]any if err := f.db.G.Table(table).Find(&rows).Error; err != nil { t.Fatal(err) } // json.Marshal would base64 a BLOB and hide a stored key from the search. for _, row := range rows { for column, value := range row { if blob, ok := value.([]byte); ok { row[column] = string(blob) } } } raw, err := json.Marshal(rows) if err != nil { t.Fatal(err) } sink("table "+table+" "+phase, string(raw)) } } clean := func(response *http.Response) string { t.Helper() if response.StatusCode != 303 { t.Fatalf("callback status %d", response.StatusCode) } location := response.Header.Get("Location") if !strings.HasPrefix(location, "/conversation/settings/github") || strings.Contains(location, "state=") || strings.Contains(location, "code=") { t.Fatal("callback URL not clean") } if response.Header.Get("Cache-Control") != "no-store" || response.Header.Get("Referrer-Policy") != "no-referrer" { t.Fatal("callback caching or referrer") } sink("location", location) sink("callback body", githubBody(t, response)) return location } callback := f.server.URL + "/github/connect/manifest?" + url.Values{"state": {state}, "code": {g.Code}}.Encode() location := clean(clientGet(t, client, callback)) dump("after conversion") var connections []github.Connection if err := f.db.G.Find(&connections).Error; err != nil { t.Fatal(err) } if len(connections) != 1 || connections[0].Confirmed || connections[0].SealedKey == "" { t.Fatal("conversion activated or failed to seal") } install := clientGet(t, client, f.server.URL+location) if install.StatusCode != 303 { t.Fatalf("install handoff %d", install.StatusCode) } installURL := mustURL(t, install.Header.Get("Location")) githubBody(t, install) installState := installURL.Query().Get("state") if installURL.Host != "github.com" || installState == "" || installState == state { t.Fatal("invalid installation handoff") } clean(clientGet(t, client, f.server.URL+"/github/connect/installation?"+url.Values{"state": {installState}, "installation_id": {"999999"}}.Encode())) page := clientGet(t, client, f.server.URL+"/conversation/settings/github") if strings.Contains(page.Header.Get("Content-Security-Policy"), "github.com") { t.Fatal("CSP exception spread") } body := githubBody(t, page) sink("page", body) if !strings.Contains(body, "Repositories: 2") || !strings.Contains(body, `action="/github/connect/confirm"`) { t.Fatal("verified installation confirmation absent") } id := connections[0].ID clean(clientPost(t, client, f.server.URL+"/github/connect/confirm", testOrigin, url.Values{"id": {id}})) page = clientGet(t, client, f.server.URL+"/conversation/settings/github") body = githubBody(t, page) sink("page", body) if !strings.Contains(body, "GitHub is connected") { t.Fatal("Connect not reflected") } dump("after connect") clean(clientGet(t, client, callback)) if g.Calls("POST", "/app-manifests/"+g.Code+"/conversions") != 1 { t.Fatal("callback replay converted again") } clean(clientPost(t, client, f.server.URL+"/github/connect/disconnect", testOrigin, url.Values{"id": {id}})) page = clientGet(t, client, f.server.URL+"/conversation/settings/github") sink("page", githubBody(t, page)) // Search every application table, including audits, reports, frames and prompts. // Credential boundaries above are the only permitted code/state surfaces. dump("after disconnect") sink("log", f.logs.String()) githubValueSearch(t, seen, g, state, installState) } // githubValueSearch looks for single-line key fragments, which survive JSON, // log and HTML escaping, as well as the other credential values. The raw PEM // spans lines, so a dump that escapes its newlines would hide it. func githubValueSearch(t *testing.T, seen map[string]string, g *forgetest.GitHub, state, installState string) { t.Helper() lines := strings.Split(strings.TrimSpace(g.PEM), "\n") if len(lines) < 4 { t.Fatal("generated PEM too short") } forbidden := map[string]string{ "PEM body line": lines[len(lines)/2], "DER base64": base64.StdEncoding.EncodeToString(x509.MarshalPKCS1PrivateKey(g.Key)), "client secret": g.ClientSecret, "webhook secret": g.WebhookSecret, "token": g.Token, "code": g.Code, "state": state, "installation state": installState, } for name, secret := range forbidden { if len(secret) < 16 { t.Fatal("weak value-search fixture:", name) } for label, value := range seen { if strings.Contains(value, secret) || strings.Contains(html.UnescapeString(value), secret) { t.Errorf("%s escaped into %s", name, label) } } } } func TestGitHubHTTPAuthority(t *testing.T) { f, g := githubFixture(t, true) client := signinClient(t, f.server.URL) signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) fields := url.Values{"account": {g.Login}, "account_type": {g.AccountType}} for _, origin := range []string{"", "https://evil.example"} { response := clientPost(t, client, f.server.URL+"/github/connect/start", origin, fields) if response.StatusCode != 403 { t.Fatalf("CSRF status %d", response.StatusCode) } githubBody(t, response) } if err := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("role", equipo.RoleMember).Error; err != nil { t.Fatal(err) } for _, path := range []string{"start", "check", "confirm", "disconnect"} { response := clientPost(t, client, f.server.URL+"/github/connect/"+path, testOrigin, fields) if response.StatusCode != 403 { t.Fatalf("member %s status %d", path, response.StatusCode) } githubBody(t, response) } page := clientGet(t, client, f.server.URL+"/conversation/settings/github") if page.StatusCode != 403 { t.Fatal("member setup visible") } githubBody(t, page) var n int64 f.db.G.Model(&github.Connection{}).Count(&n) if n != 0 { t.Fatal("forbidden Start wrote") } } func TestGitHubInvalidCallbackCleanURL(t *testing.T) { f, _ := githubFixture(t, true) client := signinClient(t, f.server.URL) for _, path := range []string{"manifest", "installation"} { response := clientGet(t, client, f.server.URL+"/github/connect/"+path+"?state=unknown-state&code=unknown-code") if response.StatusCode != 303 || response.Header.Get("Location") != "/conversation/settings/github?failed=1" { t.Fatalf("unauthenticated callback not cleaned: status %d", response.StatusCode) } githubBody(t, response) } } type githubHTTPTransportFunc func(*http.Request) (*http.Response, error) func (f githubHTTPTransportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func TestGitHubCallbackSessionRevokedDuringConversion(t *testing.T) { var f githubAuthFixture f, g := githubFixture(t, true, func(r *http.Request) { if strings.HasSuffix(r.URL.Path, "/conversions") { if e := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("session_epoch", time.Now().Add(time.Minute).Unix()).Error; e != nil { t.Error(e) } } }) client := signinClient(t, f.server.URL) signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) response := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) _, _, state := githubManifestForm(t, githubBody(t, response)) response = clientGet(t, client, f.server.URL+"/github/connect/manifest?"+url.Values{"state": {state}, "code": {g.Code}}.Encode()) githubBody(t, response) var rows []github.Connection if e := f.db.G.Find(&rows).Error; e != nil { t.Fatal(e) } if len(rows) != 1 || rows[0].SealedKey != "" { t.Fatal("revoked browser session saved an App key") } } func TestGitHubInventorySessionRevoked(t *testing.T) { for _, action := range []string{"check", "confirm"} { t.Run(action, func(t *testing.T) { var f githubAuthFixture f, g := githubFixture(t, true, func(r *http.Request) { if r.URL.Path == "/installation/repositories" { if e := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("session_epoch", time.Now().Add(time.Minute).Unix()).Error; e != nil { t.Error(e) } } }) client := signinClient(t, f.server.URL) signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) response := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) _, _, state := githubManifestForm(t, githubBody(t, response)) response = clientGet(t, client, f.server.URL+"/github/connect/manifest?"+url.Values{"state": {state}, "code": {g.Code}}.Encode()) githubBody(t, response) var c github.Connection if e := f.db.G.First(&c).Error; e != nil { t.Fatal(e) } response = clientPost(t, client, f.server.URL+"/github/connect/"+action, testOrigin, url.Values{"id": {c.ID}}) githubBody(t, response) if e := f.db.G.First(&c).Error; e != nil { t.Fatal(e) } if c.CountKnown || c.Confirmed { t.Fatal("revoked browser session committed inventory") } if g.Calls("DELETE", "/installation/token") != 1 { t.Fatal("refused inventory retained metadata token") } }) } }