/
admin.go
718 lines (649 loc) · 15 KB
/
admin.go
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// Various administration endpoints for logged in users
package server
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"meguca/auth"
"meguca/common"
"meguca/config"
"meguca/db"
"meguca/templates"
"meguca/websockets/feeds"
"net/http"
"regexp"
"strconv"
"time"
)
const (
// Body size limit for POST request JSON. Should never exceed 32 KB.
// Consider anything bigger an attack.
jsonLimit = 1 << 15
maxAnswers = 100 // Maximum number of eightball answers
maxEightballLen = 2000 // Total chars in eightball
)
var (
errTooManyAnswers = errors.New("too many eightball answers")
errEightballTooLong = common.ErrTooLong("eightball")
errTitleTooLong = common.ErrTooLong("board title")
errNoticeTooLong = common.ErrTooLong("notice")
errRulesTooLong = common.ErrTooLong("rules")
errReasonTooLong = common.ErrTooLong("reason")
errInvalidBoardName = errors.New("invalid board name")
errBoardNameTaken = errors.New("board name taken")
errAccessDenied = errors.New("access denied")
errNoReason = errors.New("no reason provided")
errNoDuration = errors.New("no ban duration provided")
boardNameValidation = regexp.MustCompile(`^[a-z0-9]{1,10}$`)
)
type boardActionRequest struct {
Board string
auth.Captcha
}
type boardConfigSettingRequest struct {
auth.Captcha
config.BoardConfigs
}
type boardCreationRequest struct {
auth.Captcha
ID, Title string
}
// Decode JSON sent in a request with a read limit of 8 KB. Returns if the
// decoding succeeded.
func decodeJSON(w http.ResponseWriter, r *http.Request, dest interface{}) bool {
decoder := json.NewDecoder(io.LimitReader(r.Body, jsonLimit))
if err := decoder.Decode(dest); err != nil {
http.Error(w, fmt.Sprintf("400 %s", err), 400)
return false
}
return true
}
// Set board-specific configurations to the user's owned board
func configureBoard(w http.ResponseWriter, r *http.Request) {
var msg boardConfigSettingRequest
if !decodeJSON(w, r, &msg) {
return
}
msg.ID = extractParam(r, "board")
_, ok := canPerform(w, r, msg.ID, auth.BoardOwner, &msg.Captcha)
if !ok || !validateBoardConfigs(w, msg.BoardConfigs) {
return
}
if err := db.UpdateBoard(msg.BoardConfigs); err != nil {
text500(w, r, err)
return
}
}
// Assert user can perform a moderation action. If the action does not need a
// captcha verification, pass captcha as nil.
func canPerform(
w http.ResponseWriter,
r *http.Request,
board string,
level auth.ModerationLevel,
captcha *auth.Captcha,
) (
creds auth.SessionCreds, can bool,
) {
if !auth.IsBoard(board) {
text400(w, errInvalidBoardName)
return
}
if captcha != nil && !auth.AuthenticateCaptcha(*captcha) {
text403(w, errInvalidCaptcha)
return
}
creds, ok := isLoggedIn(w, r)
if !ok {
return
}
can, err := db.CanPerform(creds.UserID, board, level)
switch {
case err != nil:
text500(w, r, err)
return
case !can:
text403(w, errAccessDenied)
return
default:
can = true
return
}
}
// Assert client can moderate a post of unknown parenthood and return userID
func canModeratePost(
w http.ResponseWriter,
r *http.Request,
id uint64,
level auth.ModerationLevel,
) (
board, userID string,
can bool,
) {
board, err := db.GetPostBoard(id)
switch err {
case nil:
case sql.ErrNoRows:
text400(w, err)
return
default:
text500(w, r, err)
return
}
creds, can := canPerform(w, r, board, level, nil)
if !can {
text403(w, errAccessDenied)
return
}
userID = creds.UserID
return
}
// Validate length limit compliance of various fields
func validateBoardConfigs(
w http.ResponseWriter,
conf config.BoardConfigs,
) bool {
totalLen := 0
for _, answer := range conf.Eightball {
totalLen += len(answer)
}
var err error
switch {
case len(conf.Eightball) > maxAnswers:
err = errTooManyAnswers
case totalLen > maxEightballLen:
err = errEightballTooLong
case len(conf.Notice) > common.MaxLenNotice:
err = errNoticeTooLong
case len(conf.Rules) > common.MaxLenRules:
err = errRulesTooLong
case len(conf.Title) > common.MaxLenBoardTitle:
err = errTitleTooLong
}
if err == nil {
matched := false
for _, t := range common.Themes {
if conf.DefaultCSS == t {
matched = true
break
}
}
if !matched {
err = errors.New("invalid default theme")
}
}
if err != nil {
http.Error(w, fmt.Sprintf("400 %s", err), 400)
return false
}
return true
}
// Serve the current board configurations to the client, including publically
// unexposed ones. Intended to be used before setting the the configs with
// configureBoard().
func servePrivateBoardConfigs(w http.ResponseWriter, r *http.Request) {
conf, ok := boardConfData(w, r)
if !ok {
return
}
serveJSON(w, r, "", conf)
}
// Serve the current server configurations. Available only to the "admin"
// account
func servePrivateServerConfigs(w http.ResponseWriter, r *http.Request) {
if isAdmin(w, r) {
serveJSON(w, r, "", config.Get())
}
}
func isAdmin(w http.ResponseWriter, r *http.Request) bool {
creds, ok := isLoggedIn(w, r)
if !ok {
return false
}
if creds.UserID != "admin" {
text403(w, errAccessDenied)
return false
}
return true
}
// Determine, if the client has access rights to the configurations, and return
// them, if so
func boardConfData(w http.ResponseWriter, r *http.Request) (
config.BoardConfigs, bool,
) {
var (
conf config.BoardConfigs
board = extractParam(r, "board")
)
if _, ok := canPerform(w, r, board, auth.BoardOwner, nil); !ok {
return conf, false
}
conf = config.GetBoardConfigs(board).BoardConfigs
conf.ID = board
if conf.ID == "" {
text404(w)
return conf, false
}
return conf, true
}
// Handle requests to create a board
func createBoard(w http.ResponseWriter, r *http.Request) {
var msg boardCreationRequest
if !decodeJSON(w, r, &msg) {
return
}
creds, ok := isLoggedIn(w, r)
if !ok {
return
}
// Returns, if the board name, matches a reserved ID
isReserved := func() bool {
for _, s := range [...]string{"html", "json", "api", "assets", "all"} {
if msg.ID == s {
return true
}
}
return false
}
// Validate request data
var err error
switch {
case creds.UserID != "admin" && config.Get().DisableUserBoards:
err = errAccessDenied
case !boardNameValidation.MatchString(msg.ID),
msg.ID == "",
len(msg.ID) > common.MaxLenBoardID,
isReserved():
err = errInvalidBoardName
case len(msg.Title) > 100:
err = errTitleTooLong
case !auth.AuthenticateCaptcha(msg.Captcha):
err = errInvalidCaptcha
}
if err != nil {
text400(w, err)
return
}
tx, err := db.StartTransaction()
if err != nil {
text500(w, r, err)
return
}
defer db.RollbackOnError(tx, &err)
err = db.WriteBoard(tx, db.BoardConfigs{
Created: time.Now(),
BoardConfigs: config.BoardConfigs{
BoardPublic: config.BoardPublic{
Title: msg.Title,
DefaultCSS: config.Get().DefaultCSS,
},
ID: msg.ID,
Eightball: config.EightballDefaults,
},
})
switch {
case err == nil:
case db.IsConflictError(err):
text400(w, errBoardNameTaken)
return
default:
text500(w, r, err)
return
}
err = db.WriteStaff(tx, msg.ID, map[string][]string{
"owners": []string{creds.UserID},
})
if err != nil {
text500(w, r, err)
return
}
if err := tx.Commit(); err != nil {
text500(w, r, err)
}
}
// Set the server configuration to match the one sent from the admin account
// user
func configureServer(w http.ResponseWriter, r *http.Request) {
var msg config.Configs
if !decodeJSON(w, r, &msg) || !isAdmin(w, r) {
return
}
if err := db.WriteConfigs(msg); err != nil {
text500(w, r, err)
}
}
// Delete a board owned by the client
func deleteBoard(w http.ResponseWriter, r *http.Request) {
var msg boardActionRequest
if !decodeJSON(w, r, &msg) {
return
}
_, ok := canPerform(w, r, msg.Board, auth.BoardOwner, &msg.Captcha)
if !ok {
return
}
if err := db.DeleteBoard(msg.Board); err != nil {
text500(w, r, err)
}
}
// Delete one or multiple posts on a moderated board
func deletePost(w http.ResponseWriter, r *http.Request) {
moderatePosts(w, r, auth.Janitor, db.DeletePost)
}
// Perform a moderation action an a single post. If ok == false, the caller
// should return.
func moderatePost(
w http.ResponseWriter,
r *http.Request,
id uint64,
level auth.ModerationLevel,
fn func(userID string) error,
) (
ok bool,
) {
_, userID, can := canModeratePost(w, r, id, level)
if !can {
return
}
switch err := fn(userID); err {
case nil:
return true
case sql.ErrNoRows:
text400(w, err)
return
default:
text500(w, r, err)
return
}
}
// Same as moderatePost, but works on an array of posts
func moderatePosts(
w http.ResponseWriter,
r *http.Request,
level auth.ModerationLevel,
fn func(id uint64, userID string) error,
) {
var ids []uint64
if !decodeJSON(w, r, &ids) {
return
}
for _, id := range ids {
ok := moderatePost(w, r, id, auth.Janitor, func(userID string) error {
return fn(id, userID)
})
if !ok {
return
}
}
}
// Permanently delete an image from a post
func deleteImage(w http.ResponseWriter, r *http.Request) {
moderatePosts(w, r, auth.Janitor, db.DeleteImage)
}
// Spoiler image as a moderator
func modSpoilerImage(w http.ResponseWriter, r *http.Request) {
moderatePosts(w, r, auth.Janitor, db.ModSpoilerImage)
}
// Ban a specific IP from a specific board
func ban(w http.ResponseWriter, r *http.Request) {
var msg struct {
Global bool
Duration uint64
Reason string
IDs []uint64
}
// Decode and validate
if !decodeJSON(w, r, &msg) {
return
}
creds, ok := isLoggedIn(w, r)
switch {
case !ok:
return
case msg.Global && creds.UserID != "admin":
text403(w, errAccessDenied)
return
case len(msg.Reason) > common.MaxLenReason:
text400(w, errReasonTooLong)
return
case msg.Reason == "":
text400(w, errNoReason)
return
case msg.Duration == 0:
text400(w, errNoDuration)
return
}
// Group posts by board
byBoard := make(map[string][]uint64, 2)
if msg.Global {
byBoard["all"] = msg.IDs
} else {
for _, id := range msg.IDs {
board, err := db.GetPostBoard(id)
switch err {
case nil:
case sql.ErrNoRows:
text400(w, err)
return
default:
text500(w, r, err)
return
}
byBoard[board] = append(byBoard[board], id)
}
// Assert rights to moderate for all affected boards
for b := range byBoard {
if _, ok := canPerform(w, r, b, auth.Moderator, nil); !ok {
return
}
}
}
// Apply bans
expires := time.Now().Add(time.Duration(msg.Duration) * time.Minute)
for board, ids := range byBoard {
ips, err := db.Ban(board, msg.Reason, creds.UserID, expires, ids...)
if err != nil {
text500(w, r, err)
return
}
// Redirect all banned connected clients to the /all/ board
for ip := range ips {
for _, cl := range common.GetByIPAndBoard(ip, board) {
cl.Redirect("all")
}
}
}
}
// Send a textual message to all connected clients
func sendNotification(w http.ResponseWriter, r *http.Request) {
var msg string
if !decodeJSON(w, r, &msg) || !isAdmin(w, r) {
return
}
data, err := common.EncodeMessage(common.MessageNotification, msg)
if err != nil {
text500(w, r, err)
return
}
for _, cl := range feeds.All() {
cl.Send(data)
}
}
// Assign moderation staff to a board
func assignStaff(w http.ResponseWriter, r *http.Request) {
var msg struct {
boardActionRequest
Owners, Moderators, Janitors []string
}
if !decodeJSON(w, r, &msg) {
return
}
_, ok := canPerform(w, r, msg.Board, auth.BoardOwner, &msg.Captcha)
if !ok {
return
}
switch {
// Ensure there always is at least one board owner
case len(msg.Owners) == 0:
text400(w, errors.New("no board owners set"))
return
default:
// Maximum of 100 staff per position
for _, s := range [...][]string{msg.Owners, msg.Moderators, msg.Janitors} {
if len(s) > 100 {
text400(w, errors.New("too many staff per position"))
return
}
}
}
// Write to database
tx, err := db.StartTransaction()
if err != nil {
text500(w, r, err)
return
}
defer db.RollbackOnError(tx, &err)
err = db.WriteStaff(tx, msg.Board, map[string][]string{
"owners": msg.Owners,
"moderators": msg.Moderators,
"janitors": msg.Janitors,
})
if err != nil {
text500(w, r, err)
return
}
err = tx.Commit()
if err != nil {
text500(w, r, err)
}
}
// Retrieve posts with the same IP on the target board
func getSameIPPosts(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(extractParam(r, "id"), 10, 64)
if err != nil {
text400(w, err)
return
}
board, _, ok := canModeratePost(w, r, id, auth.Janitor)
if !ok {
return
}
posts, err := db.GetSameIPPosts(id, board)
if err != nil {
text500(w, r, err)
return
}
serveJSON(w, r, "", posts)
}
// Set the sticky flag of a thread
func setThreadSticky(w http.ResponseWriter, r *http.Request) {
var msg struct {
ID uint64
Sticky bool
}
if !decodeJSON(w, r, &msg) {
return
}
if _, _, ok := canModeratePost(w, r, msg.ID, auth.Moderator); !ok {
return
}
switch err := db.SetThreadSticky(msg.ID, msg.Sticky); err {
case nil:
case sql.ErrNoRows:
text400(w, err)
default:
text500(w, r, err)
}
}
// Render list of bans on a board with unban links for authenticated staff
func banList(w http.ResponseWriter, r *http.Request) {
board := extractParam(r, "board")
if !auth.IsBoard(board) {
text404(w)
return
}
bans, err := db.GetBoardBans(board)
if err != nil {
text500(w, r, err)
return
}
canUnban := detectCanPerform(r, board, auth.Moderator)
html := []byte(templates.BanList(bans, board, canUnban))
serveHTML(w, r, "", html, nil)
}
// Detect, if a client can perform moderation on a board. Unlike canPerform,
// this will not send any errors to the client, if no access rights detected.
func detectCanPerform(
r *http.Request,
board string,
level auth.ModerationLevel,
) (
can bool,
) {
creds := extractLoginCreds(r)
if creds.UserID == "" || creds.Session == "" {
return
}
ok, err := db.IsLoggedIn(creds.UserID, creds.Session)
if err != nil || !ok {
return
}
can, err = db.CanPerform(creds.UserID, board, level)
return
}
// Unban a specific board -> banned post combination
func unban(w http.ResponseWriter, r *http.Request) {
board := extractParam(r, "board")
creds, ok := canPerform(w, r, board, auth.Moderator, nil)
if !ok {
return
}
// Extract post IDs from form
r.Body = http.MaxBytesReader(w, r.Body, jsonLimit)
err := r.ParseForm()
if err != nil {
text400(w, err)
return
}
var (
id uint64
ids = make([]uint64, 0, 32)
)
for key, vals := range r.Form {
if len(vals) == 0 || vals[0] != "on" {
continue
}
id, err = strconv.ParseUint(key, 10, 64)
if err != nil {
text400(w, err)
return
}
ids = append(ids, id)
}
// Unban posts
for _, id := range ids {
switch err := db.Unban(board, id, creds.UserID); err {
case nil, sql.ErrNoRows:
default:
text500(w, r, err)
return
}
}
http.Redirect(w, r, fmt.Sprintf("/%s/", board), 303)
}
// Serve moderation log for a specific board
func modLog(w http.ResponseWriter, r *http.Request) {
board := extractParam(r, "board")
if !auth.IsBoard(board) {
text404(w)
return
}
log, err := db.GetModLog(board)
if err != nil {
text500(w, r, err)
return
}
serveHTML(w, r, "", []byte(templates.ModLog(log)), nil)
}