package api
import (
"context"
"encoding/json"
"errors"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// "quarry login": a machine logs in as the person who approves it. The
// start is a setup start of kind login; approval mints one token on the
// claiming person's own account and nothing else.
func loginBody(label, pickup string) string {
return `{"kind":"login","label":` + jsonString(label) + `,"pickup":"` + pickup + `"}`
}
func jsonString(s string) string {
b, _ := json.Marshal(s)
return string(b)
}
// beginLogin starts a login and returns its code and the key that
// collects it.
func (g *startRig) beginLogin(label string) (code, key string) {
g.t.Helper()
key, pickup := newPickupKey(g.t)
status, body, _ := g.start(loginBody(label, pickup), "")
var out setupStartOut
if err := json.Unmarshal([]byte(body), &out); err != nil || status != 200 || out.Code == "" {
g.t.Fatalf("FAIL: a login start answered %d %s", status, body)
}
return out.Code, key
}
func (g *startRig) claimLogin(who, code, repos string) (string, error) {
out, err := g.r.Invoke(asUser(who), "setup.start.claim", setupClaimIn{Code: code, Repos: repos})
if err != nil {
return "", err
}
return out.(setupClaimOut).Request, nil
}
// loggedIn runs the whole flow for who and returns the request id, the
// key and the token value collected.
func (g *startRig) loggedIn(who, label string) (id, value string) {
g.t.Helper()
code, key := g.beginLogin(label)
id, err := g.claimLogin(who, code, "")
if err != nil {
g.t.Fatalf("FAIL: claiming: %v", err)
}
if err := g.decideLogin(who, id, label); err != nil {
g.t.Fatalf("FAIL: approving: %v", err)
}
st, body := g.collectNow(key)
var got struct {
Op string
Secret struct{ Value string }
}
if err := json.Unmarshal([]byte(body), &got); st != 200 || err != nil || got.Op != loginOp || got.Secret.Value == "" {
g.t.Fatalf("FAIL: collecting: %d %v", st, err)
}
return id, got.Secret.Value
}
// decideLogin approves a login the way a person who typed the machine's name
// does, from no particular network.
func (g *startRig) decideLogin(person, id, label string) error {
g.t.Helper()
_, err := g.r.Invoke(asUser(person), "signoff.decide", signOffDecideIn{ID: id, Approve: true, Confirm: label})
return err
}
func accountCount(g *startRig) int {
accts, _ := g.db.Accounts()
return len(accts)
}
// The whole flow: start, claim, approve, collect gives a token on the
// claiming person's own account, with their own letters.
func TestLoginStartClaimApproveCollectGivesATokenAsThePerson(t *testing.T) {
g := newStartRig(t)
before := accountCount(g)
id, value := g.loggedIn("jva", "mac-mini, pi-c")
if accountCount(g) != before {
t.Errorf("FAIL: a login made an account")
}
tok, ok := g.db.ResolveToken("jva", value, "api")
if !ok || tok.Account != "jva" {
t.Fatalf("FAIL: the collected value is not a token of jva: %+v", tok)
}
if _, ok := g.db.ResolveToken("jva", value, "sync"); !ok {
t.Errorf("FAIL: the token has no sync scope")
}
if tok.Ceiling != "" || len(tok.Repos) != 0 || tok.Expires != "" || tok.Name != "mac-mini, pi-c" {
t.Errorf("FAIL: the token is not the person's own, unlimited, labelled, undated: %+v", tok)
}
for _, repo := range []string{"suit", "ctx", "secret"} {
if got, want := g.db.TokenCaps(tok, repo), g.db.EffectiveCaps("jva", repo); got != want {
t.Errorf("FAIL: on %s the token holds %q, the person %q", repo, got, want)
}
}
if grants, _ := g.db.GrantsFor("jva"); len(grants) != 0 {
t.Errorf("FAIL: a login granted jva something: %v", grants)
}
row, _, _ := g.db.SignOffByID(id)
if row.Agent != clientAsker("jva") || row.Owner != "jva" || row.Op != loginOp {
t.Errorf("FAIL: the request: %+v", row)
}
if st, _ := g.collectNow(wrongKey(t)); st == 200 {
t.Errorf("FAIL: a collect with another key succeeded")
}
if !t.Failed() {
t.Log("ok")
}
}
func wrongKey(t *testing.T) string {
t.Helper()
k, _ := newPickupKey(t)
return k
}
// postTo sends body to path as ctx's caller, asking as an agent would.
func (g *setupRig) postTo(ctx context.Context, path, body string) (int, string) {
g.t.Helper()
req := httptest.NewRequest("POST", path, strings.NewReader(body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Quarry-Ask", "let me act as you")
w := httptest.NewRecorder()
g.h.ServeHTTP(w, req)
return w.Code, w.Body.String()
}
// The page's lines come from the stored request: the label, the person,
// the scopes and the reach, nothing more.
func TestLoginRequestViewCarriesTheRecordThatSetsTheToken(t *testing.T) {
g := newStartRig(t)
code, _ := g.beginLogin("pi-c")
id, err := g.claimLogin("jva", code, "suit,ctx")
if err != nil {
t.Fatal(err)
}
v := g.get("jva", id).Setup
if v == nil || v.Kind != loginKind || v.Label != "pi-c" || v.Account != "jva" || v.Ceiling != "" ||
strings.Join(v.Scopes, ",") != "api,sync,login" || strings.Join(v.TokenRepos, ",") != "suit,ctx" || v.Done {
t.Fatalf("FAIL: the view: %+v", v)
}
if !strings.Contains(v.Gives, "pi-c") || !strings.Contains(v.Gives, "jva") {
t.Errorf("FAIL: the sentence does not name the machine and the person: %q", v.Gives)
}
if err := g.decideLogin("jva", id, "pi-c"); err != nil {
t.Fatal(err)
}
done := g.get("jva", id).Setup
if done == nil || !done.Done || strings.Join(done.Scopes, ",") != "api,sync,login" || done.Token != "pi-c" {
t.Errorf("FAIL: the view after approval: %+v", done)
}
if !t.Failed() {
t.Log("ok")
}
}
// An optional list of repositories limits the token; one the person
// cannot read is refused at the claim.
func TestLoginClaimMayLimitTheTokenToRepositories(t *testing.T) {
g := newStartRig(t)
code, key := g.beginLogin("laptop")
if _, err := g.claimLogin("jva", code, "secret"); !errors.Is(err, ops.ErrInvalid) {
t.Errorf("FAIL: claiming a repository jva cannot read: %v", err)
}
code, key = g.beginLogin("laptop")
id, err := g.claimLogin("jva", code, "suit")
if err != nil {
t.Fatal(err)
}
if err := g.decideLogin("jva", id, "laptop"); err != nil {
t.Fatal(err)
}
_, body := g.collectNow(key)
var got struct{ Secret struct{ Value string } }
_ = json.Unmarshal([]byte(body), &got)
tok, ok := g.db.ResolveToken("jva", got.Secret.Value, "api")
if !ok || strings.Join(tok.Repos, ",") != "suit" {
t.Errorf("FAIL: the token: %+v", tok)
}
if !t.Failed() {
t.Log("ok")
}
}
// What a login start may say is held as tightly as any start's.
func TestLoginStartHoldsWhatTheClientMaySay(t *testing.T) {
g := newStartRig(t)
_, pickup := newPickupKey(t)
for what, body := range map[string]string{
"a name beside the label": `{"kind":"login","label":"mac","name":"x","pickup":"` + pickup + `"}`,
"a repo named": `{"kind":"login","label":"mac","repo":"suit","pickup":"` + pickup + `"}`,
"no label": `{"kind":"login","pickup":"` + pickup + `"}`,
"markup in the label": loginBody("<b>mac</b>", pickup),
"a long label": loginBody(strings.Repeat("a", 65), pickup),
"a newline in the label": loginBody("mac\nmini", pickup),
"a label on a push": `{"kind":"push","name":"x","label":"mac","pickup":"` + pickup + `"}`,
"a pickup not a hash": loginBody("mac", "nothex"),
} {
if status, _, _ := g.start(body, ""); status != 400 {
t.Errorf("FAIL: %s answered %d, want 400", what, status)
}
}
if status, _, _ := g.start(loginBody("mac-mini, pi-c", pickup), ""); status != 200 {
t.Errorf("FAIL: a good label answered %d", status)
}
if !t.Failed() {
t.Log("ok")
}
}
// The start shares the existing protections: the per-address cap on
// unclaimed starts and the ten minutes of a code's life.
func TestLoginStartSharesTheStartLimitsAndLife(t *testing.T) {
g := newStartRig(t)
for i := 0; i < setupStartPerShare; i++ {
_, pickup := newPickupKey(t)
if status, _, _ := g.start(loginBody("m", pickup), "203.0.113.7"); status != 200 {
t.Fatalf("FAIL: start %d answered %d", i, status)
}
}
_, pickup := newPickupKey(t)
if status, _, h := g.start(loginBody("m", pickup), "203.0.113.7"); status != 429 || h.Get("Retry-After") == "" {
t.Errorf("FAIL: past the share a login start answered %d", status)
}
code, _ := g.beginLogin("late")
if _, ok, _ := g.db.SetupStartByCode(code, g.clock); !ok {
t.Errorf("FAIL: a fresh login code is not held")
}
if _, ok, _ := g.db.SetupStartByCode(code, g.clock.Add(oltp.SetupStartLife+time.Minute)); ok {
t.Errorf("FAIL: a login code is held past its ten minutes")
}
if !t.Failed() {
t.Log("ok")
}
}
// The look says what the page needs for a login: its kind, the label,
// where it came from, and no agent name to pick.
func TestLoginLookOffersNoAgentNameAndTheNetwork(t *testing.T) {
g := newStartRig(t)
code, _ := g.beginLogin("mac-mini")
look, err := g.look("jva", code)
if err != nil {
t.Fatal(err)
}
if look.Kind != loginKind || look.Name != "mac-mini" || look.Address == "" || look.NameTaken != "" || look.Suggest != "" ||
len(look.Roles) != 0 || look.CanCreate || !hasName(repoNames(look.Repos), "suit") || hasName(repoNames(look.Repos), "secret") {
t.Errorf("FAIL: the look: %+v", look)
}
if !t.Failed() {
t.Log("ok")
}
}
func hasName(list []string, s string) bool {
for _, have := range list {
if have == s {
return true
}
}
return false
}
// Nobody collects: the token is revoked after the window, the account
// is untouched.
func TestAnUncollectedLoginTokenIsRevokedAfterTheWindow(t *testing.T) {
g := newStartRig(t)
code, _ := g.beginLogin("never-collected")
id, err := g.claimLogin("jva", code, "")
if err != nil {
t.Fatal(err)
}
if err := g.decideLogin("jva", id, "never-collected"); err != nil {
t.Fatal(err)
}
live := func() int {
n := 0
toks, _ := g.db.Tokens("jva")
for _, tk := range toks {
if tk.Revoked == "" {
n++
}
}
return n
}
if live() != 1 {
t.Fatalf("FAIL: approving left %d live tokens, want 1", live())
}
if n, err := g.deps.LapseSignOffSecrets(time.Now().Add(time.Hour)); err != nil || n != 0 || live() != 1 {
t.Errorf("FAIL: an hour on the sweep finished %d (%v), live %d", n, err, live())
}
if n, err := g.deps.LapseSignOffSecrets(time.Now().Add(25 * time.Hour)); err != nil || n != 1 || live() != 0 {
t.Errorf("FAIL: past the window the sweep finished %d (%v), live %d", n, err, live())
}
if _, ok := g.db.AccountByName("jva"); !ok {
t.Errorf("FAIL: the person's account went with the token")
}
if !t.Failed() {
t.Log("ok")
}
}
// A login token can do what its person can, but never manage their
// credentials, and never answer a sign-off.
func TestALoginTokenCannotMintDecideOrChangeThePassword(t *testing.T) {
g := newStartRig(t)
_, value := g.loggedIn("dmestas", "mac")
tok, ok := g.db.ResolveToken("dmestas", value, "api")
if !ok {
t.Fatal("FAIL: no token")
}
tctx := ops.WithToken(ops.WithUser(context.Background(), "dmestas"), ops.TokenAuth{ID: tok.ID,
Caps: func(repo string) ops.Caps { return g.db.TokenCaps(tok, repo) }, Reaches: tok.Reaches})
// A second request waits on dmestas; the token may not answer it, the
// signed-in person may.
code, _ := g.beginLogin("another")
id, err := g.claimLogin("dmestas", code, "")
if err != nil {
t.Fatal(err)
}
for _, c := range []struct {
op string
in any
}{
{"me.sync.token", struct{}{}},
{"me.sync.token.list", struct{}{}},
{"me.sync.token.revoke", meSyncTokenRevokeIn{}},
{"me.passwd", mePasswdIn{Current: "a-long-enough-password", New: "another-long-password"}},
{"signoff.decide", signOffDecideIn{ID: id, Approve: true}},
{"setup.start.claim", setupClaimIn{Code: "AAAA-AAAA"}},
} {
if _, err := g.r.Invoke(tctx, c.op, c.in); !errors.Is(err, ops.ErrForbidden) {
t.Errorf("FAIL: %s on a login token: %v, want forbidden", c.op, err)
}
}
if row, _, _ := g.db.SignOffByID(id); row.State != "pending" {
t.Errorf("FAIL: the token moved the request to %s", row.State)
}
if !g.db.VerifyPassword("dmestas", "a-long-enough-password") {
t.Errorf("FAIL: the password changed")
}
if err := g.decide("dmestas", id, false); err != nil {
t.Errorf("FAIL: the signed-in person could not answer: %v", err)
}
if !t.Failed() {
t.Log("ok")
}
}
// An agent cannot ask for a login: only a person's claim of a client's
// start files one.
func TestAnAgentCannotAskForALoginToken(t *testing.T) {
g := newStartRig(t)
body := `{"label":"x","repos":[]}`
req := tokenCtx("zeitgeist")
status, out := g.postTo(req, "/api/v1/login/token", body)
if status == 202 || status == 200 {
t.Errorf("FAIL: an agent's ask for a login answered %d %s", status, out)
}
if rows := g.requestsOf("dmestas"); len(rows) != 0 {
t.Errorf("FAIL: an agent filed %d login requests", len(rows))
}
if !t.Failed() {
t.Log("ok")
}
}
// Only the person who holds the code gets anything: a wrong code is
// not found and spends the misses; an agent or a token cannot claim;
// and the token lands on whoever claimed, never on another.
func TestAStrangerCannotClaimSomeoneElsesLoginCode(t *testing.T) {
g := newStartRig(t)
code, key := g.beginLogin("mac")
if _, err := g.claimLogin("jva", "ABCD-EFGH", ""); !errors.Is(err, ops.ErrNotFound) {
t.Errorf("FAIL: a guessed code: %v", err)
}
for _, who := range []string{"dmestas-bot", "zeitgeist"} {
if _, err := g.claimLogin(who, code, ""); !errors.Is(err, ops.ErrForbidden) {
t.Errorf("FAIL: agent %s claiming: %v", who, err)
}
}
// A token, even the person's own, is not a signed-in person.
if _, err := g.r.Invoke(tokenCtx("jva"), "setup.start.claim", setupClaimIn{Code: code}); !errors.Is(err, ops.ErrForbidden) {
t.Errorf("FAIL: a token claiming: %v", err)
}
// Too many guesses hold the account on every door.
for i := 0; i < setupMissesPerUser+1; i++ {
_, _ = g.claimLogin("jva", "ZZZZ-ZZZZ", "")
}
if _, err := g.claimLogin("jva", code, ""); !errors.Is(err, ops.ErrRateLimited) {
t.Errorf("FAIL: a guesser then holding the real code: %v", err)
}
// dmestas, who typed the code, gets a token of their own account; one
// claim wins.
id, err := g.claimLogin("dmestas", code, "")
if err != nil {
t.Fatal(err)
}
if _, err := g.claimLogin("dmestas", code, ""); !errors.Is(err, ops.ErrNotFound) {
t.Errorf("FAIL: a second claim: %v", err)
}
if err := g.decideLogin("dmestas", id, "mac"); err != nil {
t.Fatal(err)
}
_, body := g.collectNow(key)
var got struct{ Secret struct{ Value string } }
_ = json.Unmarshal([]byte(body), &got)
if _, ok := g.db.ResolveToken("jva", got.Secret.Value, "api"); ok {
t.Errorf("FAIL: the token acts as the guesser")
}
if tok, ok := g.db.ResolveToken("dmestas", got.Secret.Value, "api"); !ok || tok.Account != "dmestas" {
t.Errorf("FAIL: the token does not act as the claimant")
}
if !t.Failed() {
t.Log("ok")
}
}
// The token is on its person's list, as a credential of theirs, and
// revoking it there ends it at once.
func TestALoginTokenIsListedAndRevocable(t *testing.T) {
g := newStartRig(t)
_, value := g.loggedIn("jva", "mac-mini, pi-c")
d := g.deps
d.SyncTokens = g.db
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
out, err := r.Invoke(asUser("jva"), "me.sync.token.list", struct{}{})
if err != nil {
t.Fatal(err)
}
var row *meTokenRow
for _, r := range out.(meSyncTokenListOut).Tokens {
if r.Name == "mac-mini, pi-c" {
r := r
row = &r
}
}
if row == nil {
t.Fatalf("FAIL: no row named for the machine in %+v", out)
}
if strings.Join(row.Scopes, ",") != "api,sync,login" || row.Ceiling != "" || row.Revoked != "" {
t.Fatalf("FAIL: the list: %+v", row)
}
if _, ok := g.db.ResolveToken("jva", value, "api"); !ok {
t.Fatalf("FAIL: the token did not resolve before revoking")
}
if _, err := r.Invoke(asUser("jva"), "me.sync.token.revoke", meSyncTokenRevokeIn{ID: row.ID}); err != nil {
t.Fatal(err)
}
if _, ok := g.db.ResolveToken("jva", value, "api"); ok {
t.Errorf("FAIL: the token still resolves after revoking")
}
if _, ok := g.db.ResolveToken("jva", value, "sync"); ok {
t.Errorf("FAIL: the token still pushes after revoking")
}
if !t.Failed() {
t.Log("ok")
}
}
// A login from another network is approved only with the machine's label
// typed, on every surface: the check is in signoff.decide.
func TestALoginFromAnotherNetworkNeedsItsLabelTypedAtTheAPI(t *testing.T) {
g := newStartRig(t)
code, _ := g.beginLogin("pi-c")
from := "198.51.100." + strconv.Itoa(g.addr)
id, err := g.claimLogin("jva", code, "")
if err != nil {
t.Fatal(err)
}
elsewhere := ops.WithAddr(asUser("jva"), "203.0.113.77")
here := ops.WithAddr(asUser("jva"), from)
for what, c := range map[string]struct {
ctx context.Context
confirm string
}{
"another network, nothing typed": {elsewhere, ""},
"another network, another name": {elsewhere, "mac"},
"no network known, nothing typed": {asUser("jva"), ""},
} {
if _, err := g.r.Invoke(c.ctx, "signoff.decide", signOffDecideIn{ID: id, Approve: true, Confirm: c.confirm}); !errors.Is(err, ops.ErrInvalid) {
t.Errorf("FAIL: %s: %v, want a refusal", what, err)
}
if row, _, _ := g.db.SignOffByID(id); row.State != "pending" {
t.Fatalf("FAIL: %s moved the request to %s", what, row.State)
}
}
if toks, _ := g.db.Tokens("jva"); len(toks) != 0 {
t.Errorf("FAIL: a refused approval minted %d tokens", len(toks))
}
if _, err := g.r.Invoke(elsewhere, "signoff.decide", signOffDecideIn{ID: id, Approve: true, Confirm: "pi-c"}); err != nil {
t.Errorf("FAIL: the typed name was refused: %v", err)
}
// The same network is one tap.
code2, _ := g.beginLogin("pi-d")
from2 := "198.51.100." + strconv.Itoa(g.addr)
id2, err := g.claimLogin("jva", code2, "")
if err != nil {
t.Fatal(err)
}
_ = here
if _, err := g.r.Invoke(ops.WithAddr(asUser("jva"), from2), "signoff.decide", signOffDecideIn{ID: id2, Approve: true}); err != nil {
t.Errorf("FAIL: a machine on this network needed its name typed: %v", err)
}
if !t.Failed() {
t.Log("ok")
}
}