Skip to content
quarry Artifact [dbbfdc46b7]
Login

Artifact [dbbfdc46b7]

Artifact dbbfdc46b7e1901ab5b4fb490db101d23091ed2ef2e8b388b1ce2cbac46c2b3b:


package api

import (
	"context"
	"errors"
	"testing"

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

// limitedTo is a token of who limited to the one repository repo.
func limitedTo(who, repo string) context.Context {
	return ops.WithToken(ops.WithUser(context.Background(), who), ops.TokenAuth{ID: "L",
		Caps:    func(string) ops.Caps { return oltp.CapSet("") },
		Limited: true,
		Reaches: func(r string) bool { return r == repo }})
}

// A token limited to repositories reads its own requests about them,
// which the limited-token gate used to refuse, but sees no request about
// another repository or about none, and never collects a credential.
func TestALimitedTokenReadsItsOwnRequestsButCollectsNothing(t *testing.T) {
	c := newCredRig(t)
	id := c.ask("jva-bot", "jva", "/api/v1/r/test/ci/tokens", `{"label":"ci"}`)

	out, err := c.r.Invoke(limitedTo("jva-bot", "test"), "signoff.get", signOffGetIn{ID: id})
	if err != nil {
		t.Fatalf("FAIL: a limited token reading its own request: %v", err)
	}
	got := out.(signOffGetOut)
	if got.Request.ID != id || len(got.Secret) != 0 || got.Note == "" {
		t.Errorf("FAIL: limited read: id %q secret %d note %q", got.Request.ID, len(got.Secret), got.Note)
	}

	if _, err := c.r.Invoke(limitedTo("jva-bot", "elsewhere"), "signoff.get", signOffGetIn{ID: id}); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: a token limited to another repository: %v", err)
	}

	// The secret is still there for the account's unlimited token.
	if first := c.get("jva-bot", id); len(first.Secret) == 0 {
		t.Errorf("FAIL: the limited read used up the secret")
	}

	c.agentOf("jva-lost", "jva")
	c.mint("jva-lost", "work", "api", []string{"test"}, 30)
	_, about := c.file("jva-bot", reissuePath, `{"name":"jva-lost"}`)
	if _, err := c.r.Invoke(limitedTo("jva-bot", "test"), "signoff.get", signOffGetIn{ID: about}); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: a limited token read a request about no repository: %v", err)
	}

	if _, err := c.r.Invoke(limitedTo("jva-bot", "test"), "me.account", meAccountIn{}); err != nil {
		t.Errorf("FAIL: me.account refused to a limited token: %v", err)
	}
	if _, err := c.r.Invoke(limitedTo("jva-bot", "test"), "signoff.list", signOffListIn{}); err == nil {
		t.Errorf("FAIL: signoff.list opened to a limited token")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}