forked from d33mobile/dday
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
259 lines (230 loc) · 9.25 KB
/
Copy pathserver.go
File metadata and controls
259 lines (230 loc) · 9.25 KB
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
// HTTP wiring shared by every handler: the dependency bundle, the mux, the
// static pages, token decoding, the template render helpers and the small
// capacity/identity utilities. The per-area handlers live in register.go,
// panel.go, admin.go and api.go.
package main
import (
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
"github.com/d33mobile/dday/internal/matrixbot"
"github.com/d33mobile/dday/internal/store"
"filippo.io/age"
)
// tokenTTL bounds how long a registration link stays valid after it was issued.
// A token older than this (or issued in the future beyond a small clock-skew
// tolerance) is rejected in decode().
const tokenTTL = 48 * time.Hour
// tokenFutureSkew tolerates a small amount of clock drift when the token's
// Issued time is ahead of the server's clock.
const tokenFutureSkew = 5 * time.Minute
// deps carries the runtime dependencies of the registration handlers, so the
// mux can be built in tests with an in-memory store, an ephemeral key and an
// injectable time gate.
type deps struct {
store *store.Store
identity age.Identity
seatLimit int // confirmed participant places (numbers 1..seatLimit)
waitlistLimit int // waiting-list places (numbers seatLimit+1..seatLimit+waitlistLimit)
isOpen func() bool
files http.FileSystem // static files for GET /
internalToken string // bearer token guarding /api/registered; empty disables it
adminToken string // bearer/query token guarding /admin; empty disables it
tokenSecret string // shared HMAC key authenticating registration tokens
}
// total is the overall capacity: confirmed seats plus waiting-list places. A
// registration is refused only once total is reached.
func (d deps) total() int { return d.seatLimit + d.waitlistLimit }
// formView is the data model for the registration form template.
type formView struct {
Title string
Token string
Nick string
City string
Email string
Error string
Count int
Limit int
Waitlist bool // true when confirmed seats are gone: this signup joins the waiting list
}
// resultView backs the success/duplicate/waitlist/message pages.
type resultView struct {
Title string
Nick string
Number int
WaitlistPos int // position on the waiting list (number-seatLimit); 0 for confirmed participants
Message string
Detail string
}
// newMux builds the HTTP handler with every route, wrapped in the security
// middleware. It is the single place both main() and the tests construct.
func newMux(d deps) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
})
mux.HandleFunc("/register", d.handleRegister)
mux.HandleFunc("/panel", d.handlePanel)
mux.HandleFunc("/api/count", d.handleCount)
mux.HandleFunc("/api/registered", d.handleRegistered)
mux.HandleFunc("/api/registrations", d.handleRegistrations)
mux.HandleFunc("/admin", d.handleAdmin)
mux.HandleFunc("/privacy", d.handlePrivacy)
mux.HandleFunc("/style.css", d.handleStylesheet)
mux.HandleFunc("/", d.handleRoot)
return secure(mux)
}
// handleRoot serves the landing page for "/" only. Unlike http.FileServer it
// never walks the static directory, so STATIC_DIR=. (a dev convenience that
// points at the repo root) can never leak matrix.env, the age key or the SQLite
// DB via an arbitrary path — anything other than "/" is a 404.
func (d deps) handleRoot(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
if r.Method != http.MethodGet {
methodNotAllowed(w)
return
}
d.serveStatic(w, "index.html", contentTypeHTML)
}
// Content types of the static files the handlers may serve.
const (
contentTypeHTML = "text/html; charset=utf-8"
contentTypeCSS = "text/css; charset=utf-8"
)
// stylesheetMaxAge is how long /style.css may be cached. Short enough that a
// redeployed stylesheet reaches visitors quickly, long enough to spare the
// server a request per page view.
const stylesheetMaxAge = time.Hour
// serveStatic writes one of the fixed, known files from d.files with the given
// content type. Only the names the handlers reference can be served — there is
// no path input, so a STATIC_DIR pointing at a directory with secrets cannot
// expose them.
func (d deps) serveStatic(w http.ResponseWriter, name, contentType string) {
f, err := d.files.Open(name)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
defer f.Close()
w.Header().Set("Content-Type", contentType)
if _, err := io.Copy(w, f); err != nil {
log.Printf("serve %s: %v", name, err)
}
}
// handleStylesheet serves the one stylesheet shared by the landing page, the
// privacy page and the server-rendered templates.
func (d deps) handleStylesheet(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
methodNotAllowed(w)
return
}
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(stylesheetMaxAge.Seconds())))
d.serveStatic(w, "style.css", contentTypeCSS)
}
// methodNotAllowed writes a 405 with an Allow: GET header, for the GET-only
// read endpoints.
func methodNotAllowed(w http.ResponseWriter) {
w.Header().Set("Allow", "GET")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
// ready reports whether registration can run (key loaded and DB open). When it
// is false the site still serves the landing page; only registration degrades.
func (d deps) ready() bool { return d.store != nil && d.identity != nil }
// waitlistPos maps a rank (position among current registrations, ordered by id)
// to a waiting-list position, or 0 for a confirmed participant. Status is
// derived from the rank rather than the participant number, so when someone
// withdraws everyone behind them moves up a place.
func (d deps) waitlistPos(rank int) int {
if rank > d.seatLimit {
return rank - d.seatLimit
}
return 0
}
func (d deps) handlePrivacy(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
methodNotAllowed(w)
return
}
d.serveStatic(w, "privacy.html", contentTypeHTML)
}
// decode validates a token and checks it was issued for wantKind; on failure it
// writes a 400 page and returns ok=false. The kind is covered by the token's
// HMAC, so a registration link presented to /panel (or a panel link presented to
// /register) is rejected with a deliberately vague "Nieprawidłowy link".
func (d deps) decode(w http.ResponseWriter, token, wantKind string) (matrixbot.RegPayload, bool) {
if strings.TrimSpace(token) == "" {
d.renderMessage(w, http.StatusBadRequest, "Nieprawidłowy link",
"Brak tokenu rejestracji.",
"Skorzystaj z linku otrzymanego od bota na czacie Matrix.")
return matrixbot.RegPayload{}, false
}
payload, err := matrixbot.DecodeRegToken(d.identity, d.tokenSecret, token)
if err != nil {
d.renderMessage(w, http.StatusBadRequest, "Nieprawidłowy link",
"Ten link rejestracyjny jest nieprawidłowy lub uszkodzony.",
"Poproś bota o nowy link na czacie Matrix.")
return matrixbot.RegPayload{}, false
}
// TTL: reject a stale link, or one whose Issued time is too far in the
// future (beyond a small clock-skew tolerance).
elapsed := time.Now().Unix() - payload.Issued
if elapsed > int64(tokenTTL/time.Second) || elapsed < -int64(tokenFutureSkew/time.Second) {
d.renderMessage(w, http.StatusBadRequest, "Link wygasł",
"Ten link rejestracyjny wygasł.",
"Poproś bota o nowy link na czacie Matrix.")
return matrixbot.RegPayload{}, false
}
// Kind scoping: the token must have been minted for this endpoint. The
// message stays generic so it does not reveal which link the visitor holds.
if matrixbot.NormalizeKind(payload.Kind) != matrixbot.NormalizeKind(wantKind) {
d.renderMessage(w, http.StatusBadRequest, "Nieprawidłowy link",
"Ten link jest nieprawidłowy.",
"Poproś bota o nowy link na czacie Matrix.")
return matrixbot.RegPayload{}, false
}
return payload, true
}
func (d deps) renderForm(w http.ResponseWriter, v formView) {
v.Title = "Zapis"
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.ExecuteTemplate(w, "form", v); err != nil {
log.Printf("render form: %v", err)
}
}
func (d deps) renderResult(w http.ResponseWriter, name string, v resultView) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.ExecuteTemplate(w, name, v); err != nil {
log.Printf("render %s: %v", name, err)
}
}
func (d deps) renderMessage(w http.ResponseWriter, status int, title, msg, detail string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
if err := tmpl.ExecuteTemplate(w, "message", resultView{Title: title, Message: msg, Detail: detail}); err != nil {
log.Printf("render message: %v", err)
}
}
func (d deps) serverError(w http.ResponseWriter, ctx string, err error) {
log.Printf("%s: %v", ctx, err)
http.Error(w, "internal error", http.StatusInternalServerError)
}
// nickFromHandle turns a Matrix MXID "@alice:hs.org" into the localpart "alice".
// Any string that does not match the @local:server shape is returned unchanged.
func nickFromHandle(handle string) string {
if !strings.HasPrefix(handle, "@") {
return handle
}
rest := handle[1:]
i := strings.IndexByte(rest, ':')
if i <= 0 {
return handle
}
return rest[:i]
}