package harness
import (
"os/exec"
"regexp"
"strings"
"testing"
"craftdesign.group/quarry/internal/oltp"
)
var hashes = regexp.MustCompile(`[0-9a-f]{12}`)
// pushWith pushes dir as user with a token's value as the password.
func (f *protectForge) pushWith(t *testing.T, dir, user, password string) (string, error) {
t.Helper()
cmd := exec.Command("zit", "push", f.srv.URL+"/r/alpha", "--user", user, "--password", password)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
return string(out), err
}
// A machine logged in as the owner of a protected branch lands through
// landings only: its sync push to the branch is refused as a stranger's
// is, while the owner's ordinary sync token is admitted.
func TestALoginTokenCannotPushStraightToAProtectedBranch(t *testing.T) {
f := newProtectForge(t)
f.odb.SyncProjectCode = func(string) (string, bool) { return f.code, true }
id := f.openLanding(t, "feat-login", "l.txt")
_ = id
loginVal, _, err := f.odb.MintToken("alice", oltp.TokenSpec{Name: "mac-mini", Scopes: []string{oltp.ScopeAPI, oltp.ScopeSync, oltp.ScopeLogin}})
if err != nil {
t.Fatal(err)
}
plainVal, _, err := f.odb.MintToken("alice", oltp.TokenSpec{Name: "plain", Scopes: []string{oltp.ScopeSync}})
if err != nil {
t.Fatal(err)
}
alice := f.clone(t)
zrun(t, alice, "update", "trunk")
zrun(t, alice, "merge", "feat-login")
zrun(t, alice, "commit", "-m", "alice merges by hand")
out, err := f.pushWith(t, alice, "alice", loginVal)
if err == nil {
t.Fatalf("FAIL: a login token pushed straight to trunk:\n%s", out)
}
if !strings.Contains(out, "trunk") {
t.Errorf("FAIL: the refusal does not name the branch:\n%s", out)
}
f.sync()
if tl := zout(t, f.store, "timeline", "-n", "3"); strings.Contains(tl, "alice merges by hand") {
t.Fatalf("FAIL: part of the refused push reached the store:\n%s", tl)
}
// The same refusal, in the same words, as a stranger's push gets.
bob := f.clone(t)
zrun(t, bob, "update", "trunk")
zrun(t, bob, "merge", "feat-login")
zrun(t, bob, "commit", "-m", "bob merges by hand")
bobOut, _ := f.push(t, bob, "bob")
norm := func(s string) string {
return hashes.ReplaceAllString(strings.ReplaceAll(strings.ReplaceAll(s, "alice", "U"), "bob", "U"), "H")
}
// The client cuts the line at a fixed width that the user's name counts
// toward, so the words are compared up to the branch.
head := func(s string) string {
h, _, _ := strings.Cut(norm(s), "'trunk'.")
return h
}
if head(out) != head(bobOut) || !strings.Contains(out, "'trunk'.") {
t.Errorf("FAIL: the refusal differs from a non-owner's:\nlogin: %s\nbob: %s", out, bobOut)
}
if out, err := f.pushWith(t, alice, "alice", plainVal); err != nil {
t.Fatalf("FAIL: the owner's own sync token was refused: %v\n%s", err, out)
}
if !t.Failed() {
t.Log("ok")
}
}