summaryrefslogtreecommitdiff
path: root/src/http/http.go
blob: 6e57a774801d05ba0c1d1c640f59f0a8f58897d3 (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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Package http implements the HTTP-based api for the mediocre-blog.
package http

import (
	"context"
	"embed"
	"encoding/json"
	"errors"
	"fmt"
	"html/template"
	"net"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"dev.mediocregopher.com/mediocre-blog.git/src/cache"
	"dev.mediocregopher.com/mediocre-blog.git/src/cfg"
	"dev.mediocregopher.com/mediocre-blog.git/src/http/apiutil"
	"dev.mediocregopher.com/mediocre-blog.git/src/post"
	"dev.mediocregopher.com/mediocre-blog.git/src/post/asset"
	"dev.mediocregopher.com/mediocre-blog.git/src/render"
	"dev.mediocregopher.com/mediocre-go-lib.git/mctx"
	"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
)

//go:embed static
var staticFS embed.FS

// Params are used to instantiate a new API instance. All fields are required
// unless otherwise noted.
type Params struct {
	Logger *mlog.Logger
	Cache  cache.Cache

	PostStore       post.Store
	PostAssetStore  asset.Store
	PostAssetLoader asset.Loader
	PostDraftStore  post.DraftStore

	// PublicURL is the base URL which site visitors can navigate to.
	PublicURL *url.URL

	// GeminiPublicURL is the base URL which gemini site visitors can navigate
	// to.
	GeminiPublicURL *url.URL

	// ListenProto and ListenAddr are passed into net.Listen to create the
	// API's listener. Both "tcp" and "unix" protocols are explicitly
	// supported.
	ListenProto, ListenAddr string

	// AuthUsers keys are usernames which are allowed to edit server-side data,
	// and the values are the password hash which accompanies those users. The
	// password hash must have been produced by NewPasswordHash.
	AuthUsers map[string]string

	// AuthRatelimit indicates how much time must pass between subsequent auth
	// attempts.
	AuthRatelimit time.Duration

	// GeminiGatewayURL will be used to translate links for `gemini://` into
	// `http(s)://`. See gmi.GemtextToMarkdown.
	GeminiGatewayURL *url.URL
}

// SetupCfg implement the cfg.Cfger interface.
func (p *Params) SetupCfg(cfg *cfg.Cfg) {

	publicURLStr := cfg.String("http-public-url", "http://localhost:4000", "URL this service is accessible at")
	geminiGatewayURLStr := cfg.String("http-gemini-gateway-url", "", "Optional URL to prefix to all gemini:// links, to make them accessible over https")

	cfg.StringVar(&p.ListenProto, "http-listen-proto", "tcp", "Protocol to listen for HTTP requests with")
	cfg.StringVar(&p.ListenAddr, "http-listen-addr", ":4000", "Address/unix socket path to listen for HTTP requests on")

	httpAuthUsersStr := cfg.String("http-auth-users", "{}", "JSON object with usernames as values and password hashes (produced by the hash-password binary) as values. Denotes users which are able to edit server-side data")

	httpAuthRatelimitStr := cfg.String("http-auth-ratelimit", "5s", "Minimum duration which must be waited between subsequent auth attempts")

	cfg.OnInit(func(context.Context) error {

		err := json.Unmarshal([]byte(*httpAuthUsersStr), &p.AuthUsers)

		if err != nil {
			return fmt.Errorf("unmarshaling -http-auth-users: %w", err)
		}

		if p.AuthRatelimit, err = time.ParseDuration(*httpAuthRatelimitStr); err != nil {
			return fmt.Errorf("unmarshaling -http-auth-ratelimit: %w", err)
		}

		if !strings.HasSuffix(*publicURLStr, "/") {
			*publicURLStr += "/"
		}

		if p.PublicURL, err = url.Parse(*publicURLStr); err != nil {
			return fmt.Errorf("parsing -http-public-url: %w", err)
		}

		if *geminiGatewayURLStr != "" {
			if p.GeminiGatewayURL, err = url.Parse(*geminiGatewayURLStr); err != nil {
				return fmt.Errorf("parsing -http-gemini-gateway-url: %w", err)
			}
		}

		return nil
	})
}

// Annotate implements mctx.Annotator interface.
func (p *Params) Annotate(a mctx.Annotations) {
	a["httpPublicURL"] = p.PublicURL
	a["httpListenProto"] = p.ListenProto
	a["httpListenAddr"] = p.ListenAddr
	a["httpAuthRatelimit"] = p.AuthRatelimit
}

// API will listen on the port configured for it, and serve HTTP requests for
// the mediocre-blog.
type API interface {
	Shutdown(ctx context.Context) error
}

type api struct {
	params Params
	srv    *http.Server

	redirectTpl *template.Template
	auther      Auther
	urlBuilder  render.URLBuilder
}

// New initializes and returns a new API instance, including setting up all
// listening ports.
func New(params Params) (API, error) {

	l, err := net.Listen(params.ListenProto, params.ListenAddr)
	if err != nil {
		return nil, fmt.Errorf("creating listen socket: %w", err)
	}

	if params.ListenProto == "unix" {
		if err := os.Chmod(params.ListenAddr, 0777); err != nil {
			return nil, fmt.Errorf("chmod-ing unix socket: %w", err)
		}
	}

	a := &api{
		params: params,
		auther: NewAuther(params.AuthUsers, params.AuthRatelimit),
		urlBuilder: render.NewURLBuilder(
			params.PublicURL,
			params.PublicURL, // httpURL
			params.GeminiPublicURL,
		),
	}

	a.redirectTpl = mustParseTpl(template.New(""), "redirect.html")

	a.srv = &http.Server{Handler: a.handler()}

	go func() {

		err := a.srv.Serve(l)
		if err != nil && !errors.Is(err, http.ErrServerClosed) {
			ctx := mctx.WithAnnotator(context.Background(), &a.params)
			params.Logger.Fatal(ctx, "serving http server", err)
		}
	}()

	return a, nil
}

func (a *api) Shutdown(ctx context.Context) error {
	defer a.auther.Close()
	if err := a.srv.Shutdown(ctx); err != nil {
		return err
	}

	return nil
}

func (a *api) blogHandler() http.Handler {

	mux := http.NewServeMux()

	mux.Handle("/posts/", http.StripPrefix("/posts",
		apiutil.MethodMux(map[string]http.Handler{
			"GET":     a.getPostsHandler(),
			"EDIT":    a.editPostHandler(false),
			"MANAGE":  a.managePostsHandler(),
			"POST":    a.postPostHandler(),
			"DELETE":  a.deletePostHandler(false),
			"PREVIEW": a.previewPostHandler(),
		}),
	))

	mux.Handle("/assets/", http.StripPrefix("/assets",
		apiutil.MethodMux(map[string]http.Handler{
			"GET":    a.getPostAssetHandler(),
			"MANAGE": a.managePostAssetsHandler(),
			"POST":   a.postPostAssetHandler(),
			"DELETE": a.deletePostAssetHandler(),
		}),
	))

	mux.Handle("/drafts/", http.StripPrefix("/drafts",

		// everything to do with drafts is protected
		authMiddleware(a.auther)(

			apiutil.MethodMux(map[string]http.Handler{
				"EDIT":    a.editPostHandler(true),
				"MANAGE":  a.manageDraftPostsHandler(),
				"POST":    a.postDraftPostHandler(),
				"DELETE":  a.deletePostHandler(true),
				"PREVIEW": a.previewPostHandler(),
			}),
		),
	))

	mux.Handle("/static/", http.FileServer(http.FS(staticFS)))
	mux.Handle("/follow", a.renderDumbTplHandler("follow.html"))
	mux.Handle("/admin", a.renderDumbTplHandler("admin.html"))
	mux.Handle("/feed.xml", a.renderFeedHandler())
	mux.Handle("/", a.renderIndexHandler())

	readOnlyMiddlewares := []middleware{
		logReqMiddleware, // only log GETs on cache miss
		cacheMiddleware(a.params.Cache, a.params.PublicURL),
	}

	readWriteMiddlewares := []middleware{
		purgeCacheOnOKMiddleware(a.params.Cache),
		authMiddleware(a.auther),
	}

	h := apiutil.MethodMux(map[string]http.Handler{
		"GET":    applyMiddlewares(mux, readOnlyMiddlewares...),
		"MANAGE": applyMiddlewares(mux, readOnlyMiddlewares...),
		"EDIT":   applyMiddlewares(mux, readOnlyMiddlewares...),
		"*":      applyMiddlewares(mux, readWriteMiddlewares...),
	})

	return h
}

func (a *api) handler() http.Handler {

	mux := http.NewServeMux()

	mux.Handle("/", a.blogHandler())

	noCacheMiddleware := addResponseHeadersMiddleware(map[string]string{
		"Cache-Control": "no-store, max-age=0",
		"Pragma":        "no-cache",
		"Expires":       "0",
	})

	h := applyMiddlewares(
		apiutil.MethodMux(map[string]http.Handler{
			"GET":    applyMiddlewares(mux),
			"MANAGE": applyMiddlewares(mux, noCacheMiddleware),
			"EDIT":   applyMiddlewares(mux, noCacheMiddleware),
			"*": applyMiddlewares(
				mux,
				a.checkCSRFMiddleware,
				noCacheMiddleware,
			),
		}),
		setLoggerMiddleware(a.params.Logger),
	)

	return h
}