package api
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// file asks as agent with Quarry-Ask and leaves the request waiting.
func (c *credRig) file(agent, path, body string) (int, string) {
c.t.Helper()
ctx := ops.WithToken(ops.WithUser(context.Background(), agent), ops.TokenAuth{ID: "T",
Caps: func(string) ops.Caps { return oltp.CapSet("") }})
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")
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
}
func (c *credRig) get(agent, id string) signOffGetOut {
c.t.Helper()
out, err := c.r.Invoke(asUser(agent), "signoff.get", signOffGetIn{ID: id})
if err != nil {
c.t.Fatal(err)
}
return out.(signOffGetOut)
}
// A plan step that mints a token carries the limits of what it mints; a
// step that mints nothing carries 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)
}
g := c.get("fbot", po.(planOut).SignOff.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")
}
}
// An agent asks for a replacement with Quarry-Ask: the request shows the
// limits and the tokens it ends; approving ends them, mints one with the
// same limits, and the secret and its credentials come out once.
func TestAnAgentAsksForAReplacementTokenAndGetsItOnce(t *testing.T) {
c := newCredRig(t)
var olds []string
for i := 0; i < 2; i++ {
v, _, err := c.db.MintToken("jva-bot", oltp.TokenSpec{Name: "work", Scopes: []string{oltp.ScopeAPI}, Repos: []string{"test"}})
if err != nil {
t.Fatal(err)
}
olds = append(olds, v)
}
code, id := c.file("jva-bot", "/api/v1/agents/tokens/reissue", `{"name":"jva-bot"}`)
if code != 202 || id == "" {
t.Fatalf("FAIL: asking: %d", code)
}
if c.get("jva-bot", id).Mint == nil || len(c.get("jva-bot", id).Mint.Replaces) != 0 {
t.Errorf("FAIL: the asker is told which tokens end, or has no view")
}
waiting := c.get("jva", id)
m := waiting.Mint
if m == nil || m.Agent != "jva-bot" || strings.Join(m.Scopes, ",") != "api" || strings.Join(m.Repos, ",") != "test" || len(m.Replaces) != 2 {
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-bot", 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-bot", 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-bot" || strings.Join(cr.Scopes, ",") != "api" || strings.Join(cr.Repos, ",") != "test" || cr.TokenID == "" {
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 !t.Failed() {
t.Log("ok")
}
}
// Nobody replaces the token of an agent that is not their person's: the
// ask is refused as the plain call is, and nothing is filed or revoked.
func TestACallerMayNotReplaceAnotherPersonsAgentsToken(t *testing.T) {
c := newCredRig(t)
if err := c.db.AddAccount("dan-bot", "a-long-enough-password", false); err != nil {
t.Fatal(err)
}
if err := c.db.SetOperator("dan-bot", "dmestas"); err != nil {
t.Fatal(err)
}
value, _, err := c.db.MintToken("dan-bot", oltp.TokenSpec{Name: "dan", Scopes: []string{oltp.ScopeAPI}})
if err != nil {
t.Fatal(err)
}
code, id := c.file("jva-bot", "/api/v1/agents/tokens/reissue", `{"name":"dan-bot"}`)
if code != 403 || id != "" {
t.Errorf("FAIL: asking for another person's agent: %d %q", code, id)
}
if _, ok := c.db.ResolveToken("dan-bot", value, oltp.ScopeAPI); !ok {
t.Errorf("FAIL: the other agent's token was revoked")
}
if !t.Failed() {
t.Log("ok")
}
}