package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
func postAs(t *testing.T, r *ops.Registry, ctx context.Context, path, body, ask string) *httptest.ResponseRecorder {
t.Helper()
holds := func(string, string) CapSet { return oltp.CapSet("a") }
h, err := RouterWithCaps(r, "v", holds, nil)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("POST", path, strings.NewReader(body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
if ask != "" {
req.Header.Set("Quarry-Ask", ask)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
return w
}
// loginAskCall posts ci.checks.set as ctx's caller, with Quarry-Ask when
// ask is not empty.
func loginAskCall(t *testing.T, r *ops.Registry, ctx context.Context, ask string) *httptest.ResponseRecorder {
return postAs(t, r, ctx, "/api/v1/r/test/ci/required-checks", `{"branch":"trunk","checks":["go","vet"]}`, ask)
}
func tokenWith(user, id, name string, login bool) context.Context {
ctx := ops.WithToken(ops.WithUser(context.Background(), user),
ops.TokenAuth{ID: id, Name: name, Login: login, Caps: func(string) ops.Caps { return oltp.CapSet("a") }})
return ops.WithAddr(ctx, "203.0.113.9")
}
func tokenAs(user string, login bool) context.Context { return tokenWith(user, "T", "mac", login) }
// loginTokenOf mints a real token for person and returns a login context.
func loginTokenOf(t *testing.T, db *oltp.DB, person, name string) (context.Context, string) {
t.Helper()
_, tok, err := db.MintToken(person, oltp.TokenSpec{Name: name, Scopes: []string{oltp.ScopeAPI}})
if err != nil {
t.Fatal(err)
}
return tokenWith(person, tok.ID, name, true), tok.ID
}
func askedFrom(t *testing.T, w *httptest.ResponseRecorder) SignOffRequest {
t.Helper()
if w.Code != http.StatusAccepted {
t.Fatalf("FAIL: asking answered %d: %s", w.Code, w.Body)
}
var asked struct {
SignOff SignOffRequest `json:"signoff"`
}
if err := json.Unmarshal(w.Body.Bytes(), &asked); err != nil || asked.SignOff.ID == "" {
t.Fatalf("FAIL: the request: %s", w.Body)
}
return asked.SignOff
}
// A person's own login token is refused a hard stop; with Quarry-Ask it
// files a request for themselves, runs nothing, and approving runs it.
func TestALoginTokenAsksItsOwnPersonForAHardStop(t *testing.T) {
r, db, _ := requiredChecksFixture(t)
seed := []string{"go", "lint", "vet"}
if err := db.SetCheckRule("test", "trunk", seed); err != nil {
t.Fatal(err)
}
ctx, tokID := loginTokenOf(t, db, "jva", "mac")
w := loginAskCall(t, r, ctx, "")
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), browserOnlyCode) {
t.Errorf("FAIL: without the header: %d %s", w.Code, w.Body)
}
s := askedFrom(t, loginAskCall(t, r, ctx, "gate trunk"))
if s.Owner != "jva" || s.State != "pending" || !IsSelfAsker(s.Agent) {
t.Fatalf("FAIL: the request: %+v", s)
}
if _, id, ok := selfAskerOf(s.Agent); !ok || id != tokID {
t.Errorf("FAIL: the asker does not name its token: %q", s.Agent)
}
var via struct{ Label, Addr string }
if json.Unmarshal([]byte(s.Via), &via) != nil || via.Label != "mac" || via.Addr == "" {
t.Errorf("FAIL: the client is not recorded: %q", s.Via)
}
if got := db.RequiredChecks("test", "trunk"); !reflect.DeepEqual(got, seed) {
t.Fatalf("FAIL: the ask wrote before approval: %v", got)
}
if _, err := r.Invoke(ctx, "signoff.get", signOffGetIn{ID: s.ID}); err != nil {
t.Errorf("FAIL: the asker could not read its request: %v", err)
}
// Another login token of the same person is another asker.
other, _ := loginTokenOf(t, db, "jva", "pi")
if o := askedFrom(t, loginAskCall(t, r, other, "gate trunk")); o.Agent == s.Agent || o.ID == s.ID {
t.Errorf("FAIL: two tokens share an asker: %q", o.Agent)
}
if _, err := r.Invoke(ctx, "signoff.decide", signOffDecideIn{ID: s.ID, Approve: true}); !errors.Is(err, ops.ErrForbidden) {
t.Errorf("FAIL: a token decided: %v", err)
}
if _, err := r.Invoke(asUser("jva"), "signoff.decide", signOffDecideIn{ID: s.ID, Approve: true}); err != nil {
t.Fatalf("FAIL: approving: %v", err)
}
if got := db.RequiredChecks("test", "trunk"); !reflect.DeepEqual(got, []string{"go", "vet"}) {
t.Errorf("FAIL: approval left %v", got)
}
if !t.Failed() {
t.Log("ok")
}
}
// Ending the token that asked voids what it asked.
func TestApprovingAfterTheAskingTokenIsRevokedIsRefused(t *testing.T) {
r, db, _ := requiredChecksFixture(t)
seed := []string{"go", "lint", "vet"}
if err := db.SetCheckRule("test", "trunk", seed); err != nil {
t.Fatal(err)
}
ctx, tokID := loginTokenOf(t, db, "jva", "mac")
s := askedFrom(t, loginAskCall(t, r, ctx, "gate trunk"))
if err := db.RevokeToken("jva", tokID); err != nil {
t.Fatal(err)
}
if _, err := r.Invoke(asUser("jva"), "signoff.decide", signOffDecideIn{ID: s.ID, Approve: true}); !errors.Is(err, ops.ErrInvalid) {
t.Errorf("FAIL: approving after revoke: %v", err)
}
if got := db.RequiredChecks("test", "trunk"); !reflect.DeepEqual(got, seed) {
t.Errorf("FAIL: a voided ask wrote %v", got)
}
if !t.Failed() {
t.Log("ok")
}
}
// A mint asked by a login token needs a pickup key, or it is a 400.
func TestAMintSelfAskedNeedsAPickupKey(t *testing.T) {
r, db, _ := requiredChecksFixture(t)
ctx, _ := loginTokenOf(t, db, "jva", "mac")
w := postAs(t, r, ctx, "/api/v1/agents/tokens", `{"agent":"jva-bot","name":"n","scopes":"api"}`, "a token")
if w.Code != http.StatusBadRequest {
t.Errorf("FAIL: a mint without a pickup key: %d %s", w.Code, w.Body)
}
if !t.Failed() {
t.Log("ok")
}
}
// A login token of an agent account, or of a shut one, does not ask.
func TestOnlyAnOpenPersonsLoginTokenAsks(t *testing.T) {
r, db, _ := requiredChecksFixture(t)
if err := db.SetCheckRule("test", "trunk", []string{"go", "lint", "vet"}); err != nil {
t.Fatal(err)
}
bot := tokenWith("jva-bot", "B", "bot", true)
// An agent's token asks as the agent, its person answering; never as itself.
if w := loginAskCall(t, r, bot, "x"); w.Code == http.StatusAccepted && IsSelfAsker(askedFrom(t, w).Agent) {
t.Errorf("FAIL: an agent's login token asked itself: %s", w.Body)
}
if err := db.AddAccount("kim", "a-long-enough-password", false); err != nil {
t.Fatal(err)
}
ctx, _ := loginTokenOf(t, db, "kim", "mac")
if err := db.SetDisabled("kim", true); err != nil {
t.Fatal(err)
}
if w := loginAskCall(t, r, ctx, "x"); w.Code == http.StatusAccepted {
t.Errorf("FAIL: a shut account asked: %s", w.Body)
}
if !t.Failed() {
t.Log("ok")
}
}
// Adding checks runs outright for a login token and for an agent holding
// letter a; removing one does not, and a reordered superset is a superset.
func TestAddingRequiredChecksNeedsNoSignOff(t *testing.T) {
r, db, _ := requiredChecksFixture(t)
call := func(ctx context.Context, checks string) *httptest.ResponseRecorder {
return postAs(t, r, ctx, "/api/v1/r/test/ci/required-checks", `{"branch":"trunk","checks":`+checks+`}`, "")
}
rule := func() []string { return db.RequiredChecks("test", "trunk") }
if w := call(tokenAs("jva", true), `["go"]`); w.Code != 200 || !reflect.DeepEqual(rule(), []string{"go"}) {
t.Errorf("FAIL: a login token's first rule: %d %s %v", w.Code, w.Body, rule())
}
if w := call(tokenAs("jva-bot", false), `["vet","go"]`); w.Code != 200 || len(rule()) != 2 {
t.Errorf("FAIL: an agent adding a check, reordered: %d %s %v", w.Code, w.Body, rule())
}
if w := call(tokenAs("jva", true), `["lint","vet","go"]`); w.Code != 200 || len(rule()) != 3 {
t.Errorf("FAIL: a login token's reordered superset: %d %s %v", w.Code, w.Body, rule())
}
for _, c := range []string{`["go"]`, `[]`, `["go","go"]`, `["go go"]`} {
w := call(tokenAs("jva", true), c)
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), browserOnlyCode) || len(rule()) != 3 {
t.Errorf("FAIL: a login token removing with %s: %d %s", c, w.Code, w.Body)
}
if w := call(tokenAs("jva-bot", false), c); w.Code != http.StatusForbidden || len(rule()) != 3 {
t.Errorf("FAIL: an agent removing with %s: %d %s", c, w.Code, w.Body)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A glob rule is another rule: tightening trunk neither reads nor needs it.
func TestTighteningTrunkIgnoresAGlobRule(t *testing.T) {
r, db, _ := requiredChecksFixture(t)
if err := db.SetCheckRule("test", "tr*", []string{"slow", "go"}); err != nil {
t.Fatal(err)
}
w := postAs(t, r, tokenAs("jva", true), "/api/v1/r/test/ci/required-checks", `{"branch":"trunk","checks":["vet"]}`, "")
if w.Code != 200 {
t.Errorf("FAIL: a first rule on trunk beside a glob: %d %s", w.Code, w.Body)
}
w = postAs(t, r, tokenAs("jva", true), "/api/v1/r/test/ci/required-checks", `{"branch":"tr*","checks":["go"]}`, "")
if w.Code != http.StatusForbidden {
t.Errorf("FAIL: dropping a check from the glob rule itself: %d %s", w.Code, w.Body)
}
if !t.Failed() {
t.Log("ok")
}
}
// The write itself holds a login token or an agent to adding: a rule a
// caller read as smaller than it now is cannot be written over.
func TestTheWriteRefusesWhatTheGateReadStale(t *testing.T) {
_, db, _ := requiredChecksFixture(t)
if err := db.SetCheckRule("test", "trunk", []string{"go", "vet"}); err != nil {
t.Fatal(err)
}
if err := db.TightenCheckRule("test", "trunk", []string{"go"}); !errors.Is(err, oltp.ErrLoosensChecks) {
t.Errorf("FAIL: a stale list was written: %v", err)
}
if err := db.TightenCheckRule("test", "trunk", []string{"vet", "go", "lint"}); err != nil {
t.Errorf("FAIL: a superset was refused: %v", err)
}
if got := db.RequiredChecks("test", "trunk"); !reflect.DeepEqual(got, []string{"go", "lint", "vet"}) {
t.Errorf("FAIL: left %v", got)
}
if !t.Failed() {
t.Log("ok")
}
}
// An agent without letter a is refused even a tightening.
func TestAnAgentWithoutLetterACannotTightenChecks(t *testing.T) {
r, db, _ := requiredChecksFixture(t)
ctx := ops.WithToken(ops.WithUser(context.Background(), "jva-bot"), ops.TokenAuth{ID: "T", Caps: func(string) ops.Caps { return oltp.CapSet("oi") }})
if _, err := r.Invoke(ctx, "ci.checks.set", checkRuleSetIn{Repo: "test", Branch: "trunk", Checks: []string{"go"}}); !errors.Is(err, ops.ErrForbidden) {
t.Errorf("FAIL: an agent without a: %v", err)
}
if got := db.RequiredChecks("test", "trunk"); len(got) != 0 {
t.Errorf("FAIL: wrote %v", got)
}
if !t.Failed() {
t.Log("ok")
}
}