Skip to content
quarry Artifact [86211ca1ed]
Login

Artifact [86211ca1ed]

Artifact 86211ca1ed33b058b2f04c6f7dd1f1f947ba81cb2ebccd57a1dda51ccd92e238:


package api

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"reflect"
	"testing"

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

// endRig is a start rig whose registry reaches the token store, with a
// login token made for each name given.
type endRig struct {
	*startRig
	reg    *ops.Registry
	values map[string]string
}

func newEndRig(t *testing.T, labels ...string) *endRig {
	t.Helper()
	g := newStartRig(t)
	d := g.deps
	d.SyncTokens = g.db
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	e := &endRig{startRig: g, reg: r, values: map[string]string{}}
	for _, l := range labels {
		_, e.values[l] = g.loggedIn("dmestas", l)
	}
	return e
}

func (e *endRig) live(label string) bool {
	_, ok := e.db.ResolveToken("dmestas", e.values[label], "api")
	return ok
}

// as is the context a request on the token labelled label arrives in.
func (e *endRig) as(label string) (tok oltp.Token, ctx ops.TokenAuth) {
	tok, ok := e.db.ResolveToken("dmestas", e.values[label], "api")
	if !ok {
		e.t.Fatalf("FAIL: no live token %q", label)
	}
	return tok, ops.TokenAuth{ID: tok.ID, Name: tok.Name, Login: tok.Has("login"),
		Caps: func(repo string) ops.Caps { return e.db.TokenCaps(tok, repo) }, Reaches: tok.Reaches}
}

// A login token ends itself, and only itself: the machine's other
// token keeps working.
func TestALoginTokenEndsOnlyItself(t *testing.T) {
	e := newEndRig(t, "mac", "pi")
	_, ta := e.as("mac")
	ctx := ops.WithToken(ops.WithUser(t.Context(), "dmestas"), ta)
	if _, err := e.reg.Invoke(ctx, "me.token.end", struct{}{}); err != nil {
		t.Fatalf("FAIL: a login token could not end itself: %v", err)
	}
	if e.live("mac") {
		t.Errorf("FAIL: the token still resolves after ending itself")
	}
	if !e.live("pi") {
		t.Errorf("FAIL: ending one token ended another")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The op takes no id, so there is no way to name another token, and the
// gate that refuses a login token its credentials still refuses the rest.
func TestTokenEndNamesNoTokenAndTheHardStopStillHoldsForTheRest(t *testing.T) {
	e := newEndRig(t, "mac", "pi")
	desc, ok := e.reg.Lookup("me.token.end")
	if !ok {
		t.Fatal("FAIL: no me.token.end op")
	}
	if n := reflect.ValueOf(desc.NewIn()).Elem().NumField(); n != 0 {
		t.Errorf("FAIL: me.token.end takes %d input fields, it takes none", n)
	}
	_, ta := e.as("mac")
	ctx := ops.WithToken(ops.WithUser(t.Context(), "dmestas"), ta)
	for _, op := range []string{"me.sync.token", "me.sync.token.list", "me.sync.token.revoke"} {
		d, _ := e.reg.Lookup(op)
		_, err := e.reg.Invoke(ctx, op, reflect.ValueOf(d.NewIn()).Elem().Interface())
		if err == nil {
			t.Errorf("FAIL: a login token was let into %s", op)
		}
	}
	if !e.live("pi") || !e.live("mac") {
		t.Errorf("FAIL: a refused call ended a token")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The person signed in with a password has no token to end.
func TestTokenEndNeedsAToken(t *testing.T) {
	e := newEndRig(t, "mac")
	if _, err := e.reg.Invoke(asUser("dmestas"), "me.token.end", struct{}{}); err == nil {
		t.Errorf("FAIL: a call with no token ended something")
	}
	if !e.live("mac") {
		t.Errorf("FAIL: the token was ended by a call that was not on it")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Ending is a revoke as the tokens list's: the row is marked, not gone,
// and it is out of the list of live tokens.
func TestTokenEndRevokesLikeTheListDoes(t *testing.T) {
	e := newEndRig(t, "mac")
	tok, ta := e.as("mac")
	ctx := ops.WithToken(ops.WithUser(t.Context(), "dmestas"), ta)
	if _, err := e.reg.Invoke(ctx, "me.token.end", struct{}{}); err != nil {
		t.Fatal(err)
	}
	toks, err := e.db.Tokens("dmestas")
	if err != nil {
		t.Fatal(err)
	}
	found := false
	for _, r := range toks {
		if r.ID == tok.ID {
			found = true
			if r.Revoked == "" {
				t.Errorf("FAIL: the row is not marked revoked")
			}
		}
	}
	if !found {
		t.Errorf("FAIL: the revoked row is gone from the list")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Over HTTP: the route ends the caller's token, and the next call on it
// is refused 401 with a next that names the login command.
func TestTokenEndOverHTTPThenTheTokenIsRefusedWithANext(t *testing.T) {
	e := newEndRig(t, "mac")
	_, ta := e.as("mac")
	verify := func(_, user, pass string, _ ops.Auth) Decision {
		if _, ok := e.db.ResolveToken(user, pass, "api"); ok {
			return Allowed
		}
		return Denied
	}
	h, err := RouterWithGates(e.reg, "v", nil, nil, nil, verify)
	if err != nil {
		t.Fatal(err)
	}
	// What the token door does: a request with the token's context.
	call := func() *httptest.ResponseRecorder {
		req := httptest.NewRequest("POST", "/api/v1/me/token/end", nil)
		req.SetBasicAuth("dmestas", e.values["mac"])
		req = req.WithContext(ops.WithToken(req.Context(), ta))
		w := httptest.NewRecorder()
		h.ServeHTTP(w, req)
		return w
	}
	if w := call(); w.Code != http.StatusOK {
		t.Fatalf("FAIL: ending the token answered %d %s", w.Code, w.Body.String())
	}
	w := call()
	if w.Code != http.StatusUnauthorized {
		t.Fatalf("FAIL: the ended token answered %d", w.Code)
	}
	var body struct {
		Code string `json:"code"`
		Next struct {
			Cmd string `json:"cmd"`
		} `json:"next"`
	}
	if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
		t.Fatal(err)
	}
	if body.Code != "no_login" || body.Next.Cmd != "quarry auth login" {
		t.Errorf("FAIL: refusal %s", w.Body.String())
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// RFC 0032's table and the code's say the same thing: the first row's
// sentence carries the exception.
func TestTheCredentialsStopNamesTheException(t *testing.T) {
	last := hardStopList()[len(hardStopList())-1]
	if last != "manage your sign-in and credentials, except to end this token" {
		t.Errorf("FAIL: the stop says %q", last)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A login token limited to named repositories can still end itself: the
// op is about the caller's own record, not a repository.
func TestARepoLimitedLoginTokenEndsItself(t *testing.T) {
	e := newEndRig(t, "mac")
	_, ta := e.as("mac")
	ta.Limited = true
	ta.Reaches = func(repo string) bool { return repo == "suit" }
	ctx := ops.WithToken(ops.WithUser(t.Context(), "dmestas"), ta)
	if _, err := e.reg.Invoke(ctx, "me.token.end", struct{}{}); err != nil {
		t.Fatalf("FAIL: a limited login token could not end itself: %v", err)
	}
	if e.live("mac") {
		t.Errorf("FAIL: the token still resolves")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Every denied caller gets the one body, from the router and from the
// upload door alike, so it says nothing about which cause it was.
func TestTheDeniedBodyIsTheSameAtTheRouterAndTheUploadDoor(t *testing.T) {
	w1, w2 := httptest.NewRecorder(), httptest.NewRecorder()
	writeDenied(w1)
	e := newEndRig(t)
	h := UploadReceiver(e.deps, e.reg, func(string, string, string, ops.Auth) Decision { return Denied }, nil)
	req := httptest.NewRequest("POST", "/x", nil)
	req.SetPathValue("repo", "suit")
	req.SetPathValue("target", "t")
	h.ServeHTTP(w2, req)
	if w1.Code != 401 || w2.Code != 401 || w1.Body.String() != w2.Body.String() {
		t.Errorf("FAIL: router %d %q, upload door %d %q", w1.Code, w1.Body.String(), w2.Code, w2.Body.String())
	}
	var body struct {
		Code string `json:"code"`
		Next struct {
			Say, Cmd string
		} `json:"next"`
	}
	if err := json.Unmarshal(w2.Body.Bytes(), &body); err != nil || body.Code != "no_login" || body.Next.Cmd != "quarry auth login" || body.Next.Say == "" {
		t.Errorf("FAIL: %s", w2.Body.String())
	}
	if !t.Failed() {
		t.Log("ok")
	}
}