// Package githubtest serves a fake GitHub that holds the Apps, // installations, and repositories a test puts in it. It answers the // requests package github sends and no others, and it checks each // statement an App signs against that App's public key, as GitHub does. package githubtest import ( "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" ) // Fake is GitHub's state. type Fake struct { // URL is the address of the fake's API. URL string mu sync.Mutex apps map[string]*app forks map[string]bool issued []*Issued sequence int } type app struct { slug string key *rsa.PublicKey permissions map[string]string installations map[string]int } // Issued is one installation token the fake gave. type Issued struct { Token string Repository string Permissions map[string]string Revoked bool } // Start serves a Fake for the length of the test. func Start(t *testing.T) *Fake { t.Helper() f := &Fake{apps: map[string]*app{}, forks: map[string]bool{}} server := httptest.NewServer(f) t.Cleanup(server.Close) f.URL = server.URL return f } var testKey = sync.OnceValue(func() *rsa.PrivateKey { key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { panic(err) } return key }) // Key answers the one private key that every App of a test shares, so // the tests make one key and not one for each App. func Key() *rsa.PrivateKey { return testKey() } // KeyPEM answers Key in the PEM that GitHub gives for an App's key. func KeyPEM() []byte { return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(Key())}) } var otherKey = sync.OnceValue(func() *rsa.PrivateKey { key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { panic(err) } return key }) // OtherKeyPEM answers a private key that no App of the fake signs with. func OtherKeyPEM() []byte { return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(otherKey())}) } // AddApp registers an App that signs with Key and holds the permissions. func (f *Fake) AddApp(clientID, slug string, permissions map[string]string) { f.mu.Lock() defer f.mu.Unlock() f.apps[clientID] = &app{slug: slug, key: &Key().PublicKey, permissions: permissions, installations: map[string]int{}} } // Install installs an App on every repository of an owner. func (f *Fake) Install(clientID, owner string) { f.mu.Lock() defer f.mu.Unlock() f.sequence++ f.apps[clientID].installations[strings.ToLower(owner)] = f.sequence } // AddRepository makes a repository exist, and says whether it is a fork. func (f *Fake) AddRepository(owner, name string, fork bool) { f.mu.Lock() defer f.mu.Unlock() f.forks[strings.ToLower(owner+"/"+name)] = fork } // Tokens answers every token the fake gave, in the order it gave them. func (f *Fake) Tokens() []Issued { f.mu.Lock() defer f.mu.Unlock() tokens := make([]Issued, len(f.issued)) for i, issued := range f.issued { tokens[i] = *issued } return tokens } func (f *Fake) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() mux := http.NewServeMux() mux.HandleFunc("GET /app", f.asApp(func(w http.ResponseWriter, _ *http.Request, a *app) { answer(w, http.StatusOK, map[string]any{"slug": a.slug}) })) mux.HandleFunc("GET /repos/{owner}/{repo}/installation", f.asApp(func(w http.ResponseWriter, r *http.Request, a *app) { repository := strings.ToLower(r.PathValue("owner") + "/" + r.PathValue("repo")) id, installed := a.installations[strings.ToLower(r.PathValue("owner"))] if _, exists := f.forks[repository]; !installed || !exists { answer(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) return } answer(w, http.StatusOK, map[string]any{"id": id}) })) mux.HandleFunc("POST /app/installations/{id}/access_tokens", f.asApp(f.issue)) mux.HandleFunc("GET /repos/{owner}/{repo}", f.asToken(func(w http.ResponseWriter, r *http.Request, issued *Issued) { repository := strings.ToLower(r.PathValue("owner") + "/" + r.PathValue("repo")) if issued.Repository != repository { answer(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) return } answer(w, http.StatusOK, map[string]any{"full_name": repository, "fork": f.forks[repository]}) })) mux.HandleFunc("DELETE /installation/token", f.asToken(func(w http.ResponseWriter, _ *http.Request, issued *Issued) { issued.Revoked = true w.WriteHeader(http.StatusNoContent) })) mux.ServeHTTP(w, r) } func (f *Fake) issue(w http.ResponseWriter, r *http.Request, a *app) { var asked struct { Repositories []string `json:"repositories"` Permissions map[string]string `json:"permissions"` } json.NewDecoder(r.Body).Decode(&asked) owner := "" for name, id := range a.installations { if fmt.Sprint(id) == r.PathValue("id") { owner = name } } if owner == "" || len(asked.Repositories) != 1 { answer(w, http.StatusNotFound, map[string]any{"message": "Not Found"}) return } for name, level := range asked.Permissions { if held := a.permissions[name]; held == "" || (level == "write" && held != "write") { answer(w, http.StatusUnprocessableEntity, map[string]any{"message": "The permissions requested are not granted to this installation."}) return } } f.sequence++ issued := &Issued{ Token: fmt.Sprintf("ghs_fake%d", f.sequence), Repository: owner + "/" + strings.ToLower(asked.Repositories[0]), Permissions: asked.Permissions, } f.issued = append(f.issued, issued) answer(w, http.StatusCreated, map[string]any{"token": issued.Token, "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339)}) } // asApp admits a request that carries a statement signed by a // registered App: a JWT whose issuer is the App's client ID, signed with // its key, and not expired. func (f *Fake) asApp(next func(http.ResponseWriter, *http.Request, *app)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { parts := strings.Split(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), ".") if len(parts) != 3 { unauthorized(w) return } payload, _ := base64.RawURLEncoding.DecodeString(parts[1]) var claims struct { Issuer string `json:"iss"` Expires int64 `json:"exp"` } json.Unmarshal(payload, &claims) a, ok := f.apps[claims.Issuer] signature, _ := base64.RawURLEncoding.DecodeString(parts[2]) digest := sha256.Sum256([]byte(parts[0] + "." + parts[1])) if !ok { answer(w, http.StatusNotFound, map[string]any{"message": "Integration not found"}) return } if time.Now().Unix() > claims.Expires || rsa.VerifyPKCS1v15(a.key, crypto.SHA256, digest[:], signature) != nil { unauthorized(w) return } next(w, r, a) } } // asToken admits a request that carries a token the fake gave and has // not revoked. func (f *Fake) asToken(next func(http.ResponseWriter, *http.Request, *Issued)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") for _, issued := range f.issued { if issued.Token == token && !issued.Revoked { next(w, r, issued) return } } unauthorized(w) } } func unauthorized(w http.ResponseWriter) { answer(w, http.StatusUnauthorized, map[string]any{"message": "Bad credentials"}) } func answer(w http.ResponseWriter, status int, body any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(body) }