Skip to content
quarry Artifact [ebc4de93ba]
Login

Artifact [ebc4de93ba]

Artifact ebc4de93bafcf6c3b78ec8b70afd2da75fde7519f84b8757bc9b7dfe2f203fa9:


package xfer

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"log"
	"mime"
	"net/http"
	"sync"
)

// native.go answers a sync request this forge will not serve the way
// Fossil's own server answers it (xfer.c, page_xfer), so a stock fossil
// client gets the reply it is built for and prints the sentence in it.
//
// Every reply here is HTTP 200 with one error card, as fossil's are:
// fossil never uses 401 or 404 for a refused login or a missing letter.
// The one exception is fossil's own: a Basic credential that matches no
// user is answered 401 before a card is read (login.c,
// login_basic_authentication).
//
// A 401 for a Basic credential that resolves to nobody is a sign-in's
// answer like any other: BasicSignIn counted it, and a held name gets
// the hold sentence whether its credential is right or wrong.
//
// The answers depend on what the request offered and never on whether
// the repository exists, so a private repository and one that does not
// exist answer byte for byte alike, except the codes a refused clone is
// told (cloneCodes).

// syncProtocol reports a request in the sync protocol's own content
// type, which every fossil and zit round carries and a browser or curl
// does not.
func syncProtocol(req *http.Request) bool {
	mt, _, err := mime.ParseMediaType(req.Header.Get("Content-Type"))
	if err != nil {
		return false
	}
	switch mt {
	case "application/x-fossil", "application/x-fossil-uncompressed", "application/x-fossil-debug":
		return true
	}
	return false
}

// refuseSync is refuseRead for a sync-protocol request.
//
// In fossil's order: a Basic credential that resolves to nobody is 401
// (fossil checks it before the body); a login card that does not verify
// is "login failed"; then the first card the caller lacks the letter
// for. A clone is told the project code before its error, which is what
// lets fossil's second round sign a login card at all: the client
// ignores the error on a clone's first round (xfer.c, "when cloning we
// will sometimes get an error on the first message exchange") and
// retries with the card.
//
// A held account is told so in an error card too, which fossil prints;
// a 429 reached it as "server says: Too Many Requests" and no sentence.
func (f *Fronter) refuseSync(w http.ResponseWriter, req *http.Request, pr pushRequest, st loginState) {
	repo := req.PathValue("repo")
	var reply []byte
	switch {
	case st.held:
		reply = errorCard(holdSentence(st.wait))
	case st.basic && st.user == "" && st.basicAccount == "":
		f.challenge(w, req, st)
		return
	case st.offered && st.user == "":
		reply = errorCard(loginFailed)
	case pr.hasClone:
		server, project := f.cloneCodes(repo)
		reply = append([]byte("push "+server+" "+project+"\n"), errorCard(notAuthorized("clone", st))...)
	case pr.hasPull || !pr.hasPush:
		reply = errorCard(notAuthorized("read", st))
	default:
		reply = errorCard(notAuthorized("write", st))
	}
	log.Printf("xfer: %s: sync refused in the protocol: %s", repo, st.why())
	w.Header().Set("Content-Type", "application/x-fossil")
	w.Write(encodeContainer(reply))
}

// What a refused sync is told. Fossil's server says "login failed" and
// "not authorized to clone" and may add why after them (xfer.c,
// whyNotAuth); a client matches the words at the front and prints the
// whole, so the remedy rides after them. Constant, so it cannot differ
// between a private repository and one that does not exist.
const (
	loginFailed = "login failed: check the account name, and that the password is a live sync token of that account," +
		" not its account password. Do not retry with variations: refused logins put a hold on the account"
	signInHint = "name your account and give its sync token: zit clone --user NAME with the token in ZIT_PASSWORD," +
		" or fossil clone --save-http-password https://NAME:TOKEN@HOST/r/REPO (see /llms.txt)"
)

// notAuthorized is Fossil's "not authorized to VERB", with how to sign
// in when the caller signed in as nobody.
func notAuthorized(verb string, st loginState) string {
	msg := "not authorized to " + verb
	if st.user == "" {
		msg += ": " + signInHint
	}
	return msg
}

// SetProjectCode installs the in-memory lookup of a served repository's
// project code, which a refused clone is told (Fossil's server sends it
// before the error, and the client's second round is signed with it).
// It must not start anything: a lookup that ran a process for a real
// repository and not for a made-up one would time apart the two.
func (f *Fronter) SetProjectCode(c func(repo string) (string, bool)) { f.codeOf = c }

// SetDecoyKey installs the key the made-up codes are derived under.
// It must be the same across restarts and across every node that
// answers for the same repositories (on the forge: derived from
// secret.key beside oltp.db, which nodes sharing that database share),
// or a made-up code that changes when a real one does not tells the two
// apart. The forge refuses to start without one when it has a read gate;
// a front with none falls back to a key for this process, logged, and
// exists only in tests.
func (f *Fronter) SetDecoyKey(k []byte) { f.decoy = k }

// processDecoy is the stand-in key, one per process.
var processDecoy = sync.OnceValue(func() []byte {
	k := make([]byte, 32)
	rand.Read(k)
	log.Printf("xfer: NO KEY for the codes a refused clone is told (SetDecoyKey); using one made for this process, so they change on restart and tell a made-up repository from a real one")
	return k
})

func (f *Fronter) decoyKeyBytes() []byte {
	if len(f.decoy) == 0 {
		return processDecoy()
	}
	return f.decoy
}

// cloneCodes is the server code and project code a refused clone of repo
// is told. The project code is the real one when the forge serves repo
// under that name, and otherwise made up; the server code is always made
// up (fossil's client ignores it). Made-up codes are an HMAC of the
// address under the forge's key: 40 lowercase hex digits, the same for
// an address across requests and restarts, different between addresses,
// and computed for every refusal so the two cases cost the same.
//
// Revealing a private repository's real project code here is accepted:
// it is what a fossil client needs to sign its second round, and it
// reads nothing else of the repository.
func (f *Fronter) cloneCodes(repo string) (server, project string) {
	key := f.decoyKeyBytes()
	derive := func(what string) string {
		m := hmac.New(sha256.New, key)
		m.Write([]byte(what))
		m.Write([]byte{0})
		m.Write([]byte(repo))
		return hex.EncodeToString(m.Sum(nil))[:40]
	}
	server, project = derive("server-code"), derive("project-code")
	if f.codeOf != nil {
		if c, ok := f.codeOf(repo); ok && validProjectCode(c) {
			project = c
		}
	}
	return server, project
}