| 1 | package forgetest |
| 2 | |
| 3 | import ( |
| 4 | "crypto" |
| 5 | "crypto/rand" |
| 6 | "crypto/rsa" |
| 7 | "crypto/sha256" |
| 8 | "crypto/x509" |
| 9 | "encoding/base64" |
| 10 | "encoding/json" |
| 11 | "encoding/pem" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "net/url" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "testing" |
| 21 | "time" |
| 22 | ) |
| 23 | |
| 24 | // GitHub is a generated-key installation API. It has no write-token route. |
| 25 | // Tests configure fields before a request; the request ledger is synchronized. |
| 26 | type GitHub struct { |
| 27 | Server *httptest.Server |
| 28 | Key *rsa.PrivateKey |
| 29 | PEM string |
| 30 | Code, ClientSecret, WebhookSecret, Token string |
| 31 | AppID, AccountID, InstallationID int64 |
| 32 | Login, AccountType, Selection string |
| 33 | Count int |
| 34 | Suspended, Uninstalled bool |
| 35 | Now time.Time |
| 36 | FailPath string |
| 37 | FailStatus int |
| 38 | FailBody string |
| 39 | FailHeaders http.Header |
| 40 | mu sync.Mutex |
| 41 | calls map[string]int |
| 42 | converted bool |
| 43 | revoked bool |
| 44 | tokenGeneration int |
| 45 | t testing.TB |
| 46 | } |
| 47 | |
| 48 | func NewGitHub(t testing.TB) *GitHub { |
| 49 | t.Helper() |
| 50 | key, err := rsa.GenerateKey(rand.Reader, 2048) |
| 51 | if err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | 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{}} |
| 55 | g.PEM = string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})) |
| 56 | nonce := func() string { |
| 57 | b := make([]byte, 24) |
| 58 | if _, err := rand.Read(b); err != nil { |
| 59 | t.Fatal(err) |
| 60 | } |
| 61 | return base64.RawURLEncoding.EncodeToString(b) |
| 62 | } |
| 63 | g.Code, g.ClientSecret, g.WebhookSecret, g.Token = nonce(), nonce(), nonce(), "ghs_"+nonce() |
| 64 | g.Server = httptest.NewServer(http.HandlerFunc(g.serve)) |
| 65 | t.Cleanup(g.Server.Close) |
| 66 | return g |
| 67 | } |
| 68 | |
| 69 | func (g *GitHub) Calls(method, path string) int { |
| 70 | g.mu.Lock() |
| 71 | defer g.mu.Unlock() |
| 72 | return g.calls[method+" "+path] |
| 73 | } |
| 74 | |
| 75 | func (g *GitHub) permissions() map[string]string { |
| 76 | return map[string]string{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"} |
| 77 | } |
| 78 | func (g *GitHub) account() map[string]any { |
| 79 | return map[string]any{"id": g.AccountID, "login": g.Login, "type": g.AccountType} |
| 80 | } |
| 81 | func (g *GitHub) app() map[string]any { |
| 82 | return map[string]any{"id": g.AppID, "slug": "equipo-test-app", "owner": g.account(), "permissions": g.permissions(), "events": []string{}} |
| 83 | } |
| 84 | func (g *GitHub) installation() map[string]any { |
| 85 | 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} |
| 86 | if g.Suspended { |
| 87 | v["suspended_at"] = g.Now.Format(time.RFC3339) |
| 88 | } |
| 89 | return v |
| 90 | } |
| 91 | func (g *GitHub) jwt(raw string) bool { |
| 92 | bits := strings.Split(strings.TrimPrefix(raw, "Bearer "), ".") |
| 93 | if len(bits) != 3 { |
| 94 | return false |
| 95 | } |
| 96 | header, e := base64.RawURLEncoding.DecodeString(bits[0]) |
| 97 | if e != nil { |
| 98 | return false |
| 99 | } |
| 100 | var h struct{ Alg string } |
| 101 | if json.Unmarshal(header, &h) != nil || h.Alg != "RS256" { |
| 102 | return false |
| 103 | } |
| 104 | payload, e := base64.RawURLEncoding.DecodeString(bits[1]) |
| 105 | if e != nil { |
| 106 | return false |
| 107 | } |
| 108 | var v struct { |
| 109 | Iss string |
| 110 | Iat, Exp int64 |
| 111 | } |
| 112 | if json.Unmarshal(payload, &v) != nil { |
| 113 | return false |
| 114 | } |
| 115 | if v.Iss != strconv.FormatInt(g.AppID, 10) || v.Iat > g.Now.Unix() || v.Exp <= g.Now.Unix() || v.Exp-g.Now.Unix() > 600 { |
| 116 | return false |
| 117 | } |
| 118 | sig, e := base64.RawURLEncoding.DecodeString(bits[2]) |
| 119 | if e != nil { |
| 120 | return false |
| 121 | } |
| 122 | digest := sha256.Sum256([]byte(bits[0] + "." + bits[1])) |
| 123 | return rsa.VerifyPKCS1v15(&g.Key.PublicKey, crypto.SHA256, digest[:], sig) == nil |
| 124 | } |
| 125 | func (g *GitHub) serve(w http.ResponseWriter, r *http.Request) { |
| 126 | g.mu.Lock() |
| 127 | defer g.mu.Unlock() |
| 128 | g.calls[r.Method+" "+r.URL.Path]++ |
| 129 | w.Header().Set("Content-Type", "application/json") |
| 130 | if r.Header.Get("X-GitHub-Api-Version") != "2022-11-28" || r.Header.Get("Accept") != "application/vnd.github+json" || r.UserAgent() == "" { |
| 131 | w.WriteHeader(400) |
| 132 | return |
| 133 | } |
| 134 | if r.URL.Path == g.FailPath { |
| 135 | for k, v := range g.FailHeaders { |
| 136 | w.Header()[k] = v |
| 137 | } |
| 138 | w.WriteHeader(g.FailStatus) |
| 139 | _, _ = io.WriteString(w, g.FailBody) |
| 140 | return |
| 141 | } |
| 142 | answer := func(status int, v any) { w.WriteHeader(status); _ = json.NewEncoder(w).Encode(v) } |
| 143 | if r.Method == "POST" && r.URL.Path == "/app-manifests/"+g.Code+"/conversions" { |
| 144 | if g.converted || r.Header.Get("Authorization") != "" { |
| 145 | w.WriteHeader(422) |
| 146 | return |
| 147 | } |
| 148 | g.converted = true |
| 149 | v := g.app() |
| 150 | v["pem"], v["client_secret"], v["webhook_secret"] = g.PEM, g.ClientSecret, g.WebhookSecret |
| 151 | answer(201, v) |
| 152 | return |
| 153 | } |
| 154 | if strings.HasPrefix(r.URL.Path, "/app-manifests/") { |
| 155 | w.WriteHeader(404) |
| 156 | return |
| 157 | } |
| 158 | if strings.HasPrefix(r.URL.Path, "/app") && !g.jwt(r.Header.Get("Authorization")) { |
| 159 | w.WriteHeader(401) |
| 160 | return |
| 161 | } |
| 162 | switch { |
| 163 | case r.Method == "GET" && r.URL.Path == "/app": |
| 164 | answer(200, g.app()) |
| 165 | case r.Method == "GET" && r.URL.Path == "/app/installations": |
| 166 | rows := []any{} |
| 167 | if !g.Uninstalled { |
| 168 | rows = append(rows, g.installation()) |
| 169 | } |
| 170 | answer(200, rows) |
| 171 | case r.Method == "GET" && r.URL.Path == fmt.Sprintf("/app/installations/%d", g.InstallationID): |
| 172 | if g.Uninstalled { |
| 173 | w.WriteHeader(404) |
| 174 | return |
| 175 | } |
| 176 | answer(200, g.installation()) |
| 177 | case r.Method == "POST" && r.URL.Path == fmt.Sprintf("/app/installations/%d/access_tokens", g.InstallationID): |
| 178 | var body map[string]json.RawMessage |
| 179 | if json.NewDecoder(r.Body).Decode(&body) != nil || len(body) != 1 { |
| 180 | w.WriteHeader(422) |
| 181 | return |
| 182 | } |
| 183 | var permissions map[string]string |
| 184 | if json.Unmarshal(body["permissions"], &permissions) != nil || len(permissions) != 1 || permissions["metadata"] != "read" { |
| 185 | w.WriteHeader(422) |
| 186 | return |
| 187 | } |
| 188 | if g.Uninstalled || g.Suspended { |
| 189 | w.WriteHeader(403) |
| 190 | return |
| 191 | } |
| 192 | g.revoked = false |
| 193 | g.tokenGeneration++ |
| 194 | if g.tokenGeneration > 1 { |
| 195 | g.Token = "ghs_" + rand.Text() |
| 196 | } |
| 197 | answer(201, map[string]any{"token": g.Token, "expires_at": g.Now.Add(time.Hour).Format(time.RFC3339), "permissions": permissions, "repository_selection": g.Selection}) |
| 198 | case r.URL.Path == "/installation/repositories" && r.Method == "GET": |
| 199 | if g.revoked || r.Header.Get("Authorization") != "Bearer "+g.Token { |
| 200 | w.WriteHeader(401) |
| 201 | return |
| 202 | } |
| 203 | page, _ := strconv.Atoi(r.URL.Query().Get("page")) |
| 204 | if page < 1 { |
| 205 | page = 1 |
| 206 | } |
| 207 | rows := []any{} |
| 208 | for i := (page - 1) * 100; i < page*100 && i < g.Count; i++ { |
| 209 | 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}}) |
| 210 | } |
| 211 | if page*100 < g.Count { |
| 212 | w.Header().Set("Link", fmt.Sprintf(`<https://api.github.com/installation/repositories?per_page=100&page=%d>; rel="next"`, page+1)) |
| 213 | } |
| 214 | etag := fmt.Sprintf(`"inventory-%d-%d-%d"`, g.tokenGeneration, g.Count, page) |
| 215 | w.Header().Set("ETag", etag) |
| 216 | w.Header().Set("Vary", "Authorization") |
| 217 | w.Header().Set("Cache-Control", "private, max-age=60, s-maxage=60") |
| 218 | if r.Header.Get("If-None-Match") == etag { |
| 219 | w.WriteHeader(304) |
| 220 | return |
| 221 | } |
| 222 | answer(200, map[string]any{"total_count": g.Count, "repositories": rows}) |
| 223 | case r.Method == "GET" && r.URL.Path == "/repos/"+g.Login+"/probe/contents/README.md": |
| 224 | if g.revoked || r.Header.Get("Authorization") != "Bearer "+g.Token { |
| 225 | w.WriteHeader(401) |
| 226 | } else { |
| 227 | w.WriteHeader(403) |
| 228 | } |
| 229 | case r.URL.Path == "/installation/token" && r.Method == "DELETE": |
| 230 | if r.Header.Get("Authorization") != "Bearer "+g.Token { |
| 231 | w.WriteHeader(401) |
| 232 | return |
| 233 | } |
| 234 | g.revoked = true |
| 235 | w.WriteHeader(204) |
| 236 | default: |
| 237 | g.t.Error("unexpected GitHub route or verb") |
| 238 | w.WriteHeader(404) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | type githubTransport struct { |
| 243 | base http.RoundTripper |
| 244 | target *url.URL |
| 245 | } |
| 246 | |
| 247 | func (t githubTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 248 | if r.URL.Scheme != "https" || r.URL.Host != "api.github.com" { |
| 249 | return nil, fmt.Errorf("unexpected GitHub endpoint") |
| 250 | } |
| 251 | copy := r.Clone(r.Context()) |
| 252 | u := *r.URL |
| 253 | copy.URL = &u |
| 254 | copy.URL.Scheme, copy.URL.Host = t.target.Scheme, t.target.Host |
| 255 | return t.base.RoundTrip(copy) |
| 256 | } |
| 257 | |
| 258 | // Transport preserves the production URL contract and routes only that host to the fake. |
| 259 | func (g *GitHub) Transport() http.RoundTripper { |
| 260 | u, _ := url.Parse(g.Server.URL) |
| 261 | return githubTransport{http.DefaultTransport, u} |
| 262 | } |
| 263 | |