about summary refs log tree commit diff stats
path: root/internal/website/mux.go
blob: 68445513973681d2d63a56c6ac1c2918040441ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package website

import (
	"encoding/json"
	"net/http"
	"strings"

	"go.alanpearce.eu/website/internal/config"
	ihttp "go.alanpearce.eu/website/internal/http"
	"go.alanpearce.eu/x/log"
	"go.alanpearce.eu/website/templates"

	"github.com/benpate/digit"
	"github.com/kevinpollet/nego"
	"gitlab.com/tozd/go/errors"
)

func CanonicalisePath(path string) (cPath string, differs bool) {
	cPath = path
	if strings.HasSuffix(path, "/index.html") {
		cPath, differs = strings.CutSuffix(path, "index.html")
	} else if !strings.HasSuffix(path, "/") && files[path+"/"] != nil {
		cPath, differs = path+"/", true
	}

	return cPath, differs
}

type webHandler func(http.ResponseWriter, *http.Request) *ihttp.Error

type WrappedWebHandler struct {
	config  *config.Config
	handler webHandler
	log     *log.Logger
}

func wrapHandler(cfg *config.Config, webHandler webHandler, log *log.Logger) WrappedWebHandler {
	return WrappedWebHandler{
		config:  cfg,
		handler: webHandler,
		log:     log,
	}
}

func (fn WrappedWebHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if fail := recover(); fail != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fn.log.Error("runtime panic!", "error", fail)
		}
	}()
	if err := fn.handler(w, r); err != nil {
		if strings.Contains(r.Header.Get("Accept"), "text/html") {
			w.WriteHeader(err.Code)
			err := templates.Error(fn.config, r.URL.Path, err).Render(r.Context(), w)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		} else {
			http.Error(w, err.Message, err.Code)
		}
	}
}

func NewMux(cfg *config.Config, root string, log *log.Logger) (mux *http.ServeMux, err error) {
	mux = &http.ServeMux{}

	log.Debug("registering content files", "root", root)
	err = registerContentFiles(root, log)
	if err != nil {
		return nil, errors.WithMessagef(err, "registering content files")
	}
	templates.Setup()

	mux.Handle("/", wrapHandler(cfg, func(w http.ResponseWriter, r *http.Request) *ihttp.Error {
		urlPath, shouldRedirect := CanonicalisePath(r.URL.Path)
		if shouldRedirect {
			http.Redirect(w, r, urlPath, 302)

			return nil
		}
		file := GetFile(urlPath)
		if file == nil {
			return &ihttp.Error{
				Message: "File not found",
				Code:    http.StatusNotFound,
			}
		}
		w.Header().Add("ETag", file.etag)
		w.Header().Add("Vary", "Accept-Encoding")
		w.Header().Add("Content-Security-Policy", cfg.CSP.String())
		for k, v := range cfg.Extra.Headers {
			w.Header().Add(k, v)
		}
		enc := nego.NegotiateContentEncoding(r, file.AvailableEncodings()...)
		switch enc {
		case "br", "gzip":
			w.Header().Add("Content-Encoding", enc)
			w.Header().Add("Content-Type", file.contentType)
		}
		http.ServeFile(w, r, files[urlPath].alternatives[enc])

		return nil
	}, log))

	var acctResource = "acct:" + cfg.Email
	me := digit.NewResource(acctResource).
		Link("http://openid.net/specs/connect/1.0/issuer", "", cfg.OIDCHost.String())

	mux.HandleFunc("/.well-known/webfinger", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("resource") == acctResource {
			obj, err := json.Marshal(me)
			if err != nil {
				http.Error(
					w,
					http.StatusText(http.StatusInternalServerError),
					http.StatusInternalServerError,
				)

				return
			}

			w.Header().Add("Content-Type", "application/jrd+json")
			w.Header().Add("Access-Control-Allow-Origin", "*")
			_, err = w.Write(obj)
			if err != nil {
				log.Warn("error writing webfinger request", "error", err)
			}
		}
	})
	const oidcPath = "/.well-known/openid-configuration"
	mux.HandleFunc(
		oidcPath,
		func(w http.ResponseWriter, r *http.Request) {
			u := cfg.OIDCHost.JoinPath(oidcPath)
			http.Redirect(w, r, u.String(), 302)
		})

	return mux, nil
}