Skip to content
quarry Artifact [be2ca3f1ba]
Login

Artifact [be2ca3f1ba]

Artifact be2ca3f1bae23b7a73e1b3403571b9b902e3c49b53ddf94affa54a9ba00b5968:


package api

import (
	"context"
	"net/http"
	"net/http/httptest"
	"regexp"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

// EVERY ROUTE THAT NAMES A REPOSITORY ANSWERS AN UNREADABLE ONE AS A
// MISSING ONE.
//
// A route that told the two apart, by status or by body, lets anyone
// test whether a private repository name exists (ticket 465: mergebase
// answered 404 for one and 400 from input validation for the other).
// This walks every route with {repo} in its path, with input that would
// fail validation, and compares the answer for a repository that exists
// and is not the caller's with the answer for a name nobody holds.
func TestEveryRepoRouteAnswersAnUnreadableRepositoryAsAMissingOne(t *testing.T) {
	SetRepoKnown(func(name string) bool { return name == "secret" || name == "open" })
	defer SetRepoKnown(func(string) bool { return true })
	r := ops.NewRegistry()
	if err := RegisterAll(r, Deps{Version: "v", Repos: NewRepos(map[string]*Repo{})}); err != nil {
		t.Fatal(err)
	}
	apiToken := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			if user, _, ok := req.BasicAuth(); ok && user == "tok" {
				ctx := ops.WithUser(req.Context(), "tok")
				ctx = ops.WithToken(ctx, ops.TokenAuth{ID: "T1", Caps: func(repo string) ops.Caps {
					// A token holds what its account holds, and a stranger holds
					// nothing on a repository that is not theirs.
					if repo == "secret" {
						return oltp.CapSet("")
					}
					return oltp.CapSet("abcdefghijklmnopqrstuvwxyz0123456789")
				}})
				req = req.WithContext(ctx)
			}
			next.ServeHTTP(w, req)
		})
	}
	h, err := RouterWithCaps(r, "v",
		func(string, string) CapSet { return oltp.CapSet("") },
		// As the forge's: a name that is private is unreadable, and every
		// other name, one nobody holds included, counts as public.
		func(_ context.Context, repo string) bool { return repo != "secret" },
		func(_, user, _ string, auth ops.Auth) Decision {
			if user == "" && auth != ops.Anonymous {
				return Denied
			}
			return Allowed
		})
	if err != nil {
		t.Fatal(err)
	}
	h = apiToken(h)
	param := regexp.MustCompile(`\{[a-zA-Z]+(\.\.\.)?\}`)
	asked := func(d *ops.Descriptor, repo string, token bool) (int, string) {
		path := param.ReplaceAllStringFunc(d.Pattern, func(p string) string {
			if p == "{repo}" {
				return repo
			}
			return "abcd1234"
		})
		var body *strings.Reader
		if d.Method != "GET" && d.Method != "HEAD" {
			body = strings.NewReader("{}")
		} else {
			body = strings.NewReader("")
		}
		req := httptest.NewRequest(d.Method, path, body)
		req.Header.Set("Content-Type", "application/json")
		if token {
			req.SetBasicAuth("tok", "x")
		}
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		return w.Code, strings.ReplaceAll(w.Body.String(), repo, "<repo>")
	}
	walked := 0
	for _, d := range r.All() {
		if !strings.Contains(d.Pattern, "{repo}") {
			continue
		}
		walked++
		for _, token := range []bool{false, true} {
			who := map[bool]string{false: "no token", true: "an api token"}[token]
			sc, sb := asked(d, "secret", token)
			mc, mb := asked(d, "nope", token)
			if sc != mc || sb != mb {
				t.Errorf("FAIL: %s %s with %s: an unreadable repository answers %d %q, a missing one %d %q",
					d.Method, d.Pattern, who, sc, sb, mc, mb)
			}
		}
	}
	if walked < 100 {
		t.Errorf("FAIL: only %d routes with {repo} were walked", walked)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}