Skip to content
quarry Artifact [5d8eda93b1]
Login

Artifact [5d8eda93b1]

Artifact 5d8eda93b1c49030736bb966c1fc7661c6304fb0ec532401e6d11181bc4e596f:


package web

import (
	"net/http"
	"net/http/httptest"
	"testing"

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

// Who is asking has to reach the ops layer, or every gate that asks
// answers for a stranger.
//
// This is the line a private repository turned on: its read gate asks
// ops.User who is looking, got nothing on every page that does not
// separately gate, and returned the not-found a private repository owes
// an outsider -- to its own owner.
func TestIdentityReachesTheOpsLayer(t *testing.T) {
	for _, tc := range []struct {
		name  string
		token string
		want  string
	}{
		{"a resolved session names the reader", "good", "dan"},
		{"no session names nobody", "", ""},
	} {
		var got string
		var known bool
		h := withIdentity(fakeSessions{user: "dan"}, false, false, nil, "", "",
			http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
				got = ops.User(req.Context())
				known = true
			}))
		req := httptest.NewRequest("GET", "/r/alpha", nil)
		if tc.token != "" {
			req.AddCookie(&http.Cookie{Name: sessionCookie, Value: tc.token})
		}
		h.ServeHTTP(httptest.NewRecorder(), req)
		if !known {
			t.Fatalf("FAIL: %s: the handler never ran", tc.name)
		}
		if got != tc.want {
			t.Errorf("FAIL: %s: ops.User = %q, want %q", tc.name, got, tc.want)
			continue
		}
		t.Logf("ok: %s", tc.name)
	}
}

// Naming the reader must not name them as somebody else: a stranger
// stays a stranger rather than inheriting the last session seen.
func TestIdentityDoesNotInventAReader(t *testing.T) {
	h := withIdentity(fakeSessions{user: "dan"}, false, false, nil, "", "",
		http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			if u := ops.User(req.Context()); u != "" {
				t.Errorf("FAIL: an unauthenticated request was named %q", u)
				return
			}
			t.Log("ok: an unauthenticated request names nobody")
		}))
	h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/r/alpha", nil))
}