package api
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"time"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// fileWith asks as agent over HTTP with Quarry-Ask, on auth, bound to
// pickup when it is not empty, and leaves the request waiting.
func (c *credRig) fileWith(agent string, auth ops.TokenAuth, pickup, path, body string) (int, string, string) {
c.t.Helper()
ctx := ops.WithToken(ops.WithUser(context.Background(), agent), auth)
req := httptest.NewRequest("POST", path, strings.NewReader(body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Quarry-Ask", "for a test")
if pickup != "" {
req.Header.Set("Quarry-Pickup", pickup)
}
w := httptest.NewRecorder()
c.h.ServeHTTP(w, req)
var asked struct {
SignOff SignOffRequest `json:"signoff"`
}
_ = json.Unmarshal(w.Body.Bytes(), &asked)
return w.Code, asked.SignOff.ID, w.Body.String()
}
var fakeAuth = ops.TokenAuth{ID: "T", Caps: func(string) ops.Caps { return oltp.CapSet("") }}
// file asks for a replacement as agent on an unreadable test token.
func (c *credRig) file(agent, path, body string) (int, string) {
code, id, _ := c.fileWith(agent, fakeAuth, "", path, body)
return code, id
}
// realAuth is the context a request on the minted token tok carries.
func realAuth(tok oltp.Token) ops.TokenAuth {
a := ops.TokenAuth{ID: tok.ID, Caps: func(string) ops.Caps { return oltp.CapSet("") }}
if len(tok.Repos) > 0 {
a.Limited = true
a.Reaches = func(r string) bool {
for _, have := range tok.Repos {
if have == r {
return true
}
}
return false
}
}
return a
}
func (c *credRig) get(who, id string) signOffGetOut {
c.t.Helper()
out, err := c.r.Invoke(asUser(who), "signoff.get", signOffGetIn{ID: id})
if err != nil {
c.t.Fatal(err)
}
return out.(signOffGetOut)
}
func (c *credRig) mint(agent, name, scopes string, repos []string, days int) (string, oltp.Token) {
c.t.Helper()
spec := oltp.TokenSpec{Name: name, Scopes: strings.Split(scopes, ","), Repos: repos}
if days > 0 {
spec.Expires = time.Now().Add(time.Duration(days) * 24 * time.Hour)
}
v, tok, err := c.db.MintToken(agent, spec)
if err != nil {
c.t.Fatal(err)
}
return v, tok
}
func (c *credRig) agentOf(name, person string) {
c.t.Helper()
if err := c.db.AddAccount(name, "a-long-enough-password", false); err != nil {
c.t.Fatal(err)
}
if err := c.db.SetOperator(name, person); err != nil {
c.t.Fatal(err)
}
}
const reissuePath = "/api/v1/agents/tokens/reissue"
// A plan step that mints a token carries the limits of what it mints, to
// the person asked; a step that mints nothing carries none, and the
// asker is shown none.
func TestAPlanStepThatMintsCarriesItsLimits(t *testing.T) {
c := newCredRig(t)
step := func(op, in string) planStepIn { return planStepIn{Op: op, Input: json.RawMessage(in)} }
po, err := c.r.Invoke(asUser("fbot"), planOp, planIn{Title: "mint and make", Steps: []planStepIn{
step("agent.token.new", `{"agent":"fbot","name":"a","scopes":"sync,api","repos":"test","ceiling":"uv3bBC78","days":30}`),
agentStep("alpha"),
}})
if err != nil {
t.Fatal(err)
}
id := po.(planOut).SignOff.ID
for _, st := range po.(planOut).Steps {
if st.Mint != nil {
t.Errorf("FAIL: the asker is shown a step's limits: %+v", st.Mint)
}
}
g := c.get("dmestas", id)
if len(g.Steps) != 2 || g.Steps[0].Mint == nil || g.Steps[1].Mint != nil {
t.Fatalf("FAIL: mint views: %+v", g.Steps)
}
m := g.Steps[0].Mint
if m.Agent != "fbot" || strings.Join(m.Scopes, ",") != "sync,api" || strings.Join(m.Repos, ",") != "test" || m.Ceiling != "uv3bBC78" || m.Days != 30 {
t.Errorf("FAIL: the mint view: %+v", m)
}
raw, _ := json.Marshal(g.Steps)
for _, k := range []string{`"mint"`, `"agent"`, `"scopes"`, `"repos"`, `"ceiling"`, `"days"`} {
if !strings.Contains(string(raw), k) {
t.Errorf("FAIL: steps lack key %s: %s", k, raw)
}
}
if strings.Count(string(raw), `"mint"`) != 1 {
t.Errorf("FAIL: a step with nothing to mint has a mint key: %s", raw)
}
if !t.Failed() {
t.Log("ok")
}
}
// A replacement of a sibling agent's tokens: the person sees the limits
// and the tokens that end while it waits, the asker neither; approving
// ends them, mints one with the same limits and the same fixed expiry,
// and the secret and its credentials come out once. A denied request no
// longer lists tokens that end.
func TestAnAgentAsksForAReplacementTokenAndGetsItOnce(t *testing.T) {
c := newCredRig(t)
c.agentOf("jva-lost", "jva")
var olds []string
for i := 0; i < 2; i++ {
v, _ := c.mint("jva-lost", "work", "api", []string{"test"}, 30)
olds = append(olds, v)
}
code, id := c.file("jva-bot", reissuePath, `{"name":"jva-lost"}`)
if code != 202 || id == "" {
t.Fatalf("FAIL: asking: %d", code)
}
if c.get("jva-bot", id).Mint != nil {
t.Errorf("FAIL: the asker is shown the limits")
}
m := c.get("jva", id).Mint
if m == nil || m.Agent != "jva-lost" || strings.Join(m.Scopes, ",") != "api" || strings.Join(m.Repos, ",") != "test" || len(m.Replaces) != 2 || m.Expires == "" {
t.Fatalf("FAIL: the waiting request's mint view: %+v", m)
}
c.approve("jva", id)
for _, v := range olds {
if _, ok := c.db.ResolveToken("jva-lost", v, oltp.ScopeAPI); ok {
t.Errorf("FAIL: an old token still authenticates")
}
}
first := c.get("jva-bot", id)
var sec struct{ Value string }
if err := json.Unmarshal(first.Secret, &sec); err != nil || sec.Value == "" {
t.Fatalf("FAIL: no secret: %v", err)
}
if _, ok := c.db.ResolveToken("jva-lost", sec.Value, oltp.ScopeAPI); !ok {
t.Errorf("FAIL: the new secret does not authenticate")
}
if len(first.Credentials) != 1 {
t.Fatalf("FAIL: credentials: %+v", first.Credentials)
}
cr := first.Credentials[0]
if cr.Agent != "jva-lost" || strings.Join(cr.Scopes, ",") != "api" || strings.Join(cr.Repos, ",") != "test" || cr.TokenID == "" || cr.Expires == "" {
t.Errorf("FAIL: the credential: %+v", cr)
}
if again := c.get("jva-bot", id); len(again.Secret) != 0 {
t.Errorf("FAIL: the secret came out twice")
}
if done := c.get("jva", id).Mint; done == nil || len(done.Replaces) != 0 {
t.Errorf("FAIL: an approved request still lists tokens that end: %+v", done)
}
_, id2 := c.file("jva-bot", reissuePath, `{"name":"jva-lost"}`)
if _, err := c.r.Invoke(asUser("jva"), "signoff.decide", signOffDecideIn{ID: id2, Approve: false}); err != nil {
t.Fatal(err)
}
if denied := c.get("jva", id2).Mint; denied == nil || len(denied.Replaces) != 0 {
t.Errorf("FAIL: a denied request lists tokens that end: %+v", denied)
}
if !t.Failed() {
t.Log("ok")
}
}
// An agent replacing its own token, on a real minted token: refused
// without a pickup code, since approving revokes the token it would read
// the answer with; with one, the new secret is collected by the key.
func TestAnAgentReplacingItsOwnTokenMustCollectByPickup(t *testing.T) {
c := newCredRig(t)
oldValue, tok := c.mint("jva-bot", "work", "api", []string{"test"}, 0)
code, id, body := c.fileWith("jva-bot", realAuth(tok), "", reissuePath, `{"name":"jva-bot"}`)
if code == 202 || id != "" || !strings.Contains(body, "Quarry-Pickup") {
t.Fatalf("FAIL: a self-ask without pickup: %d %s", code, body)
}
if _, ok := c.db.ResolveToken("jva-bot", oldValue, oltp.ScopeAPI); !ok {
t.Fatalf("FAIL: a refused ask revoked the token")
}
key, pcode := newPickupKey(t)
code, id, body = c.fileWith("jva-bot", realAuth(tok), pcode, reissuePath, `{"name":"jva-bot"}`)
if code != 202 || id == "" {
t.Fatalf("FAIL: asking with pickup: %d %s", code, body)
}
c.approve("jva", id)
if _, ok := c.db.ResolveToken("jva-bot", oldValue, oltp.ScopeAPI); ok {
t.Errorf("FAIL: the old token still authenticates")
}
coll := NewPickupCollector(c.deps, &missLimiter{miss: map[string]int{}}, nil)
collect := func() (int, string) {
req := httptest.NewRequest("POST", "/api/v1/pickups/collect", nil)
req.Header.Set("Authorization", "Pickup "+key)
req.RemoteAddr = "192.0.2.9:4000"
w := httptest.NewRecorder()
coll.ServeHTTP(w, req)
return w.Code, w.Body.String()
}
st, got := collect()
var out struct {
Credentials []Credential
Secret struct{ Value string }
}
if err := json.Unmarshal([]byte(got), &out); st != 200 || err != nil || out.Secret.Value == "" || len(out.Credentials) != 1 || out.Credentials[0].Agent != "jva-bot" {
t.Fatalf("FAIL: collecting: %d %v %s", st, err, got)
}
if _, ok := c.db.ResolveToken("jva-bot", out.Secret.Value, oltp.ScopeAPI); !ok {
t.Errorf("FAIL: the collected secret does not authenticate")
}
if st, _ := collect(); st == 200 {
t.Errorf("FAIL: the secret was collected twice")
}
if !t.Failed() {
t.Log("ok")
}
}
// Nobody replaces the token of an agent that is not their person's, a
// site admin's agent included: the ask is refused as the plain call is,
// and nothing is filed or revoked.
func TestACallerMayNotReplaceAnotherPersonsAgentsToken(t *testing.T) {
c := newCredRig(t)
c.agentOf("dan-bot", "dmestas")
value, _ := c.mint("dan-bot", "dan", "api", nil, 0)
jvaValue, _ := c.mint("jva-bot", "jv", "api", nil, 0)
code, id := c.file("jva-bot", reissuePath, `{"name":"dan-bot"}`)
if code != 403 || id != "" {
t.Errorf("FAIL: asking for another person's agent: %d %q", code, id)
}
// fbot answers to the site admin dmestas, who could replace any
// agent's tokens as themselves; asked, the reach stops at their own.
code, id = c.file("fbot", reissuePath, `{"name":"jva-bot"}`)
if code != 403 || id != "" {
t.Errorf("FAIL: a site admin's agent asking for another person's agent: %d %q", code, id)
}
for acct, v := range map[string]string{"dan-bot": value, "jva-bot": jvaValue} {
if _, ok := c.db.ResolveToken(acct, v, oltp.ScopeAPI); !ok {
t.Errorf("FAIL: the token of %s was revoked", acct)
}
}
// And at approval: a request that names another person's agent
// (as if filed before the agent changed hands) runs nothing.
c.agentOf("moved-bot", "jva")
mv, _ := c.mint("moved-bot", "m", "api", nil, 0)
_, id = c.file("jva-bot", reissuePath, `{"name":"moved-bot"}`)
if err := c.db.SetOperator("moved-bot", "dmestas"); err != nil {
t.Fatal(err)
}
if _, err := c.r.Invoke(asUser("jva"), "signoff.decide", signOffDecideIn{ID: id, Approve: true}); err == nil {
t.Errorf("FAIL: approving replaced the token of an agent that changed hands")
}
if _, ok := c.db.ResolveToken("moved-bot", mv, oltp.ScopeAPI); !ok {
t.Errorf("FAIL: the moved agent's token was revoked")
}
if !t.Failed() {
t.Log("ok")
}
}
// What approval mints is what was filed: a broader sibling token used
// between ask and approve is not copied, and a token made meanwhile
// makes approval refuse rather than revoke something unshown.
func TestAReplacementMintsWhatWasFiledNotWhatIsUsedNow(t *testing.T) {
c := newCredRig(t)
c.agentOf("jva-lost", "jva")
broad, _ := c.mint("jva-lost", "broad", "api,web", nil, 0)
narrow, _ := c.mint("jva-lost", "narrow", "api", []string{"test"}, 0)
if _, ok := c.db.ResolveToken("jva-lost", narrow, oltp.ScopeAPI); !ok {
t.Fatal("FAIL: the narrow token does not authenticate")
}
_, id := c.file("jva-bot", reissuePath, `{"name":"jva-lost"}`)
if id == "" {
t.Fatal("FAIL: not filed")
}
time.Sleep(1100 * time.Millisecond)
if _, ok := c.db.ResolveToken("jva-lost", broad, oltp.ScopeAPI); !ok {
t.Fatal("FAIL: the broad token does not authenticate")
}
shown := c.get("jva", id).Mint
if shown == nil || strings.Join(shown.Scopes, ",") != "api" || strings.Join(shown.Repos, ",") != "test" {
t.Fatalf("FAIL: the page follows the live tokens, not the request: %+v", shown)
}
c.approve("jva", id)
cr := c.get("jva-bot", id).Credentials
if len(cr) != 1 || strings.Join(cr[0].Scopes, ",") != "api" || strings.Join(cr[0].Repos, ",") != "test" {
t.Errorf("FAIL: minted something other than what was shown: %+v", cr)
}
_, id = c.file("jva-bot", reissuePath, `{"name":"jva-lost"}`)
extra, _ := c.mint("jva-lost", "extra", "api", nil, 0)
if _, err := c.r.Invoke(asUser("jva"), "signoff.decide", signOffDecideIn{ID: id, Approve: true}); err == nil {
t.Errorf("FAIL: approving revoked a token that was not shown")
}
if _, ok := c.db.ResolveToken("jva-lost", extra, oltp.ScopeAPI); !ok {
t.Errorf("FAIL: the refused replacement revoked a token")
}
if !t.Failed() {
t.Log("ok")
}
}
// A token asks only for what it holds itself: one limited to a
// repository is refused a replacement wider than it, and may ask for
// one no wider.
func TestALimitedTokenCannotAskForAWiderReplacement(t *testing.T) {
c := newCredRig(t)
_, pcode := newPickupKey(t)
_, narrow := c.mint("jva-bot", "narrow", "api", []string{"test"}, 0)
time.Sleep(1100 * time.Millisecond)
wide, _ := c.mint("jva-bot", "wide", "api", nil, 0)
if _, ok := c.db.ResolveToken("jva-bot", wide, oltp.ScopeAPI); !ok {
t.Fatal("FAIL: the wide token does not authenticate")
}
// The wide token is the most recently used, so the replacement would
// reach every repository: more than the narrow token asking.
code, id, body := c.fileWith("jva-bot", realAuth(narrow), pcode, reissuePath, `{"name":"jva-bot"}`)
if code != 403 || id != "" {
t.Errorf("FAIL: a repository-limited token asked for a wider replacement: %d %s", code, body)
}
// A plan step is judged the same.
ctx := ops.WithToken(ops.WithUser(context.Background(), "jva-bot"), realAuth(narrow))
if _, err := c.r.Invoke(ctx, planOp, planIn{Title: "t", Pickup: pcode, Steps: []planStepIn{
{Op: reissueOp, Input: json.RawMessage(`{"name":"jva-bot"}`)}}}); err == nil {
t.Errorf("FAIL: a plan step asked for a wider replacement")
}
// A replacement no wider than the asking token is allowed.
c.agentOf("x-bot", "jva")
_, xnarrow := c.mint("x-bot", "n", "api", []string{"test"}, 0)
if code, id, body = c.fileWith("x-bot", realAuth(xnarrow), pcode, reissuePath, `{"name":"x-bot"}`); code != 202 || id == "" {
t.Errorf("FAIL: a limited token asked for a replacement no wider than itself: %d %s", code, body)
}
if !t.Failed() {
t.Log("ok")
}
}
// A token asking about a sibling agent is compared by the letters each
// can actually use, not by whether a ceiling is written: an unrestricted
// reader-bot token cannot collect an admin sibling's token, while a
// sibling whose letters are within the asker's may be replaced.
func TestAReplacementIsComparedByEffectiveLettersAcrossAccounts(t *testing.T) {
c := newCredRig(t)
c.letters["jva-bot"] = "o"
c.agentOf("adm-bot", "jva")
c.agentOf("ro-bot", "jva")
c.letters["adm-bot"], c.letters["ro-bot"] = "a", "o"
_, asker := c.mint("jva-bot", "reader", "api", nil, 0)
admValue, _ := c.mint("adm-bot", "admin", "api", nil, 0)
c.mint("ro-bot", "reader", "api", nil, 0)
code, id, body := c.fileWith("jva-bot", realAuth(asker), "", reissuePath, `{"name":"adm-bot"}`)
if code != 403 || id != "" {
t.Errorf("FAIL: a reader's unrestricted token asked for an admin sibling's replacement: %d %s", code, body)
}
if _, ok := c.db.ResolveToken("adm-bot", admValue, oltp.ScopeAPI); !ok {
t.Errorf("FAIL: the admin sibling's token was revoked")
}
if code, id, body = c.fileWith("jva-bot", realAuth(asker), "", reissuePath, `{"name":"ro-bot"}`); code != 202 || id == "" {
t.Errorf("FAIL: a sibling within the asker's letters was refused: %d %s", code, body)
}
if !t.Failed() {
t.Log("ok")
}
}