Skip to content
quarry Artifact [1bef5d77ba]
Login

Artifact [1bef5d77ba]

Artifact 1bef5d77baf97d6bed0012b62bb397ee8d643423db986bf149f103fdecd989ff:


package main

import (
	"context"
	"net"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"

	"craftdesign.group/quarry/internal/api"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/web"
	"craftdesign.group/quarry/internal/xfer"
)

// tokenDoors is RFC 0021's one resolver as the forge's doors see it: a
// token presented as an HTTP Basic password, checked for the door's
// scope, with every refused token counted as a miss against the
// account it names on the limiter the sign-in form already uses.
//
// A password without a token's shape never reaches it, so an account
// that holds no token meets every door exactly as before.
type tokenDoors struct {
	// places is how the router reads an address; nil on a flat node.
	places *web.Addresses
	db     *oltp.DB
	limit  *web.LoginLimiter // nil: misses are not counted
	// addr is the client's address by the trusted-proxy rule; set once
	// the proxy is known, the peer address until then.
	addr func(*http.Request) string
}

// presented is what a request's Basic credential turned out to be.
type presented int

const (
	notToken presented = iota // no Basic, or a password without a token's shape
	held                      // a token for an account the limiter is holding
	refused                   // a token that did not resolve for this scope
	resolved
)

func (d *tokenDoors) ip(req *http.Request) string {
	if d.addr != nil {
		return d.addr(req)
	}
	if host, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
		return host
	}
	return req.RemoteAddr
}

// resolve answers the token req's Basic password is, for scope or, when
// a door takes more than one, for any of also. One request is one
// outcome to the limiter however many scopes it was tried against.
func (d *tokenDoors) resolve(req *http.Request, scope string, also ...string) (oltp.Token, presented) {
	user, pass, ok := req.BasicAuth()
	if d == nil || d.db == nil || !ok || user == "" {
		return oltp.Token{}, notToken
	}
	shaped := oltp.LooksLikeToken(pass)
	if !shaped && scope != oltp.ScopeSync {
		return oltp.Token{}, notToken
	}
	// The sync door also takes the push credentials minted before
	// tokens had a shape; those are not counted, being indistinguishable
	// from the wrong password the password check already refused.
	count := shaped && d.limit != nil
	if count {
		if ok, _ := d.limit.Allowed(user, d.ip(req)); !ok {
			return oltp.Token{}, held
		}
	}
	tok, ok := d.db.ResolveToken(user, pass, scope)
	for _, s := range also {
		if ok {
			break
		}
		tok, ok = d.db.ResolveToken(user, pass, s)
	}
	switch {
	case ok && count:
		d.limit.Succeeded(user, d.ip(req))
	case !ok && count:
		d.limit.Failed(user, d.ip(req))
	}
	if !ok {
		if shaped {
			return oltp.Token{}, refused
		}
		return oltp.Token{}, notToken
	}
	return tok, resolved
}

// verify is the Verify behind a door of scope. A password shaped like a
// token is a token: found by its id, checked for this door's scope, its
// expiry, revocation and repositories, and judged on the letters it
// resolves to. Anything else is byPassword's, as it always was.
func (d *tokenDoors) verify(scope string, byPassword api.Verify) api.Verify {
	return func(repo, user, pass string, need ops.Auth) api.Decision {
		if d.db == nil || !d.db.HasAccounts() || !oltp.LooksLikeToken(pass) {
			return byPassword(repo, user, pass, need)
		}
		tok, ok := d.db.ResolveToken(user, pass, scope)
		// The API's forge scope is the router's to judge for a token
		// limited to repositories, since one op there (the caller's own
		// identity) stays open to it. Every other door takes Reaches
		// as it stands.
		if !ok || !(tok.Reaches(repo) || (repo == "" && scope == oltp.ScopeAPI)) {
			return api.Denied
		}
		// The Admin rule is the token's own (ops.TokenAuth.MayAt); only
		// the exemption above is this door's.
		if need != ops.Admin || d.auth(tok).MayAt(repo, need) {
			return api.Allowed
		}
		return api.Insufficient
	}
}

// auth is the token as ops carries it on the context.
func (d *tokenDoors) auth(tok oltp.Token) ops.TokenAuth {
	return ops.TokenAuth{ID: tok.ID, Caps: func(repo string) ops.Caps { return d.db.TokenCaps(tok, repo) },
		Limited: len(tok.Repos) > 0, Reaches: tok.Reaches, Site: func() bool { return d.db.SiteToken(tok) },
		ForgeAgent: func() bool { return d.db.UpkeepToken(tok) }}
}

// wrap puts the token a page or API request came in on onto its
// context, where the router's and the pages' capability checks read
// it, and answers a held account at once. The verifier behind each door
// still makes the decision; this is what makes the decision bounded
// and narrowed.
func (d *tokenDoors) wrap(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		req = d.bearerAsBasic(req)
		scope := oltp.ScopeWeb
		if strings.HasPrefix(req.URL.Path, "/api/") {
			scope = oltp.ScopeAPI
		} else if c, err := req.Cookie(web.SessionCookie); err == nil {
			// A page request with a live session cookie is the cookie's:
			// the web layer reads the cookie first, so a Basic token
			// beside it never speaks. A session opened by a sign-in
			// link carries its token, so the page gates read the
			// token's letters and never the account's.
			if _, tok, bound, ok := d.db.SessionPrincipal(c.Value); ok {
				if bound {
					req = req.WithContext(ops.WithToken(req.Context(), d.auth(tok)))
				}
				next.ServeHTTP(w, req)
				return
			}
		}
		// An account password at a page or API door is a sign-in like the
		// form's and the sync lane's: the hold is asked before anything
		// is looked up, and the one outcome this request gets is the
		// credential check's own, never the status its surface happened
		// to end on. A 403 for a caller the repository does not admit, or
		// a 200 from a page that ignores a wrong Basic, says nothing
		// about whether the password was right, and counting either would
		// let a guesser buy a cleared count with one anonymous request.
		//
		// A token-shaped password resolves through resolve below, which
		// counts it once; a live session answers for the browser before
		// this line, so a stale Basic beside it is not a sign-in and
		// cannot lock a signed-in person out; and the sign-in form is
		// left out because its own handler reads the form's password and
		// charges the same limiter (web.go's POST /login), where a Basic
		// credential the browser replays beside it would spend two of
		// the six misses on one mistyped form.
		if d.limit != nil && d.db != nil && !formOwnsTheSignIn(req) {
			if user, pass, ok := req.BasicAuth(); ok && user != "" && pass != "" &&
				!oltp.LooksLikeToken(pass) && d.db.HasAccounts() {
				if allowed, wait := d.limit.Allowed(user, d.ip(req)); !allowed {
					w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())))
					http.Error(w, "too many failed sign-ins; try again in "+wait.String(), http.StatusTooManyRequests)
					return
				}
				if _, ok := d.db.Authenticate(user, pass); ok {
					d.limit.Succeeded(user, d.ip(req))
				} else {
					d.limit.Failed(user, d.ip(req))
				}
			}
		}
		// An archive is the repository's contents, which the sync scope
		// already reads whole: a runner fetches a pair's merged tree
		// with the same sync token its clones carry, and a private
		// repository answered it as a stranger (ticket 440).
		archiveKey, archive := d.archiveRead(req)
		var tok oltp.Token
		var p presented
		if archive {
			tok, p = d.resolve(req, scope, oltp.ScopeSync)
			if p == resolved && !tok.Has(scope) && !tok.Reaches(archiveKey) {
				// A sync token of another repository is not a reader
				// of this one.
				p = notToken
			}
		} else {
			tok, p = d.resolve(req, scope)
		}
		switch p {
		case held:
			user, _, _ := req.BasicAuth()
			_, wait := d.limit.Allowed(user, d.ip(req))
			w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())))
			http.Error(w, "too many failed sign-ins; try again in "+wait.String(), http.StatusTooManyRequests)
			return
		case refused:
			// A run token whose run is over is told so, not told it
			// failed to authenticate (RFC 0021 §runs).
			user, pass, _ := req.BasicAuth()
			if why := d.db.RunTokenEnded(user, pass); why != "" {
				http.Error(w, why, http.StatusUnauthorized)
				return
			}
		case resolved:
			ctx := ops.WithToken(req.Context(), d.auth(tok))
			// A page READ with a web token is read as its account: the
			// pages judge a private repository by who is looking, and
			// without this every one read as missing to a token that may
			// see it while the API served it. Reads only: a browser
			// replays cached Basic credentials by itself, and a viewer
			// on a POST would be a cross-site forgery's gift. Write pages
			// keep their own gate.
			if scope == oltp.ScopeWeb && tok.Account != "" && ops.User(ctx) == "" &&
				(req.Method == http.MethodGet || req.Method == http.MethodHead) {
				ctx = ops.WithUser(ctx, tok.Account)
			}
			// The same for an archive: the pages and the op judge the
			// reader by name, and a sync token is the name's, narrowed
			// to its repositories and letters by the token on the
			// context (CanRead asks the token first).
			if archive && !tok.Has(scope) {
				if ops.User(ctx) == "" {
					user, _, _ := req.BasicAuth()
					ctx = ops.WithUser(ctx, user)
				}
				ctx = ops.WithArchiveReader(ctx, archiveKey)
			}
			req = req.WithContext(ctx)
		}
		next.ServeHTTP(w, req)
	})
}

// archiveRead is the key of the repository whose archive req asks for,
// when it asks for one: the route's own shape, /archive/<version> right
// under the repository, found as the router finds the repository (a
// key, then an owner and handle, then a bare handle: web.namespaced).
// A path that merely has "archive" in it, a tree or a wiki page called
// that, is not one.
func (d *tokenDoors) archiveRead(req *http.Request) (string, bool) {
	if d == nil || (req.Method != http.MethodGet && req.Method != http.MethodHead) {
		return "", false
	}
	if _, _, ok := req.BasicAuth(); !ok {
		return "", false
	}
	// The router matches on the escaped path, where an encoded slash
	// stays inside its segment; so does this.
	escaped := req.URL.EscapedPath()
	path, ok := strings.CutPrefix(escaped, "/api/v1/r/")
	if !ok {
		if path, ok = strings.CutPrefix(escaped, "/r/"); !ok {
			return "", false
		}
	}
	segs := strings.Split(path, "/")
	for i, seg := range segs {
		un, err := url.PathUnescape(seg)
		if err != nil {
			return "", false
		}
		segs[i] = un
	}
	key, rest := segs[0], segs[1:]
	if d.places != nil {
		if _, _, isRepo := d.places.Of(key); isRepo {
			// the key itself
		} else if at, found := d.atAddress(key, rest); found {
			key, rest = at, rest[1:]
		} else if keys := d.places.Named(key); len(keys) == 1 {
			key = keys[0]
		} else {
			return "", false
		}
	}
	if key == "" || len(rest) != 2 || rest[0] != "archive" || rest[1] == "" {
		return "", false
	}
	return key, true
}

// atAddress is the repository at owner/handle, owner being first and
// handle rest's first segment.
func (d *tokenDoors) atAddress(owner string, rest []string) (string, bool) {
	if len(rest) == 0 {
		return "", false
	}
	return d.places.At(owner, rest[0])
}

// bearerAsBasic lets a token arrive as "Authorization: Bearer <token>",
// which names no account, by turning it into the Basic account:token
// pair every door already checks. The account is read from the token's
// id; the door then checks the token as it checks any other, so a bearer
// token is limited, held and scoped exactly as a Basic one is. A request
// that also carries Basic credentials keeps them.
//
// Bearer is the form a client should send: a credential in a header is
// never written into a URL, where a Basic user:password is, by every
// tool that prints the URL it followed.
func (d *tokenDoors) bearerAsBasic(req *http.Request) *http.Request {
	if d == nil || d.db == nil {
		return req
	}
	auth := req.Header.Get("Authorization")
	value, ok := strings.CutPrefix(auth, "Bearer ")
	if !ok {
		return req
	}
	value = strings.TrimSpace(value)
	account, ok := d.db.TokenAccount(value)
	if !ok {
		return req
	}
	req = req.Clone(req.Context())
	req.SetBasicAuth(account, value)
	return req
}

// Allowed, Failed and Succeeded are the limiter as the xfer front's
// login card sees it.
func (d *tokenDoors) Allowed(req *http.Request, user string) (bool, time.Duration) {
	if d.limit == nil {
		return true, 0
	}
	return d.limit.Allowed(user, d.ip(req))
}

func (d *tokenDoors) Failed(req *http.Request, user string) {
	if d.limit != nil {
		d.limit.Failed(user, d.ip(req))
	}
}

func (d *tokenDoors) Succeeded(req *http.Request, user string) {
	if d.limit != nil {
		d.limit.Succeeded(user, d.ip(req))
	}
}

// tokenCtx is a context naming the token's account and carrying the
// token, for a door that resolved one outside wrap.
func (d *tokenDoors) tokenCtx(ctx context.Context, user string, tok oltp.Token) context.Context {
	return ops.WithToken(ops.WithUser(ctx, user), d.auth(tok))
}

// basicSyncLogin is xfer.BasicLogin: the account and credential the
// request's Basic password is on the sync lane, with the letters the
// token resolves to on repo. Only a sync token or push credential
// resolves; an account's password never does.
//
// Uncounted, and asked only after syncSignIn has counted the request's
// Basic and found it resolves and its account is not held.
func (d *tokenDoors) basicSyncLogin(req *http.Request, repo string) (string, xfer.Credential, bool) {
	user, _, ok := req.BasicAuth()
	if d == nil || d.db == nil || !ok || user == "" {
		return "", xfer.Credential{}, false
	}
	tok, p := (&tokenDoors{db: d.db}).resolve(req, oltp.ScopeSync)
	if p != resolved {
		return "", xfer.Credential{}, false
	}
	c, ok := d.db.TokenCredential(repo, tok)
	return user, c, ok
}

// syncSignIn is xfer.BasicSignIn: the request's Basic credential as one
// sign-in, on the limiter the sign-in form uses, keyed as it keys them
// (account and address). Held is asked first and nothing is checked for
// a held name, so a right and a wrong credential are answered alike.
// Otherwise the account password, then a live sync token (or a push
// credential minted before tokens had a shape), and one success or one
// miss is counted. An empty password is nobody's and counts nothing:
// a client that names its account in the URL sends one unasked.
func (d *tokenDoors) syncSignIn(req *http.Request) (string, bool, time.Duration) {
	user, pass, ok := req.BasicAuth()
	if d == nil || d.db == nil || !ok || user == "" || pass == "" {
		return "", false, 0
	}
	if d.limit != nil {
		if ok, wait := d.limit.Allowed(user, d.ip(req)); !ok {
			return "", true, wait
		}
	}
	_, resolved := d.db.Authenticate(user, pass)
	if !resolved {
		_, resolved = d.db.ResolveToken(user, pass, oltp.ScopeSync)
	}
	if d.limit != nil {
		if resolved {
			d.limit.Succeeded(user, d.ip(req))
		} else {
			d.limit.Failed(user, d.ip(req))
		}
	}
	if !resolved {
		return "", false, 0
	}
	return user, false, 0
}

// formOwnsTheSignIn reports whether this request's password, if it has
// one, is the form's and is already counted by the handler that reads it:
// the one form that signs a person in.
func formOwnsTheSignIn(req *http.Request) bool {
	return req.Method == http.MethodPost && req.URL.Path == "/login"
}