package main
import (
"net/http"
"net/http/httptest"
"testing"
"craftdesign.group/quarry/internal/oltp"
)
// What the sync front may take from a Basic credential that comes with
// no login card: a live sync token, with ITS letters, and never the
// account's password.
func TestBasicSyncLoginTakesTokensAndNeverThePassword(t *testing.T) {
rg := newTestRegistrar(t, 25)
const pw = "pw12345678"
if err := rg.odb.AddAccount("jan", pw, false); err != nil {
t.Fatal(err)
}
if err := rg.odb.AddRepo("vault", t.TempDir(), "", oltp.Private); err != nil {
t.Fatal(err)
}
if err := rg.odb.SetCaps("jan", "vault", "oiy"); err != nil {
t.Fatal(err)
}
rg.odb.SyncProjectCode = func(string) (string, bool) { return "CODE", true }
doors := &tokenDoors{db: rg.odb}
basic := func(user, secret string) *http.Request {
req := httptest.NewRequest(http.MethodPost, "/r/vault", nil)
req.SetBasicAuth(user, secret)
return req
}
full, err := rg.odb.MintSyncToken("jan")
if err != nil {
t.Fatal(err)
}
acct, c, ok := doors.basicSyncLogin(basic("jan", full), "vault")
if !ok || acct != "jan" || c.Token == "" || !c.CheckIn || !c.Publish || c.Secret != "" {
t.Errorf("FAIL: a sync token in Basic: %q %+v ok=%v", acct, c, ok)
}
if _, _, ok := doors.basicSyncLogin(basic("jan", pw), "vault"); ok {
t.Errorf("FAIL: the account password authorised a sync login")
}
if _, _, ok := doors.basicSyncLogin(basic("kim", full), "vault"); ok {
t.Errorf("FAIL: a token resolved for another account's name")
}
// A narrowed token keeps its ceiling and its repository list.
value, tok, err := rg.odb.MintToken("jan", oltp.TokenSpec{Name: "n", Scopes: []string{oltp.ScopeSync}, Ceiling: "y", Repos: []string{"vault"}})
if err != nil {
t.Fatal(err)
}
_, c, ok = doors.basicSyncLogin(basic("jan", value), "vault")
if !ok || c.Token != tok.ID || c.CheckIn || !c.Publish {
t.Errorf("FAIL: a y-only token gained letters: %+v ok=%v", c, ok)
}
if _, _, ok := doors.basicSyncLogin(basic("jan", value), "elsewhere"); ok {
t.Errorf("FAIL: a token resolved on a repository it does not name")
}
if err := rg.odb.RevokeSyncToken("jan"); err != nil {
t.Fatal(err)
}
if _, _, ok := doors.basicSyncLogin(basic("jan", full), "vault"); ok {
t.Errorf("FAIL: a revoked token still logs in")
}
if !t.Failed() {
t.Log("ok")
}
}