Skip to content
quarry Artifact [c0315e54d0]
Login

Artifact [c0315e54d0]

Artifact c0315e54d07b1efc25438f9eb792cdf378e648c4aff84a3bb0cbc339ee94768b:


package web

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

// A login start is a machine asking to log in as the person: its claim
// page says so with hooks, offers an optional limit and no name or role.
func TestTheClaimPageOfALoginIsAMachineActingAsThePerson(t *testing.T) {
	f := newClaimForge(t)
	f.kind = "login"
	body := f.do("POST", "/setup", url.Values{"code": {"ABCD-EFGH"}}, true).Body.String()
	if v, ok := hookAttr(t, body, "setup-claim", "data-kind"); !ok || v != "login" {
		t.Fatalf("FAIL: data-kind %q (present %v)", v, ok)
	}
	if v, _ := hookAttr(t, body, "setup-claim-account", "data-account"); v != "jva" {
		t.Errorf("FAIL: the person it acts as is %q", v)
	}
	if v, _ := hookAttr(t, body, "setup-claim-agent", "data-agent"); v != "e-desktop" {
		t.Errorf("FAIL: the machine is %q", v)
	}
	for _, hook := range []string{"setup-claim-gives", "setup-claim-from", "setup-claim-warn", "setup-claim-discard", "setup-claim-approve", "setup-claim-repos",
		"setup-claim-reach", "setup-claim-expires", "setup-claim-collector", "setup-claim-lapse"} {
		if !hasHook(body, hook) {
			t.Errorf("FAIL: the page has no %s", hook)
		}
	}
	for _, hook := range []string{"setup-claim-role", "setup-claim-rename", "setup-claim-new", "setup-claim-kind", "setup-claim-continue", "setup-claim-code"} {
		if hasHook(body, hook) {
			t.Errorf("FAIL: a login page has %s", hook)
		}
	}
	if v, _ := hookAttr(t, body, "setup-claim-from", "data-match"); v != "true" {
		t.Errorf("FAIL: match %q", v)
	}
	// The repository limit is folded away and nothing is ticked.
	if !hasHook(body, "setup-claim-limit") || strings.Contains(body, `data-hook="setup-claim-repo" checked`) || strings.Contains(body, `data-hook="setup-claim-limit" open`) {
		t.Errorf("FAIL: the limit is not a collapsed, unticked choice")
	}
	// With no repository to limit to, the page still continues.
	f.repos = nil
	body = f.do("POST", "/setup", url.Values{"code": {"ABCD-EFGH"}}, true).Body.String()
	if hasHook(body, "setup-claim-repos") || !hasHook(body, "setup-claim-approve") || hasHook(body, "setup-claim-empty") {
		t.Errorf("FAIL: a login with no repositories to pick")
	}
	// Approve is one press: it claims with the optional picks and answers
	// the request it filed, as the person.
	f.repos = repoRows("ctx", "suit")
	rec := f.do("POST", "/setup/claim", url.Values{"code": {"ABCD-EFGH"}, "do": {"approve"}, "repos": {"suit"}}, true)
	if rec.Code != 303 || rec.Header().Get("Location") != "/me/requests/req123" {
		t.Errorf("FAIL: approve answered %d to %q", rec.Code, rec.Header().Get("Location"))
	}
	if len(f.claimed) != 1 || f.claimed[0].Repos != "suit" || f.claimed[0].Role != "" {
		t.Errorf("FAIL: the claim sent %+v", f.claimed)
	}
	if len(f.decided) != 1 || f.decided[0].ID != "req123" || !f.decided[0].Approve {
		t.Errorf("FAIL: the decision: %+v", f.decided)
	}
	// Deny throws the start away and decides nothing.
	if rec := f.do("POST", "/setup/claim", url.Values{"code": {"ABCD-EFGH"}, "do": {"discard"}}, true); rec.Code != 303 || f.discarded != 1 || len(f.decided) != 1 {
		t.Errorf("FAIL: deny answered %d, discarded %d, decided %d", rec.Code, f.discarded, len(f.decided))
	}
	// A login claimed any other way is refused: it would skip the typed name.
	if rec := f.do("POST", "/setup/claim", url.Values{"code": {"ABCD-EFGH"}, "do": {"continue"}, "repos": {"suit"}}, true); rec.Code != http.StatusBadRequest || len(f.claimed) != 1 {
		t.Errorf("FAIL: a login claimed with continue answered %d, claimed %d", rec.Code, len(f.claimed))
	}
	// A kind that is not a login never decides for the person.
	f.kind = "read"
	f.do("POST", "/setup/claim", url.Values{"code": {"ABCD-EFGH"}, "do": {"approve"}, "repos": {"suit"}}, true)
	if len(f.decided) != 1 {
		t.Errorf("FAIL: a read client's claim was decided for the person")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The approval page's lines are the stored record's: the sentence, the
// machine, the person, the scopes, no ceiling, no named repository and
// the network.
func TestTheApprovalPageOfALoginSaysWhatItGrantsFromTheRecord(t *testing.T) {
	code := "3f9a81c207de" + strings.Repeat("0", 52)
	sentence := "This machine (pi-c) gets a token that acts as you, jva."
	page := renderSetup(t, meSignOff{ID: "abc", Agent: "client of jva", Summary: "Log in pi-c as you", State: "pending",
		Requested: "2026-11-13T10:00:00Z", Pickup: code,
		Setup: &meSetupView{Kind: "login", Agent: "pi-c", Label: "pi-c", Account: "jva", Gives: sentence, Address: "203.0.113.5",
			Scopes: []string{"api", "sync", "login"}, TokenRepos: []string{}, Pickup: code}})
	for _, c := range []struct{ hook, attr, want string }{
		{"setup", "data-kind", "login"},
		{"login-machine", "data-label", "pi-c"},
		{"login-account", "data-account", "jva"},
		{"setup-scope", "data-scopes", "api,sync,login"},
		{"setup-reach", "data-repos", ""},
		{"setup-expires", "data-days", "0"},
		{"setup-collector", "data-pickup", code[:12]},
		{"login-from", "data-address", "203.0.113.5"},
		{"login-from", "data-match", "false"},
		{"login-elsewhere", "data-match", "false"},
	} {
		if got, ok := hookAttr(t, page, c.hook, c.attr); !ok || got != c.want {
			t.Errorf("FAIL: %s %s is %q (present %v), want %q", c.hook, c.attr, got, ok, c.want)
		}
	}
	if !strings.Contains(page, sentence) || !hasHook(page, "login-gives") {
		t.Errorf("FAIL: the page does not carry the stored sentence")
	}
	for _, hook := range []string{"setup-agent", "setup-role", "setup-repos", "setup-ceiling"} {
		if hasHook(page, hook) {
			t.Errorf("FAIL: a login page draws %s", hook)
		}
	}
	if strings.Index(page, `data-hook="login-gives"`) > strings.Index(page, `data-hook="signoff-approve"`) {
		t.Errorf("FAIL: the sentence comes after the buttons")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A machine on another network is approved by typing its name: the page
// asks for it and the server refuses an approval without it.
func TestAMachineOnAnotherNetworkIsApprovedByTypingItsName(t *testing.T) {
	f := newClaimForge(t)
	f.kind = "login"
	// The same network: one tap, no field.
	body := f.do("POST", "/setup", url.Values{"code": {"ABCD-EFGH"}}, true).Body.String()
	if hasHook(body, "setup-claim-confirm") {
		t.Errorf("FAIL: a machine on this network asks for its name")
	}
	if v, _ := hookAttr(t, body, "setup-claim-approve", "data-confirm-needed"); v != "false" {
		t.Errorf("FAIL: same network: data-confirm-needed %q", v)
	}
	f.addr = "203.0.113.5"
	body = f.do("POST", "/setup", url.Values{"code": {"ABCD-EFGH"}}, true).Body.String()
	if !hasHook(body, "setup-claim-confirm") {
		t.Fatalf("FAIL: a machine on another network has no field for its name")
	}
	if v, _ := hookAttr(t, body, "setup-claim-approve", "data-confirm-needed"); v != "true" || !strings.Contains(body, `data-hook="setup-claim-approve" disabled`) {
		t.Errorf("FAIL: the approve button is not held until the name is typed (%q)", v)
	}
	for what, confirm := range map[string]string{"nothing typed": "", "another name": "other-machine"} {
		rec := f.do("POST", "/setup/claim", url.Values{"code": {"ABCD-EFGH"}, "do": {"approve"}, "confirm": {confirm}}, true)
		if rec.Code != http.StatusBadRequest || len(f.claimed) != 0 || len(f.decided) != 0 || !hasHook(rec.Body.String(), "setup-claim-confirm") {
			t.Errorf("FAIL: %s answered %d; claimed %d, decided %d", what, rec.Code, len(f.claimed), len(f.decided))
		}
	}
	rec := f.do("POST", "/setup/claim", url.Values{"code": {"ABCD-EFGH"}, "do": {"approve"}, "confirm": {"e-desktop"}}, true)
	if rec.Code != http.StatusSeeOther || len(f.claimed) != 1 || len(f.decided) != 1 || !f.decided[0].Approve || f.decided[0].Confirm != "e-desktop" {
		t.Errorf("FAIL: the typed name answered %d; claimed %d, decided %v", rec.Code, len(f.claimed), f.decided)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A post a browser says came from another site is refused before anything
// is looked at or claimed.
func TestACrossOriginPostToTheClaimIsRefused(t *testing.T) {
	f := newClaimForge(t)
	f.kind = "login"
	post := func(path string, h map[string]string) int {
		req := httptest.NewRequest("POST", path, strings.NewReader(url.Values{"code": {"ABCD-EFGH"}, "do": {"approve"}}.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.RemoteAddr = "198.51.100.4:1234"
		req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
		for k, v := range h {
			req.Header.Set(k, v)
		}
		rec := httptest.NewRecorder()
		f.h.ServeHTTP(rec, req)
		return rec.Code
	}
	for _, path := range []string{"/setup/claim", "/setup"} {
		for what, h := range map[string]map[string]string{
			"Sec-Fetch-Site cross-site": {"Sec-Fetch-Site": "cross-site"},
			"Sec-Fetch-Site same-site":  {"Sec-Fetch-Site": "same-site"},
			"a foreign Origin":          {"Origin": "https://evil.example"},
		} {
			if code := post(path, h); code != http.StatusForbidden {
				t.Errorf("FAIL: %s %s answered %d, want 403", path, what, code)
			}
		}
	}
	if len(f.claimed) != 0 || len(f.decided) != 0 {
		t.Errorf("FAIL: a cross-origin post claimed %d and decided %d", len(f.claimed), len(f.decided))
	}
	if code := post("/setup/claim", map[string]string{"Sec-Fetch-Site": "same-origin"}); code != http.StatusSeeOther || len(f.decided) != 1 {
		t.Errorf("FAIL: a same-origin post answered %d, decided %d", code, len(f.decided))
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// An approval that does not go through is said on the page, and the
// request it filed is withdrawn so nothing is left waiting.
func TestAFailedOneTapApprovalIsShownAndWithdrawn(t *testing.T) {
	f := newClaimForge(t)
	f.kind = "login"
	f.failDecide = true
	rec := f.do("POST", "/setup/claim", url.Values{"code": {"ABCD-EFGH"}, "do": {"approve"}}, true)
	if rec.Code == http.StatusSeeOther || !hasHook(rec.Body.String(), "setup-failed") {
		t.Errorf("FAIL: a failed approval answered %d without saying so", rec.Code)
	}
	if len(f.decided) != 2 || !f.decided[0].Approve || f.decided[1].Approve || f.decided[1].ID != "req123" {
		t.Errorf("FAIL: the request was not withdrawn: %+v", f.decided)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The request's own page asks for the machine's name too when the login
// came from another network.
func TestTheRequestPageOfAFarLoginAsksForTheName(t *testing.T) {
	mk := func(match bool) string {
		return renderSetup(t, meSignOff{ID: "abc", Agent: "client of jva", State: "pending", Requested: "2026-11-13T10:00:00Z",
			Setup: &meSetupView{Kind: "login", Label: "pi-c", Account: "jva", Address: "203.0.113.5", Match: match, Scopes: []string{"api", "sync", "login"}}})
	}
	far := mk(false)
	if !strings.Contains(far, `id="approve-abc"`) || !strings.Contains(far, `form="approve-abc"`) || strings.Index(far, `data-hook="signoff-confirm"`) > strings.Index(far, `data-hook="signoff-deny"`) {
		t.Errorf("FAIL: the name field is not above the buttons and tied to the approve form")
	}
	if !hasHook(far, "signoff-confirm") || hasHook(mk(true), "signoff-confirm") {
		t.Errorf("FAIL: the typed-name field is not exactly for a login from another network")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}