package xfer
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// signInWith is a BasicSignIn over lim, as the forge's is over its
// sign-in limiter: held first, then one success or one miss. good maps
// an account to the one secret that resolves for it (password or token).
func signInWith(lim *countingLimit, good map[string]string, calls *int) BasicSignIn {
return func(req *http.Request) (string, bool, time.Duration) {
*calls++
u, p, ok := req.BasicAuth()
if !ok || u == "" {
return "", false, 0
}
if ok, wait := lim.Allowed(req, u); !ok {
return "", true, wait
}
if want, known := good[u]; known && want == p {
lim.Succeeded(req, u)
return u, false, 0
}
lim.Failed(req, u)
return "", false, 0
}
}
// A request is one sign-in per account, whatever it carries: Basic is
// checked once, and a card naming the same account is not a second
// attempt, neither a miss beside Basic's success nor a second miss
// beside its failure. A card naming another account is that account's.
func TestABasicCredentialIsOneSignInPerRequest(t *testing.T) {
const covered = "pull aaaa bbbb\n"
type tc struct {
name string
basicPW, cardUser string
wantJan, wantOther int
}
for _, c := range []tc{
{"good Basic, unverifiable card", "tok", "jan", 0, 0},
{"wrong Basic, unverifiable card", "nope", "jan", 2, 0},
{"good Basic, another account's bad card", "tok", "kim", 0, 1},
} {
lim := &countingLimit{max: 9, misses: map[string]int{"jan": 1}}
calls := 0
f := New()
f.SetAuth(secrets{"jan": "right", "kim": "kright"})
f.SetLoginLimit(lim)
f.SetBasicSignIn(signInWith(lim, map[string]string{"jan": "tok"}, &calls))
f.SetBasicLogin(basicFor(map[string]Credential{"jan": fullTok}))
body := []byte(loginOver(c.cardUser, "wrong", covered))
req := nativePost(t, "alpha", string(body))
req.SetBasicAuth("jan", c.basicPW)
f.verifiedLogin("alpha", req, body, scanRequest(body))
if calls != 1 {
t.Errorf("FAIL: %s: Basic checked %d times", c.name, calls)
}
if lim.misses["jan"] != c.wantJan || lim.misses["kim"] != c.wantOther {
t.Errorf("FAIL: %s: misses jan %d kim %d, want %d %d", c.name, lim.misses["jan"], lim.misses["kim"], c.wantJan, c.wantOther)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A held account is answered the same for a right and a wrong
// credential, password or token, and for a private repository and an
// address that names nothing: the hold sentence in the protocol, and
// what a held plain request gets for anything else. N wrong passwords
// hold it, and the right one is refused while it is held.
func TestAHeldBasicAnswersAlikeRightOrWrong(t *testing.T) {
lim := &countingLimit{max: 3, misses: map[string]int{}}
calls := 0
f := nativeFronter(t)
f.SetAuth(&mapAuth{users: map[string]string{}})
f.SetLoginLimit(lim)
f.SetBasicSignIn(signInWith(lim, map[string]string{"jan": "pw-right"}, &calls))
for i := 0; i < lim.max; i++ {
req := nativePost(t, "secret", cloneRound1)
req.SetBasicAuth("jan", "pw-wrong")
w := httptest.NewRecorder()
f.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("FAIL: wrong password %d answered %d, want 401", i, w.Code)
}
}
if lim.misses["jan"] != lim.max {
t.Fatalf("FAIL: %d wrong passwords counted %d misses", lim.max, lim.misses["jan"])
}
for _, protocol := range []bool{true, false} {
var first *httptest.ResponseRecorder
for _, repo := range []string{"secret", "absent"} {
for _, pw := range []string{"pw-right", "pw-wrong", "qat_right_token", "qat_wrong_token"} {
req := nativePost(t, repo, cloneRound1)
if !protocol {
req = plainPost(t, repo)
}
req.SetBasicAuth("jan", pw)
w := httptest.NewRecorder()
f.ServeHTTP(w, req)
if first == nil {
first = w
continue
}
if !bytes.Equal(w.Body.Bytes(), first.Body.Bytes()) {
t.Errorf("FAIL: protocol %v: %s with %s: body differs", protocol, repo, pw)
}
sameHeaders(t, repo+" "+pw, first, w)
}
}
switch {
case protocol && (first.Code != http.StatusOK || replyCards(t, first) != string(errorCard(holdSentence(90*time.Second)))):
t.Errorf("FAIL: held sync: %d %q", first.Code, first.Body.Bytes())
case !protocol && first.Code != http.StatusTooManyRequests:
t.Errorf("FAIL: held plain request: %d", first.Code)
}
}
if lim.misses["jan"] != lim.max {
t.Errorf("FAIL: attempts while held were counted: %d", lim.misses["jan"])
}
if !t.Failed() {
t.Log("ok")
}
}
// basicPushRig is a gated front with one repository behind a stand-in
// child, Basic signing in jan by password "pw" and by token "tok".
type basicPushRig struct {
f *Fronter
reached *bool
cred Credential
}
func newBasicPushRig(t *testing.T, cred Credential) *basicPushRig {
t.Helper()
r := &basicPushRig{cred: cred}
f := New()
t.Cleanup(f.Close)
srv, _ := fakeChild(t, f, "alpha")
reached := false
srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
reached = true
w.Header().Set("Content-Type", "application/x-fossil")
w.Write(encodeContainer([]byte("pragma ok\n")))
})
f.SetAuth(adoptSecrets{secrets{"jan": "card-secret"}})
f.SetBasicSignIn(func(req *http.Request) (string, bool, time.Duration) {
u, p, _ := req.BasicAuth()
if u == "jan" && (p == "pw" || p == "tok") {
return u, false, 0
}
return "", false, 0
})
f.SetBasicLogin(func(req *http.Request, _ string) (string, Credential, bool) {
if u, p, _ := req.BasicAuth(); u == "jan" && p == "tok" {
return u, r.cred, true
}
return "", Credential{}, false
})
r.f, r.reached = f, &reached
return r
}
// push sends cards with jan's Basic secret and the given content type,
// and returns the reply's cards.
func (r *basicPushRig) push(t *testing.T, secret, contentType, cards string) string {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/r/alpha", nil)
req.SetPathValue("repo", "alpha")
req.Header.Set("Content-Type", contentType)
req.Header.Set("User-Agent", fossilUA)
req.SetBasicAuth("jan", secret)
req.Body = io.NopCloser(bytes.NewReader(encodeContainer([]byte(cards))))
w := httptest.NewRecorder()
r.f.ServeHTTP(w, req)
return string(decodeContainer(w.Body.Bytes()))
}
// adoptSecrets is secrets that can derive under another project code.
type adoptSecrets struct{ secrets }
func (adoptSecrets) SecretsAt(repo, user, code string) []Credential { return nil }
const basicPushCards = "push aaaa bbbb\n"
// Basic stands in for a login card only on the sync protocol: the same
// push with Content-Type text/plain, which a cross-site request may send
// without a preflight, is nobody's.
func TestBasicStandsOnlyOnTheSyncProtocol(t *testing.T) {
r := newBasicPushRig(t, fullTok)
cards := basicPushCards + pushedFile([]byte("a check-in\n"))
if reply := r.push(t, "tok", "text/plain", cards); !strings.HasPrefix(reply, "error ") || *r.reached {
t.Errorf("FAIL: a text/plain push stood on Basic: %q, reached %v", reply, *r.reached)
}
if reply := r.push(t, "tok", "application/x-fossil", cards); strings.HasPrefix(reply, "error ") || !*r.reached {
t.Errorf("FAIL: the same push on the sync protocol was refused: %q", reply)
}
if !t.Failed() {
t.Log("ok")
}
}
// A push through Basic keeps every rule a card signed with the same
// credential meets.
func TestABasicPushMeetsTheCardsRules(t *testing.T) {
checkin := basicPushCards + pushedFile([]byte("a check-in\n"))
r := newBasicPushRig(t, Credential{Token: "UV", CheckIn: false, Publish: true})
if reply := r.push(t, "tok", "application/x-fossil", checkin); !strings.Contains(reply, `unversioned\sfiles\sonly`) || *r.reached {
t.Errorf("FAIL: a token without the check-in letter pushed a check-in: %q", reply)
}
r = newBasicPushRig(t, fullTok)
if reply := r.push(t, "pw", "application/x-fossil", checkin); !strings.HasPrefix(reply, "error ") || *r.reached {
t.Errorf("FAIL: the account password pushed: %q", reply)
}
r = newBasicPushRig(t, fullTok)
r.f.SetHoldGate(func(*http.Request, string, string) string { return "this repository is unavailable for legal reasons" })
if reply := r.push(t, "tok", "application/x-fossil", checkin); !strings.Contains(reply, `error this\srepository\sis\sunavailable`) || *r.reached {
t.Errorf("FAIL: a takedown let a Basic push through: %q", reply)
}
if !t.Failed() {
t.Log("ok")
}
}
// A Basic push naming a project the repository does not hold is judged
// by the adoption rules, as a card-signed one is: a code another
// repository holds is refused, an empty repository is let adopt it, and
// a repository that is not empty is told "wrong project", as Fossil's
// server tells it.
func TestABasicPushIntoAnEmptyRepositoryIsJudgedForAdoption(t *testing.T) {
const held = "0123456789abcdef0123456789abcdef01234567"
const foreign = "fedcba9876543210fedcba9876543210fedcba98"
cards := "push " + foreign + " " + foreign + "\n" + pushedFile([]byte("a check-in\n"))
for _, c := range []struct {
name string
empty bool
claim Claim
want string
passes bool
}{
{"taken", true, ClaimTaken, "error " + strings.ReplaceAll(adoptTakenSentence, " ", `\s`), false},
{"adopted", true, ClaimOK, "pragma ok", true},
{"not empty", false, ClaimOK, `error wrong\sproject`, false},
} {
r := newBasicPushRig(t, fullTok)
claims, adopted := 0, 0
r.f.SetAdoption(&Adoption{
Code: func(string) (string, bool) { return held, true },
Empty: func(string) bool { return c.empty },
Recorded: func(string) string { return "" },
Claim: func(string, string) Claim { claims++; return c.claim },
Adopted: func(string) bool { adopted++; return true },
})
reply := r.push(t, "tok", "application/x-fossil", cards)
if !strings.HasPrefix(reply, c.want) || *r.reached != c.passes {
t.Errorf("FAIL: %s: %q, reached %v", c.name, reply, *r.reached)
}
if c.empty && claims != 1 {
t.Errorf("FAIL: %s: %d claims", c.name, claims)
}
if c.passes && adopted == 0 {
t.Errorf("FAIL: %s: the adopted code was not read back", c.name)
}
}
if !t.Failed() {
t.Log("ok")
}
}