package forgetest import ( "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "io" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "sync" "testing" "time" ) // GitHub is a generated-key installation API. It has no write-token route. // Tests configure fields before a request; the request ledger is synchronized. type GitHub struct { Server *httptest.Server Key *rsa.PrivateKey PEM string Code, ClientSecret, WebhookSecret, Token string AppID, AccountID, InstallationID int64 Login, AccountType, Selection string Count int Suspended, Uninstalled bool Now time.Time FailPath string FailStatus int FailBody string FailHeaders http.Header mu sync.Mutex calls map[string]int converted bool revoked bool tokenGeneration int t testing.TB } func NewGitHub(t testing.TB) *GitHub { t.Helper() key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { t.Fatal(err) } g := &GitHub{t: t, Key: key, AppID: 101, AccountID: 202, InstallationID: 303, Login: "oficina-test", AccountType: "Organization", Selection: "selected", Count: 2, Now: time.Now().UTC(), calls: map[string]int{}} g.PEM = string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})) nonce := func() string { b := make([]byte, 24) if _, err := rand.Read(b); err != nil { t.Fatal(err) } return base64.RawURLEncoding.EncodeToString(b) } g.Code, g.ClientSecret, g.WebhookSecret, g.Token = nonce(), nonce(), nonce(), "ghs_"+nonce() g.Server = httptest.NewServer(http.HandlerFunc(g.serve)) t.Cleanup(g.Server.Close) return g } func (g *GitHub) Calls(method, path string) int { g.mu.Lock() defer g.mu.Unlock() return g.calls[method+" "+path] } func (g *GitHub) permissions() map[string]string { return map[string]string{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"} } func (g *GitHub) account() map[string]any { return map[string]any{"id": g.AccountID, "login": g.Login, "type": g.AccountType} } func (g *GitHub) app() map[string]any { return map[string]any{"id": g.AppID, "slug": "equipo-test-app", "owner": g.account(), "permissions": g.permissions(), "events": []string{}} } func (g *GitHub) installation() map[string]any { v := map[string]any{"id": g.InstallationID, "app_id": g.AppID, "account": g.account(), "permissions": g.permissions(), "events": []string{}, "repository_selection": g.Selection, "suspended_at": nil} if g.Suspended { v["suspended_at"] = g.Now.Format(time.RFC3339) } return v } func (g *GitHub) jwt(raw string) bool { bits := strings.Split(strings.TrimPrefix(raw, "Bearer "), ".") if len(bits) != 3 { return false } header, e := base64.RawURLEncoding.DecodeString(bits[0]) if e != nil { return false } var h struct{ Alg string } if json.Unmarshal(header, &h) != nil || h.Alg != "RS256" { return false } payload, e := base64.RawURLEncoding.DecodeString(bits[1]) if e != nil { return false } var v struct { Iss string Iat, Exp int64 } if json.Unmarshal(payload, &v) != nil { return false } if v.Iss != strconv.FormatInt(g.AppID, 10) || v.Iat > g.Now.Unix() || v.Exp <= g.Now.Unix() || v.Exp-g.Now.Unix() > 600 { return false } sig, e := base64.RawURLEncoding.DecodeString(bits[2]) if e != nil { return false } digest := sha256.Sum256([]byte(bits[0] + "." + bits[1])) return rsa.VerifyPKCS1v15(&g.Key.PublicKey, crypto.SHA256, digest[:], sig) == nil } func (g *GitHub) serve(w http.ResponseWriter, r *http.Request) { g.mu.Lock() defer g.mu.Unlock() g.calls[r.Method+" "+r.URL.Path]++ w.Header().Set("Content-Type", "application/json") if r.Header.Get("X-GitHub-Api-Version") != "2022-11-28" || r.Header.Get("Accept") != "application/vnd.github+json" || r.UserAgent() == "" { w.WriteHeader(400) return } if r.URL.Path == g.FailPath { for k, v := range g.FailHeaders { w.Header()[k] = v } w.WriteHeader(g.FailStatus) _, _ = io.WriteString(w, g.FailBody) return } answer := func(status int, v any) { w.WriteHeader(status); _ = json.NewEncoder(w).Encode(v) } if r.Method == "POST" && r.URL.Path == "/app-manifests/"+g.Code+"/conversions" { if g.converted || r.Header.Get("Authorization") != "" { w.WriteHeader(422) return } g.converted = true v := g.app() v["pem"], v["client_secret"], v["webhook_secret"] = g.PEM, g.ClientSecret, g.WebhookSecret answer(201, v) return } if strings.HasPrefix(r.URL.Path, "/app-manifests/") { w.WriteHeader(404) return } if strings.HasPrefix(r.URL.Path, "/app") && !g.jwt(r.Header.Get("Authorization")) { w.WriteHeader(401) return } switch { case r.Method == "GET" && r.URL.Path == "/app": answer(200, g.app()) case r.Method == "GET" && r.URL.Path == "/app/installations": rows := []any{} if !g.Uninstalled { rows = append(rows, g.installation()) } answer(200, rows) case r.Method == "GET" && r.URL.Path == fmt.Sprintf("/app/installations/%d", g.InstallationID): if g.Uninstalled { w.WriteHeader(404) return } answer(200, g.installation()) case r.Method == "POST" && r.URL.Path == fmt.Sprintf("/app/installations/%d/access_tokens", g.InstallationID): var body map[string]json.RawMessage if json.NewDecoder(r.Body).Decode(&body) != nil || len(body) != 1 { w.WriteHeader(422) return } var permissions map[string]string if json.Unmarshal(body["permissions"], &permissions) != nil || len(permissions) != 1 || permissions["metadata"] != "read" { w.WriteHeader(422) return } if g.Uninstalled || g.Suspended { w.WriteHeader(403) return } g.revoked = false g.tokenGeneration++ if g.tokenGeneration > 1 { g.Token = "ghs_" + rand.Text() } answer(201, map[string]any{"token": g.Token, "expires_at": g.Now.Add(time.Hour).Format(time.RFC3339), "permissions": permissions, "repository_selection": g.Selection}) case r.URL.Path == "/installation/repositories" && r.Method == "GET": if g.revoked || r.Header.Get("Authorization") != "Bearer "+g.Token { w.WriteHeader(401) return } page, _ := strconv.Atoi(r.URL.Query().Get("page")) if page < 1 { page = 1 } rows := []any{} for i := (page - 1) * 100; i < page*100 && i < g.Count; i++ { rows = append(rows, map[string]any{"id": 1000 + i, "full_name": fmt.Sprintf("%s/repo%d", g.Login, i), "owner": g.account(), "permissions": map[string]bool{"admin": false, "maintain": false, "push": false, "triage": false, "pull": false}}) } if page*100 < g.Count { w.Header().Set("Link", fmt.Sprintf(`; rel="next"`, page+1)) } etag := fmt.Sprintf(`"inventory-%d-%d-%d"`, g.tokenGeneration, g.Count, page) w.Header().Set("ETag", etag) w.Header().Set("Vary", "Authorization") w.Header().Set("Cache-Control", "private, max-age=60, s-maxage=60") if r.Header.Get("If-None-Match") == etag { w.WriteHeader(304) return } answer(200, map[string]any{"total_count": g.Count, "repositories": rows}) case r.Method == "GET" && r.URL.Path == "/repos/"+g.Login+"/probe/contents/README.md": if g.revoked || r.Header.Get("Authorization") != "Bearer "+g.Token { w.WriteHeader(401) } else { w.WriteHeader(403) } case r.URL.Path == "/installation/token" && r.Method == "DELETE": if r.Header.Get("Authorization") != "Bearer "+g.Token { w.WriteHeader(401) return } g.revoked = true w.WriteHeader(204) default: g.t.Error("unexpected GitHub route or verb") w.WriteHeader(404) } } type githubTransport struct { base http.RoundTripper target *url.URL } func (t githubTransport) RoundTrip(r *http.Request) (*http.Response, error) { if r.URL.Scheme != "https" || r.URL.Host != "api.github.com" { return nil, fmt.Errorf("unexpected GitHub endpoint") } copy := r.Clone(r.Context()) u := *r.URL copy.URL = &u copy.URL.Scheme, copy.URL.Host = t.target.Scheme, t.target.Host return t.base.RoundTrip(copy) } // Transport preserves the production URL contract and routes only that host to the fake. func (g *GitHub) Transport() http.RoundTripper { u, _ := url.Parse(g.Server.URL) return githubTransport{http.DefaultTransport, u} }