package oltp
import (
"strings"
"testing"
"time"
)
// A Git mirror's access token is sealed at rest, comes back whole to
// the fetch, shows on the mirror only as held or not, clears, and is
// refused for a mirror that does not follow Git.
func TestMirrorGitTokenIsSealedAndOnlyForGit(t *testing.T) {
d := openTest(t)
if err := d.SetMirror("g", "https://example.invalid/owner/g", time.Hour); err != nil {
t.Fatal(err)
}
if err := d.SetMirrorGitToken("g", "github_pat_abc"); err == nil {
t.Fatal("FAIL: a token was kept for a mirror that does not follow Git")
}
if err := d.SetMirrorGit("g"); err != nil {
t.Fatal(err)
}
if err := d.SetMirrorGitToken("g", "github_pat_abc"); err != nil {
t.Fatal(err)
}
m, _, _ := d.MirrorFor("g")
tok, err := d.MirrorGitToken("g")
if err != nil || tok != "github_pat_abc" || !m.GitToken {
t.Fatalf("FAIL: token %q held %v (%v)", tok, m.GitToken, err)
}
var stored string
if err := d.db.QueryRow(`SELECT git_token_enc FROM mirror WHERE repo = 'g'`).Scan(&stored); err != nil || stored == "" || strings.Contains(stored, "abc") {
t.Fatalf("FAIL: the token is stored as %q (%v)", stored, err)
}
t.Log("ok: sealed at rest, whole to the fetch, and the mirror says only that one is held")
if err := d.SetMirrorGitToken("g", ""); err != nil {
t.Fatal(err)
}
m, _, _ = d.MirrorFor("g")
if tok, _ := d.MirrorGitToken("g"); tok != "" || m.GitToken {
t.Fatalf("FAIL: a cleared token is still held: %q %v", tok, m.GitToken)
}
if tok, err := d.MirrorGitToken("none"); tok != "" || err != nil {
t.Fatalf("FAIL: a repository with no mirror has token %q (%v)", tok, err)
}
t.Log("ok: a cleared token is gone, and no mirror means no token")
if err := d.SetMirrorGitToken("g", "github_pat_abc"); err != nil {
t.Fatal(err)
}
if err := d.DetachMirror("g"); err != nil {
t.Fatal(err)
}
if tok, _ := d.MirrorGitToken("g"); tok != "" {
t.Fatalf("FAIL: a detached mirror still holds its token %q", tok)
}
t.Log("ok: detaching, which ends the pulls, removes the token")
}