| 1 | package github |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner/forge/forgetest" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | type transportFunc func(*http.Request) (*http.Response, error) |
| 19 | |
| 20 | func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 21 | func alter(g *forgetest.GitHub, path string, change func(map[string]any)) http.RoundTripper { |
| 22 | base := g.Transport() |
| 23 | return transportFunc(func(r *http.Request) (*http.Response, error) { |
| 24 | response, err := base.RoundTrip(r) |
| 25 | if err != nil || r.URL.Path != path { |
| 26 | return response, err |
| 27 | } |
| 28 | var body map[string]any |
| 29 | err = json.NewDecoder(response.Body).Decode(&body) |
| 30 | response.Body.Close() |
| 31 | if err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | change(body) |
| 35 | raw, err := json.Marshal(body) |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | response.Body = io.NopCloser(strings.NewReader(string(raw))) |
| 40 | return response, nil |
| 41 | }) |
| 42 | } |
| 43 | func TestAppResponseGuards(t *testing.T) { |
| 44 | for _, tc := range []struct { |
| 45 | name, path string |
| 46 | change func(map[string]any) |
| 47 | stage string |
| 48 | }{ |
| 49 | {"app id", "/app", func(v map[string]any) { v["id"] = 999 }, "app"}, |
| 50 | {"account id", "/app", func(v map[string]any) { v["owner"].(map[string]any)["id"] = 999 }, "app"}, |
| 51 | {"account type", "/app", func(v map[string]any) { v["owner"].(map[string]any)["type"] = "User" }, "app"}, |
| 52 | {"app slug", "/app", func(v map[string]any) { v["slug"] = "../different" }, "app"}, |
| 53 | {"permissions", "/app", func(v map[string]any) { v["permissions"].(map[string]any)["workflows"] = "write" }, "app"}, |
| 54 | {"missing events", "/app", func(v map[string]any) { delete(v, "events") }, "app"}, |
| 55 | {"missing count", "/installation/repositories", func(v map[string]any) { delete(v, "total_count"); v["repositories"] = []any{} }, "token"}, |
| 56 | {"missing rows", "/installation/repositories", func(v map[string]any) { delete(v, "repositories"); v["total_count"] = 0 }, "token"}, |
| 57 | {"events", "/app", func(v map[string]any) { v["events"] = []string{"push"} }, "app"}, |
| 58 | {"installation id", "/app/installations/303", func(v map[string]any) { v["id"] = 999 }, "installation"}, |
| 59 | {"installation app", "/app/installations/303", func(v map[string]any) { v["app_id"] = 999 }, "installation"}, |
| 60 | {"installation account", "/app/installations/303", func(v map[string]any) { v["account"].(map[string]any)["id"] = 999 }, "installation"}, |
| 61 | {"installation type", "/app/installations/303", func(v map[string]any) { v["account"].(map[string]any)["type"] = "User" }, "installation"}, |
| 62 | {"installation permissions", "/app/installations/303", func(v map[string]any) { v["permissions"].(map[string]any)["contents"] = "read" }, "installation"}, |
| 63 | {"installation events", "/app/installations/303", func(v map[string]any) { v["events"] = []string{"push"} }, "installation"}, |
| 64 | {"selection", "/app/installations/303", func(v map[string]any) { v["repository_selection"] = "unknown" }, "installation"}, |
| 65 | {"token permissions", "/app/installations/303/access_tokens", func(v map[string]any) { v["permissions"].(map[string]any)["contents"] = "write" }, "token"}, |
| 66 | {"token missing permissions", "/app/installations/303/access_tokens", func(v map[string]any) { delete(v, "permissions") }, "token"}, |
| 67 | {"token expired", "/app/installations/303/access_tokens", func(v map[string]any) { v["expires_at"] = time.Now().Add(-time.Minute) }, "token"}, |
| 68 | {"token long expiry", "/app/installations/303/access_tokens", func(v map[string]any) { v["expires_at"] = time.Now().Add(2 * time.Hour) }, "token"}, |
| 69 | {"token selection", "/app/installations/303/access_tokens", func(v map[string]any) { v["repository_selection"] = "all" }, "token"}, |
| 70 | {"repository account", "/installation/repositories", func(v map[string]any) { |
| 71 | v["repositories"].([]any)[0].(map[string]any)["owner"].(map[string]any)["id"] = 999 |
| 72 | }, "token"}, |
| 73 | {"duplicate repository", "/installation/repositories", func(v map[string]any) { rows := v["repositories"].([]any); rows[1] = rows[0] }, "token"}, |
| 74 | {"partial inventory", "/installation/repositories", func(v map[string]any) { v["total_count"] = 3 }, "token"}, |
| 75 | } { |
| 76 | t.Run(tc.name, func(t *testing.T) { |
| 77 | g := forgetest.NewGitHub(t) |
| 78 | api := NewAPI(alter(g, tc.path, tc.change), func() time.Time { return g.Now }) |
| 79 | app, err := api.Convert(context.Background(), g.Code) |
| 80 | if err != nil { |
| 81 | t.Fatal(err) |
| 82 | } |
| 83 | switch tc.stage { |
| 84 | case "app": |
| 85 | _, err = api.Verify(context.Background(), app) |
| 86 | case "installation": |
| 87 | _, err = api.Installation(context.Background(), app, g.InstallationID) |
| 88 | case "token": |
| 89 | inst, e := api.Installation(context.Background(), app, g.InstallationID) |
| 90 | if e != nil { |
| 91 | t.Fatal(e) |
| 92 | } |
| 93 | var got Inventory |
| 94 | got, err = api.Inventory(context.Background(), app, inst) |
| 95 | if len(got.Repositories) != 0 { |
| 96 | t.Fatal("partial or unsafe inventory published") |
| 97 | } |
| 98 | } |
| 99 | if err == nil { |
| 100 | t.Fatal("unsafe API answer accepted") |
| 101 | } |
| 102 | }) |
| 103 | } |
| 104 | } |
| 105 | func TestAppRedirectAndDeadline(t *testing.T) { |
| 106 | g := forgetest.NewGitHub(t) |
| 107 | var calls int |
| 108 | base := g.Transport() |
| 109 | api := NewAPI(transportFunc(func(r *http.Request) (*http.Response, error) { |
| 110 | calls++ |
| 111 | if calls > 1 { |
| 112 | return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("{}")), Request: r}, nil |
| 113 | } |
| 114 | return &http.Response{StatusCode: 302, Header: http.Header{"Location": {"https://api.github.com/app"}}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil |
| 115 | }), nil) |
| 116 | if _, err := api.Convert(context.Background(), g.Code); err == nil || calls != 1 { |
| 117 | t.Fatal("redirect followed") |
| 118 | } |
| 119 | api = NewAPI(base, nil) |
| 120 | if api.client.Timeout <= 0 || api.client.Timeout > 10*time.Second { |
| 121 | t.Fatal("unbounded deadline") |
| 122 | } |
| 123 | ctx, cancel := context.WithCancel(context.Background()) |
| 124 | cancel() |
| 125 | if _, err := api.Convert(ctx, g.Code); err == nil { |
| 126 | t.Fatal("cancelled API call continued") |
| 127 | } |
| 128 | } |
| 129 | func TestAppTokenLifetime(t *testing.T) { |
| 130 | g := forgetest.NewGitHub(t) |
| 131 | api := NewAPI(g.Transport(), func() time.Time { return g.Now }) |
| 132 | ctx := context.Background() |
| 133 | app, e := api.Convert(ctx, g.Code) |
| 134 | if e != nil { |
| 135 | t.Fatal(e) |
| 136 | } |
| 137 | inst, e := api.Installation(ctx, app, g.InstallationID) |
| 138 | if e != nil { |
| 139 | t.Fatal(e) |
| 140 | } |
| 141 | if _, e = api.Inventory(ctx, app, inst); e != nil { |
| 142 | t.Fatal(e) |
| 143 | } |
| 144 | g.Now = g.Now.Add(time.Hour - 29*time.Second) |
| 145 | if _, e = api.Inventory(ctx, app, inst); e != nil { |
| 146 | t.Fatal(e) |
| 147 | } |
| 148 | if g.Calls("POST", fmt.Sprintf("/app/installations/%d/access_tokens", g.InstallationID)) != 2 { |
| 149 | t.Fatal("expired token reused") |
| 150 | } |
| 151 | if g.Calls("DELETE", "/installation/token") != 1 { |
| 152 | t.Fatal("old token not revoked") |
| 153 | } |
| 154 | inst.Suspended = &g.Now |
| 155 | if _, e = api.Inventory(ctx, app, inst); !errors.Is(e, ErrAccess) { |
| 156 | t.Fatal("suspended inventory admitted") |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | func TestInventoryConditionalScope(t *testing.T) { |
| 161 | g := forgetest.NewGitHub(t) |
| 162 | base := g.Transport() |
| 163 | var conditional int |
| 164 | api := NewAPI(transportFunc(func(r *http.Request) (*http.Response, error) { |
| 165 | if r.URL.Path == "/installation/repositories" && r.Header.Get("If-None-Match") != "" { |
| 166 | conditional++ |
| 167 | } |
| 168 | return base.RoundTrip(r) |
| 169 | }), func() time.Time { return g.Now }) |
| 170 | ctx := context.Background() |
| 171 | app, e := api.Convert(ctx, g.Code) |
| 172 | if e != nil { |
| 173 | t.Fatal(e) |
| 174 | } |
| 175 | inst, e := api.Installation(ctx, app, g.InstallationID) |
| 176 | if e != nil { |
| 177 | t.Fatal(e) |
| 178 | } |
| 179 | for i := 0; i < 2; i++ { |
| 180 | got, e := api.Inventory(ctx, app, inst) |
| 181 | if e != nil || got.Count != 2 { |
| 182 | t.Fatal("conditional inventory", e) |
| 183 | } |
| 184 | } |
| 185 | if conditional != 1 { |
| 186 | t.Fatal("ETag not revalidated") |
| 187 | } |
| 188 | app.generation++ |
| 189 | if _, e = api.Inventory(ctx, app, inst); e != nil { |
| 190 | t.Fatal(e) |
| 191 | } |
| 192 | if conditional != 1 { |
| 193 | t.Fatal("ETag crossed connection generation") |
| 194 | } |
| 195 | api.Forget(ctx, app.ID) |
| 196 | if _, e = api.Inventory(ctx, app, inst); e != nil { |
| 197 | t.Fatal(e) |
| 198 | } |
| 199 | if conditional != 1 { |
| 200 | t.Fatal("ETag crossed invalidation") |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func TestMetadataMemoryDeadline(t *testing.T) { |
| 205 | r := storeRig(t) |
| 206 | v := r.created(t) |
| 207 | if _, e := r.s.Check(context.Background(), r.owner, v.ID); e != nil { |
| 208 | t.Fatal(e) |
| 209 | } |
| 210 | r.advance(time.Hour - 29*time.Second) |
| 211 | r.s.Maintain = func(tx *gorm.DB) error { var owners []testOwner; return tx.Find(&owners).Error } |
| 212 | if e := r.s.Sweep(context.Background()); e != nil { |
| 213 | t.Fatal(e) |
| 214 | } |
| 215 | r.s.API.mu.Lock() |
| 216 | n := len(r.s.API.tokens) |
| 217 | r.s.API.mu.Unlock() |
| 218 | if n != 0 { |
| 219 | t.Fatal("idle expired token retained in instance memory") |
| 220 | } |
| 221 | if r.g.Calls("DELETE", "/installation/token") != 1 { |
| 222 | t.Fatal("idle expiring token not revoked") |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | func TestMetadataCannotReadContentsAndRevocation(t *testing.T) { |
| 227 | g := forgetest.NewGitHub(t) |
| 228 | api := NewAPI(g.Transport(), func() time.Time { return g.Now }) |
| 229 | ctx := context.Background() |
| 230 | app, e := api.Convert(ctx, g.Code) |
| 231 | if e != nil { |
| 232 | t.Fatal(e) |
| 233 | } |
| 234 | inst, e := api.Installation(ctx, app, g.InstallationID) |
| 235 | if e != nil { |
| 236 | t.Fatal(e) |
| 237 | } |
| 238 | token, e := api.metadata(ctx, app, inst) |
| 239 | if e != nil { |
| 240 | t.Fatal(e) |
| 241 | } |
| 242 | if _, e = api.request(ctx, "GET", "/repos/"+g.Login+"/probe/contents/README.md", token, nil, nil); !errors.Is(e, ErrAccess) { |
| 243 | t.Fatal("metadata token read contents") |
| 244 | } |
| 245 | api.Forget(ctx, app.ID) |
| 246 | _, e = api.request(ctx, "GET", "/installation/repositories?per_page=100&page=1", token, nil, nil) |
| 247 | var refusal *APIError |
| 248 | if !errors.As(e, &refusal) || refusal.Status != 401 { |
| 249 | t.Fatal("revoked token survived") |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | type countingBody struct { |
| 254 | reader *strings.Reader |
| 255 | read int |
| 256 | } |
| 257 | |
| 258 | func (b *countingBody) Read(p []byte) (int, error) { |
| 259 | n, e := b.reader.Read(p) |
| 260 | b.read += n |
| 261 | return n, e |
| 262 | } |
| 263 | func (*countingBody) Close() error { return nil } |
| 264 | func TestAppBodyBound(t *testing.T) { |
| 265 | for _, size := range []int{maxAnswer + 1, maxAnswer + 4096} { |
| 266 | t.Run(fmt.Sprint(size), func(t *testing.T) { |
| 267 | body := &countingBody{reader: strings.NewReader(`{"ok":true}` + strings.Repeat(" ", size-len(`{"ok":true}`)))} |
| 268 | api := NewAPI(transportFunc(func(req *http.Request) (*http.Response, error) { |
| 269 | return &http.Response{StatusCode: 200, Header: http.Header{}, Body: body, Request: req}, nil |
| 270 | }), nil) |
| 271 | var out map[string]any |
| 272 | if _, e := api.request(context.Background(), "GET", "/app", "", nil, &out); e == nil { |
| 273 | t.Fatal("oversized valid JSON accepted") |
| 274 | } |
| 275 | if body.read > maxAnswer+1 { |
| 276 | t.Fatal("API read beyond bounded body") |
| 277 | } |
| 278 | }) |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | func TestAppCustomDefaultTransport(t *testing.T) { |
| 283 | g := forgetest.NewGitHub(t) |
| 284 | before := http.DefaultTransport |
| 285 | http.DefaultTransport = g.Transport() |
| 286 | defer func() { http.DefaultTransport = before }() |
| 287 | api := NewAPI(nil, func() time.Time { return g.Now }) |
| 288 | if _, e := api.Convert(context.Background(), g.Code); e != nil { |
| 289 | t.Fatal("custom default transport ignored", e) |
| 290 | } |
| 291 | } |
| 292 | |