Recipes
What this covers: four things borgo deliberately does not ship, each built from what it does ship — a background job, a password reset by mail, a route another origin may call, and file storage that is not the local disk. Each recipe says which parts are borgo's and which are yours.
A background job#
borgo has no scheduler. A job is a goroutine started from main, and the one thing it needs from the framework is to know when the process is stopping. borgo.Serve owns the signals and tells nobody; borgo.ServeContext takes a context of yours, so the job and the server can share one.
// every runs job at once and then every interval, until ctx ends. One run at
// a time: a run that outlasts the interval delays the next one, it does not
// overlap it.
func every(ctx context.Context, interval time.Duration, name string, job func(context.Context) error) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
runJob(ctx, name, job)
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func runJob(ctx context.Context, name string, job func(context.Context) error) {
// borgo recovers a handler that panics; a goroutine of yours is yours,
// and a panic in it ends the process
defer func() {
if v := recover(); v != nil {
log.Printf("%s: panicked: %v", name, v)
}
}()
if err := job(ctx); err != nil && ctx.Err() == nil {
log.Printf("%s: %v", name, err)
}
}
main starts it, serves, and waits for the run in progress before it exits. It is not compiled here because it needs os/signal:
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// once the first signal has arrived, a second one ends the process:
// what borgo.Serve does for a shutdown that takes too long
go func() { <-ctx.Done(); stop() }()
var jobs sync.WaitGroup
jobs.Add(1)
go func() {
defer jobs.Done()
every(ctx, time.Hour, "prune uploads", pruneUploads)
}()
// returns when ctx ends, after draining as Serve does
if err := borgo.ServeContext(ctx); err != nil {
log.Fatal(err)
}
stop() // ServeContext also returns when its launcher died: end the jobs then too
jobs.Wait() // the run in progress saw ctx end, and finishes or gives up
}
- The job has to honour its context.
jobs.Wait()waits for as long as a run takes to notice thatctxended; passctxto every query and outgoing call the job makes. The supervisor's stop grace covers the server's shutdown and the job's last run together. - It runs in every instance. With more than one, each has its own ticker and the job runs once per instance per interval. Make the job safe to run twice, or let the database decide who runs it — a row claimed in a transaction, an advisory lock.
- Under
borgo devit restarts with the binary, on every Go change, and runs at once each time. - It is not a queue. Nothing is kept between runs, and work that must survive a restart belongs in a table the job reads.
Password reset by mail#
borgo has no password reset and sends no mail. What it has are the pieces a reset is built from: the hashing, the form validation and the limiter. The parts that are yours: a table of reset requests, and a way to send a message.
Three rules make a reset safe, and the code below keeps each:
- The token is stored hashed. A copy of the table must not open any account, so the table holds the SHA-256 of the token and the mail holds the token.
- A token works once, and stops working after half an hour.
- Asking for a reset says nothing about who has an account. The answer is the same for a username nobody has.
// ResetStore is a table of yours, one row per request: the digest of a
// token, whose it is, and when it stops working.
type ResetStore interface {
// Issue mints a token, stores its SHA-256, and returns the token.
// "" and no error for a username nobody has.
Issue(ctx context.Context, username string, expires time.Time) (token string, err error)
// Redeem deletes the row a token names and reports whose it was: false
// for a token it does not hold, or one past its time.
Redeem(ctx context.Context, token string, now time.Time) (username string, ok bool, err error)
SetPassword(ctx context.Context, username, hash string) error
}
var resets ResetStore
// sendResetMail is a PLACEHOLDER. borgo sends no mail: call your provider here.
func sendResetMail(ctx context.Context, username, link string) error { return nil }
type ResetRequest struct {
Username string `json:"username"`
}
func requestReset(w http.ResponseWriter, r *http.Request) {
body, err := borgo.Bind[ResetRequest](r)
if err != nil {
borgo.BindError(w, err)
return
}
token, err := resets.Issue(r.Context(), body.Username, time.Now().Add(30*time.Minute))
if err != nil {
borgo.Log(r).Error("reset: issue", "err", err)
borgo.Error(w, http.StatusInternalServerError, map[string]string{"error": "try again in a moment"})
return
}
if token != "" {
// your own address, never the request's Host header
link := "https://app.example.com/reset?token=" + token
if err := sendResetMail(r.Context(), body.Username, link); err != nil {
borgo.Log(r).Error("reset: mail", "err", err)
}
}
// the same answer whether or not the username exists
w.WriteHeader(http.StatusAccepted)
}
type ResetForm struct {
Token string `json:"token"`
Password string `json:"password"`
}
func (f ResetForm) Validate() error {
bad := borgo.Invalid{}
if f.Token == "" {
bad["token"] = "the link is incomplete"
}
if len(f.Password) < 12 {
bad["password"] = "at least 12 characters"
}
return bad.OrNil()
}
func completeReset(w http.ResponseWriter, r *http.Request) {
form, err := borgo.BindValid[ResetForm](r)
if err != nil {
borgo.BindError(w, err)
return
}
// hashed before the token is spent, in one of the slots sign-in uses: a
// request shed with 503 has not used up its link
var hash string
var hashErr error
if !borgo.WithHashSlot(w, r, func() { hash, hashErr = borgo.DefaultHasher().Hash(form.Password) }) {
return
}
if hashErr != nil {
borgo.Log(r).Error("reset: hash", "err", hashErr)
borgo.Error(w, http.StatusInternalServerError, map[string]string{"error": "try again in a moment"})
return
}
username, ok, err := resets.Redeem(r.Context(), form.Token, time.Now())
if err == nil && ok {
err = resets.SetPassword(r.Context(), username, hash)
}
switch {
case err != nil:
borgo.Log(r).Error("reset: complete", "err", err)
borgo.Error(w, http.StatusInternalServerError, map[string]string{"error": "try again in a moment"})
case !ok:
// 422 {error, fields}, the shape the form already reads
borgo.BindError(w, borgo.Invalid{"token": "this link has expired or was already used"})
default:
w.WriteHeader(http.StatusNoContent)
}
}
func init() {
// three requests an hour from one client: each one is a mail somebody receives
borgo.Handle("POST /api/password-reset", borgo.Limit(3, time.Hour, nil)(requestReset))
borgo.Handle("POST /api/password-reset/complete", borgo.Limit(10, time.Hour, nil)(completeReset))
}
The store's two operations are where the first two rules live. They are yours and are not compiled here; the shape is:
// crypto/rand, crypto/sha256, encoding/base64, encoding/hex
func newToken() (token, digest string, err error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return "", "", err
}
token = base64.RawURLEncoding.EncodeToString(raw)
sum := sha256.Sum256([]byte(token))
return token, hex.EncodeToString(sum[:]), nil
}
// Redeem is one statement, so two requests with one token cannot both win:
//
// delete from password_resets where digest = $1 and expires > $2 returning username
RedeemandSetPasswordbelong in one transaction where the store has them: as written, a password that fails to save has still spent the link.- A token is 32 random bytes, so SHA-256 is enough. A password needs a slow hash because it can be guessed; a random token cannot, and a plain digest lets the row be found by it.
- A reset should end the sessions that came before it. Record the moment in the cutoff your
CheckSessionreads, as "log out everywhere" does: whoever knew the old password is otherwise still signed in. - The mail is sent on the request here, which makes a request for a real account slower than one for nobody, and that difference can be measured. Hand the send to a goroutine or a job once the reset matters to somebody.
- Both routes are wrapped in
borgo.Limit, so borgogen leaves their typesunknownand warns: why. The limit counts per instance. - The page that opens the link reads
tokenfrom its URL in a loader and posts it back with the new password;error.fields()on theApiErrorholds whatValidateor the expired link said.
A route another origin may call#
borgo sends no Access-Control-* header and answers no preflight. That is the stance, not an omission: a page from another origin cannot read a response from your api, and cannot send it a request a plain form could not send. The CSRF check leans on exactly that — a cross-origin script cannot set the X-CSRF-Token header without an approval borgo does not give.
Some routes are meant for other origins: public data a partner's page fetches. Approve those routes and no others, by wrapping their handlers:
// allowOrigin lets pages of one other origin read a route's answer
func allowOrigin(origin string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// the answer differs by who asks: a cache must not hand one to the other
w.Header().Add("Vary", "Origin")
if r.Header.Get("Origin") == origin {
w.Header().Set("Access-Control-Allow-Origin", origin)
if r.Method == http.MethodOptions {
// the preflight: what the real request may be
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Max-Age", "600")
w.WriteHeader(http.StatusNoContent)
return
}
}
next(w, r)
}
}
func listPrices(w http.ResponseWriter, r *http.Request) {
borgo.JSON(w, http.StatusOK, map[string]int{"basic": 9})
}
func init() {
partner := func(h http.HandlerFunc) http.HandlerFunc { return allowOrigin("https://partner.example", h) }
borgo.Handle("GET /api/public/prices", partner(listPrices))
// a preflight is its own request, with its own method: without a route
// for it the mux answers 405 and the browser stops there
borgo.Handle("OPTIONS /api/public/prices", partner(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
}
- Name origins; do not echo them. Writing back whatever
Originarrived approves every site on the internet.*is the honest way to say "anyone" for data that is public. - Do not add
Access-Control-Allow-Credentials. The session cookie isSameSite=Lax, so a browser does not attach it to a cross-sitefetchwhatever the header says. From a sibling subdomain it would be attached, and that is the caller the CSRF check exists for: its unsafe requests carry your cookies and cannot produce the token, and they are answered403before your handler. A session does not cross origins in borgo. An api for other origins authenticates with a token of its own in a header, and thenAuthorizationjoinsAccess-Control-Allow-Headers. - A
POSTwith a JSON body is always preflighted, becauseborgo.Bindaccepts no other content type andapplication/jsonis not one a form can send. Every route that takes one needs itsOPTIONStwin. - The wrapper costs the route its generated types, as any wrapper but
borgo.Autheddoes. A route for other origins is not called through your own typed client, so that is seldom a loss. - This is about
fetch. A WebSocket is checked by itsOriginagainst the server's own, with no list to add to: realtime surface.
File storage beyond local disk#
borgo.Uploads is two fields, Dir and Types, and five operations that all read and write files in Dir. There is no storage interface to implement and nothing to plug an object store into. What can be changed is where Dir is:
// every instance mounts the same share at this path
var shared = borgo.Uploads{
Dir: "/data/uploads",
Types: []string{"image/png", "image/jpeg", "application/pdf"},
}
A network file system or a volume attached to every instance, mounted at the same path, is the whole change: Save, SaveReader, Serve, ServePreview and Remove work as on one disk. The files are created 0600 in a directory created 0700, so every instance has to run as the same user.
For an object store — S3 and the like — Uploads does not apply to the stored file, and the app owns what Uploads decided for it. Here is the list, so that nothing on it is dropped by accident:
- What the bytes are.
Savesniffs the content (http.DetectContentType) and refuses whatTypesdoes not list. The client'sContent-Typeis a claim. - The name they live under. A random key, never the client's file name.
- The headers a download goes out with. The sniffed type with
X-Content-Type-Options: nosniff;Content-Disposition: attachmentfor everything but PNG, JPEG, GIF and WebP;Content-Security-Policy: default-src 'none'; sandbox;Cache-Control: private, no-cache. An object served straight from a bucket carries whatever was set on the object, so these go on at upload time, or the app streams the object through a handler that sets them. - Who may download. Already yours with
Uploads, and still yours: a link to a bucket is not an authorization.
One arrangement keeps the first two: let Save take the upload as it does now — the file it writes is Dir/<Key> — then copy that file to the store under the same key and Remove the local one. The sniffed type and the size are in the Stored it returned. Serving is then entirely the app's, with the headers above.
Being found: canonical addresses, robots, a sitemap#
Three things a public site owes a search engine, none of which needs anything of borgo beyond what a page and a route already are.
The canonical address of a page, and the same page in other languages, are links in its head: written on the server, kept in step by client navigation.
import type { Head } from "borgo-framework";
export const head = (props: { post: { slug: string; title: string } }): Head => ({
title: props.post.title,
lang: "en",
links: [
{ rel: "canonical", href: `https://example.com/blog/${props.post.slug}` },
{ rel: "alternate", hreflang: "it", href: `https://example.com/it/blog/${props.post.slug}` },
],
});
Write the canonical address in full, with the scheme and the host people should arrive at: a path would be resolved against whichever host the page was reached by, which is the thing a canonical address exists to settle.
robots.txt is a file: put it in public/, and it is served from the root.
User-agent: *
Disallow: /account
Sitemap: https://example.com/api/sitemap.xml
A sitemap that lists what is in the database is a route. Go routes live under /api, and a sitemap may live anywhere on the host as long as robots.txt names it, as the line above does: that line is what lets it list addresses outside its own directory.
//borgo:route GET /api/sitemap.xml
func Sitemap(w http.ResponseWriter, r *http.Request) {
posts, err := db.PublishedPosts(r.Context())
if err != nil {
http.Error(w, "the sitemap could not be read", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
// the same for everybody, so a proxy may keep it for an hour
borgo.Cache(w, time.Hour)
fmt.Fprint(w, `<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
for _, p := range posts {
fmt.Fprintf(w, "<url><loc>https://example.com/blog/%s</loc><lastmod>%s</lastmod></url>",
url.PathEscape(p.Slug), p.UpdatedAt.UTC().Format("2006-01-02"))
}
fmt.Fprint(w, "</urlset>")
}
A site whose pages are all files in pages/ and never change between deploys can write public/sitemap.xml by hand, or from a script in its build, and skip the route.