Skip to content
quarry Artifact [6f253e3239]
Login

Artifact [6f253e3239]

Artifact 6f253e3239d81d7bf2eb8a786923d8e05d7a6056cd3d03f4631abceba7034fec:


package web

import (
	"context"
	"errors"
	"html/template"
	"net/http"
	"net/url"
	"strings"

	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

// RFC 0030, Starting without a credential. A client with no credential
// starts a setup and shows its person a short code; the person types it
// here, sees what the client asked for, picks the repositories and
// continues, which files an ordinary request for them to approve. The
// code travels in a form body only, never in a URL.

// setupPageView is /setup in whichever state it is drawn.
type setupPageView struct {
	// State is "" for the code's own form, "nocode" for a code that is
	// not held (every way of not being held reads the same), "held" for
	// an account or address that has missed too often, and "claim" for a
	// found code.
	State string
	// The found code's start. Match says the start came from the network
	// the person is on now.
	Code, Name, Kind, Address, Created string
	Match                              bool
	Repos                              []setupRepo
	Roles                              []string
	Problem, Error                     string
	// NameTaken is the sentence that the started name is already an
	// account, and Suggest a free name to offer in its place; both are
	// empty for a free name. CanCreate offers a new private repository
	// (push), in the person's own namespace (User) or one of Namespaces.
	NameTaken, Suggest string
	// LookAlike names the accounts the started name could be mistaken for.
	LookAlike  []string
	CanCreate  bool
	Namespaces []string
	User       string
	// What the person had picked before a refusal.
	Picked   map[string]bool
	PickRole string
	// PickName is the name they typed for the agent, PickNew says they
	// chose to have a repository made, under PickNewName in PickNamespace.
	PickName, PickNewName, PickNamespace string
	PickNew                              bool
}

// RenameValue is what the agent's name field starts with: what the person
// typed before a refusal, else the free suggestion.
func (v setupPageView) RenameValue() string {
	if v.PickName != "" {
		return v.PickName
	}
	return v.Suggest
}

// CanContinue says there is something to pick: a repository that exists or
// one to be made.
func (v setupPageView) CanContinue() bool { return len(v.Repos) > 0 || (v.Push() && v.CanCreate) }

func (v setupPageView) Push() bool { return v.Kind == "push" }

// LookAlikes is the look-alike names as one list, for the page.
func (v setupPageView) LookAlikes() string { return strings.Join(v.LookAlike, ", ") }

// LookAlikeNames is the same, as the data hook carries it.
func (v setupPageView) LookAlikeNames() string { return strings.Join(v.LookAlike, ",") }

// Filterable says the list is long enough to want a filter.
func (v setupPageView) Filterable() bool { return len(v.Repos) > 12 }

// Count is how many repositories were picked before a refusal.
func (v setupPageView) Count() int { return len(v.Picked) }

// setupRepo is one row of the picker.
type setupRepo struct {
	Name       string `json:"name"`
	Handle     string `json:"handle"`
	Visibility string `json:"visibility"`
	Namespace  string `json:"namespace"`
}

type setupLook struct {
	Code    string      `json:"code"`
	Name    string      `json:"name"`
	Kind    string      `json:"kind"`
	Address string      `json:"address"`
	Created string      `json:"created"`
	Repos   []setupRepo `json:"repos"`
	Roles   []string    `json:"roles"`
	Problem string      `json:"problem"`
	// See api.setupClaimLookOut.
	LookAlike  []string `json:"look_alike"`
	NameTaken  string   `json:"name_taken"`
	Suggest    string   `json:"suggest"`
	CanCreate  bool     `json:"can_create"`
	Namespaces []string `json:"namespaces"`
}

// setupNewPick is the value the picker's "new repository" choice posts as
// a repository; no repository's name can be this.
const setupNewPick = "@new"

func registerSetupPages(mux *http.ServeMux, r *ops.Registry, sessions Sessions) {
	entry := func(w http.ResponseWriter, req *http.Request, v setupPageView, status int) {
		renderStatus(r, w, req, setupEntryTmpl, pageData{Title: "Set up a client", SetupPage: &v, OwnH1: true, Appear: appearanceOf(req)}, status)
	}
	claim := func(w http.ResponseWriter, req *http.Request, v setupPageView, status int) {
		v.State = "claim"
		renderStatus(r, w, req, setupClaimTmpl, pageData{Title: "A client asks for access", SetupPage: &v, OwnH1: true, Appear: appearanceOf(req)}, status)
	}
	signedIn := func(w http.ResponseWriter, req *http.Request) (string, bool) {
		user, ok := sessions.Resolve(cookieToken(req))
		if !ok {
			http.Redirect(w, req, "/login?next="+url.QueryEscape("/setup"), http.StatusSeeOther)
		}
		return user, ok
	}
	// notHeld draws what an op's refusal of a code means: a code not held
	// is the one state, whatever became of it.
	notHeld := func(w http.ResponseWriter, req *http.Request, err error) {
		switch {
		case errors.Is(err, ops.ErrNotFound):
			entry(w, req, setupPageView{State: "nocode"}, http.StatusNotFound)
		case errors.Is(err, ops.ErrRateLimited):
			w.Header().Set("Retry-After", "60")
			entry(w, req, setupPageView{State: "held"}, http.StatusTooManyRequests)
		case errors.Is(err, ops.ErrUnavailable):
			entry(w, req, setupPageView{State: "lost"}, http.StatusServiceUnavailable)
		default:
			fail(r, w, req, err)
		}
	}
	// as is the call's context: the person, and the address the page was
	// asked from, which the ops count misses against.
	as := func(req *http.Request, user string) context.Context {
		return ops.WithAddr(ops.WithUser(req.Context(), user), clientIP(req))
	}
	look := func(req *http.Request, user, code string) (setupLook, error) {
		var l setupLook
		if len(code) > 64 {
			code = code[:64]
		}
		out, err := invoke(as(req, user), r, "setup.start.look", url.Values{"code": {code}})
		if err != nil {
			return l, err
		}
		remarshal(out, &l)
		return l, nil
	}
	view := func(req *http.Request, user string, l setupLook) setupPageView {
		return setupPageView{Code: l.Code, Name: l.Name, Kind: l.Kind, Address: l.Address, Created: l.Created,
			Match: l.Address == oltp.AddrGroup(clientIP(req)), Repos: l.Repos, Roles: l.Roles, Problem: l.Problem,
			LookAlike: l.LookAlike, NameTaken: l.NameTaken, Suggest: l.Suggest, CanCreate: l.CanCreate, Namespaces: l.Namespaces, User: user}
	}
	mux.HandleFunc("GET /setup", func(w http.ResponseWriter, req *http.Request) {
		if _, ok := signedIn(w, req); !ok {
			return
		}
		entry(w, req, setupPageView{}, http.StatusOK)
	})
	mux.HandleFunc("POST /setup", func(w http.ResponseWriter, req *http.Request) {
		user, ok := signedIn(w, req)
		if !ok {
			return
		}
		l, err := look(req, user, req.FormValue("code"))
		if err != nil {
			notHeld(w, req, err)
			return
		}
		claim(w, req, view(req, user, l), http.StatusOK)
	})
	mux.HandleFunc("POST /setup/claim", func(w http.ResponseWriter, req *http.Request) {
		user, ok := signedIn(w, req)
		if !ok {
			return
		}
		code := req.FormValue("code")
		if req.FormValue("do") == "discard" {
			if _, err := invoke(as(req, user), r, "setup.start.discard", url.Values{"code": {code}}); err != nil {
				notHeld(w, req, err)
				return
			}
			http.Redirect(w, req, "/setup", http.StatusSeeOther)
			return
		}
		repos := make([]string, 0, len(req.Form["repos"]))
		// The "new repository" choice replaces the pick: the claim then
		// names the repository to make, and where.
		makeNew := false
		for _, repo := range req.Form["repos"] {
			if repo = strings.TrimSpace(repo); repo == setupNewPick {
				makeNew = true
			} else if repo != "" {
				repos = append(repos, repo)
			}
		}
		name, newName, newSpace := strings.TrimSpace(req.FormValue("name")), strings.TrimSpace(req.FormValue("new_name")), req.FormValue("new_namespace")
		args := url.Values{"code": {code}, "repos": {strings.Join(repos, ",")}, "role": {req.FormValue("role")}, "name": {name}}
		if makeNew && newName != "" {
			args.Set("new_repo", newName)
			args.Set("namespace", newSpace)
		}
		// refused draws the same page again, with the sentence and the
		// picks kept.
		refused := func(sentence string, status int) {
			l, lerr := look(req, user, code)
			if lerr != nil {
				notHeld(w, req, lerr)
				return
			}
			v := view(req, user, l)
			v.Error, v.PickRole = sentence, req.FormValue("role")
			v.PickName, v.PickNew, v.PickNewName, v.PickNamespace = name, makeNew, newName, newSpace
			v.Picked = map[string]bool{}
			for _, repo := range repos {
				v.Picked[repo] = true
			}
			claim(w, req, v, status)
		}
		if makeNew && newName == "" {
			refused("Type a name for the new repository.", http.StatusBadRequest)
			return
		}
		out, err := invoke(as(req, user), r, "setup.start.claim", args)
		if err != nil {
			if errors.Is(err, ops.ErrInvalid) || errors.Is(err, ops.ErrForbidden) {
				refused(opsSentence(err), http.StatusBadRequest)
				return
			}
			notHeld(w, req, err)
			return
		}
		var got struct {
			Request string `json:"request"`
		}
		remarshal(out, &got)
		http.Redirect(w, req, "/me/requests/"+url.PathEscape(got.Request), http.StatusSeeOther)
	})
}

// setupEntryTmpl is the form that takes a client's code.
var setupEntryTmpl = page(template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}{{with .SetupPage}}
<section class="approve" data-hook="setup-entry" data-state="{{.State}}">
<h1>Set up a client</h1>
<p>A client that has no access yet showed you a code. Type it here to see what it asks for. Nothing is made until you approve a request.</p>
{{if eq .State "nocode"}}<p class="status err" role="alert" data-hook="setup-nocode">There is no such code. It may be mistyped, already used, discarded, or past its ten minutes; the client can start again.</p>{{end}}
{{if eq .State "held"}}<p class="status err" role="alert" data-hook="setup-held">Too many codes were tried that are not held. Wait a few minutes and try again.</p>{{end}}
{{if eq .State "lost"}}<p class="status err" role="alert" data-hook="setup-lost">The request could not be filed, and the code was lost with it. Start again from the client.</p>{{end}}
<form method="post" action="/setup" class="auth-form" data-hook="setup-code-form">
<p><label>Code from the client<br><input name="code" data-hook="setup-code" placeholder="XXXX-XXXX" maxlength="40" autocomplete="off" autocapitalize="characters" spellcheck="false" required autofocus></label></p>
<p><button type="submit" class="btn-primary" data-hook="setup-look">Look up</button></p>
</form>
</section>{{end}}{{end}}`)))

// setupClaimTmpl shows what a client asked for and takes the person's
// picks.
var setupClaimTmpl = page(template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}{{with .SetupPage}}
<section class="approve" data-hook="setup-claim" data-kind="{{.Kind}}">
<h1>A client asks for access</h1>
<p class="approve-title">It asks to be set up as <strong data-hook="setup-claim-name">{{.Name}}</strong>, {{if .Push}}pushing to the repositories you pick{{else}}reading the repositories you pick{{end}}.</p>
<dl class="review-definition">
<dt>Agent</dt><dd data-hook="setup-claim-agent" data-agent="{{.Name}}">{{if .NameTaken}}A new agent, under a name you give below.{{else}}{{.Name}}, a new agent.{{end}} {{if .Push}}Pick one repository you administer and it belongs to that repository, its admins managing it; otherwise, and always for several, it is yours.{{else}}Yours: you answer for it.{{end}}</dd>
<dt>Kind</dt><dd data-hook="setup-claim-kind" data-kind="{{.Kind}}">{{if .Push}}Pushes: sync only, to the repositories you pick, with the role you choose.{{else}}Reads: the code, tickets, wiki and CI runs of the repositories you pick, and nothing else.{{end}}</dd>
<dt>Code</dt><dd><code data-hook="setup-claim-code">{{.Code}}</code></dd>
<dt>Started</dt><dd data-hook="setup-claim-from" data-address="{{.Address}}" data-match="{{.Match}}">From {{if .Match}}this network{{else}}<code>{{.Address}}</code>{{end}}, <span data-hook="setup-claim-when">{{ago .Created}}</span>.</dd>
</dl>
{{if not .Match}}<p class="status err" role="alert" data-hook="setup-claim-elsewhere" data-match="false">This client is on a different network than you are. That is expected only if the client runs on another machine than the one you are using now.</p>{{end}}
{{if .LookAlike}}<p class="status err" role="alert" data-hook="setup-claim-lookalike" data-names="{{.LookAlikeNames}}">The name {{if .NameTaken}}offered{{else}}{{.Name}}{{end}} looks like {{.LookAlikes}}. Check the spelling before you continue.</p>{{end}}
<p data-hook="setup-claim-warn"><strong>Continue only for a client you started yourself, just now, on a device you are using.</strong> Never use a code someone sent you: anyone can start a client and send its code to you.</p>
{{with .Error}}<p class="status err" role="alert" data-hook="setup-claim-error"><strong>{{.}}</strong></p>{{end}}
<form method="post" action="/setup/claim" data-hook="setup-claim-form">
<input type="hidden" name="code" value="{{.Code}}">
{{if .NameTaken}}<p class="status err" role="alert" data-hook="setup-claim-taken">{{.NameTaken}} Give the agent another name; it learns it when it collects.</p>
<p><label>Name for the agent<br><input name="name" data-hook="setup-claim-rename" value="{{.RenameValue}}" maxlength="64" pattern="[A-Za-z0-9][A-Za-z0-9._\-]*" autocomplete="off" autocapitalize="off" spellcheck="false" required></label></p>{{end}}
{{if .CanContinue}}<div class="claim-pick" data-hook="setup-claim-repos" data-signals="{q: '', n: {{.Count}}, mk: {{.PickNew}}}" data-on:change="$n = evt.target.form.querySelectorAll('input[name=repos]:checked').length; $mk = !!evt.target.form.querySelector('[data-hook=setup-claim-new]:checked')">
<h2>Pick the repositories <span class="tl-meta-inline"><span data-hook="setup-claim-count" data-text="$n">{{.Count}}</span> selected</span></h2>
{{if .Filterable}}<p><input type="search" class="claim-filter" placeholder="Filter repositories" aria-label="Filter repositories" autocomplete="off" data-bind="q" data-hook="setup-claim-filter"></p>{{end}}
<ul class="claim-list">
{{if and .Push .CanCreate}}<li data-hook="setup-claim-new-row"><label class="claim-row"><input type="checkbox" name="repos" value="@new" data-hook="setup-claim-new"{{if .PickNew}} checked{{end}}><span class="claim-name">A new private repository</span><span class="claim-meta">made when you approve</span></label>
<div class="claim-new" data-hook="setup-claim-new-fields" data-show="$mk"{{if not .PickNew}} style="display: none"{{end}}>
{{if .Namespaces}}<p><label>Owner<br><select name="new_namespace" data-hook="setup-claim-namespace"><option value=""{{if not .PickNamespace}} selected{{end}}>{{.User}}</option>{{range .Namespaces}}<option value="{{.}}"{{if eq . $.SetupPage.PickNamespace}} selected{{end}}>{{.}}</option>{{end}}</select></label></p>{{end}}
<p><label>Repository name<br><input name="new_name" data-hook="setup-claim-new-name" value="{{.PickNewName}}" maxlength="64" pattern="[A-Za-z0-9][A-Za-z0-9._\-]*" autocomplete="off" autocapitalize="off" spellcheck="false"></label></p>
</div></li>
{{end}}{{range .Repos}}<li data-hook="setup-claim-row" data-show="!$q || '{{.Name}} {{.Namespace}}'.toLowerCase().includes($q.toLowerCase())"><label class="claim-row"><input type="checkbox" name="repos" value="{{.Name}}" data-hook="setup-claim-repo"{{if index $.SetupPage.Picked .Name}} checked{{end}}><span class="claim-name">{{repoName .Name}}</span><span class="claim-meta">{{with .Visibility}}{{.}}{{end}}{{if and .Visibility .Namespace}} ยท {{end}}{{with .Namespace}}{{.}}{{end}}</span></label></li>
{{end}}</ul>
</div>
{{if .Push}}<p><label>Role<br><select name="role" data-hook="setup-claim-role">{{range .Roles}}<option value="{{.}}"{{if or (eq . $.SetupPage.PickRole) (and (not $.SetupPage.PickRole) (eq . "developer"))}} selected{{end}}>{{.}}</option>{{end}}</select></label></p>{{end}}
<p>Continue files a request for you to approve, with exactly these picks. Nothing is made until you do.</p>
{{else}}<p class="status err" role="alert" data-hook="setup-claim-empty">{{with .Problem}}{{.}}{{else}}There is no repository you may set this agent up on.{{end}} There is nothing to continue with: discard the code.</p>{{end}}
<div class="signoff-acts"><button type="submit" name="do" value="discard" class="btn" formnovalidate data-hook="setup-claim-discard">Discard</button>{{if .CanContinue}}<button type="submit" name="do" value="continue" class="btn btn-primary" data-hook="setup-claim-continue">Continue</button>{{end}}</div>
</form>
</section>{{end}}{{end}}`)))